Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 | 1x 1x 1x 1x 1x 8x 8x 7x 7x 12x 9x 9x 9x 9x 12x 1x 1x 1x 7x 7x 7x 1x 1x 1x 1x 1x 1x 9x 8x 8x 8x 9x 2x 2x 2x 6x 6x 1x 1x 1x 1x 1x 1x 9x 7x 9x 9x 2x 2x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 5x 5x 5x 5x 5x 1x 5x 4x 4x 4x 4x 1x 1x 4x 5x 6x 8x 4x 4x 2x 2x 5x 5x 5x 9x 2x 2x 2x 2x 5x 5x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 22x 21x 21x 21x 21x 21x 21x 21x 60049x 60049x 60049x 4x 21x 21x 21x 1x 1x 1x 1x 1x 1x 23x 22x 22x 22x 22x 23x 2x 2x 20x 20x 20x 20x 20x 20x 20x 20x 23x 2x 2x 2x 2x 2x 2x 2x 2x 20x 20x 1x 1x 1x 22x 60034x 60025x 60025x 60034x 22x 1x 1x 1x 20x 20x 20x 60025x 60025x 60025x 60025x 60025x 60033x 60033x 20x 20x 20x 1x 1x 1x 20x 20x 20x 20x 20x 60027x 20x 20x 60027x 60027x 20x 20x 20x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 6x 6x 6x 6x 6x 6x 6x 2x 2x 1x 1x 1x 1x 1x 2x 6x 3x 3x 3x 5x 6x 1x 1x 1x 5x 6x 1x 1x 1x 6x 4x 4x 4x 4x 5x 5x 6x 6x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1x 1x 1x | const diffPreparationMethods = {
/**
* Extrae lineas permitidas desde un diff normalizado.
*/
_extractAllowedLinesFromDiff(diffText, includeDeleted = true) {
const allowed = new Set();
if (!diffText) return allowed;
diffText.split("\n").forEach((line) => {
if (line.startsWith("+")) {
const normalized = line.slice(1).trim();
if (normalized) allowed.add(normalized);
return;
}
if (line.startsWith("-") && includeDeleted) {
const normalized = line.slice(1).trim();
if (normalized) allowed.add(normalized);
}
});
return allowed;
},
/**
* Extrae path de archivo desde location.
*/
_extractFilePathFromLocation(location) {
if (!location || typeof location !== "string") return null;
const normalized = location.replace(/\\/g, "/");
const match = normalized.match(/\/(?:[^\s:]+\/)+[^\s:]+\.[a-z0-9]+/i);
if (!match) {
this.logger?.debug(`No se pudo extraer ruta de location: ${location}`);
return null;
}
return match[0];
},
/**
* Filtra issues fuera del diff.
*/
_filterIssuesToDiff(issues, diffByFile, includeDeleted = true) {
if (!issues || issues.length === 0) return issues;
const diffKeys = diffByFile ? Object.keys(diffByFile) : [];
if (diffKeys.length === 0) {
this.logger?.warn(
" ⚠️ Diff sin archivos validos. Se omiten issues para evitar falsos positivos.",
);
return [];
}
const allowedByFile = {};
diffKeys.forEach((filePath) => {
allowedByFile[filePath] = this._extractAllowedLinesFromDiff(
diffByFile[filePath],
includeDeleted,
);
});
const allAllowedLines = new Set();
diffKeys.forEach((key) => {
allowedByFile[key].forEach((line) => allAllowedLines.add(line));
});
const filtered = issues.filter((issue) => {
const code = (issue.code || "").trim();
if (!code) return false;
const codeLines = code
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
const issuePath = this._extractFilePathFromLocation(issue.location);
let allowedLines = null;
if (issuePath) {
const normalizedIssuePath = issuePath.replace(/\\/g, "/");
const directMatch = diffKeys.find(
(key) => key.replace(/\\/g, "/") === normalizedIssuePath,
);
if (directMatch) {
allowedLines = allowedByFile[directMatch];
} else {
const suffixMatch = diffKeys.find((key) =>
key.replace(/\\/g, "/").endsWith(normalizedIssuePath),
);
if (suffixMatch) {
allowedLines = allowedByFile[suffixMatch];
}
}
}
if (!allowedLines) {
return codeLines.some((line) => allAllowedLines.has(line));
}
return codeLines.some((line) => allowedLines.has(line));
});
const removed = issues.length - filtered.length;
if (removed > 0) {
this.logger?.warn(
` ⚠️ Se descartaron ${removed} issue(s) por no existir en las diferencias del PR`,
);
}
return filtered;
},
/**
* Normaliza diff para revision.
*/
_normalizeDiffForReview(
diffContent,
contextLines = 0,
includeDeleted = true,
) {
if (!diffContent) return "";
const withContext = this._extractOnlyChangedLines(
diffContent,
contextLines,
);
const lines = withContext.split("\n");
const filtered = lines.filter((line) => {
if (line.trim() === "...") return false;
if (line.startsWith("+")) return true;
if (line.startsWith("-")) return includeDeleted;
return false;
});
return filtered.join("\n");
},
/**
* Extrae solo lineas modificadas con contexto minimo.
*/
_extractOnlyChangedLines(diffContent, contextLines = 3) {
if (!diffContent) return "";
const lines = diffContent.split("\n");
const changedIndices = this._findChangedLineIndices(lines);
if (changedIndices.length === 0) {
return diffContent;
}
const includedIndices = this._expandIndicesWithContext(
changedIndices,
lines.length,
contextLines,
);
const optimizedDiff = this._buildDiffFromIndices(lines, includedIndices);
if (diffContent.length > optimizedDiff.length * 1.2) {
const reduction = (
((diffContent.length - optimizedDiff.length) / diffContent.length) *
100
).toFixed(0);
this.logger?.info(
` 📉 Diff optimizado: ${diffContent.length} → ${optimizedDiff.length} chars (${reduction}% reducción)`,
);
}
return optimizedDiff;
},
_findChangedLineIndices(lines) {
return lines.reduce((acc, line, idx) => {
if (line.startsWith("+") || line.startsWith("-")) {
acc.push(idx);
}
return acc;
}, []);
},
_expandIndicesWithContext(changedIndices, totalLines, contextLines) {
const includedIndices = new Set();
changedIndices.forEach((idx) => {
for (
let i = Math.max(0, idx - contextLines);
i <= Math.min(totalLines - 1, idx + contextLines);
i++
) {
includedIndices.add(i);
}
});
return includedIndices;
},
_buildDiffFromIndices(lines, includedIndices) {
const result = [];
const sortedIndices = Array.from(includedIndices).sort((a, b) => a - b);
let lastIdx = -2;
sortedIndices.forEach((idx) => {
if (idx > lastIdx + 1) {
result.push("...");
}
result.push(lines[idx]);
lastIdx = idx;
});
return result.join("\n");
},
_loadIgnoredFilePatterns() {
try {
const vscode = require("vscode");
const config = vscode.workspace.getConfiguration("gbot");
const inspected =
typeof config.inspect === "function"
? config.inspect("prReview.ignoredFilePatterns")
: null;
const hasExplicitSettingsValue = Boolean(
inspected &&
(inspected.globalValue !== undefined ||
inspected.workspaceValue !== undefined ||
inspected.workspaceFolderValue !== undefined),
);
let patterns;
let sourceLabel;
if (hasExplicitSettingsValue) {
patterns = config.get("prReview.ignoredFilePatterns");
if (!Array.isArray(patterns)) {
this.logger?.warn(
"⚠️ gbot.prReview.ignoredFilePatterns no es un array. Se usará array vacío.",
);
patterns = [];
}
sourceLabel = "settings de VS Code";
} else {
patterns = this._loadIgnoredFilePatternsFromConfigJson(vscode);
sourceLabel = "config.json";
}
if (!hasExplicitSettingsValue && (!patterns || patterns.length === 0)) {
patterns = this.constructor.DEFAULT_IGNORED_FILE_PATTERNS;
sourceLabel = "valores por defecto";
}
if (sourceLabel === "valores por defecto") {
this.logger?.info(
"⚙️ Usando patrones de archivos ignorados por defecto",
);
} else {
this.logger?.info(
`⚙️ Cargados ${Array.isArray(patterns) ? patterns.length : 0} patrones de archivos ignorados desde ${sourceLabel}`,
);
}
this.ignoredFilePatterns = this._compileIgnoredFilePatterns(
patterns || [],
);
} catch (error) {
this.logger?.warn(
`⚠️ Error cargando patrones ignorados: ${error.message}. Usando defaults.`,
);
this.ignoredFilePatterns = this._compileIgnoredFilePatterns(
this.constructor.DEFAULT_IGNORED_FILE_PATTERNS,
);
}
},
_loadIgnoredFilePatternsFromConfigJson(vscode) {
const fs = require("fs");
const path = require("path");
const candidates = [];
const workspaceFolders = vscode?.workspace?.workspaceFolders || [];
workspaceFolders.forEach((folder) => {
const rootPath = folder?.uri?.fsPath;
if (rootPath) {
candidates.push(path.join(rootPath, "config.json"));
}
});
// Compatibilidad: buscar también junto al package de la extensión en modo desarrollo.
candidates.push(path.join(__dirname, "..", "..", "..", "config.json"));
for (const configPath of candidates) {
try {
if (!fs.existsSync(configPath)) {
continue;
}
const configContent = fs.readFileSync(configPath, "utf-8");
const configData = JSON.parse(configContent);
const patterns = configData?.prReview?.ignoredFilePatterns;
if (Array.isArray(patterns)) {
return patterns;
}
} catch (error) {
this.logger?.warn(
`⚠️ Error leyendo ${configPath}: ${error.message}. Se intentará con otra fuente.`,
);
}
}
return null;
},
_compileIgnoredFilePatterns(patterns) {
if (!Array.isArray(patterns)) {
return [];
}
return patterns
.map((pattern) => {
try {
if (typeof pattern !== "string") {
this.logger?.warn(
`⚠️ Patrón ignorado (tipo inválido): ${String(pattern).substring(0, 50)}`,
);
return null;
}
const normalizedPattern = pattern.trim();
if (!normalizedPattern) {
return null;
}
if (normalizedPattern.length > 200) {
this.logger?.warn(
`⚠️ Patrón ignorado (demasiado largo): ${normalizedPattern.substring(0, 50)}`,
);
return null;
}
return new RegExp(normalizedPattern, "i");
} catch {
this.logger?.warn(`⚠️ Patrón inválido ignorado: ${pattern}`);
return null;
}
})
.filter((p) => p !== null);
},
_shouldIgnoreFile(filePath) {
return this.ignoredFilePatterns.some((pattern) => pattern.test(filePath));
},
_getIgnoreReason(filePath) {
if (
/\.(md|txt|rst|adoc)$/i.test(filePath) ||
/(README|CHANGELOG|CONTRIBUTING|LICENSE)/i.test(filePath) ||
/\/(docs|documentation)\//i.test(filePath)
) {
return "archivo de documentación (no es código)";
}
if (/\.(dacpac|bacpac)$/i.test(filePath)) {
return "archivo de base de datos (excede límite de tokens)";
}
if (/\.(dll|exe|pdb)$/i.test(filePath)) {
return "archivo binario";
}
if (/\.(bak|publish\.xml)$/i.test(filePath)) {
return "archivo de configuración/backup";
}
if (/\.(vs|vsidx|wsuo|suo|user)/.test(filePath)) {
return "archivo de IDE";
}
if (/(bin|obj|node_modules)\//i.test(filePath)) {
return "carpeta de build/dependencias";
}
return "archivo de IDE/build";
},
_formatChangesForPrompt(changes, options = {}) {
const contextLines =
typeof options.contextLines === "number" ? options.contextLines : 0;
const includeDeleted =
typeof options.includeDeleted === "boolean"
? options.includeDeleted
: true;
if (!changes || changes.length === 0) {
return {
formattedPrompt: "No se pudieron obtener los cambios del código.",
includedFiles: 0,
skippedFiles: [],
largeFiles: [],
};
}
const sortedChanges = [...changes].sort((a, b) => {
const pathA = a.path || "";
const pathB = b.path || "";
const pathComparison = pathA.localeCompare(pathB);
if (pathComparison !== 0) {
return pathComparison;
}
const typeA = a.changeType || "";
const typeB = b.changeType || "";
return typeA.localeCompare(typeB);
});
let formatted =
"⚠️ IMPORTANTE: Revisa SOLO las líneas marcadas con + (agregadas) o - (eliminadas).\n";
formatted += "NO analices código que no está en estas diferencias.\n\n";
let totalChars = 0;
let includedFiles = 0;
const skippedFiles = [];
const largeFiles = [];
const diffByFile = {};
for (const change of sortedChanges) {
if (this._shouldIgnoreFile(change.path)) {
const reason = this._getIgnoreReason(change.path);
skippedFiles.push({
path: change.path,
reason,
});
continue;
}
const maxTotalDiff =
this.currentModelLimits?.maxTotalDiff ||
this.constructor.MAX_TOTAL_DIFF_CHARS;
if (totalChars >= maxTotalDiff) {
skippedFiles.push({
path: change.path,
reason: "límite total alcanzado",
});
continue;
}
formatted += `\n--- DIFERENCIAS Archivo ${includedFiles + 1}: ${
change.path
} (${change.changeType}) ---\n`;
if (change.diff) {
const diffContent = change.diff;
if (
diffContent.includes("Sin diferencias detectables") ||
diffContent.includes("posible renombre") ||
diffContent.includes("cambio de metadata")
) {
skippedFiles.push({
path: change.path,
reason: "sin diferencias visibles (metadata/renombre)",
});
continue;
}
const normalizedDiff = this._normalizeDiffForReview(
diffContent,
contextLines,
includeDeleted,
);
if (!normalizedDiff || normalizedDiff.trim().length === 0) {
skippedFiles.push({
path: change.path,
reason: "sin lineas modificadas relevantes",
});
continue;
}
const maxSingleFile =
this.currentModelLimits?.maxSingleFile ||
this.constructor.MAX_SINGLE_FILE_CHARS;
if (normalizedDiff.length > maxSingleFile) {
this.logger?.info(
` 📦 Archivo grande marcado para análisis separado: ${change.path} (${(diffContent.length / 1000).toFixed(0)}k chars → ${(normalizedDiff.length / 1000).toFixed(0)}k normalizado)`,
);
largeFiles.push({
path: change.path,
changeType: change.changeType,
size: normalizedDiff.length,
diff: normalizedDiff,
reason: `tamaño ${(diffContent.length / 1000).toFixed(0)}k > límite ${(maxSingleFile / 1000).toFixed(0)}k (normalizado a ${(normalizedDiff.length / 1000).toFixed(0)}k)`,
});
diffByFile[change.path] = normalizedDiff;
continue;
}
if (totalChars + normalizedDiff.length > maxTotalDiff) {
this.logger?.info(
` 📦 Archivo pospuesto para siguiente bloque: ${change.path} (bloque lleno, normalizado ${(diffContent.length / 1000).toFixed(0)}k → ${(normalizedDiff.length / 1000).toFixed(0)}k)`,
);
largeFiles.push({
path: change.path,
changeType: change.changeType,
size: normalizedDiff.length,
diff: normalizedDiff,
reason: "no cabía en bloque actual",
});
diffByFile[change.path] = normalizedDiff;
continue;
}
formatted += normalizedDiff + "\n";
totalChars += normalizedDiff.length;
includedFiles++;
diffByFile[change.path] = normalizedDiff;
}
}
if (skippedFiles.length > 0 || largeFiles.length > 0) {
formatted += `\n${"=".repeat(60)}\n`;
formatted += `📊 RESUMEN DE PROCESAMIENTO:\n`;
formatted += ` ✅ Archivos analizados: ${includedFiles}\n`;
if (largeFiles.length > 0) {
formatted += ` 📦 Archivos grandes (procesamiento separado): ${largeFiles.length}\n`;
largeFiles.slice(0, 3).forEach((f) => {
formatted += ` - ${f.path} (${(f.size / 1000).toFixed(0)}k chars)\n`;
});
if (largeFiles.length > 3) {
formatted += ` ... y ${largeFiles.length - 3} más\n`;
}
}
if (skippedFiles.length > 0) {
formatted += ` ⏭️ Archivos omitidos: ${skippedFiles.length}\n`;
const byReason = {};
skippedFiles.forEach((f) => {
const reason = f.reason || "otro";
if (!byReason[reason]) byReason[reason] = [];
byReason[reason].push(f.path);
});
for (const [reason, files] of Object.entries(byReason)) {
formatted += ` \n 📌 ${reason.toUpperCase()}:\n`;
const showFiles = files.slice(0, 3);
showFiles.forEach((file) => {
formatted += ` - ${file}\n`;
});
if (files.length > 3) {
formatted += ` ... y ${files.length - 3} más\n`;
}
}
}
formatted += `\n💡 NOTA IMPORTANTE:\n`;
if (largeFiles.length > 0) {
formatted += ` • Archivos grandes se procesarán en un análisis separado (sin truncar código)\n`;
}
formatted += ` • Archivos de base de datos (.dacpac, .bacpac) se omiten por exceder límite de tokens\n`;
formatted += ` • Archivos de IDE/build no aportan valor al code review\n`;
formatted += ` • Archivos sin diferencias visibles son solo metadata o renombres\n`;
formatted += ` • Enfócate en los archivos de código con cambios reales mostrados arriba\n`;
}
this.logger.info(
` 📊 Prompt: ${includedFiles} archivos, ${totalChars} caracteres`,
);
if (skippedFiles.length > 0) {
const dbFiles = skippedFiles.filter((f) =>
/\.(dacpac|bacpac)$/i.test(f.path),
);
if (dbFiles.length > 0) {
this.logger.info(
` 🗄️ Archivos de BD omitidos: ${dbFiles.length} (.dacpac/.bacpac - exceden límite de tokens)`,
);
}
const otherSkipped = skippedFiles.length - dbFiles.length;
if (otherSkipped > 0) {
this.logger.info(
` ⏭️ Otros omitidos: ${otherSkipped} archivos (IDE/build o límite)`,
);
}
}
if (largeFiles.length > 0) {
this.logger.info(
` 📦 Archivos grandes (análisis separado): ${largeFiles.length} - SIN TRUNCAR`,
);
}
this.lastIgnoredFiles = skippedFiles;
return {
formattedPrompt: formatted,
includedFiles,
skippedFiles,
largeFiles,
diffByFile,
};
},
_setPromptDiffContext(formattedChanges, includeDeleted) {
this._pendingLargeFiles = formattedChanges?.largeFiles || [];
this._lastDiffByFile = formattedChanges?.diffByFile || {};
this._lastDiffIncludeDeleted = includeDeleted;
},
};
module.exports = diffPreparationMethods;
|