| ... | ... | @@ -0,0 +1,871 @@ |
| 1 | #!/usr/bin/env node |
| 2 | // jj-import-merge |
| 3 | // Merge top-of-file JS/TS imports from 2-sided Jujutsu conflicts. |
| 4 | |
| 5 | import * as child_process from "node:child_process"; |
| 6 | import * as fs from "node:fs"; |
| 7 | import * as path from "node:path"; |
| 8 | import process from "node:process"; |
| 9 | |
| 10 | const SUPPORTED_EXTENSIONS = new Set([ |
| 11 | ".cjs", |
| 12 | ".cts", |
| 13 | ".js", |
| 14 | ".jsx", |
| 15 | ".mjs", |
| 16 | ".mts", |
| 17 | ".ts", |
| 18 | ".tsx", |
| 19 | ]); |
| 20 | |
| 21 | const CONFLICT_START_RE = /^<<<<<<< conflict \d+ of \d+/m; |
| 22 | const CONFLICT_END_RE = /^>>>>>>> conflict \d+ of \d+ ends$/m; |
| 23 | |
| 24 | main(); |
| 25 | |
| 26 | function main() { |
| 27 | const options = parseArgs(process.argv.slice(2)); |
| 28 | let files = options.files.map((file) => path.resolve(file)); |
| 29 | |
| 30 | if (options.allJj) { |
| 31 | files.push(...listJjConflictFiles().map((file) => path.resolve(file))); |
| 32 | } |
| 33 | |
| 34 | files = [...new Set(files)]; |
| 35 | if (files.length === 0) { |
| 36 | usage(1); |
| 37 | } |
| 38 | |
| 39 | let failed = false; |
| 40 | for (const file of files) { |
| 41 | try { |
| 42 | const result = processFile(file); |
| 43 | if (result.kind === "formatted") { |
| 44 | console.info(`formatted ${path.relative(process.cwd(), file)}`); |
| 45 | } else if (result.kind === "rewritten") { |
| 46 | console.info(`rewrote ${path.relative(process.cwd(), file)}`); |
| 47 | } |
| 48 | } catch (error) { |
| 49 | failed = true; |
| 50 | const message = error instanceof Error ? error.message : String(error); |
| 51 | console.error(`error: ${message}`); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | process.exit(failed ? 1 : 0); |
| 56 | } |
| 57 | |
| 58 | function parseArgs(argv) { |
| 59 | const options = { |
| 60 | allJj: false, |
| 61 | files: [], |
| 62 | }; |
| 63 | |
| 64 | while (argv.length > 0) { |
| 65 | const arg = argv.shift(); |
| 66 | if (arg === "-h" || arg === "--help") { |
| 67 | usage(0); |
| 68 | } else if (arg === "--all-jj") { |
| 69 | options.allJj = true; |
| 70 | } else if (arg === "--") { |
| 71 | options.files.push(...argv); |
| 72 | break; |
| 73 | } else if (arg.startsWith("-")) { |
| 74 | console.error(`error: unknown option ${JSON.stringify(arg)}`); |
| 75 | usage(1); |
| 76 | } else { |
| 77 | options.files.push(arg); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | return options; |
| 82 | } |
| 83 | |
| 84 | function usage(code) { |
| 85 | const exe = "jj-import-merge"; |
| 86 | const stream = code === 0 ? process.stdout : process.stderr; |
| 87 | stream.write(`usage: ${exe} [--all-jj] [--] <file>...\n`); |
| 88 | stream.write(`\n`); |
| 89 | stream.write(`merge top-of-file JS/TS imports from 2-sided Jujutsu conflicts\n`); |
| 90 | stream.write(`\n`); |
| 91 | stream.write(`options:\n`); |
| 92 | stream.write(` --all-jj resolve all conflicted JS/TS files from 'jj resolve --list'\n`); |
| 93 | stream.write(` -h show help\n`); |
| 94 | process.exit(code); |
| 95 | } |
| 96 | |
| 97 | function listJjConflictFiles() { |
| 98 | const result = child_process.spawnSync( |
| 99 | "jj", |
| 100 | ["--color=never", "--quiet", "resolve", "--list"], |
| 101 | { encoding: "utf8" }, |
| 102 | ); |
| 103 | |
| 104 | if (result.error) { |
| 105 | throw new Error(`failed to run jj: ${result.error.message}`); |
| 106 | } |
| 107 | if (result.status !== 0) { |
| 108 | throw new Error(result.stderr.trim() || "jj resolve --list failed"); |
| 109 | } |
| 110 | |
| 111 | return result.stdout |
| 112 | .split(/\r?\n/) |
| 113 | .map((line) => line.trimEnd()) |
| 114 | .filter(Boolean) |
| 115 | .map((line) => line.match(/^(.*?)\s{2,}.+conflict$/)) |
| 116 | .filter(Boolean) |
| 117 | .map((match) => match[1]); |
| 118 | } |
| 119 | |
| 120 | function processFile(file) { |
| 121 | if (!SUPPORTED_EXTENSIONS.has(path.extname(file))) { |
| 122 | return { kind: "noop" }; |
| 123 | } |
| 124 | |
| 125 | let original; |
| 126 | try { |
| 127 | original = fs.readFileSync(file, "utf8"); |
| 128 | } catch (error) { |
| 129 | const message = error instanceof Error ? error.message : String(error); |
| 130 | throw new Error(`cannot read ${file}: ${message}`); |
| 131 | } |
| 132 | |
| 133 | if (!CONFLICT_START_RE.test(original)) { |
| 134 | return { kind: "noop" }; |
| 135 | } |
| 136 | |
| 137 | const parsed = parseConflictFile(original); |
| 138 | if (!parsed.supported) { |
| 139 | return { kind: "noop" }; |
| 140 | } |
| 141 | |
| 142 | const leftText = parsed.parts.map((part) => part.a).join(""); |
| 143 | const rightText = parsed.parts.map((part) => part.b).join(""); |
| 144 | const leftImports = extractTopImportBlock(leftText); |
| 145 | const rightImports = extractTopImportBlock(rightText); |
| 146 | if (!leftImports || !rightImports) { |
| 147 | return { kind: "noop" }; |
| 148 | } |
| 149 | |
| 150 | const leftPrelude = leftText.slice(0, leftImports.start); |
| 151 | const rightPrelude = rightText.slice(0, rightImports.start); |
| 152 | if (leftPrelude !== rightPrelude) { |
| 153 | return { kind: "noop" }; |
| 154 | } |
| 155 | |
| 156 | const start = projectBoundaryToOriginal( |
| 157 | parsed.parts, |
| 158 | leftImports.start, |
| 159 | rightImports.start, |
| 160 | ); |
| 161 | const end = projectBoundaryToOriginal(parsed.parts, leftImports.end, rightImports.end); |
| 162 | if (start == null || end == null || end < start) { |
| 163 | return { kind: "noop" }; |
| 164 | } |
| 165 | |
| 166 | const mergedImports = mergeImportStatements( |
| 167 | leftImports.statements, |
| 168 | rightImports.statements, |
| 169 | detectNewline(original), |
| 170 | ); |
| 171 | const updated = original.slice(0, start) + mergedImports + original.slice(end); |
| 172 | |
| 173 | if (updated === original) { |
| 174 | return { kind: "noop" }; |
| 175 | } |
| 176 | |
| 177 | try { |
| 178 | fs.writeFileSync(file, updated, "utf8"); |
| 179 | } catch (error) { |
| 180 | const message = error instanceof Error ? error.message : String(error); |
| 181 | throw new Error(`cannot write ${file}: ${message}`); |
| 182 | } |
| 183 | |
| 184 | if (hasConflictMarkers(updated)) { |
| 185 | return { kind: "rewritten" }; |
| 186 | } |
| 187 | |
| 188 | const formatResult = child_process.spawnSync("autofmt", [file], { |
| 189 | encoding: "utf8", |
| 190 | stdio: "inherit", |
| 191 | }); |
| 192 | |
| 193 | if (formatResult.error || formatResult.status !== 0) { |
| 194 | fs.writeFileSync(file, original, "utf8"); |
| 195 | if (formatResult.error) { |
| 196 | throw new Error(`autofmt failed for ${file}: ${formatResult.error.message}`); |
| 197 | } |
| 198 | throw new Error(`autofmt failed for ${file}`); |
| 199 | } |
| 200 | |
| 201 | return { kind: "formatted" }; |
| 202 | } |
| 203 | |
| 204 | function parseConflictFile(text) { |
| 205 | const lines = splitLines(text); |
| 206 | const parts = []; |
| 207 | |
| 208 | let index = 0; |
| 209 | while (index < lines.length) { |
| 210 | const line = lines[index].text; |
| 211 | if (!line.startsWith("<<<<<<< conflict ")) { |
| 212 | const start = index; |
| 213 | index += 1; |
| 214 | while ( |
| 215 | index < lines.length && |
| 216 | !lines[index].text.startsWith("<<<<<<< conflict ") |
| 217 | ) { |
| 218 | index += 1; |
| 219 | } |
| 220 | const raw = joinLines(lines, start, index); |
| 221 | parts.push({ type: "plain", orig: raw, a: raw, b: raw }); |
| 222 | continue; |
| 223 | } |
| 224 | |
| 225 | const block = parseConflictBlock(lines, index); |
| 226 | if (!block.supported) { |
| 227 | return { supported: false, parts: [] }; |
| 228 | } |
| 229 | parts.push(block.part); |
| 230 | index = block.nextIndex; |
| 231 | } |
| 232 | |
| 233 | return { supported: true, parts }; |
| 234 | } |
| 235 | |
| 236 | function parseConflictBlock(lines, startIndex) { |
| 237 | let index = startIndex + 1; |
| 238 | const entries = []; |
| 239 | |
| 240 | while (index < lines.length) { |
| 241 | const line = lines[index].text; |
| 242 | if (line.startsWith(">>>>>>> conflict ")) { |
| 243 | break; |
| 244 | } |
| 245 | if (line.startsWith("+++++++ ")) { |
| 246 | const contentStart = index + 1; |
| 247 | index += 1; |
| 248 | while ( |
| 249 | index < lines.length && |
| 250 | !isConflictEntryStart(lines[index].text) && |
| 251 | !lines[index].text.startsWith(">>>>>>> conflict ") |
| 252 | ) { |
| 253 | index += 1; |
| 254 | } |
| 255 | entries.push({ |
| 256 | kind: "explicit", |
| 257 | text: joinLines(lines, contentStart, index), |
| 258 | }); |
| 259 | continue; |
| 260 | } |
| 261 | if (line.startsWith("%%%%%%% diff from:")) { |
| 262 | if (index + 1 >= lines.length || !/^\\\\+\s*to:/.test(lines[index + 1].text)) { |
| 263 | return { supported: false, nextIndex: startIndex + 1 }; |
| 264 | } |
| 265 | index += 2; |
| 266 | let text = ""; |
| 267 | while ( |
| 268 | index < lines.length && |
| 269 | !isConflictEntryStart(lines[index].text) && |
| 270 | !lines[index].text.startsWith(">>>>>>> conflict ") |
| 271 | ) { |
| 272 | const diffLine = lines[index].text; |
| 273 | const prefix = diffLine[0]; |
| 274 | if (prefix === " " || prefix === "+") { |
| 275 | text += diffLine.slice(1); |
| 276 | } else if (prefix !== "-") { |
| 277 | return { supported: false, nextIndex: startIndex + 1 }; |
| 278 | } |
| 279 | index += 1; |
| 280 | } |
| 281 | entries.push({ kind: "diff", text }); |
| 282 | continue; |
| 283 | } |
| 284 | return { supported: false, nextIndex: startIndex + 1 }; |
| 285 | } |
| 286 | |
| 287 | if ( |
| 288 | index >= lines.length || |
| 289 | !lines[index].text.startsWith(">>>>>>> conflict ") || |
| 290 | entries.length !== 2 |
| 291 | ) { |
| 292 | return { supported: false, nextIndex: startIndex + 1 }; |
| 293 | } |
| 294 | |
| 295 | return { |
| 296 | supported: true, |
| 297 | nextIndex: index + 1, |
| 298 | part: { |
| 299 | type: "conflict", |
| 300 | orig: joinLines(lines, startIndex, index + 1), |
| 301 | a: entries[0].text, |
| 302 | b: entries[1].text, |
| 303 | }, |
| 304 | }; |
| 305 | } |
| 306 | |
| 307 | function isConflictEntryStart(line) { |
| 308 | return line.startsWith("+++++++ ") || line.startsWith("%%%%%%% diff from:"); |
| 309 | } |
| 310 | |
| 311 | function splitLines(text) { |
| 312 | const lines = []; |
| 313 | let start = 0; |
| 314 | |
| 315 | for (let index = 0; index < text.length; index += 1) { |
| 316 | if (text[index] !== "\n") continue; |
| 317 | lines.push({ |
| 318 | start, |
| 319 | end: index + 1, |
| 320 | text: text.slice(start, index + 1), |
| 321 | }); |
| 322 | start = index + 1; |
| 323 | } |
| 324 | |
| 325 | if (start < text.length) { |
| 326 | lines.push({ start, end: text.length, text: text.slice(start) }); |
| 327 | } |
| 328 | |
| 329 | return lines; |
| 330 | } |
| 331 | |
| 332 | function joinLines(lines, start, end) { |
| 333 | let text = ""; |
| 334 | for (let index = start; index < end; index += 1) { |
| 335 | text += lines[index].text; |
| 336 | } |
| 337 | return text; |
| 338 | } |
| 339 | |
| 340 | function extractTopImportBlock(text) { |
| 341 | const lines = splitLines(text); |
| 342 | if (lines.length === 0) return null; |
| 343 | |
| 344 | let index = 0; |
| 345 | if (lines[0]?.text.startsWith("#!")) { |
| 346 | index += 1; |
| 347 | } |
| 348 | |
| 349 | index = skipPrelude(lines, index); |
| 350 | if (index == null || index >= lines.length) { |
| 351 | return null; |
| 352 | } |
| 353 | |
| 354 | const first = parseImportStatement(lines, index); |
| 355 | if (!first) { |
| 356 | return null; |
| 357 | } |
| 358 | |
| 359 | const start = lines[index].start; |
| 360 | const statements = [first.statement]; |
| 361 | let end = offsetForLine(lines, first.nextIndex); |
| 362 | index = first.nextIndex; |
| 363 | |
| 364 | while (true) { |
| 365 | const afterTrivia = skipBlankAndComments(lines, index); |
| 366 | if (afterTrivia == null) { |
| 367 | return null; |
| 368 | } |
| 369 | |
| 370 | const next = parseImportStatement(lines, afterTrivia); |
| 371 | if (!next) { |
| 372 | break; |
| 373 | } |
| 374 | |
| 375 | statements.push(next.statement); |
| 376 | end = offsetForLine(lines, next.nextIndex); |
| 377 | index = next.nextIndex; |
| 378 | } |
| 379 | |
| 380 | return { start, end, statements }; |
| 381 | } |
| 382 | |
| 383 | function skipPrelude(lines, startIndex) { |
| 384 | let index = startIndex; |
| 385 | while (index < lines.length) { |
| 386 | const afterTrivia = skipBlankAndComments(lines, index); |
| 387 | if (afterTrivia == null) { |
| 388 | return null; |
| 389 | } |
| 390 | if (afterTrivia >= lines.length) { |
| 391 | return afterTrivia; |
| 392 | } |
| 393 | |
| 394 | const trimmed = lines[afterTrivia].text.trim(); |
| 395 | if (isDirectiveLine(trimmed)) { |
| 396 | index = afterTrivia + 1; |
| 397 | continue; |
| 398 | } |
| 399 | return afterTrivia; |
| 400 | } |
| 401 | return index; |
| 402 | } |
| 403 | |
| 404 | function skipBlankAndComments(lines, startIndex) { |
| 405 | let index = startIndex; |
| 406 | |
| 407 | while (index < lines.length) { |
| 408 | const trimmed = lines[index].text.trim(); |
| 409 | if (trimmed === "") { |
| 410 | index += 1; |
| 411 | continue; |
| 412 | } |
| 413 | if (trimmed.startsWith("//")) { |
| 414 | index += 1; |
| 415 | continue; |
| 416 | } |
| 417 | if (trimmed.startsWith("/*")) { |
| 418 | index = skipBlockComment(lines, index); |
| 419 | if (index == null) { |
| 420 | return null; |
| 421 | } |
| 422 | continue; |
| 423 | } |
| 424 | break; |
| 425 | } |
| 426 | |
| 427 | return index; |
| 428 | } |
| 429 | |
| 430 | function skipBlockComment(lines, startIndex) { |
| 431 | for (let index = startIndex; index < lines.length; index += 1) { |
| 432 | if (lines[index].text.includes("*/")) { |
| 433 | return index + 1; |
| 434 | } |
| 435 | } |
| 436 | return null; |
| 437 | } |
| 438 | |
| 439 | function isDirectiveLine(line) { |
| 440 | return /^["'][^"'\\]*(?:\\.[^"'\\]*)*["'];?$/.test(line); |
| 441 | } |
| 442 | |
| 443 | function parseImportStatement(lines, startIndex) { |
| 444 | if (startIndex >= lines.length) { |
| 445 | return null; |
| 446 | } |
| 447 | |
| 448 | const firstLine = lines[startIndex].text.trimStart(); |
| 449 | if (!firstLine.startsWith("import")) { |
| 450 | return null; |
| 451 | } |
| 452 | if (/^import(?:\s*\(|\s*\.)/.test(firstLine)) { |
| 453 | return null; |
| 454 | } |
| 455 | |
| 456 | let raw = ""; |
| 457 | const state = { |
| 458 | braceDepth: 0, |
| 459 | inBlockComment: false, |
| 460 | stringQuote: null, |
| 461 | }; |
| 462 | |
| 463 | for (let index = startIndex; index < lines.length; index += 1) { |
| 464 | raw += lines[index].text; |
| 465 | scanLine(lines[index].text, state); |
| 466 | |
| 467 | if (state.inBlockComment || state.braceDepth !== 0) { |
| 468 | continue; |
| 469 | } |
| 470 | |
| 471 | const analysis = parseImportSemantics(raw); |
| 472 | if (analysis) { |
| 473 | return { |
| 474 | nextIndex: index + 1, |
| 475 | statement: raw, |
| 476 | }; |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | return null; |
| 481 | } |
| 482 | |
| 483 | function scanLine(line, state) { |
| 484 | for (let index = 0; index < line.length; index += 1) { |
| 485 | const char = line[index]; |
| 486 | const next = line[index + 1]; |
| 487 | |
| 488 | if (state.inBlockComment) { |
| 489 | if (char === "*" && next === "/") { |
| 490 | state.inBlockComment = false; |
| 491 | index += 1; |
| 492 | } |
| 493 | continue; |
| 494 | } |
| 495 | |
| 496 | if (state.stringQuote) { |
| 497 | if (char === "\\") { |
| 498 | index += 1; |
| 499 | continue; |
| 500 | } |
| 501 | if (char === state.stringQuote) { |
| 502 | state.stringQuote = null; |
| 503 | } |
| 504 | continue; |
| 505 | } |
| 506 | |
| 507 | if (char === "/" && next === "/") { |
| 508 | break; |
| 509 | } |
| 510 | if (char === "/" && next === "*") { |
| 511 | state.inBlockComment = true; |
| 512 | index += 1; |
| 513 | continue; |
| 514 | } |
| 515 | if (char === "'" || char === "\"" || char === "`") { |
| 516 | state.stringQuote = char; |
| 517 | continue; |
| 518 | } |
| 519 | if (char === "{") { |
| 520 | state.braceDepth += 1; |
| 521 | } else if (char === "}") { |
| 522 | state.braceDepth = Math.max(0, state.braceDepth - 1); |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | function parseImportSemantics(raw) { |
| 528 | const normalized = collapseWhitespace(raw); |
| 529 | if (!normalized.startsWith("import ")) { |
| 530 | return null; |
| 531 | } |
| 532 | |
| 533 | const sideEffectMatch = normalized.match( |
| 534 | /^import\s+(["'])(.*?)\1(\s+with\s+\{.*\})?\s*;?$/, |
| 535 | ); |
| 536 | if (sideEffectMatch) { |
| 537 | return { |
| 538 | kind: "side-effect", |
| 539 | source: sideEffectMatch[2], |
| 540 | quote: sideEffectMatch[1], |
| 541 | attributes: sideEffectMatch[3] ?? "", |
| 542 | key: `side:${sideEffectMatch[2]}:${sideEffectMatch[3] ?? ""}`, |
| 543 | }; |
| 544 | } |
| 545 | |
| 546 | const bindingMatch = normalized.match( |
| 547 | /^import\s+(type\s+)?(.+?)\s+from\s+(["'])(.*?)\3(\s+with\s+\{.*\})?\s*;?$/, |
| 548 | ); |
| 549 | if (!bindingMatch) { |
| 550 | return null; |
| 551 | } |
| 552 | |
| 553 | const parsed = parseBindingSpec(bindingMatch[2].trim()); |
| 554 | if (!parsed) { |
| 555 | return null; |
| 556 | } |
| 557 | |
| 558 | const named = parsed.namedSpecifiers.join(","); |
| 559 | return { |
| 560 | kind: "binding", |
| 561 | isTypeImport: !!bindingMatch[1], |
| 562 | defaultBinding: parsed.defaultBinding, |
| 563 | namespaceImport: parsed.namespaceImport, |
| 564 | namedSpecifiers: parsed.namedSpecifiers, |
| 565 | source: bindingMatch[4], |
| 566 | quote: bindingMatch[3], |
| 567 | attributes: bindingMatch[5] ?? "", |
| 568 | key: [ |
| 569 | "binding", |
| 570 | bindingMatch[1] ? "type" : "value", |
| 571 | parsed.defaultBinding ?? "", |
| 572 | parsed.namespaceImport ?? "", |
| 573 | named, |
| 574 | bindingMatch[4], |
| 575 | bindingMatch[5] ?? "", |
| 576 | ].join(":"), |
| 577 | }; |
| 578 | } |
| 579 | |
| 580 | function parseBindingSpec(specPart) { |
| 581 | let defaultBinding = null; |
| 582 | let namespaceImport = null; |
| 583 | let namedSpecifiers = []; |
| 584 | |
| 585 | const braceStart = specPart.indexOf("{"); |
| 586 | const braceEnd = specPart.lastIndexOf("}"); |
| 587 | if (braceStart !== -1 || braceEnd !== -1) { |
| 588 | if (braceStart === -1 || braceEnd === -1 || braceEnd < braceStart) { |
| 589 | return null; |
| 590 | } |
| 591 | |
| 592 | const beforeBrace = specPart |
| 593 | .slice(0, braceStart) |
| 594 | .trim() |
| 595 | .replace(/,\s*$/, "") |
| 596 | .trim(); |
| 597 | const afterBrace = specPart.slice(braceEnd + 1).trim(); |
| 598 | if (afterBrace !== "") { |
| 599 | return null; |
| 600 | } |
| 601 | |
| 602 | const head = parseBindingHead(beforeBrace); |
| 603 | if (!head) { |
| 604 | return null; |
| 605 | } |
| 606 | defaultBinding = head.defaultBinding; |
| 607 | namespaceImport = head.namespaceImport; |
| 608 | namedSpecifiers = splitCommaList(specPart.slice(braceStart + 1, braceEnd)); |
| 609 | } else { |
| 610 | const head = parseBindingHead(specPart); |
| 611 | if (!head) { |
| 612 | return null; |
| 613 | } |
| 614 | defaultBinding = head.defaultBinding; |
| 615 | namespaceImport = head.namespaceImport; |
| 616 | } |
| 617 | |
| 618 | return { |
| 619 | defaultBinding, |
| 620 | namespaceImport, |
| 621 | namedSpecifiers, |
| 622 | }; |
| 623 | } |
| 624 | |
| 625 | function parseBindingHead(head) { |
| 626 | if (head === "") { |
| 627 | return { defaultBinding: null, namespaceImport: null }; |
| 628 | } |
| 629 | |
| 630 | if (head.startsWith("* as ")) { |
| 631 | return { defaultBinding: null, namespaceImport: head }; |
| 632 | } |
| 633 | |
| 634 | const parts = head.split(/\s*,\s*/).filter(Boolean); |
| 635 | if (parts.length === 1) { |
| 636 | return { |
| 637 | defaultBinding: parts[0], |
| 638 | namespaceImport: null, |
| 639 | }; |
| 640 | } |
| 641 | |
| 642 | if (parts.length === 2 && parts[1].startsWith("* as ")) { |
| 643 | return { |
| 644 | defaultBinding: parts[0], |
| 645 | namespaceImport: parts[1], |
| 646 | }; |
| 647 | } |
| 648 | |
| 649 | return null; |
| 650 | } |
| 651 | |
| 652 | function splitCommaList(text) { |
| 653 | return text |
| 654 | .split(",") |
| 655 | .map((part) => collapseWhitespace(part)) |
| 656 | .filter(Boolean); |
| 657 | } |
| 658 | |
| 659 | function mergeImportStatements(leftStatements, rightStatements, newline) { |
| 660 | const merged = []; |
| 661 | |
| 662 | for (const statement of [...leftStatements, ...rightStatements]) { |
| 663 | const analysis = parseImportSemantics(statement); |
| 664 | if (!analysis) { |
| 665 | const key = `raw:${collapseWhitespace(statement)}`; |
| 666 | if (!merged.some((entry) => entry.key === key)) { |
| 667 | merged.push({ |
| 668 | key, |
| 669 | raw: ensureTrailingNewline(statement.trim(), newline), |
| 670 | analysis: null, |
| 671 | }); |
| 672 | } |
| 673 | continue; |
| 674 | } |
| 675 | |
| 676 | const exactIndex = merged.findIndex((entry) => entry.key === analysis.key); |
| 677 | if (exactIndex !== -1) { |
| 678 | continue; |
| 679 | } |
| 680 | |
| 681 | const mergeIndex = merged.findIndex( |
| 682 | (entry) => entry.analysis && canMergeImports(entry.analysis, analysis), |
| 683 | ); |
| 684 | if (mergeIndex !== -1) { |
| 685 | const nextAnalysis = mergeImports(merged[mergeIndex].analysis, analysis); |
| 686 | merged[mergeIndex] = { |
| 687 | key: nextAnalysis.key, |
| 688 | raw: renderImport(nextAnalysis, newline), |
| 689 | analysis: nextAnalysis, |
| 690 | }; |
| 691 | continue; |
| 692 | } |
| 693 | |
| 694 | merged.push({ |
| 695 | key: analysis.key, |
| 696 | raw: renderImport(analysis, newline), |
| 697 | analysis, |
| 698 | }); |
| 699 | } |
| 700 | |
| 701 | return merged |
| 702 | .map((entry) => entry.raw.trimEnd()) |
| 703 | .join(newline) + newline; |
| 704 | } |
| 705 | |
| 706 | function canMergeImports(left, right) { |
| 707 | if (left.kind !== "binding" || right.kind !== "binding") { |
| 708 | return false; |
| 709 | } |
| 710 | if ( |
| 711 | left.source !== right.source || |
| 712 | left.attributes !== right.attributes || |
| 713 | left.isTypeImport !== right.isTypeImport |
| 714 | ) { |
| 715 | return false; |
| 716 | } |
| 717 | |
| 718 | const defaultBinding = mergeField(left.defaultBinding, right.defaultBinding); |
| 719 | const namespaceImport = mergeField(left.namespaceImport, right.namespaceImport); |
| 720 | if (defaultBinding === undefined || namespaceImport === undefined) { |
| 721 | return false; |
| 722 | } |
| 723 | |
| 724 | const namedSpecifiers = unique([...left.namedSpecifiers, ...right.namedSpecifiers]); |
| 725 | if (namespaceImport && namedSpecifiers.length > 0) { |
| 726 | return false; |
| 727 | } |
| 728 | |
| 729 | return true; |
| 730 | } |
| 731 | |
| 732 | function mergeImports(left, right) { |
| 733 | const defaultBinding = mergeField(left.defaultBinding, right.defaultBinding); |
| 734 | const namespaceImport = mergeField(left.namespaceImport, right.namespaceImport); |
| 735 | const namedSpecifiers = unique([...left.namedSpecifiers, ...right.namedSpecifiers]); |
| 736 | |
| 737 | return { |
| 738 | kind: "binding", |
| 739 | isTypeImport: left.isTypeImport, |
| 740 | defaultBinding, |
| 741 | namespaceImport, |
| 742 | namedSpecifiers, |
| 743 | source: left.source, |
| 744 | quote: left.quote, |
| 745 | attributes: left.attributes, |
| 746 | key: [ |
| 747 | "binding", |
| 748 | left.isTypeImport ? "type" : "value", |
| 749 | defaultBinding ?? "", |
| 750 | namespaceImport ?? "", |
| 751 | namedSpecifiers.join(","), |
| 752 | left.source, |
| 753 | left.attributes, |
| 754 | ].join(":"), |
| 755 | }; |
| 756 | } |
| 757 | |
| 758 | function mergeField(left, right) { |
| 759 | if (left == null) return right ?? null; |
| 760 | if (right == null) return left; |
| 761 | if (left === right) return left; |
| 762 | return undefined; |
| 763 | } |
| 764 | |
| 765 | function renderImport(analysis, newline) { |
| 766 | if (analysis.kind === "side-effect") { |
| 767 | return ensureTrailingNewline( |
| 768 | `import ${analysis.quote}${analysis.source}${analysis.quote}${analysis.attributes};`, |
| 769 | newline, |
| 770 | ); |
| 771 | } |
| 772 | |
| 773 | const pieces = []; |
| 774 | if (analysis.defaultBinding) { |
| 775 | pieces.push(analysis.defaultBinding); |
| 776 | } |
| 777 | if (analysis.namespaceImport) { |
| 778 | pieces.push(analysis.namespaceImport); |
| 779 | } |
| 780 | if (analysis.namedSpecifiers.length > 0) { |
| 781 | if (analysis.namedSpecifiers.length === 1) { |
| 782 | pieces.push(`{ ${analysis.namedSpecifiers[0]} }`); |
| 783 | } else { |
| 784 | pieces.push( |
| 785 | `{${newline}${analysis.namedSpecifiers.map((spec) => ` ${spec},`).join(newline)}${newline}}`, |
| 786 | ); |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | return ensureTrailingNewline( |
| 791 | `import ${analysis.isTypeImport ? "type " : ""}${pieces.join(", ")} from ${analysis.quote}${analysis.source}${analysis.quote}${analysis.attributes};`, |
| 792 | newline, |
| 793 | ); |
| 794 | } |
| 795 | |
| 796 | function projectBoundaryToOriginal(parts, targetA, targetB) { |
| 797 | let offsetA = 0; |
| 798 | let offsetB = 0; |
| 799 | let offsetOrig = 0; |
| 800 | |
| 801 | if (targetA === 0 && targetB === 0) { |
| 802 | return 0; |
| 803 | } |
| 804 | |
| 805 | for (const part of parts) { |
| 806 | if (targetA === offsetA && targetB === offsetB) { |
| 807 | return offsetOrig; |
| 808 | } |
| 809 | |
| 810 | const nextA = offsetA + part.a.length; |
| 811 | const nextB = offsetB + part.b.length; |
| 812 | const nextOrig = offsetOrig + part.orig.length; |
| 813 | |
| 814 | if (part.type === "plain") { |
| 815 | if ( |
| 816 | targetA >= offsetA && |
| 817 | targetA <= nextA && |
| 818 | targetB >= offsetB && |
| 819 | targetB <= nextB |
| 820 | ) { |
| 821 | const deltaA = targetA - offsetA; |
| 822 | const deltaB = targetB - offsetB; |
| 823 | if (deltaA !== deltaB) { |
| 824 | return null; |
| 825 | } |
| 826 | return offsetOrig + deltaA; |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | if (targetA === nextA && targetB === nextB) { |
| 831 | return nextOrig; |
| 832 | } |
| 833 | |
| 834 | offsetA = nextA; |
| 835 | offsetB = nextB; |
| 836 | offsetOrig = nextOrig; |
| 837 | } |
| 838 | |
| 839 | if (targetA === offsetA && targetB === offsetB) { |
| 840 | return offsetOrig; |
| 841 | } |
| 842 | |
| 843 | return null; |
| 844 | } |
| 845 | |
| 846 | function hasConflictMarkers(text) { |
| 847 | return CONFLICT_START_RE.test(text) || CONFLICT_END_RE.test(text); |
| 848 | } |
| 849 | |
| 850 | function detectNewline(text) { |
| 851 | return text.includes("\r\n") ? "\r\n" : "\n"; |
| 852 | } |
| 853 | |
| 854 | function ensureTrailingNewline(text, newline) { |
| 855 | return text.endsWith(newline) ? text : `${text}${newline}`; |
| 856 | } |
| 857 | |
| 858 | function offsetForLine(lines, lineIndex) { |
| 859 | if (lineIndex >= lines.length) { |
| 860 | return lines.length === 0 ? 0 : lines[lines.length - 1].end; |
| 861 | } |
| 862 | return lines[lineIndex].start; |
| 863 | } |
| 864 | |
| 865 | function collapseWhitespace(text) { |
| 866 | return text.replace(/\s+/g, " ").trim(); |
| 867 | } |
| 868 | |
| 869 | function unique(values) { |
| 870 | return [...new Set(values)]; |
| 871 | } |