@pierre/diffs 1.3.0-beta.9 → 1.3.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/components/CodeView.d.ts +12 -13
- package/dist/components/CodeView.d.ts.map +1 -1
- package/dist/components/CodeView.js +50 -58
- package/dist/components/CodeView.js.map +1 -1
- package/dist/components/File.d.ts +10 -3
- package/dist/components/File.d.ts.map +1 -1
- package/dist/components/File.js +41 -10
- package/dist/components/File.js.map +1 -1
- package/dist/components/FileDiff.d.ts +37 -6
- package/dist/components/FileDiff.d.ts.map +1 -1
- package/dist/components/FileDiff.js +202 -19
- package/dist/components/FileDiff.js.map +1 -1
- package/dist/components/UnresolvedFile.d.ts.map +1 -1
- package/dist/components/UnresolvedFile.js +7 -2
- package/dist/components/UnresolvedFile.js.map +1 -1
- package/dist/components/VirtualizedFile.d.ts +2 -1
- package/dist/components/VirtualizedFile.d.ts.map +1 -1
- package/dist/components/VirtualizedFile.js +9 -5
- package/dist/components/VirtualizedFile.js.map +1 -1
- package/dist/components/VirtualizedFileDiff.d.ts +14 -0
- package/dist/components/VirtualizedFileDiff.d.ts.map +1 -1
- package/dist/components/VirtualizedFileDiff.js +61 -3
- package/dist/components/VirtualizedFileDiff.js.map +1 -1
- package/dist/components/Virtualizer.d.ts +14 -2
- package/dist/components/Virtualizer.d.ts.map +1 -1
- package/dist/components/Virtualizer.js +27 -2
- package/dist/components/Virtualizer.js.map +1 -1
- package/dist/edit/index.d.ts +5 -0
- package/dist/edit/index.js +3 -0
- package/dist/editor/command.d.ts +1 -1
- package/dist/editor/command.d.ts.map +1 -1
- package/dist/editor/command.js +11 -0
- package/dist/editor/command.js.map +1 -1
- package/dist/editor/editStack.d.ts +6 -2
- package/dist/editor/editStack.d.ts.map +1 -1
- package/dist/editor/editStack.js +53 -12
- package/dist/editor/editStack.js.map +1 -1
- package/dist/editor/editor.d.ts +51 -23
- package/dist/editor/editor.d.ts.map +1 -1
- package/dist/editor/editor.js +977 -241
- package/dist/editor/editor.js.map +1 -1
- package/dist/editor/editor2.js +1 -1
- package/dist/editor/languages.d.ts +26 -0
- package/dist/editor/languages.d.ts.map +1 -0
- package/dist/editor/languages.js +363 -0
- package/dist/editor/languages.js.map +1 -0
- package/dist/editor/lineAnnotations.d.ts.map +1 -1
- package/dist/editor/lineAnnotations.js +25 -26
- package/dist/editor/lineAnnotations.js.map +1 -1
- package/dist/editor/marker.d.ts +5 -3
- package/dist/editor/marker.d.ts.map +1 -1
- package/dist/editor/marker.js +111 -91
- package/dist/editor/marker.js.map +1 -1
- package/dist/editor/matchBrackets.d.ts +3 -2
- package/dist/editor/matchBrackets.d.ts.map +1 -1
- package/dist/editor/matchBrackets.js +2 -10
- package/dist/editor/matchBrackets.js.map +1 -1
- package/dist/editor/pieceTable.d.ts +2 -1
- package/dist/editor/pieceTable.d.ts.map +1 -1
- package/dist/editor/pieceTable.js +103 -39
- package/dist/editor/pieceTable.js.map +1 -1
- package/dist/editor/platform.js +2 -0
- package/dist/editor/platform.js.map +1 -1
- package/dist/editor/popover.d.ts +25 -5
- package/dist/editor/popover.d.ts.map +1 -1
- package/dist/editor/popover.js +60 -14
- package/dist/editor/popover.js.map +1 -1
- package/dist/editor/searchPanel.d.ts.map +1 -1
- package/dist/editor/searchPanel.js +9 -2
- package/dist/editor/searchPanel.js.map +1 -1
- package/dist/editor/selection.d.ts +31 -11
- package/dist/editor/selection.d.ts.map +1 -1
- package/dist/editor/selection.js +198 -70
- package/dist/editor/selection.js.map +1 -1
- package/dist/editor/selectionAction.d.ts +4 -3
- package/dist/editor/selectionAction.d.ts.map +1 -1
- package/dist/editor/selectionAction.js +9 -5
- package/dist/editor/selectionAction.js.map +1 -1
- package/dist/editor/stateStorage.d.ts +15 -0
- package/dist/editor/stateStorage.d.ts.map +1 -0
- package/dist/editor/stateStorage.js +65 -0
- package/dist/editor/stateStorage.js.map +1 -0
- package/dist/editor/textDocument.d.ts +12 -77
- package/dist/editor/textDocument.d.ts.map +1 -1
- package/dist/editor/textDocument.js +76 -34
- package/dist/editor/textDocument.js.map +1 -1
- package/dist/editor/textMeasure.d.ts +7 -12
- package/dist/editor/textMeasure.d.ts.map +1 -1
- package/dist/editor/textMeasure.js +40 -32
- package/dist/editor/textMeasure.js.map +1 -1
- package/dist/editor/{tokenzier.d.ts → tokenizer.d.ts} +3 -3
- package/dist/editor/tokenizer.d.ts.map +1 -0
- package/dist/editor/{tokenzier.js → tokenizer.js} +170 -50
- package/dist/editor/tokenizer.js.map +1 -0
- package/dist/editor/utils.js +1 -1
- package/dist/editor/utils.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +6 -5
- package/dist/managers/InteractionManager.d.ts +18 -7
- package/dist/managers/InteractionManager.d.ts.map +1 -1
- package/dist/managers/InteractionManager.js +154 -99
- package/dist/managers/InteractionManager.js.map +1 -1
- package/dist/managers/UniversalRenderingManager.d.ts.map +1 -1
- package/dist/managers/UniversalRenderingManager.js +1 -2
- package/dist/managers/UniversalRenderingManager.js.map +1 -1
- package/dist/react/CodeView.d.ts +13 -13
- package/dist/react/CodeView.d.ts.map +1 -1
- package/dist/react/CodeView.js +37 -28
- package/dist/react/CodeView.js.map +1 -1
- package/dist/react/EditContext.d.ts +20 -0
- package/dist/react/EditContext.d.ts.map +1 -0
- package/dist/react/EditContext.js +20 -0
- package/dist/react/EditContext.js.map +1 -0
- package/dist/react/File.d.ts +2 -1
- package/dist/react/File.d.ts.map +1 -1
- package/dist/react/File.js +3 -2
- package/dist/react/File.js.map +1 -1
- package/dist/react/FileDiff.d.ts +2 -2
- package/dist/react/FileDiff.d.ts.map +1 -1
- package/dist/react/FileDiff.js +3 -2
- package/dist/react/FileDiff.js.map +1 -1
- package/dist/react/MultiFileDiff.d.ts +2 -2
- package/dist/react/MultiFileDiff.d.ts.map +1 -1
- package/dist/react/MultiFileDiff.js +3 -2
- package/dist/react/MultiFileDiff.js.map +1 -1
- package/dist/react/PatchDiff.d.ts +2 -2
- package/dist/react/PatchDiff.d.ts.map +1 -1
- package/dist/react/PatchDiff.js +3 -2
- package/dist/react/PatchDiff.js.map +1 -1
- package/dist/react/UnresolvedFile.d.ts +1 -1
- package/dist/react/UnresolvedFile.js.map +1 -1
- package/dist/react/index.d.ts +4 -4
- package/dist/react/index.js +3 -3
- package/dist/react/types.d.ts +9 -1
- package/dist/react/types.d.ts.map +1 -1
- package/dist/react/utils/useFileDiffInstance.d.ts +5 -3
- package/dist/react/utils/useFileDiffInstance.d.ts.map +1 -1
- package/dist/react/utils/useFileDiffInstance.js +24 -34
- package/dist/react/utils/useFileDiffInstance.js.map +1 -1
- package/dist/react/utils/useFileInstance.d.ts +5 -3
- package/dist/react/utils/useFileInstance.d.ts.map +1 -1
- package/dist/react/utils/useFileInstance.js +23 -33
- package/dist/react/utils/useFileInstance.js.map +1 -1
- package/dist/react/utils/useUnresolvedFileInstance.js +4 -4
- package/dist/react/utils/useUnresolvedFileInstance.js.map +1 -1
- package/dist/renderers/DiffHunksRenderer.d.ts +41 -1
- package/dist/renderers/DiffHunksRenderer.d.ts.map +1 -1
- package/dist/renderers/DiffHunksRenderer.js +167 -29
- package/dist/renderers/DiffHunksRenderer.js.map +1 -1
- package/dist/renderers/FileRenderer.d.ts +20 -1
- package/dist/renderers/FileRenderer.d.ts.map +1 -1
- package/dist/renderers/FileRenderer.js +119 -29
- package/dist/renderers/FileRenderer.js.map +1 -1
- package/dist/ssr/index.d.ts +2 -2
- package/dist/ssr/preloadDiffs.d.ts.map +1 -1
- package/dist/ssr/preloadDiffs.js +3 -1
- package/dist/ssr/preloadDiffs.js.map +1 -1
- package/dist/ssr/preloadFile.d.ts.map +1 -1
- package/dist/ssr/preloadFile.js +2 -0
- package/dist/ssr/preloadFile.js.map +1 -1
- package/dist/style.js +1 -1
- package/dist/types.d.ts +192 -42
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/annotationHelpers.d.ts +20 -0
- package/dist/utils/annotationHelpers.d.ts.map +1 -0
- package/dist/utils/annotationHelpers.js +29 -0
- package/dist/utils/annotationHelpers.js.map +1 -0
- package/dist/utils/computeFileOffsets.d.ts.map +1 -1
- package/dist/utils/computeFileOffsets.js +34 -5
- package/dist/utils/computeFileOffsets.js.map +1 -1
- package/dist/utils/editSessionHunks.d.ts +66 -0
- package/dist/utils/editSessionHunks.d.ts.map +1 -0
- package/dist/utils/editSessionHunks.js +437 -0
- package/dist/utils/editSessionHunks.js.map +1 -0
- package/dist/utils/getDiffHunksRendererOptions.d.ts.map +1 -1
- package/dist/utils/getDiffHunksRendererOptions.js +2 -1
- package/dist/utils/getDiffHunksRendererOptions.js.map +1 -1
- package/dist/utils/getFileRendererOptions.d.ts.map +1 -1
- package/dist/utils/getFileRendererOptions.js +2 -1
- package/dist/utils/getFileRendererOptions.js.map +1 -1
- package/dist/utils/getHunkSideBoundaries.d.ts +7 -0
- package/dist/utils/getHunkSideBoundaries.d.ts.map +1 -0
- package/dist/utils/getHunkSideBoundaries.js +12 -0
- package/dist/utils/getHunkSideBoundaries.js.map +1 -0
- package/dist/utils/getTotalLineCountFromHunks.d.ts.map +1 -1
- package/dist/utils/getTotalLineCountFromHunks.js +2 -1
- package/dist/utils/getTotalLineCountFromHunks.js.map +1 -1
- package/dist/utils/hydratePartialDiff.d.ts.map +1 -1
- package/dist/utils/hydratePartialDiff.js +4 -3
- package/dist/utils/hydratePartialDiff.js.map +1 -1
- package/dist/utils/isGutterUtilityPath.d.ts +5 -0
- package/dist/utils/isGutterUtilityPath.d.ts.map +1 -0
- package/dist/utils/isGutterUtilityPath.js +12 -0
- package/dist/utils/isGutterUtilityPath.js.map +1 -0
- package/dist/utils/iterateOverDiff.d.ts.map +1 -1
- package/dist/utils/iterateOverDiff.js +17 -12
- package/dist/utils/iterateOverDiff.js.map +1 -1
- package/dist/utils/parseMergeConflictDiffFromFile.d.ts.map +1 -1
- package/dist/utils/parseMergeConflictDiffFromFile.js +9 -6
- package/dist/utils/parseMergeConflictDiffFromFile.js.map +1 -1
- package/dist/utils/parsePatchFiles.d.ts.map +1 -1
- package/dist/utils/parsePatchFiles.js +6 -3
- package/dist/utils/parsePatchFiles.js.map +1 -1
- package/dist/utils/realignChangeContent.d.ts +33 -0
- package/dist/utils/realignChangeContent.d.ts.map +1 -0
- package/dist/utils/realignChangeContent.js +148 -0
- package/dist/utils/realignChangeContent.js.map +1 -0
- package/dist/utils/renderDiffWithHighlighter.js +1 -1
- package/dist/utils/resolveRegion.d.ts.map +1 -1
- package/dist/utils/resolveRegion.js +18 -2
- package/dist/utils/resolveRegion.js.map +1 -1
- package/dist/utils/shouldUseTokenTransformer.d.ts +7 -3
- package/dist/utils/shouldUseTokenTransformer.d.ts.map +1 -1
- package/dist/utils/shouldUseTokenTransformer.js +1 -1
- package/dist/utils/shouldUseTokenTransformer.js.map +1 -1
- package/dist/utils/updateDiffHunks.d.ts +8 -2
- package/dist/utils/updateDiffHunks.d.ts.map +1 -1
- package/dist/utils/updateDiffHunks.js +9 -7
- package/dist/utils/updateDiffHunks.js.map +1 -1
- package/dist/utils/virtualDiffLayout.d.ts +42 -2
- package/dist/utils/virtualDiffLayout.d.ts.map +1 -1
- package/dist/utils/virtualDiffLayout.js +101 -7
- package/dist/utils/virtualDiffLayout.js.map +1 -1
- package/dist/worker/WorkerPoolManager.d.ts +2 -1
- package/dist/worker/WorkerPoolManager.d.ts.map +1 -1
- package/dist/worker/WorkerPoolManager.js +3 -0
- package/dist/worker/WorkerPoolManager.js.map +1 -1
- package/dist/worker/worker-portable.js +60 -20
- package/dist/worker/worker-portable.js.map +1 -1
- package/dist/worker/worker.js +61 -19
- package/dist/worker/worker.js.map +1 -1
- package/package.json +10 -7
- package/dist/editor/index.d.ts +0 -3
- package/dist/editor/index.js +0 -3
- package/dist/editor/tokenzier.d.ts.map +0 -1
- package/dist/editor/tokenzier.js.map +0 -1
- package/dist/react/EditorContext.d.ts +0 -15
- package/dist/react/EditorContext.d.ts.map +0 -1
- package/dist/react/EditorContext.js +0 -23
- package/dist/react/EditorContext.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parsePatchFiles.js","names":[],"sources":["../../src/utils/parsePatchFiles.ts"],"sourcesContent":["import {\n ALTERNATE_FILE_NAMES_GIT,\n COMMIT_METADATA_SPLIT,\n FILENAME_HEADER_REGEX,\n FILENAME_HEADER_REGEX_GIT,\n GIT_DIFF_FILE_BREAK_REGEX,\n INDEX_LINE_METADATA,\n} from '../constants';\nimport type {\n ChangeContent,\n ContextContent,\n FileContents,\n FileDiffMetadata,\n Hunk,\n HunkLineType,\n ParsedPatch,\n} from '../types';\nimport { cleanLastNewline } from './cleanLastNewline';\nimport { detachString, releaseStringDetachBuffer } from './detachString';\n\ninterface ParsedHunkHeader {\n additionCount: number;\n additionStart: number;\n deletionCount: number;\n deletionStart: number;\n hunkContext?: string;\n}\n\nexport function processPatch(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError?: boolean\n): ParsedPatch {\n try {\n return _processPatch(data, cacheKeyPrefix, throwOnError);\n } finally {\n releaseStringDetachBuffer();\n }\n}\n\nfunction _processPatch(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError = false\n): ParsedPatch {\n const isGitDiff = isGitDiffPatch(data);\n const rawFiles = isGitDiff\n ? splitGitDiffFiles(data)\n : splitUnifiedDiffFiles(data);\n let patchMetadata: string | undefined;\n const files: FileDiffMetadata[] = [];\n for (const fileOrPatchMetadata of rawFiles) {\n if (isGitDiff && !GIT_DIFF_FILE_BREAK_REGEX.test(fileOrPatchMetadata)) {\n if (patchMetadata == null) {\n patchMetadata = detachString(fileOrPatchMetadata);\n } else {\n if (throwOnError) {\n throw Error('parsePatchContent: unknown file blob');\n } else {\n console.error(\n 'parsePatchContent: unknown file blob:',\n fileOrPatchMetadata\n );\n }\n }\n // If we get in here, it's most likely the introductory metadata from the\n // patch, or something is fucked with the diff format\n continue;\n } else if (\n !isGitDiff &&\n !startsWithUnifiedDiffFileHeader(fileOrPatchMetadata)\n ) {\n if (patchMetadata == null) {\n patchMetadata = detachString(fileOrPatchMetadata);\n } else {\n if (throwOnError) {\n throw Error('parsePatchContent: unknown file blob');\n } else {\n console.error(\n 'parsePatchContent: unknown file blob:',\n fileOrPatchMetadata\n );\n }\n }\n continue;\n }\n const currentFile = _processFile(fileOrPatchMetadata, {\n cacheKey:\n cacheKeyPrefix != null\n ? `${cacheKeyPrefix}-${files.length}`\n : undefined,\n isGitDiff,\n throwOnError,\n });\n if (currentFile != null) {\n files.push(currentFile);\n }\n }\n return { patchMetadata, files };\n}\n\ninterface ProcessFileOptions {\n cacheKey?: string;\n isGitDiff?: boolean;\n oldFile?: FileContents;\n newFile?: FileContents;\n throwOnError?: boolean;\n}\n\nexport function processFile(\n fileDiffString: string,\n options?: ProcessFileOptions\n): FileDiffMetadata | undefined {\n try {\n return _processFile(fileDiffString, options);\n } finally {\n releaseStringDetachBuffer();\n }\n}\n\nfunction _processFile(\n fileDiffString: string,\n {\n cacheKey,\n isGitDiff = GIT_DIFF_FILE_BREAK_REGEX.test(fileDiffString),\n oldFile,\n newFile,\n throwOnError = false,\n }: ProcessFileOptions = {}\n): FileDiffMetadata | undefined {\n let lastHunkEnd = 0;\n const hunks = splitAtLinePrefix(fileDiffString, '@@ ');\n let currentFile: FileDiffMetadata | undefined;\n const isPartial = oldFile == null || newFile == null;\n let deletionLineIndex = 0;\n let additionLineIndex = 0;\n for (const hunk of hunks) {\n const lines = splitWithNewlines(hunk);\n const firstLine = lines[0];\n if (firstLine == null) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid hunk');\n } else {\n console.error('parsePatchContent: invalid hunk', hunk);\n }\n continue;\n }\n const fileHeader = parseHunkHeader(firstLine);\n let additionLines = 0;\n let deletionLines = 0;\n // Setup currentFile, this should be the first iteration of our hunks, and\n // technically not a hunk\n if (fileHeader == null || currentFile == null) {\n if (currentFile != null) {\n if (throwOnError) {\n throw Error('parsePatchContent: Invalid hunk');\n } else {\n console.error('parsePatchContent: Invalid hunk', hunk);\n }\n continue;\n }\n currentFile = {\n name: '',\n type: 'change',\n hunks: [],\n splitLineCount: 0,\n unifiedLineCount: 0,\n isPartial,\n additionLines:\n !isPartial && oldFile != null && newFile != null\n ? splitFileContents(newFile.contents)\n : [],\n deletionLines:\n !isPartial && oldFile != null && newFile != null\n ? splitFileContents(oldFile.contents)\n : [],\n cacheKey: maybeDetachOptionalString(cacheKey),\n };\n // If either file is technically empty, then we should empty the\n // arrays respectively\n if (currentFile.additionLines.length === 1 && newFile?.contents === '') {\n currentFile.additionLines.length = 0;\n }\n if (currentFile.deletionLines.length === 1 && oldFile?.contents === '') {\n currentFile.deletionLines.length = 0;\n }\n\n for (const line of lines) {\n if (line.startsWith('diff --git')) {\n const filenameMatch = line.trim().match(ALTERNATE_FILE_NAMES_GIT);\n const prevName = filenameMatch?.[1] ?? filenameMatch?.[2];\n const name = filenameMatch?.[3] ?? filenameMatch?.[4];\n if (prevName == null || name == null) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid git diff header');\n } else {\n console.error('parsePatchContent: invalid git diff header', line);\n }\n continue;\n }\n currentFile.name = detachString(name.trim());\n if (prevName !== name) {\n currentFile.prevName = detachString(prevName.trim());\n }\n continue;\n }\n\n const filenameMatch =\n line.startsWith('---') || line.startsWith('+++')\n ? line.match(\n isGitDiff ? FILENAME_HEADER_REGEX_GIT : FILENAME_HEADER_REGEX\n )\n : null;\n if (filenameMatch != null) {\n const [, type, fileName] = filenameMatch;\n if (type === '---' && fileName !== '/dev/null') {\n const detachedFileName = detachString(fileName.trim());\n currentFile.prevName = detachedFileName;\n currentFile.name = detachedFileName;\n } else if (type === '+++' && fileName !== '/dev/null') {\n currentFile.name = detachString(fileName.trim());\n }\n }\n // Git diffs have a bunch of additional metadata we can pull from\n else if (isGitDiff) {\n if (line.startsWith('new mode ')) {\n currentFile.mode = detachString(\n line.slice('new mode'.length).trim()\n );\n }\n if (line.startsWith('old mode ')) {\n currentFile.prevMode = detachString(\n line.slice('old mode'.length).trim()\n );\n }\n if (line.startsWith('new file mode')) {\n currentFile.type = 'new';\n currentFile.mode = detachString(\n line.slice('new file mode'.length).trim()\n );\n }\n if (line.startsWith('deleted file mode')) {\n currentFile.type = 'deleted';\n currentFile.mode = detachString(\n line.slice('deleted file mode'.length).trim()\n );\n }\n if (line.startsWith('similarity index')) {\n if (line.startsWith('similarity index 100%')) {\n currentFile.type = 'rename-pure';\n } else {\n currentFile.type = 'rename-changed';\n }\n }\n if (line.startsWith('index ')) {\n const [, prevObjectId, newObjectId, mode] =\n line.trim().match(INDEX_LINE_METADATA) ?? [];\n if (prevObjectId != null) {\n currentFile.prevObjectId = detachString(prevObjectId);\n }\n if (newObjectId != null) {\n currentFile.newObjectId = detachString(newObjectId);\n }\n if (mode != null) {\n currentFile.mode = detachString(mode);\n }\n }\n // We have to handle these for pure renames because there won't be\n // --- and +++ lines\n if (line.startsWith('rename from ')) {\n currentFile.prevName = detachString(\n line.slice('rename from '.length).trim()\n );\n }\n if (line.startsWith('rename to ')) {\n currentFile.name = detachString(\n line.slice('rename to '.length).trim()\n );\n }\n }\n }\n continue;\n }\n\n // Otherwise, time to start parsing out the hunk\n let currentContent: ContextContent | ChangeContent | undefined;\n let lastLineType: 'context' | 'addition' | 'deletion' | undefined;\n\n // Strip trailing bare newlines (format-patch separators between commits)\n // if needed\n while (\n lines.length > 0 &&\n (lines[lines.length - 1] === '\\n' ||\n lines[lines.length - 1] === '\\r' ||\n lines[lines.length - 1] === '\\r\\n' ||\n lines[lines.length - 1] === '')\n ) {\n lines.pop();\n }\n\n const { additionStart, deletionStart } = fileHeader;\n deletionLineIndex = isPartial ? deletionLineIndex : deletionStart - 1;\n additionLineIndex = isPartial ? additionLineIndex : additionStart - 1;\n\n const hunkData: Hunk = {\n collapsedBefore: 0,\n\n splitLineCount: 0,\n splitLineStart: 0,\n\n unifiedLineCount: 0,\n unifiedLineStart: 0,\n\n additionCount: fileHeader.additionCount,\n additionStart,\n additionLines,\n\n deletionCount: fileHeader.deletionCount,\n deletionStart,\n deletionLines,\n\n deletionLineIndex,\n additionLineIndex,\n\n hunkContent: [],\n hunkContext: maybeDetachOptionalString(fileHeader.hunkContext),\n hunkSpecs: detachString(firstLine),\n\n noEOFCRAdditions: false,\n noEOFCRDeletions: false,\n };\n\n // Now we process each line of the hunk\n let parsedAdditionLines = 0;\n let parsedDeletionLines = 0;\n for (let lineIndex = 1; lineIndex < lines.length; lineIndex++) {\n const rawLine = lines[lineIndex];\n if (\n parsedAdditionLines >= hunkData.additionCount &&\n parsedDeletionLines >= hunkData.deletionCount &&\n !rawLine.startsWith('\\\\')\n ) {\n if (\n throwOnError &&\n isHunkBodyLine(rawLine) &&\n !isFormatPatchVersionSeparator(rawLine)\n ) {\n throw Error('parsePatchContent: hunk has more lines than expected');\n }\n break;\n }\n\n const firstChar = rawLine[0];\n // If we can't properly process the line, well, lets just try to salvage\n // things and continue... It's possible an AI generated diff might have\n // some stray blank lines or something in there\n if (\n firstChar !== '+' &&\n firstChar !== '-' &&\n firstChar !== ' ' &&\n firstChar !== '\\\\'\n ) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid hunk line');\n }\n console.error(\n `parseLineType: Invalid firstChar: \"${firstChar}\", full line: \"${rawLine}\"`\n );\n console.error('processFile: invalid rawLine:', rawLine);\n continue;\n }\n\n const type = parseRawLineType(firstChar);\n if (type === 'addition') {\n if (throwOnError && parsedAdditionLines >= hunkData.additionCount) {\n throw Error('parsePatchContent: hunk has too many addition lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'change') {\n currentContent = createContentGroup(\n 'change',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n additionLineIndex++;\n parsedAdditionLines++;\n if (isPartial) {\n currentFile.additionLines.push(line);\n }\n currentContent.additions++;\n additionLines++;\n lastLineType = 'addition';\n } else if (type === 'deletion') {\n if (throwOnError && parsedDeletionLines >= hunkData.deletionCount) {\n throw Error('parsePatchContent: hunk has too many deletion lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'change') {\n currentContent = createContentGroup(\n 'change',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n deletionLineIndex++;\n parsedDeletionLines++;\n if (isPartial) {\n currentFile.deletionLines.push(line);\n }\n currentContent.deletions++;\n deletionLines++;\n lastLineType = 'deletion';\n } else if (type === 'context') {\n if (\n throwOnError &&\n (parsedDeletionLines >= hunkData.deletionCount ||\n parsedAdditionLines >= hunkData.additionCount)\n ) {\n throw Error('parsePatchContent: hunk has too many context lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'context') {\n currentContent = createContentGroup(\n 'context',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n additionLineIndex++;\n deletionLineIndex++;\n parsedAdditionLines++;\n parsedDeletionLines++;\n if (isPartial) {\n currentFile.deletionLines.push(line);\n currentFile.additionLines.push(line);\n }\n currentContent.lines++;\n lastLineType = 'context';\n } else if (type === 'metadata' && currentContent != null) {\n if (currentContent.type === 'context') {\n hunkData.noEOFCRAdditions = true;\n hunkData.noEOFCRDeletions = true;\n } else if (lastLineType === 'deletion') {\n hunkData.noEOFCRDeletions = true;\n } else if (lastLineType === 'addition') {\n hunkData.noEOFCRAdditions = true;\n }\n // If we're dealing with partial content from a diff, we need to strip\n // newlines manually from the content\n if (\n isPartial &&\n (lastLineType === 'addition' || lastLineType === 'context')\n ) {\n const lastIndex = currentFile.additionLines.length - 1;\n if (lastIndex >= 0) {\n currentFile.additionLines[lastIndex] = cleanLastNewline(\n currentFile.additionLines[lastIndex]\n );\n }\n }\n if (\n isPartial &&\n (lastLineType === 'deletion' || lastLineType === 'context')\n ) {\n const lastIndex = currentFile.deletionLines.length - 1;\n if (lastIndex >= 0) {\n currentFile.deletionLines[lastIndex] = cleanLastNewline(\n currentFile.deletionLines[lastIndex]\n );\n }\n }\n }\n }\n\n if (\n throwOnError &&\n (parsedAdditionLines !== hunkData.additionCount ||\n parsedDeletionLines !== hunkData.deletionCount)\n ) {\n throw Error('parsePatchContent: hunk line count mismatch');\n }\n\n hunkData.additionLines = additionLines;\n hunkData.deletionLines = deletionLines;\n\n hunkData.collapsedBefore = Math.max(\n hunkData.additionStart - 1 - lastHunkEnd,\n 0\n );\n currentFile.hunks.push(hunkData);\n lastHunkEnd = hunkData.additionStart + hunkData.additionCount - 1;\n for (const content of hunkData.hunkContent) {\n if (content.type === 'context') {\n hunkData.splitLineCount += content.lines;\n hunkData.unifiedLineCount += content.lines;\n } else {\n hunkData.splitLineCount += Math.max(\n content.additions,\n content.deletions\n );\n hunkData.unifiedLineCount += content.deletions + content.additions;\n }\n }\n hunkData.splitLineStart =\n currentFile.splitLineCount + hunkData.collapsedBefore;\n hunkData.unifiedLineStart =\n currentFile.unifiedLineCount + hunkData.collapsedBefore;\n\n currentFile.splitLineCount +=\n hunkData.collapsedBefore + hunkData.splitLineCount;\n currentFile.unifiedLineCount +=\n hunkData.collapsedBefore + hunkData.unifiedLineCount;\n }\n if (currentFile == null) {\n return undefined;\n }\n if (\n throwOnError &&\n isPartial &&\n !isGitDiff &&\n currentFile.hunks.length === 0\n ) {\n throw Error('parsePatchContent: unified file has no hunks');\n }\n\n // Account for collapsed lines after the final hunk and increment the\n // split/unified counts properly\n if (\n currentFile.hunks.length > 0 &&\n !isPartial &&\n currentFile.additionLines.length > 0 &&\n currentFile.deletionLines.length > 0\n ) {\n const lastHunk = currentFile.hunks[currentFile.hunks.length - 1];\n const lastHunkEnd = lastHunk.additionStart + lastHunk.additionCount - 1;\n const totalFileLines = currentFile.additionLines.length;\n const collapsedAfter = Math.max(totalFileLines - lastHunkEnd, 0);\n currentFile.splitLineCount += collapsedAfter;\n currentFile.unifiedLineCount += collapsedAfter;\n }\n\n // If this isn't a git diff style patch, then we'll need to sus out some\n // additional metadata manually\n if (!isGitDiff) {\n if (\n currentFile.prevName != null &&\n currentFile.name !== currentFile.prevName\n ) {\n if (currentFile.hunks.length > 0) {\n currentFile.type = 'rename-changed';\n } else {\n currentFile.type = 'rename-pure';\n }\n }\n // Sort of a hack for detecting deleted/added files...\n else if (\n (oldFile == null || oldFile.contents === '') &&\n newFile != null &&\n newFile.contents !== ''\n ) {\n currentFile.type = 'new';\n } else if (\n oldFile != null &&\n oldFile.contents !== '' &&\n (newFile == null || newFile.contents === '')\n ) {\n currentFile.type = 'deleted';\n }\n }\n if (\n currentFile.type !== 'rename-pure' &&\n currentFile.type !== 'rename-changed'\n ) {\n currentFile.prevName = undefined;\n }\n return currentFile;\n}\n\n/**\n * Parses a patch file string into an array of parsed patches.\n *\n * @param data - The raw patch file content (supports multi-commit patches)\n * @param cacheKeyPrefix - Optional prefix for generating cache keys. When provided,\n * each file in the patch will get a cache key in the format `prefix-patchIndex-fileIndex`.\n * This enables caching of rendered diff results in the worker pool.\n */\nexport function parsePatchFiles(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError = false\n): ParsedPatch[] {\n // NOTE(amadeus): This function is pretty forgiving in that it can accept a\n // patch file that includes commit metdata, multiple commits, or not\n const patches: ParsedPatch[] = [];\n const rawPatches = hasCommitMetadataBoundary(data)\n ? data.split(COMMIT_METADATA_SPLIT)\n : [data];\n for (const patch of rawPatches) {\n try {\n patches.push(\n processPatch(\n patch,\n cacheKeyPrefix != null\n ? `${cacheKeyPrefix}-${patches.length}`\n : undefined,\n throwOnError\n )\n );\n } catch (error) {\n if (throwOnError) {\n throw error;\n } else {\n console.error(error);\n }\n }\n }\n return patches;\n}\n\nfunction hasCommitMetadataBoundary(data: string): boolean {\n return data.startsWith('From ') || data.includes('\\nFrom ');\n}\n\nfunction splitFileContents(contents: string): string[] {\n const lines = splitWithNewlines(contents);\n for (let index = 0; index < lines.length; index++) {\n lines[index] = detachString(lines[index]);\n }\n return lines;\n}\n\nfunction splitWithNewlines(contents: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const lines: string[] = [];\n let startIndex = 0;\n for (;;) {\n const newlineIndex = contents.indexOf('\\n', startIndex);\n if (newlineIndex === -1) {\n break;\n }\n\n lines.push(contents.slice(startIndex, newlineIndex + 1));\n startIndex = newlineIndex + 1;\n }\n\n if (startIndex < contents.length) {\n lines.push(contents.slice(startIndex));\n }\n return lines;\n}\n\nfunction splitGitDiffFiles(contents: string): string[] {\n return splitAtLinePrefix(contents, 'diff --git');\n}\n\nfunction splitUnifiedDiffFiles(contents: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const parts: string[] = [];\n let partStartIndex = 0;\n let lineStartIndex = 0;\n let remainingDeletionLines = 0;\n let remainingAdditionLines = 0;\n let hasOpenedUnifiedFile = false;\n\n while (lineStartIndex < contents.length) {\n const nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n if (remainingDeletionLines <= 0 && remainingAdditionLines <= 0) {\n if (isUnifiedDiffFileHeaderAt(contents, lineStartIndex)) {\n if (lineStartIndex > partStartIndex) {\n parts.push(contents.slice(partStartIndex, lineStartIndex));\n }\n partStartIndex = lineStartIndex;\n hasOpenedUnifiedFile = true;\n lineStartIndex = getNextLineStartIndex(contents, nextLineStartIndex);\n continue;\n }\n\n if (hasOpenedUnifiedFile && contents.startsWith('@@ -', lineStartIndex)) {\n const fileHeader = parseHunkHeader(\n contents.slice(lineStartIndex, nextLineStartIndex)\n );\n if (fileHeader != null) {\n remainingDeletionLines = fileHeader.deletionCount;\n remainingAdditionLines = fileHeader.additionCount;\n }\n }\n lineStartIndex = nextLineStartIndex;\n continue;\n }\n\n const firstChar = contents[lineStartIndex];\n if (firstChar === '\\\\') {\n lineStartIndex = nextLineStartIndex;\n continue;\n }\n\n if (firstChar === ' ') {\n remainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n remainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n } else if (firstChar === '-') {\n remainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n } else if (firstChar === '+') {\n remainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n }\n lineStartIndex = nextLineStartIndex;\n }\n\n parts.push(contents.slice(partStartIndex));\n return parts;\n}\n\nfunction startsWithUnifiedDiffFileHeader(contents: string): boolean {\n return isUnifiedDiffFileHeaderAt(contents, 0);\n}\n\nfunction isUnifiedDiffFileHeaderAt(contents: string, lineStartIndex: number) {\n const nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n return (\n isUnifiedDiffHeaderLineAt(contents, lineStartIndex, '---') &&\n isUnifiedDiffHeaderLineAt(contents, nextLineStartIndex, '+++')\n );\n}\n\nfunction isUnifiedDiffHeaderLineAt(\n contents: string,\n lineStartIndex: number,\n prefix: '---' | '+++'\n): boolean {\n if (!contents.startsWith(prefix, lineStartIndex)) {\n return false;\n }\n\n const separator = contents[lineStartIndex + prefix.length];\n if (separator !== ' ' && separator !== '\\t') {\n return false;\n }\n\n for (\n let index = lineStartIndex + prefix.length + 1;\n index < contents.length;\n index++\n ) {\n const char = contents[index];\n if (char === '\\n' || char === '\\r') {\n break;\n }\n if (char !== ' ' && char !== '\\t') {\n return true;\n }\n }\n return false;\n}\n\nfunction getNextLineStartIndex(\n contents: string,\n lineStartIndex: number\n): number {\n const newlineIndex = contents.indexOf('\\n', lineStartIndex);\n return newlineIndex === -1 ? contents.length : newlineIndex + 1;\n}\n\nfunction isHunkBodyLine(line: string): boolean {\n const firstChar = line[0];\n return firstChar === '+' || firstChar === '-' || firstChar === ' ';\n}\n\nfunction isFormatPatchVersionSeparator(line: string): boolean {\n if (!line.startsWith('--')) {\n return false;\n }\n\n for (let index = 2; index < line.length; index++) {\n const char = line[index];\n if (char !== ' ' && char !== '\\t' && char !== '\\n' && char !== '\\r') {\n return false;\n }\n }\n return true;\n}\n\nfunction parseHunkHeader(line: string): ParsedHunkHeader | undefined {\n if (!line.startsWith('@@ -')) {\n return undefined;\n }\n\n let index = 4;\n const deletionStartResult = readPositiveInteger(line, index);\n if (deletionStartResult == null) {\n return undefined;\n }\n const deletionStart = deletionStartResult.value;\n index = deletionStartResult.endIndex;\n\n let deletionCount = 1;\n if (line[index] === ',') {\n const deletionCountResult = readPositiveInteger(line, index + 1);\n if (deletionCountResult == null) {\n return undefined;\n }\n deletionCount = deletionCountResult.value;\n index = deletionCountResult.endIndex;\n }\n\n if (line[index] !== ' ' || line[index + 1] !== '+') {\n return undefined;\n }\n index += 2;\n\n const additionStartResult = readPositiveInteger(line, index);\n if (additionStartResult == null) {\n return undefined;\n }\n const additionStart = additionStartResult.value;\n index = additionStartResult.endIndex;\n\n let additionCount = 1;\n if (line[index] === ',') {\n const additionCountResult = readPositiveInteger(line, index + 1);\n if (additionCountResult == null) {\n return undefined;\n }\n additionCount = additionCountResult.value;\n index = additionCountResult.endIndex;\n }\n\n if (\n line[index] !== ' ' ||\n line[index + 1] !== '@' ||\n line[index + 2] !== '@'\n ) {\n return undefined;\n }\n\n let hunkContext: string | undefined;\n const contextStartIndex = index + 3;\n if (line[contextStartIndex] === ' ') {\n hunkContext = trimLineEnd(line.slice(contextStartIndex + 1));\n }\n\n return {\n additionCount,\n additionStart,\n deletionCount,\n deletionStart,\n hunkContext,\n };\n}\n\nfunction readPositiveInteger(\n value: string,\n startIndex: number\n): { value: number; endIndex: number } | undefined {\n let index = startIndex;\n let parsedValue = 0;\n for (; index < value.length; index++) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) {\n break;\n }\n parsedValue = parsedValue * 10 + digit;\n }\n\n if (index === startIndex) {\n return undefined;\n }\n return { value: parsedValue, endIndex: index };\n}\n\nfunction trimLineEnd(value: string): string {\n if (value.endsWith('\\r\\n')) {\n return value.slice(0, -2);\n }\n if (value.endsWith('\\n')) {\n return value.slice(0, -1);\n }\n return value;\n}\n\nfunction isGitDiffPatch(data: string): boolean {\n return data.startsWith('diff --git') || data.includes('\\ndiff --git');\n}\n\nfunction splitAtLinePrefix(contents: string, prefix: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const newlinePrefix = `\\n${prefix}`;\n const firstBoundaryIndex = contents.startsWith(prefix)\n ? 0\n : findLinePrefixIndex(contents, newlinePrefix, 0);\n if (firstBoundaryIndex === -1) {\n return [contents];\n }\n\n const parts: string[] = [];\n if (firstBoundaryIndex > 0) {\n parts.push(contents.slice(0, firstBoundaryIndex));\n }\n\n let startIndex = firstBoundaryIndex;\n for (;;) {\n const nextBoundaryIndex = findLinePrefixIndex(\n contents,\n newlinePrefix,\n startIndex + 1\n );\n if (nextBoundaryIndex === -1) {\n break;\n }\n\n parts.push(contents.slice(startIndex, nextBoundaryIndex));\n startIndex = nextBoundaryIndex;\n }\n parts.push(contents.slice(startIndex));\n return parts;\n}\n\nfunction findLinePrefixIndex(\n contents: string,\n newlinePrefix: string,\n fromIndex: number\n): number {\n const index = contents.indexOf(newlinePrefix, fromIndex);\n return index === -1 ? -1 : index + 1;\n}\n\nfunction maybeDetachOptionalString<T extends string | undefined>(value: T): T {\n return (value == null ? value : detachString(value)) as T;\n}\n\nfunction parseRawLineType(\n firstChar: string | undefined\n): Exclude<HunkLineType, 'expanded'> {\n return firstChar === ' '\n ? 'context'\n : firstChar === '\\\\'\n ? 'metadata'\n : firstChar === '+'\n ? 'addition'\n : 'deletion';\n}\n\nfunction getParsedLineContent(rawLine: string): string {\n const processedLine = rawLine.slice(1);\n return detachString(processedLine === '' ? '\\n' : processedLine);\n}\n\nfunction createContentGroup(\n type: 'change',\n deletionLineIndex: number,\n additionLineIndex: number\n): ChangeContent;\nfunction createContentGroup(\n type: 'context',\n deletionLineIndex: number,\n additionLineIndex: number\n): ContextContent;\nfunction createContentGroup(\n type: 'change' | 'context',\n deletionLineIndex: number,\n additionLineIndex: number\n): ChangeContent | ContextContent {\n if (type === 'change') {\n return {\n type: 'change',\n additions: 0,\n deletions: 0,\n additionLineIndex,\n deletionLineIndex,\n };\n }\n return {\n type: 'context',\n lines: 0,\n additionLineIndex,\n deletionLineIndex,\n };\n}\n"],"mappings":";;;;AA4BA,SAAgB,aACd,MACA,gBACA,cACa;CACb,IA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O,UAAU,KAAK,KAAK,QAAQ;AACrC;AAEA,SAAS,0BAAwD,OAAa;CAC5E,OAAQ,SAAS,OAAO,QAAQ,aAAa,KAAK;AACpD;AAEA,SAAS,iBACP,WACmC;CACnC,OAAO,cAAc,MACjB,YACA,cAAc,OACZ,aACA,cAAc,MACZ,aACA;AACV;AAEA,SAAS,qBAAqB,SAAyB;CACrD,MAAM,gBAAgB,QAAQ,MAAM,CAAC;CACrC,OAAO,aAAa,kBAAkB,KAAK,OAAO,aAAa;AACjE;AAYA,SAAS,mBACP,MACA,mBACA,mBACgC;CAChC,IAAI,SAAS,UACX,OAAO;EACL,MAAM;EACN,WAAW;EACX,WAAW;EACX;EACA;CACF;CAEF,OAAO;EACL,MAAM;EACN,OAAO;EACP;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"parsePatchFiles.js","names":[],"sources":["../../src/utils/parsePatchFiles.ts"],"sourcesContent":["import {\n ALTERNATE_FILE_NAMES_GIT,\n COMMIT_METADATA_SPLIT,\n FILENAME_HEADER_REGEX,\n FILENAME_HEADER_REGEX_GIT,\n GIT_DIFF_FILE_BREAK_REGEX,\n INDEX_LINE_METADATA,\n} from '../constants';\nimport type {\n ChangeContent,\n ContextContent,\n FileContents,\n FileDiffMetadata,\n Hunk,\n HunkLineType,\n ParsedPatch,\n} from '../types';\nimport { cleanLastNewline } from './cleanLastNewline';\nimport { detachString, releaseStringDetachBuffer } from './detachString';\nimport {\n getHunkSideEndBoundary,\n getHunkSideStartBoundary,\n} from './getHunkSideBoundaries';\nimport { realignChangeContentBySimilarity } from './realignChangeContent';\n\ninterface ParsedHunkHeader {\n additionCount: number;\n additionStart: number;\n deletionCount: number;\n deletionStart: number;\n hunkContext?: string;\n}\n\nexport function processPatch(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError?: boolean\n): ParsedPatch {\n try {\n return _processPatch(data, cacheKeyPrefix, throwOnError);\n } finally {\n releaseStringDetachBuffer();\n }\n}\n\nfunction _processPatch(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError = false\n): ParsedPatch {\n const isGitDiff = isGitDiffPatch(data);\n const rawFiles = isGitDiff\n ? splitGitDiffFiles(data)\n : splitUnifiedDiffFiles(data);\n let patchMetadata: string | undefined;\n const files: FileDiffMetadata[] = [];\n for (const fileOrPatchMetadata of rawFiles) {\n if (isGitDiff && !GIT_DIFF_FILE_BREAK_REGEX.test(fileOrPatchMetadata)) {\n if (patchMetadata == null) {\n patchMetadata = detachString(fileOrPatchMetadata);\n } else {\n if (throwOnError) {\n throw Error('parsePatchContent: unknown file blob');\n } else {\n console.error(\n 'parsePatchContent: unknown file blob:',\n fileOrPatchMetadata\n );\n }\n }\n // If we get in here, it's most likely the introductory metadata from the\n // patch, or something is fucked with the diff format\n continue;\n } else if (\n !isGitDiff &&\n !startsWithUnifiedDiffFileHeader(fileOrPatchMetadata)\n ) {\n if (patchMetadata == null) {\n patchMetadata = detachString(fileOrPatchMetadata);\n } else {\n if (throwOnError) {\n throw Error('parsePatchContent: unknown file blob');\n } else {\n console.error(\n 'parsePatchContent: unknown file blob:',\n fileOrPatchMetadata\n );\n }\n }\n continue;\n }\n const currentFile = _processFile(fileOrPatchMetadata, {\n cacheKey:\n cacheKeyPrefix != null\n ? `${cacheKeyPrefix}-${files.length}`\n : undefined,\n isGitDiff,\n throwOnError,\n });\n if (currentFile != null) {\n files.push(currentFile);\n }\n }\n return { patchMetadata, files };\n}\n\ninterface ProcessFileOptions {\n cacheKey?: string;\n isGitDiff?: boolean;\n oldFile?: FileContents;\n newFile?: FileContents;\n throwOnError?: boolean;\n}\n\nexport function processFile(\n fileDiffString: string,\n options?: ProcessFileOptions\n): FileDiffMetadata | undefined {\n try {\n return _processFile(fileDiffString, options);\n } finally {\n releaseStringDetachBuffer();\n }\n}\n\nfunction _processFile(\n fileDiffString: string,\n {\n cacheKey,\n isGitDiff = GIT_DIFF_FILE_BREAK_REGEX.test(fileDiffString),\n oldFile,\n newFile,\n throwOnError = false,\n }: ProcessFileOptions = {}\n): FileDiffMetadata | undefined {\n let lastHunkEnd = 0;\n const hunks = splitAtLinePrefix(fileDiffString, '@@ ');\n let currentFile: FileDiffMetadata | undefined;\n const isPartial = oldFile == null || newFile == null;\n let deletionLineIndex = 0;\n let additionLineIndex = 0;\n for (const hunk of hunks) {\n const lines = splitWithNewlines(hunk);\n const firstLine = lines[0];\n if (firstLine == null) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid hunk');\n } else {\n console.error('parsePatchContent: invalid hunk', hunk);\n }\n continue;\n }\n const fileHeader = parseHunkHeader(firstLine);\n let additionLines = 0;\n let deletionLines = 0;\n // Setup currentFile, this should be the first iteration of our hunks, and\n // technically not a hunk\n if (fileHeader == null || currentFile == null) {\n if (currentFile != null) {\n if (throwOnError) {\n throw Error('parsePatchContent: Invalid hunk');\n } else {\n console.error('parsePatchContent: Invalid hunk', hunk);\n }\n continue;\n }\n currentFile = {\n name: '',\n type: 'change',\n hunks: [],\n splitLineCount: 0,\n unifiedLineCount: 0,\n isPartial,\n additionLines:\n !isPartial && oldFile != null && newFile != null\n ? splitFileContents(newFile.contents)\n : [],\n deletionLines:\n !isPartial && oldFile != null && newFile != null\n ? splitFileContents(oldFile.contents)\n : [],\n cacheKey: maybeDetachOptionalString(cacheKey),\n };\n // If either file is technically empty, then we should empty the\n // arrays respectively\n if (currentFile.additionLines.length === 1 && newFile?.contents === '') {\n currentFile.additionLines.length = 0;\n }\n if (currentFile.deletionLines.length === 1 && oldFile?.contents === '') {\n currentFile.deletionLines.length = 0;\n }\n\n for (const line of lines) {\n if (line.startsWith('diff --git')) {\n const filenameMatch = line.trim().match(ALTERNATE_FILE_NAMES_GIT);\n const prevName = filenameMatch?.[1] ?? filenameMatch?.[2];\n const name = filenameMatch?.[3] ?? filenameMatch?.[4];\n if (prevName == null || name == null) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid git diff header');\n } else {\n console.error('parsePatchContent: invalid git diff header', line);\n }\n continue;\n }\n currentFile.name = detachString(name.trim());\n if (prevName !== name) {\n currentFile.prevName = detachString(prevName.trim());\n }\n continue;\n }\n\n const filenameMatch =\n line.startsWith('---') || line.startsWith('+++')\n ? line.match(\n isGitDiff ? FILENAME_HEADER_REGEX_GIT : FILENAME_HEADER_REGEX\n )\n : null;\n if (filenameMatch != null) {\n const [, type, fileName] = filenameMatch;\n if (type === '---' && fileName !== '/dev/null') {\n const detachedFileName = detachString(fileName.trim());\n currentFile.prevName = detachedFileName;\n currentFile.name = detachedFileName;\n } else if (type === '+++' && fileName !== '/dev/null') {\n currentFile.name = detachString(fileName.trim());\n }\n }\n // Git diffs have a bunch of additional metadata we can pull from\n else if (isGitDiff) {\n if (line.startsWith('new mode ')) {\n currentFile.mode = detachString(\n line.slice('new mode'.length).trim()\n );\n }\n if (line.startsWith('old mode ')) {\n currentFile.prevMode = detachString(\n line.slice('old mode'.length).trim()\n );\n }\n if (line.startsWith('new file mode')) {\n currentFile.type = 'new';\n currentFile.mode = detachString(\n line.slice('new file mode'.length).trim()\n );\n }\n if (line.startsWith('deleted file mode')) {\n currentFile.type = 'deleted';\n currentFile.mode = detachString(\n line.slice('deleted file mode'.length).trim()\n );\n }\n if (line.startsWith('similarity index')) {\n if (line.startsWith('similarity index 100%')) {\n currentFile.type = 'rename-pure';\n } else {\n currentFile.type = 'rename-changed';\n }\n }\n if (line.startsWith('index ')) {\n const [, prevObjectId, newObjectId, mode] =\n line.trim().match(INDEX_LINE_METADATA) ?? [];\n if (prevObjectId != null) {\n currentFile.prevObjectId = detachString(prevObjectId);\n }\n if (newObjectId != null) {\n currentFile.newObjectId = detachString(newObjectId);\n }\n if (mode != null) {\n currentFile.mode = detachString(mode);\n }\n }\n // We have to handle these for pure renames because there won't be\n // --- and +++ lines\n if (line.startsWith('rename from ')) {\n currentFile.prevName = detachString(\n line.slice('rename from '.length).trim()\n );\n }\n if (line.startsWith('rename to ')) {\n currentFile.name = detachString(\n line.slice('rename to '.length).trim()\n );\n }\n }\n }\n continue;\n }\n\n // Otherwise, time to start parsing out the hunk\n let currentContent: ContextContent | ChangeContent | undefined;\n let lastLineType: 'context' | 'addition' | 'deletion' | undefined;\n\n // Strip trailing bare newlines (format-patch separators between commits)\n // if needed\n while (\n lines.length > 0 &&\n (lines[lines.length - 1] === '\\n' ||\n lines[lines.length - 1] === '\\r' ||\n lines[lines.length - 1] === '\\r\\n' ||\n lines[lines.length - 1] === '')\n ) {\n lines.pop();\n }\n\n const { additionStart, deletionStart } = fileHeader;\n deletionLineIndex = isPartial ? deletionLineIndex : deletionStart - 1;\n additionLineIndex = isPartial ? additionLineIndex : additionStart - 1;\n\n const hunkData: Hunk = {\n collapsedBefore: 0,\n\n splitLineCount: 0,\n splitLineStart: 0,\n\n unifiedLineCount: 0,\n unifiedLineStart: 0,\n\n additionCount: fileHeader.additionCount,\n additionStart,\n additionLines,\n\n deletionCount: fileHeader.deletionCount,\n deletionStart,\n deletionLines,\n\n deletionLineIndex,\n additionLineIndex,\n\n hunkContent: [],\n hunkContext: maybeDetachOptionalString(fileHeader.hunkContext),\n hunkSpecs: detachString(firstLine),\n\n noEOFCRAdditions: false,\n noEOFCRDeletions: false,\n };\n\n // Now we process each line of the hunk\n let parsedAdditionLines = 0;\n let parsedDeletionLines = 0;\n for (let lineIndex = 1; lineIndex < lines.length; lineIndex++) {\n const rawLine = lines[lineIndex];\n if (\n parsedAdditionLines >= hunkData.additionCount &&\n parsedDeletionLines >= hunkData.deletionCount &&\n !rawLine.startsWith('\\\\')\n ) {\n if (\n throwOnError &&\n isHunkBodyLine(rawLine) &&\n !isFormatPatchVersionSeparator(rawLine)\n ) {\n throw Error('parsePatchContent: hunk has more lines than expected');\n }\n break;\n }\n\n const firstChar = rawLine[0];\n // If we can't properly process the line, well, lets just try to salvage\n // things and continue... It's possible an AI generated diff might have\n // some stray blank lines or something in there\n if (\n firstChar !== '+' &&\n firstChar !== '-' &&\n firstChar !== ' ' &&\n firstChar !== '\\\\'\n ) {\n if (throwOnError) {\n throw Error('parsePatchContent: invalid hunk line');\n }\n console.error(\n `parseLineType: Invalid firstChar: \"${firstChar}\", full line: \"${rawLine}\"`\n );\n console.error('processFile: invalid rawLine:', rawLine);\n continue;\n }\n\n const type = parseRawLineType(firstChar);\n if (type === 'addition') {\n if (throwOnError && parsedAdditionLines >= hunkData.additionCount) {\n throw Error('parsePatchContent: hunk has too many addition lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'change') {\n currentContent = createContentGroup(\n 'change',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n additionLineIndex++;\n parsedAdditionLines++;\n if (isPartial) {\n currentFile.additionLines.push(line);\n }\n currentContent.additions++;\n additionLines++;\n lastLineType = 'addition';\n } else if (type === 'deletion') {\n if (throwOnError && parsedDeletionLines >= hunkData.deletionCount) {\n throw Error('parsePatchContent: hunk has too many deletion lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'change') {\n currentContent = createContentGroup(\n 'change',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n deletionLineIndex++;\n parsedDeletionLines++;\n if (isPartial) {\n currentFile.deletionLines.push(line);\n }\n currentContent.deletions++;\n deletionLines++;\n lastLineType = 'deletion';\n } else if (type === 'context') {\n if (\n throwOnError &&\n (parsedDeletionLines >= hunkData.deletionCount ||\n parsedAdditionLines >= hunkData.additionCount)\n ) {\n throw Error('parsePatchContent: hunk has too many context lines');\n }\n const line = getParsedLineContent(rawLine);\n if (currentContent == null || currentContent.type !== 'context') {\n currentContent = createContentGroup(\n 'context',\n deletionLineIndex,\n additionLineIndex\n );\n hunkData.hunkContent.push(currentContent);\n }\n additionLineIndex++;\n deletionLineIndex++;\n parsedAdditionLines++;\n parsedDeletionLines++;\n if (isPartial) {\n currentFile.deletionLines.push(line);\n currentFile.additionLines.push(line);\n }\n currentContent.lines++;\n lastLineType = 'context';\n } else if (type === 'metadata' && currentContent != null) {\n if (currentContent.type === 'context') {\n hunkData.noEOFCRAdditions = true;\n hunkData.noEOFCRDeletions = true;\n } else if (lastLineType === 'deletion') {\n hunkData.noEOFCRDeletions = true;\n } else if (lastLineType === 'addition') {\n hunkData.noEOFCRAdditions = true;\n }\n // If we're dealing with partial content from a diff, we need to strip\n // newlines manually from the content\n if (\n isPartial &&\n (lastLineType === 'addition' || lastLineType === 'context')\n ) {\n const lastIndex = currentFile.additionLines.length - 1;\n if (lastIndex >= 0) {\n currentFile.additionLines[lastIndex] = cleanLastNewline(\n currentFile.additionLines[lastIndex]\n );\n }\n }\n if (\n isPartial &&\n (lastLineType === 'deletion' || lastLineType === 'context')\n ) {\n const lastIndex = currentFile.deletionLines.length - 1;\n if (lastIndex >= 0) {\n currentFile.deletionLines[lastIndex] = cleanLastNewline(\n currentFile.deletionLines[lastIndex]\n );\n }\n }\n }\n }\n\n if (\n throwOnError &&\n (parsedAdditionLines !== hunkData.additionCount ||\n parsedDeletionLines !== hunkData.deletionCount)\n ) {\n throw Error('parsePatchContent: hunk line count mismatch');\n }\n\n hunkData.additionLines = additionLines;\n hunkData.deletionLines = deletionLines;\n\n hunkData.collapsedBefore = Math.max(\n getHunkSideStartBoundary(hunkData.additionStart, hunkData.additionCount) -\n lastHunkEnd,\n 0\n );\n currentFile.hunks.push(hunkData);\n lastHunkEnd = getHunkSideEndBoundary(\n hunkData.additionStart,\n hunkData.additionCount\n );\n for (const content of hunkData.hunkContent) {\n if (content.type === 'context') {\n hunkData.splitLineCount += content.lines;\n hunkData.unifiedLineCount += content.lines;\n } else {\n hunkData.splitLineCount += Math.max(\n content.additions,\n content.deletions\n );\n hunkData.unifiedLineCount += content.deletions + content.additions;\n }\n }\n hunkData.splitLineStart =\n currentFile.splitLineCount + hunkData.collapsedBefore;\n hunkData.unifiedLineStart =\n currentFile.unifiedLineCount + hunkData.collapsedBefore;\n\n currentFile.splitLineCount +=\n hunkData.collapsedBefore + hunkData.splitLineCount;\n currentFile.unifiedLineCount +=\n hunkData.collapsedBefore + hunkData.unifiedLineCount;\n }\n if (currentFile == null) {\n return undefined;\n }\n if (\n throwOnError &&\n isPartial &&\n !isGitDiff &&\n currentFile.hunks.length === 0\n ) {\n throw Error('parsePatchContent: unified file has no hunks');\n }\n\n // Account for collapsed lines after the final hunk and increment the\n // split/unified counts properly\n if (\n currentFile.hunks.length > 0 &&\n !isPartial &&\n currentFile.additionLines.length > 0 &&\n currentFile.deletionLines.length > 0\n ) {\n const lastHunk = currentFile.hunks[currentFile.hunks.length - 1];\n const lastHunkEnd = getHunkSideEndBoundary(\n lastHunk.additionStart,\n lastHunk.additionCount\n );\n const totalFileLines = currentFile.additionLines.length;\n const collapsedAfter = Math.max(totalFileLines - lastHunkEnd, 0);\n currentFile.splitLineCount += collapsedAfter;\n currentFile.unifiedLineCount += collapsedAfter;\n }\n\n // If this isn't a git diff style patch, then we'll need to sus out some\n // additional metadata manually\n if (!isGitDiff) {\n if (\n currentFile.prevName != null &&\n currentFile.name !== currentFile.prevName\n ) {\n if (currentFile.hunks.length > 0) {\n currentFile.type = 'rename-changed';\n } else {\n currentFile.type = 'rename-pure';\n }\n }\n // Sort of a hack for detecting deleted/added files...\n else if (\n (oldFile == null || oldFile.contents === '') &&\n newFile != null &&\n newFile.contents !== ''\n ) {\n currentFile.type = 'new';\n } else if (\n oldFile != null &&\n oldFile.contents !== '' &&\n (newFile == null || newFile.contents === '')\n ) {\n currentFile.type = 'deleted';\n }\n }\n if (\n currentFile.type !== 'rename-pure' &&\n currentFile.type !== 'rename-changed'\n ) {\n currentFile.prevName = undefined;\n }\n // Pair change-block lines by similarity instead of the patch's positional\n // ordering. Partial diffs work too: their hunk line indexes point into the\n // patch-built line arrays, which hold every line a block references.\n realignChangeContentBySimilarity(currentFile);\n return currentFile;\n}\n\n/**\n * Parses a patch file string into an array of parsed patches.\n *\n * @param data - The raw patch file content (supports multi-commit patches)\n * @param cacheKeyPrefix - Optional prefix for generating cache keys. When provided,\n * each file in the patch will get a cache key in the format `prefix-patchIndex-fileIndex`.\n * This enables caching of rendered diff results in the worker pool.\n */\nexport function parsePatchFiles(\n data: string,\n cacheKeyPrefix?: string,\n throwOnError = false\n): ParsedPatch[] {\n // NOTE(amadeus): This function is pretty forgiving in that it can accept a\n // patch file that includes commit metdata, multiple commits, or not\n const patches: ParsedPatch[] = [];\n const rawPatches = hasCommitMetadataBoundary(data)\n ? data.split(COMMIT_METADATA_SPLIT)\n : [data];\n for (const patch of rawPatches) {\n try {\n patches.push(\n processPatch(\n patch,\n cacheKeyPrefix != null\n ? `${cacheKeyPrefix}-${patches.length}`\n : undefined,\n throwOnError\n )\n );\n } catch (error) {\n if (throwOnError) {\n throw error;\n } else {\n console.error(error);\n }\n }\n }\n return patches;\n}\n\nfunction hasCommitMetadataBoundary(data: string): boolean {\n return data.startsWith('From ') || data.includes('\\nFrom ');\n}\n\nfunction splitFileContents(contents: string): string[] {\n const lines = splitWithNewlines(contents);\n for (let index = 0; index < lines.length; index++) {\n lines[index] = detachString(lines[index]);\n }\n return lines;\n}\n\nfunction splitWithNewlines(contents: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const lines: string[] = [];\n let startIndex = 0;\n for (;;) {\n const newlineIndex = contents.indexOf('\\n', startIndex);\n if (newlineIndex === -1) {\n break;\n }\n\n lines.push(contents.slice(startIndex, newlineIndex + 1));\n startIndex = newlineIndex + 1;\n }\n\n if (startIndex < contents.length) {\n lines.push(contents.slice(startIndex));\n }\n return lines;\n}\n\nfunction splitGitDiffFiles(contents: string): string[] {\n return splitAtLinePrefix(contents, 'diff --git');\n}\n\nfunction splitUnifiedDiffFiles(contents: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const parts: string[] = [];\n let partStartIndex = 0;\n let lineStartIndex = 0;\n let remainingDeletionLines = 0;\n let remainingAdditionLines = 0;\n let hasOpenedUnifiedFile = false;\n\n while (lineStartIndex < contents.length) {\n const nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n if (remainingDeletionLines <= 0 && remainingAdditionLines <= 0) {\n if (isUnifiedDiffFileHeaderAt(contents, lineStartIndex)) {\n if (lineStartIndex > partStartIndex) {\n parts.push(contents.slice(partStartIndex, lineStartIndex));\n }\n partStartIndex = lineStartIndex;\n hasOpenedUnifiedFile = true;\n lineStartIndex = getNextLineStartIndex(contents, nextLineStartIndex);\n continue;\n }\n\n if (hasOpenedUnifiedFile && contents.startsWith('@@ -', lineStartIndex)) {\n const fileHeader = parseHunkHeader(\n contents.slice(lineStartIndex, nextLineStartIndex)\n );\n if (fileHeader != null) {\n remainingDeletionLines = fileHeader.deletionCount;\n remainingAdditionLines = fileHeader.additionCount;\n }\n }\n lineStartIndex = nextLineStartIndex;\n continue;\n }\n\n const firstChar = contents[lineStartIndex];\n if (firstChar === '\\\\') {\n lineStartIndex = nextLineStartIndex;\n continue;\n }\n\n if (firstChar === ' ') {\n remainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n remainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n } else if (firstChar === '-') {\n remainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n } else if (firstChar === '+') {\n remainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n }\n lineStartIndex = nextLineStartIndex;\n }\n\n parts.push(contents.slice(partStartIndex));\n return parts;\n}\n\nfunction startsWithUnifiedDiffFileHeader(contents: string): boolean {\n return isUnifiedDiffFileHeaderAt(contents, 0);\n}\n\nfunction isUnifiedDiffFileHeaderAt(contents: string, lineStartIndex: number) {\n const nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n return (\n isUnifiedDiffHeaderLineAt(contents, lineStartIndex, '---') &&\n isUnifiedDiffHeaderLineAt(contents, nextLineStartIndex, '+++')\n );\n}\n\nfunction isUnifiedDiffHeaderLineAt(\n contents: string,\n lineStartIndex: number,\n prefix: '---' | '+++'\n): boolean {\n if (!contents.startsWith(prefix, lineStartIndex)) {\n return false;\n }\n\n const separator = contents[lineStartIndex + prefix.length];\n if (separator !== ' ' && separator !== '\\t') {\n return false;\n }\n\n for (\n let index = lineStartIndex + prefix.length + 1;\n index < contents.length;\n index++\n ) {\n const char = contents[index];\n if (char === '\\n' || char === '\\r') {\n break;\n }\n if (char !== ' ' && char !== '\\t') {\n return true;\n }\n }\n return false;\n}\n\nfunction getNextLineStartIndex(\n contents: string,\n lineStartIndex: number\n): number {\n const newlineIndex = contents.indexOf('\\n', lineStartIndex);\n return newlineIndex === -1 ? contents.length : newlineIndex + 1;\n}\n\nfunction isHunkBodyLine(line: string): boolean {\n const firstChar = line[0];\n return firstChar === '+' || firstChar === '-' || firstChar === ' ';\n}\n\nfunction isFormatPatchVersionSeparator(line: string): boolean {\n if (!line.startsWith('--')) {\n return false;\n }\n\n for (let index = 2; index < line.length; index++) {\n const char = line[index];\n if (char !== ' ' && char !== '\\t' && char !== '\\n' && char !== '\\r') {\n return false;\n }\n }\n return true;\n}\n\nfunction parseHunkHeader(line: string): ParsedHunkHeader | undefined {\n if (!line.startsWith('@@ -')) {\n return undefined;\n }\n\n let index = 4;\n const deletionStartResult = readPositiveInteger(line, index);\n if (deletionStartResult == null) {\n return undefined;\n }\n const deletionStart = deletionStartResult.value;\n index = deletionStartResult.endIndex;\n\n let deletionCount = 1;\n if (line[index] === ',') {\n const deletionCountResult = readPositiveInteger(line, index + 1);\n if (deletionCountResult == null) {\n return undefined;\n }\n deletionCount = deletionCountResult.value;\n index = deletionCountResult.endIndex;\n }\n\n if (line[index] !== ' ' || line[index + 1] !== '+') {\n return undefined;\n }\n index += 2;\n\n const additionStartResult = readPositiveInteger(line, index);\n if (additionStartResult == null) {\n return undefined;\n }\n const additionStart = additionStartResult.value;\n index = additionStartResult.endIndex;\n\n let additionCount = 1;\n if (line[index] === ',') {\n const additionCountResult = readPositiveInteger(line, index + 1);\n if (additionCountResult == null) {\n return undefined;\n }\n additionCount = additionCountResult.value;\n index = additionCountResult.endIndex;\n }\n\n if (\n line[index] !== ' ' ||\n line[index + 1] !== '@' ||\n line[index + 2] !== '@'\n ) {\n return undefined;\n }\n\n let hunkContext: string | undefined;\n const contextStartIndex = index + 3;\n if (line[contextStartIndex] === ' ') {\n hunkContext = trimLineEnd(line.slice(contextStartIndex + 1));\n }\n\n return {\n additionCount,\n additionStart,\n deletionCount,\n deletionStart,\n hunkContext,\n };\n}\n\nfunction readPositiveInteger(\n value: string,\n startIndex: number\n): { value: number; endIndex: number } | undefined {\n let index = startIndex;\n let parsedValue = 0;\n for (; index < value.length; index++) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) {\n break;\n }\n parsedValue = parsedValue * 10 + digit;\n }\n\n if (index === startIndex) {\n return undefined;\n }\n return { value: parsedValue, endIndex: index };\n}\n\nfunction trimLineEnd(value: string): string {\n if (value.endsWith('\\r\\n')) {\n return value.slice(0, -2);\n }\n if (value.endsWith('\\n')) {\n return value.slice(0, -1);\n }\n return value;\n}\n\nfunction isGitDiffPatch(data: string): boolean {\n return data.startsWith('diff --git') || data.includes('\\ndiff --git');\n}\n\nfunction splitAtLinePrefix(contents: string, prefix: string): string[] {\n if (contents.length === 0) {\n return [''];\n }\n\n const newlinePrefix = `\\n${prefix}`;\n const firstBoundaryIndex = contents.startsWith(prefix)\n ? 0\n : findLinePrefixIndex(contents, newlinePrefix, 0);\n if (firstBoundaryIndex === -1) {\n return [contents];\n }\n\n const parts: string[] = [];\n if (firstBoundaryIndex > 0) {\n parts.push(contents.slice(0, firstBoundaryIndex));\n }\n\n let startIndex = firstBoundaryIndex;\n for (;;) {\n const nextBoundaryIndex = findLinePrefixIndex(\n contents,\n newlinePrefix,\n startIndex + 1\n );\n if (nextBoundaryIndex === -1) {\n break;\n }\n\n parts.push(contents.slice(startIndex, nextBoundaryIndex));\n startIndex = nextBoundaryIndex;\n }\n parts.push(contents.slice(startIndex));\n return parts;\n}\n\nfunction findLinePrefixIndex(\n contents: string,\n newlinePrefix: string,\n fromIndex: number\n): number {\n const index = contents.indexOf(newlinePrefix, fromIndex);\n return index === -1 ? -1 : index + 1;\n}\n\nfunction maybeDetachOptionalString<T extends string | undefined>(value: T): T {\n return (value == null ? value : detachString(value)) as T;\n}\n\nfunction parseRawLineType(\n firstChar: string | undefined\n): Exclude<HunkLineType, 'expanded'> {\n return firstChar === ' '\n ? 'context'\n : firstChar === '\\\\'\n ? 'metadata'\n : firstChar === '+'\n ? 'addition'\n : 'deletion';\n}\n\nfunction getParsedLineContent(rawLine: string): string {\n const processedLine = rawLine.slice(1);\n return detachString(processedLine === '' ? '\\n' : processedLine);\n}\n\nfunction createContentGroup(\n type: 'change',\n deletionLineIndex: number,\n additionLineIndex: number\n): ChangeContent;\nfunction createContentGroup(\n type: 'context',\n deletionLineIndex: number,\n additionLineIndex: number\n): ContextContent;\nfunction createContentGroup(\n type: 'change' | 'context',\n deletionLineIndex: number,\n additionLineIndex: number\n): ChangeContent | ContextContent {\n if (type === 'change') {\n return {\n type: 'change',\n additions: 0,\n deletions: 0,\n additionLineIndex,\n deletionLineIndex,\n };\n }\n return {\n type: 'context',\n lines: 0,\n additionLineIndex,\n deletionLineIndex,\n };\n}\n"],"mappings":";;;;;;AAiCA,SAAgB,aACd,MACA,gBACA,cACa;CACb,IAAI;EACF,OAAO,cAAc,MAAM,gBAAgB,YAAY;CACzD,UAAU;EACR,0BAA0B;CAC5B;AACF;AAEA,SAAS,cACP,MACA,gBACA,eAAe,OACF;CACb,MAAM,YAAY,eAAe,IAAI;CACrC,MAAM,WAAW,YACb,kBAAkB,IAAI,IACtB,sBAAsB,IAAI;CAC9B,IAAI;CACJ,MAAM,QAA4B,CAAC;CACnC,KAAK,MAAM,uBAAuB,UAAU;EAC1C,IAAI,aAAa,CAAC,0BAA0B,KAAK,mBAAmB,GAAG;GACrE,IAAI,iBAAiB,MACnB,gBAAgB,aAAa,mBAAmB;QAEhD,IAAI,cACF,MAAM,MAAM,sCAAsC;QAElD,QAAQ,MACN,yCACA,mBACF;GAKJ;EACF,OAAO,IACL,CAAC,aACD,CAAC,gCAAgC,mBAAmB,GACpD;GACA,IA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AACF"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { FileDiffMetadata, Hunk } from "../types.js";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/realignChangeContent.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Re-split count-mismatched change blocks in every hunk so paired lines are
|
|
6
|
+
* chosen by content similarity instead of position, then slide blank-line
|
|
7
|
+
* insert/delete blocks to the top of their blank run. Mutates `hunks` in
|
|
8
|
+
* place; rendered row counts are unchanged (a split block covers the same
|
|
9
|
+
* split/unified rows as the original).
|
|
10
|
+
*/
|
|
11
|
+
declare function realignChangeContentBySimilarity(diff: Pick<FileDiffMetadata, 'hunks' | 'additionLines' | 'deletionLines'>): void;
|
|
12
|
+
/**
|
|
13
|
+
* Slide pure insert/delete blocks made entirely of blank lines to the top of
|
|
14
|
+
* the blank run they sit in. Adding or removing a blank line next to
|
|
15
|
+
* existing blanks is ambiguous, and the diff library reports the change at
|
|
16
|
+
* the run's bottom — so pressing Enter at the end of a line marks a blank
|
|
17
|
+
* *below* the caret as inserted while the caret's own new line renders as
|
|
18
|
+
* context. Sliding up anchors the change to the content above it (the caret
|
|
19
|
+
* line after an Enter) instead.
|
|
20
|
+
*
|
|
21
|
+
* The slide is all-or-nothing: it only applies when the block comes to rest
|
|
22
|
+
* directly beneath remaining in-hunk content. A slide that would consume the
|
|
23
|
+
* hunk's entire leading context was stopped by the hunk's edge — a context
|
|
24
|
+
* window cut, not the top of the blank run — and that landing spot is
|
|
25
|
+
* arbitrary, so the block keeps the library's bottom-of-run anchor (which
|
|
26
|
+
* sits against the content below the run). Non-blank blocks never slide, so
|
|
27
|
+
* code that merely ends like its neighbor (an added function before an
|
|
28
|
+
* identical `}`) keeps the library's canonical position.
|
|
29
|
+
*/
|
|
30
|
+
declare function slideBlankBoundaryBlocksUp(hunk: Hunk, diff: Pick<FileDiffMetadata, 'additionLines' | 'deletionLines'>): void;
|
|
31
|
+
//#endregion
|
|
32
|
+
export { realignChangeContentBySimilarity, slideBlankBoundaryBlocksUp };
|
|
33
|
+
//# sourceMappingURL=realignChangeContent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"realignChangeContent.d.ts","names":[],"sources":["../../src/utils/realignChangeContent.ts"],"mappings":";;;;;AAmCA;;;;;iBAAgB,gCAAA,CACd,IAAA,EAAM,IAAI,CAAC,gBAAA;;;AAA8D;AAoC3E;;;;;;;;;;;;;;AAEiE;iBAFjD,0BAAA,CACd,IAAA,EAAM,IAAA,EACN,IAAA,EAAM,IAAA,CAAK,gBAAA"}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
//#region src/utils/realignChangeContent.ts
|
|
2
|
+
const MAX_ALIGNMENT_COMPARISONS = 4096;
|
|
3
|
+
const MIN_IMPROVEMENT_PER_PAIR = .5;
|
|
4
|
+
/**
|
|
5
|
+
* Re-split count-mismatched change blocks in every hunk so paired lines are
|
|
6
|
+
* chosen by content similarity instead of position, then slide blank-line
|
|
7
|
+
* insert/delete blocks to the top of their blank run. Mutates `hunks` in
|
|
8
|
+
* place; rendered row counts are unchanged (a split block covers the same
|
|
9
|
+
* split/unified rows as the original).
|
|
10
|
+
*/
|
|
11
|
+
function realignChangeContentBySimilarity(diff) {
|
|
12
|
+
for (const hunk of diff.hunks) {
|
|
13
|
+
for (let index = 0; index < hunk.hunkContent.length; index++) {
|
|
14
|
+
const content = hunk.hunkContent[index];
|
|
15
|
+
if (content.type !== "change") continue;
|
|
16
|
+
const replacement = realignChangeBlock(diff, content);
|
|
17
|
+
if (replacement != null) {
|
|
18
|
+
hunk.hunkContent.splice(index, 1, ...replacement);
|
|
19
|
+
index += replacement.length - 1;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
slideBlankBoundaryBlocksUp(hunk, diff);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Slide pure insert/delete blocks made entirely of blank lines to the top of
|
|
27
|
+
* the blank run they sit in. Adding or removing a blank line next to
|
|
28
|
+
* existing blanks is ambiguous, and the diff library reports the change at
|
|
29
|
+
* the run's bottom — so pressing Enter at the end of a line marks a blank
|
|
30
|
+
* *below* the caret as inserted while the caret's own new line renders as
|
|
31
|
+
* context. Sliding up anchors the change to the content above it (the caret
|
|
32
|
+
* line after an Enter) instead.
|
|
33
|
+
*
|
|
34
|
+
* The slide is all-or-nothing: it only applies when the block comes to rest
|
|
35
|
+
* directly beneath remaining in-hunk content. A slide that would consume the
|
|
36
|
+
* hunk's entire leading context was stopped by the hunk's edge — a context
|
|
37
|
+
* window cut, not the top of the blank run — and that landing spot is
|
|
38
|
+
* arbitrary, so the block keeps the library's bottom-of-run anchor (which
|
|
39
|
+
* sits against the content below the run). Non-blank blocks never slide, so
|
|
40
|
+
* code that merely ends like its neighbor (an added function before an
|
|
41
|
+
* identical `}`) keeps the library's canonical position.
|
|
42
|
+
*/
|
|
43
|
+
function slideBlankBoundaryBlocksUp(hunk, diff) {
|
|
44
|
+
const { hunkContent } = hunk;
|
|
45
|
+
for (let index = 1; index < hunkContent.length; index++) {
|
|
46
|
+
const block = hunkContent[index];
|
|
47
|
+
const previous = hunkContent[index - 1];
|
|
48
|
+
if (block.type !== "change" || block.additions > 0 && block.deletions > 0 || previous.type !== "context") continue;
|
|
49
|
+
const isInsert = block.additions > 0;
|
|
50
|
+
const lines = isInsert ? diff.additionLines : diff.deletionLines;
|
|
51
|
+
const blockStart = isInsert ? block.additionLineIndex : block.deletionLineIndex;
|
|
52
|
+
const blockLength = isInsert ? block.additions : block.deletions;
|
|
53
|
+
const unit = lines[blockStart] ?? "";
|
|
54
|
+
if (unit.trim() !== "") continue;
|
|
55
|
+
let uniform = true;
|
|
56
|
+
for (let offset = 1; offset < blockLength; offset++) if (lines[blockStart + offset] !== unit) {
|
|
57
|
+
uniform = false;
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
if (!uniform) continue;
|
|
61
|
+
let slide = 0;
|
|
62
|
+
while (slide < previous.lines && diff.additionLines[previous.additionLineIndex + previous.lines - 1 - slide] === unit) slide++;
|
|
63
|
+
if (slide === 0) continue;
|
|
64
|
+
if (index === 1 && slide === previous.lines) continue;
|
|
65
|
+
block.additionLineIndex -= slide;
|
|
66
|
+
block.deletionLineIndex -= slide;
|
|
67
|
+
const blockAdditionEnd = block.additionLineIndex + block.additions;
|
|
68
|
+
const blockDeletionEnd = block.deletionLineIndex + block.deletions;
|
|
69
|
+
const next = hunkContent[index + 1];
|
|
70
|
+
if (next?.type === "context") {
|
|
71
|
+
next.lines += slide;
|
|
72
|
+
next.additionLineIndex = blockAdditionEnd;
|
|
73
|
+
next.deletionLineIndex = blockDeletionEnd;
|
|
74
|
+
} else hunkContent.splice(index + 1, 0, {
|
|
75
|
+
type: "context",
|
|
76
|
+
lines: slide,
|
|
77
|
+
additionLineIndex: blockAdditionEnd,
|
|
78
|
+
deletionLineIndex: blockDeletionEnd
|
|
79
|
+
});
|
|
80
|
+
previous.lines -= slide;
|
|
81
|
+
if (previous.lines === 0) {
|
|
82
|
+
hunkContent.splice(index - 1, 1);
|
|
83
|
+
index--;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function realignChangeBlock(diff, content) {
|
|
88
|
+
const { deletions, additions, deletionLineIndex, additionLineIndex } = content;
|
|
89
|
+
const pairCount = Math.min(deletions, additions);
|
|
90
|
+
const surplus = Math.abs(additions - deletions);
|
|
91
|
+
if (pairCount === 0 || surplus === 0 || pairCount * (surplus + 1) > MAX_ALIGNMENT_COMPARISONS) return null;
|
|
92
|
+
const strippedDeletions = [];
|
|
93
|
+
for (let line = 0; line < deletions; line++) strippedDeletions.push(stripWhitespace(diff.deletionLines[deletionLineIndex + line] ?? ""));
|
|
94
|
+
const strippedAdditions = [];
|
|
95
|
+
for (let line = 0; line < additions; line++) strippedAdditions.push(stripWhitespace(diff.additionLines[additionLineIndex + line] ?? ""));
|
|
96
|
+
const additionsAreLonger = additions > deletions;
|
|
97
|
+
let bestOffset = 0;
|
|
98
|
+
let bestScore = -1;
|
|
99
|
+
for (let offset = 0; offset <= surplus; offset++) {
|
|
100
|
+
let score = 0;
|
|
101
|
+
for (let pair = 0; pair < pairCount; pair++) score += lineSimilarity(strippedDeletions[pair + (additionsAreLonger ? 0 : offset)], strippedAdditions[pair + (additionsAreLonger ? offset : 0)]);
|
|
102
|
+
if (offset === 0) bestScore = score + pairCount * MIN_IMPROVEMENT_PER_PAIR;
|
|
103
|
+
else if (score > bestScore) {
|
|
104
|
+
bestScore = score;
|
|
105
|
+
bestOffset = offset;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (bestOffset === 0) return null;
|
|
109
|
+
const blocks = [];
|
|
110
|
+
const pushBlock = (blockDeletions, blockAdditions, blockDeletionIndex, blockAdditionIndex) => {
|
|
111
|
+
if (blockDeletions > 0 || blockAdditions > 0) blocks.push({
|
|
112
|
+
type: "change",
|
|
113
|
+
deletions: blockDeletions,
|
|
114
|
+
additions: blockAdditions,
|
|
115
|
+
deletionLineIndex: blockDeletionIndex,
|
|
116
|
+
additionLineIndex: blockAdditionIndex
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
if (additionsAreLonger) {
|
|
120
|
+
pushBlock(0, bestOffset, deletionLineIndex, additionLineIndex);
|
|
121
|
+
pushBlock(pairCount, pairCount, deletionLineIndex, additionLineIndex + bestOffset);
|
|
122
|
+
pushBlock(0, additions - pairCount - bestOffset, deletionLineIndex + pairCount, additionLineIndex + bestOffset + pairCount);
|
|
123
|
+
} else {
|
|
124
|
+
pushBlock(bestOffset, 0, deletionLineIndex, additionLineIndex);
|
|
125
|
+
pushBlock(pairCount, pairCount, deletionLineIndex + bestOffset, additionLineIndex);
|
|
126
|
+
pushBlock(deletions - pairCount - bestOffset, 0, deletionLineIndex + bestOffset + pairCount, additionLineIndex + pairCount);
|
|
127
|
+
}
|
|
128
|
+
return blocks;
|
|
129
|
+
}
|
|
130
|
+
const WHITESPACE = /\s+/g;
|
|
131
|
+
function stripWhitespace(line) {
|
|
132
|
+
return line.replace(WHITESPACE, "");
|
|
133
|
+
}
|
|
134
|
+
function lineSimilarity(a, b) {
|
|
135
|
+
if (a === b) return 1;
|
|
136
|
+
const maxLength = Math.max(a.length, b.length);
|
|
137
|
+
const minLength = Math.min(a.length, b.length);
|
|
138
|
+
if (minLength === 0) return 0;
|
|
139
|
+
let prefix = 0;
|
|
140
|
+
while (prefix < minLength && a[prefix] === b[prefix]) prefix++;
|
|
141
|
+
let suffix = 0;
|
|
142
|
+
while (suffix < minLength - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
|
|
143
|
+
return (prefix + suffix) / maxLength;
|
|
144
|
+
}
|
|
145
|
+
//#endregion
|
|
146
|
+
export { realignChangeContentBySimilarity, slideBlankBoundaryBlocksUp };
|
|
147
|
+
|
|
148
|
+
//# sourceMappingURL=realignChangeContent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"realignChangeContent.js","names":[],"sources":["../../src/utils/realignChangeContent.ts"],"sourcesContent":["import type {\n ChangeContent,\n ContextContent,\n FileDiffMetadata,\n Hunk,\n} from '../types';\n\n// The diff library emits one change block per replaced run, ordering every\n// deleted line before every added line. Renderers pair a block's lines\n// positionally (deletion[i] across from addition[i] in split view), so a\n// block like { deletions: 1, additions: 2 } pairs the deleted line with\n// whichever addition happens to come first — even when a later addition is\n// the edited version of it (e.g. pressing Enter above a changed line pushes\n// a blank line in front of it). These helpers re-split such blocks so the\n// most similar lines pair up and the surplus renders as pure insert/delete\n// rows at the block's edges.\n\n// Skip realignment when a block would need more than this many line\n// comparisons; pathological blocks keep the library's positional pairing.\nconst MAX_ALIGNMENT_COMPARISONS = 4096;\n\n// A shifted pairing must beat the positional one by this much per paired\n// line before the block is re-split. Near-ties (e.g. lines that merely share\n// an import-statement shape) keep the library's canonical order; the\n// realignment is meant for decisive wins like a blank or unrelated inserted\n// line displacing an edited one, where the gap approaches 1.\nconst MIN_IMPROVEMENT_PER_PAIR = 0.5;\n\n/**\n * Re-split count-mismatched change blocks in every hunk so paired lines are\n * chosen by content similarity instead of position, then slide blank-line\n * insert/delete blocks to the top of their blank run. Mutates `hunks` in\n * place; rendered row counts are unchanged (a split block covers the same\n * split/unified rows as the original).\n */\nexport function realignChangeContentBySimilarity(\n diff: Pick<FileDiffMetadata, 'hunks' | 'additionLines' | 'deletionLines'>\n): void {\n for (const hunk of diff.hunks) {\n for (let index = 0; index < hunk.hunkContent.length; index++) {\n const content = hunk.hunkContent[index];\n if (content.type !== 'change') {\n continue;\n }\n const replacement = realignChangeBlock(diff, content);\n if (replacement != null) {\n hunk.hunkContent.splice(index, 1, ...replacement);\n index += replacement.length - 1;\n }\n }\n slideBlankBoundaryBlocksUp(hunk, diff);\n }\n}\n\n/**\n * Slide pure insert/delete blocks made entirely of blank lines to the top of\n * the blank run they sit in. Adding or removing a blank line next to\n * existing blanks is ambiguous, and the diff library reports the change at\n * the run's bottom — so pressing Enter at the end of a line marks a blank\n * *below* the caret as inserted while the caret's own new line renders as\n * context. Sliding up anchors the change to the content above it (the caret\n * line after an Enter) instead.\n *\n * The slide is all-or-nothing: it only applies when the block comes to rest\n * directly beneath remaining in-hunk content. A slide that would consume the\n * hunk's entire leading context was stopped by the hunk's edge — a context\n * window cut, not the top of the blank run — and that landing spot is\n * arbitrary, so the block keeps the library's bottom-of-run anchor (which\n * sits against the content below the run). Non-blank blocks never slide, so\n * code that merely ends like its neighbor (an added function before an\n * identical `}`) keeps the library's canonical position.\n */\nexport function slideBlankBoundaryBlocksUp(\n hunk: Hunk,\n diff: Pick<FileDiffMetadata, 'additionLines' | 'deletionLines'>\n): void {\n const { hunkContent } = hunk;\n for (let index = 1; index < hunkContent.length; index++) {\n const block = hunkContent[index];\n const previous = hunkContent[index - 1];\n if (\n block.type !== 'change' ||\n (block.additions > 0 && block.deletions > 0) ||\n previous.type !== 'context'\n ) {\n continue;\n }\n const isInsert = block.additions > 0;\n const lines = isInsert ? diff.additionLines : diff.deletionLines;\n const blockStart = isInsert\n ? block.additionLineIndex\n : block.deletionLineIndex;\n const blockLength = isInsert ? block.additions : block.deletions;\n\n // Sliding through identical lines is only well-defined when the block is\n // a uniform run; require every block line to equal the first one, and\n // that line to be blank.\n const unit = lines[blockStart] ?? '';\n if (unit.trim() !== '') {\n continue;\n }\n let uniform = true;\n for (let offset = 1; offset < blockLength; offset++) {\n if (lines[blockStart + offset] !== unit) {\n uniform = false;\n break;\n }\n }\n if (!uniform) {\n continue;\n }\n\n // Slide distance: how many trailing context lines match the block's line\n // exactly (context lines are identical on both sides by definition).\n let slide = 0;\n while (\n slide < previous.lines &&\n diff.additionLines[\n previous.additionLineIndex + previous.lines - 1 - slide\n ] === unit\n ) {\n slide++;\n }\n if (slide === 0) {\n continue;\n }\n // Stopped by the hunk's leading edge rather than by content: the blank\n // run extends to (and possibly beyond) the hunk's top, so there is no\n // in-hunk line to anchor beneath. Keep the bottom-of-run position.\n if (index === 1 && slide === previous.lines) {\n continue;\n }\n\n block.additionLineIndex -= slide;\n block.deletionLineIndex -= slide;\n const blockAdditionEnd = block.additionLineIndex + block.additions;\n const blockDeletionEnd = block.deletionLineIndex + block.deletions;\n const next = hunkContent[index + 1];\n if (next?.type === 'context') {\n next.lines += slide;\n next.additionLineIndex = blockAdditionEnd;\n next.deletionLineIndex = blockDeletionEnd;\n } else {\n hunkContent.splice(index + 1, 0, {\n type: 'context',\n lines: slide,\n additionLineIndex: blockAdditionEnd,\n deletionLineIndex: blockDeletionEnd,\n });\n }\n previous.lines -= slide;\n if (previous.lines === 0) {\n hunkContent.splice(index - 1, 1);\n index--;\n }\n }\n}\n\n// Returns the split blocks for one change block, or null when the block is\n// balanced, too large to scan, or already best paired positionally.\nfunction realignChangeBlock(\n diff: Pick<FileDiffMetadata, 'additionLines' | 'deletionLines'>,\n content: ChangeContent\n): (ContextContent | ChangeContent)[] | null {\n const { deletions, additions, deletionLineIndex, additionLineIndex } =\n content;\n const pairCount = Math.min(deletions, additions);\n const surplus = Math.abs(additions - deletions);\n if (\n pairCount === 0 ||\n surplus === 0 ||\n pairCount * (surplus + 1) > MAX_ALIGNMENT_COMPARISONS\n ) {\n return null;\n }\n\n // Whitespace (indentation, formatter churn, trailing spaces, the line\n // break itself) is noise for deciding which lines pair — the rendered diff\n // still shows every whitespace change on the paired row. Strip it once per\n // line here rather than per comparison.\n const strippedDeletions: string[] = [];\n for (let line = 0; line < deletions; line++) {\n strippedDeletions.push(\n stripWhitespace(diff.deletionLines[deletionLineIndex + line] ?? '')\n );\n }\n const strippedAdditions: string[] = [];\n for (let line = 0; line < additions; line++) {\n strippedAdditions.push(\n stripWhitespace(diff.additionLines[additionLineIndex + line] ?? '')\n );\n }\n\n // Score every offset of the shorter side along the longer side and keep\n // the best one only when it decisively beats the positional pairing.\n const additionsAreLonger = additions > deletions;\n let bestOffset = 0;\n let bestScore = -1;\n for (let offset = 0; offset <= surplus; offset++) {\n let score = 0;\n for (let pair = 0; pair < pairCount; pair++) {\n score += lineSimilarity(\n strippedDeletions[pair + (additionsAreLonger ? 0 : offset)],\n strippedAdditions[pair + (additionsAreLonger ? offset : 0)]\n );\n }\n if (offset === 0) {\n bestScore = score + pairCount * MIN_IMPROVEMENT_PER_PAIR;\n } else if (score > bestScore) {\n bestScore = score;\n bestOffset = offset;\n }\n }\n if (bestOffset === 0) {\n return null;\n }\n\n const blocks: ChangeContent[] = [];\n const pushBlock = (\n blockDeletions: number,\n blockAdditions: number,\n blockDeletionIndex: number,\n blockAdditionIndex: number\n ) => {\n if (blockDeletions > 0 || blockAdditions > 0) {\n blocks.push({\n type: 'change',\n deletions: blockDeletions,\n additions: blockAdditions,\n deletionLineIndex: blockDeletionIndex,\n additionLineIndex: blockAdditionIndex,\n });\n }\n };\n if (additionsAreLonger) {\n pushBlock(0, bestOffset, deletionLineIndex, additionLineIndex);\n pushBlock(\n pairCount,\n pairCount,\n deletionLineIndex,\n additionLineIndex + bestOffset\n );\n pushBlock(\n 0,\n additions - pairCount - bestOffset,\n deletionLineIndex + pairCount,\n additionLineIndex + bestOffset + pairCount\n );\n } else {\n pushBlock(bestOffset, 0, deletionLineIndex, additionLineIndex);\n pushBlock(\n pairCount,\n pairCount,\n deletionLineIndex + bestOffset,\n additionLineIndex\n );\n pushBlock(\n deletions - pairCount - bestOffset,\n 0,\n deletionLineIndex + bestOffset + pairCount,\n additionLineIndex + pairCount\n );\n }\n return blocks;\n}\n\nconst WHITESPACE = /\\s+/g;\n\nfunction stripWhitespace(line: string): string {\n return line.replace(WHITESPACE, '');\n}\n\n// Cheap 0..1 similarity over whitespace-stripped lines: shared prefix plus\n// shared suffix over the longer length. Exact for lines that differ only in\n// whitespace, 0 for a blank against content — enough to steer pairing\n// without a real edit-distance pass.\nfunction lineSimilarity(a: string, b: string): number {\n if (a === b) {\n return 1;\n }\n const maxLength = Math.max(a.length, b.length);\n const minLength = Math.min(a.length, b.length);\n if (minLength === 0) {\n return 0;\n }\n let prefix = 0;\n while (prefix < minLength && a[prefix] === b[prefix]) {\n prefix++;\n }\n let suffix = 0;\n while (\n suffix < minLength - prefix &&\n a[a.length - 1 - suffix] === b[b.length - 1 - suffix]\n ) {\n suffix++;\n }\n return (prefix + suffix) / maxLength;\n}\n"],"mappings":";AAmBA,MAAM,4BAA4B;AAOlC,MAAM,2BAA2B;;;;;;;;AASjC,SAAgB,iCACd,MACM;CACN,KAAK,MAAM,QAAQ,KAAK,OAAO;EAC7B,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,YAAY,QAAQ,SAAS;GAC5D,MAAM,UAAU,KAAK,YAAY;GACjC,IAAI,QAAQ,SAAS,UACnB;GAEF,MAAM,cAAc,mBAAmB,MAAM,OAAO;GACpD,IAAI,eAAe,MAAM;IACvB,KAAK,YAAY,OAAO,OAAO,GAAG,GAAG,WAAW;IAChD,SAAS,YAAY,SAAS;GAChC;EACF;EACA,2BAA2B,MAAM,IAAI;CACvC;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,2BACd,MACA,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ACpB,oBAAoB,aAAa,SACnC;CACF,OAAO;EACL,UAAU,YAAY,GAAG,mBAAmB,iBAAiB;EAC7D,UACE,WACA,WACA,oBAAoB,YACpB,iBACF;EACA,UACE,YAAY,YAAY,YACxB,GACA,oBAAoB,aAAa,WACjC,oBAAoB,SACtB;CACF;CACA,OAAO;AACT;AAEA,MAAM,aAAa;AAEnB,SAAS,gBAAgB,MAAsB;CAC7C,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;AAMA,SAAS,eAAe,GAAW,GAAmB;CACpD,IAAI,MAAM,GACR,OAAO;CAET,MAAM,YAAY,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM;CAC7C,MAAM,YAAY,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM;CAC7C,IAAI,cAAc,GAChB,OAAO;CAET,IAAI,SAAS;CACb,OAAO,SAAS,aAAa,EAAE,YAAY,EAAE,SAC3C;CAEF,IAAI,SAAS;CACb,OACE,SAAS,YAAY,UACrB,EAAE,EAAE,SAAS,IAAI,YAAY,EAAE,EAAE,SAAS,IAAI,SAE9C;CAEF,QAAQ,SAAS,UAAU;AAC7B"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { DEFAULT_THEMES } from "../constants.js";
|
|
2
|
+
import { cleanLastNewline } from "./cleanLastNewline.js";
|
|
2
3
|
import { getFiletypeFromFileName } from "./getFiletypeFromFileName.js";
|
|
3
4
|
import { createTransformerWithState } from "./createTransformerWithState.js";
|
|
4
5
|
import { formatCSSVariablePrefix } from "./formatCSSVariablePrefix.js";
|
|
5
6
|
import { getHighlighterThemeStyles } from "./getHighlighterThemeStyles.js";
|
|
6
7
|
import { getLineNodes } from "./getLineNodes.js";
|
|
7
8
|
import { iterateOverDiff } from "./iterateOverDiff.js";
|
|
8
|
-
import { cleanLastNewline } from "./cleanLastNewline.js";
|
|
9
9
|
import { createDiffSpanDecoration, pushOrJoinSpan } from "./parseDiffDecorations.js";
|
|
10
10
|
import { diffChars, diffWordsWithSpace } from "diff";
|
|
11
11
|
//#region src/utils/renderDiffWithHighlighter.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveRegion.d.ts","names":[],"sources":["../../src/utils/resolveRegion.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"resolveRegion.d.ts","names":[],"sources":["../../src/utils/resolveRegion.ts"],"mappings":";;;UAWU,sBAAA;EACR,SAAA;EACA,iBAAA;EACA,eAAA;EACA,UAAA;EACA,eAAA,GAAkB,GAAG;AAAA;AAAA,iBAYP,aAAA,CACd,IAAA,EAAM,gBAAA,EACN,MAAA,EAAQ,sBAAA,GACP,gBAAA"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getHunkSideEndBoundary, getHunkSideStartBoundary } from "./getHunkSideBoundaries.js";
|
|
1
2
|
//#region src/utils/resolveRegion.ts
|
|
2
3
|
function resolveRegion(diff, target) {
|
|
3
4
|
const { resolution, hunkIndex, startContentIndex, endContentIndex, indexesToDelete = /* @__PURE__ */ new Set() } = target;
|
|
@@ -31,7 +32,7 @@ function resolveRegion(diff, target) {
|
|
|
31
32
|
const updatesEOFState = hunkIndex === hunks.length - 1 && endContentIndex === currentHunk.hunkContent.length - 1;
|
|
32
33
|
const shouldProcessCollapsedContext = !diff.isPartial;
|
|
33
34
|
for (const [index, hunk] of hunks.entries()) {
|
|
34
|
-
processCollapsedContext(diff, resolvedDiff, cursor, hunk.
|
|
35
|
+
processCollapsedContext(diff, resolvedDiff, cursor, getHunkSideStartBoundary(hunk.deletionStart, hunk.deletionCount) - hunk.collapsedBefore, getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount) - hunk.collapsedBefore, hunk.collapsedBefore, shouldProcessCollapsedContext);
|
|
35
36
|
const newHunk = {
|
|
36
37
|
...hunk,
|
|
37
38
|
hunkContent: [],
|
|
@@ -88,10 +89,25 @@ function resolveRegion(diff, target) {
|
|
|
88
89
|
newHunk.noEOFCRAdditions = noEOFCR;
|
|
89
90
|
newHunk.noEOFCRDeletions = noEOFCR;
|
|
90
91
|
}
|
|
92
|
+
if (newHunk.additionCount === 0) {
|
|
93
|
+
newHunk.additionStart--;
|
|
94
|
+
if (!diff.isPartial) newHunk.additionLineIndex--;
|
|
95
|
+
}
|
|
96
|
+
if (newHunk.deletionCount === 0) {
|
|
97
|
+
newHunk.deletionStart--;
|
|
98
|
+
if (!diff.isPartial) newHunk.deletionLineIndex--;
|
|
99
|
+
}
|
|
91
100
|
resolvedDiff.hunks.push(newHunk);
|
|
92
101
|
}
|
|
93
102
|
const finalHunk = hunks.at(-1);
|
|
94
|
-
if (finalHunk != null && !diff.isPartial)
|
|
103
|
+
if (finalHunk != null && !diff.isPartial) {
|
|
104
|
+
const finalDeletionEnd = getHunkSideEndBoundary(finalHunk.deletionStart, finalHunk.deletionCount);
|
|
105
|
+
const finalAdditionEnd = getHunkSideEndBoundary(finalHunk.additionStart, finalHunk.additionCount);
|
|
106
|
+
const trailingContext = Math.min(deletionLines.length - finalDeletionEnd, additionLines.length - finalAdditionEnd);
|
|
107
|
+
pushCollapsedContextLines(resolvedDiff, deletionLines, additionLines, finalDeletionEnd, finalAdditionEnd, trailingContext);
|
|
108
|
+
cursor.splitLineCount += trailingContext;
|
|
109
|
+
cursor.unifiedLineCount += trailingContext;
|
|
110
|
+
}
|
|
95
111
|
resolvedDiff.splitLineCount = cursor.splitLineCount;
|
|
96
112
|
resolvedDiff.unifiedLineCount = cursor.unifiedLineCount;
|
|
97
113
|
return resolvedDiff;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveRegion.js","names":[],"sources":["../../src/utils/resolveRegion.ts"],"sourcesContent":["import type {\n ChangeContent,\n ContextContent,\n FileDiffMetadata,\n Hunk,\n} from '../types';\n\ninterface RegionResolutionTarget {\n hunkIndex: number;\n startContentIndex: number;\n endContentIndex: number;\n resolution: 'deletions' | 'additions' | 'both';\n indexesToDelete?: Set<number>;\n}\n\ninterface CursorState {\n nextAdditionLineIndex: number;\n nextDeletionLineIndex: number;\n nextAdditionStart: number;\n nextDeletionStart: number;\n splitLineCount: number;\n unifiedLineCount: number;\n}\n\nexport function resolveRegion(\n diff: FileDiffMetadata,\n target: RegionResolutionTarget\n): FileDiffMetadata {\n const {\n resolution,\n hunkIndex,\n startContentIndex,\n endContentIndex,\n indexesToDelete = new Set(),\n } = target;\n const currentHunk = diff.hunks[hunkIndex];\n if (currentHunk == null) {\n console.error({ diff, hunkIndex });\n throw new Error(`resolveRegion: Invalid hunk index: ${hunkIndex}`);\n }\n\n if (\n startContentIndex < 0 ||\n endContentIndex >= currentHunk.hunkContent.length ||\n startContentIndex > endContentIndex\n ) {\n throw new Error(\n `resolveRegion: Invalid content range, ${startContentIndex}, ${endContentIndex}`\n );\n }\n\n const { hunks, additionLines, deletionLines } = diff;\n const resolvedDiff: FileDiffMetadata = {\n ...diff,\n hunks: [],\n deletionLines: [],\n additionLines: [],\n splitLineCount: 0,\n unifiedLineCount: 0,\n cacheKey:\n diff.cacheKey != null\n ? `${diff.cacheKey}:${resolution[0]}-${hunkIndex}:${startContentIndex}-${endContentIndex}`\n : undefined,\n };\n\n const cursor: CursorState = {\n nextAdditionLineIndex: 0,\n nextDeletionLineIndex: 0,\n nextAdditionStart: 1,\n nextDeletionStart: 1,\n splitLineCount: 0,\n unifiedLineCount: 0,\n };\n const updatesEOFState =\n hunkIndex === hunks.length - 1 &&\n endContentIndex === currentHunk.hunkContent.length - 1;\n const shouldProcessCollapsedContext = !diff.isPartial;\n\n for (const [index, hunk] of hunks.entries()) {\n processCollapsedContext(\n diff,\n resolvedDiff,\n cursor,\n hunk.deletionLineIndex - hunk.collapsedBefore,\n hunk.additionLineIndex - hunk.collapsedBefore,\n hunk.collapsedBefore,\n shouldProcessCollapsedContext\n );\n\n const newHunk: Hunk = {\n ...hunk,\n hunkContent: [],\n additionStart: cursor.nextAdditionStart,\n deletionStart: cursor.nextDeletionStart,\n additionLineIndex: cursor.nextAdditionLineIndex,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionCount: 0,\n deletionCount: 0,\n deletionLines: 0,\n additionLines: 0,\n splitLineStart: cursor.splitLineCount,\n unifiedLineStart: cursor.unifiedLineCount,\n splitLineCount: 0,\n unifiedLineCount: 0,\n };\n\n for (const [contentIndex, content] of hunk.hunkContent.entries()) {\n // If we are outside of the targeted hunk or content region\n if (\n index !== hunkIndex ||\n contentIndex < startContentIndex ||\n contentIndex > endContentIndex\n ) {\n pushContentLinesToDiff(\n content,\n resolvedDiff,\n deletionLines,\n additionLines\n );\n const newContent = {\n ...content,\n additionLineIndex: cursor.nextAdditionLineIndex,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n };\n newHunk.hunkContent.push(newContent);\n advanceCursor(newContent, cursor, newHunk);\n }\n // If we are at an index to delete, replace with an empty context node\n else if (indexesToDelete.has(contentIndex)) {\n newHunk.hunkContent.push({\n type: 'context',\n lines: 0,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionLineIndex: cursor.nextAdditionLineIndex,\n });\n }\n // There's nothing to `resolve` with context nodes, so just push them as\n // they are\n else if (content.type === 'context') {\n pushContentLinesToDiff(\n content,\n resolvedDiff,\n deletionLines,\n additionLines\n );\n const newContent: ContextContent = {\n ...content,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionLineIndex: cursor.nextAdditionLineIndex,\n };\n newHunk.hunkContent.push(newContent);\n advanceCursor(newContent, cursor, newHunk);\n }\n // Looks like we have a change to resolve and push\n else {\n pushResolveLinesToDiff(\n resolution,\n content,\n resolvedDiff,\n deletionLines,\n additionLines\n );\n const newContent: ContextContent = {\n type: 'context',\n lines:\n resolution === 'deletions'\n ? content.deletions\n : resolution === 'additions'\n ? content.additions\n : content.deletions + content.additions,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionLineIndex: cursor.nextAdditionLineIndex,\n };\n newHunk.hunkContent.push(newContent);\n advanceCursor(newContent, cursor, newHunk);\n }\n }\n\n if (index === hunkIndex && updatesEOFState) {\n const noEOFCR =\n resolution === 'deletions'\n ? hunk.noEOFCRDeletions\n : hunk.noEOFCRAdditions;\n newHunk.noEOFCRAdditions = noEOFCR;\n newHunk.noEOFCRDeletions = noEOFCR;\n }\n\n resolvedDiff.hunks.push(newHunk);\n }\n\n const finalHunk = hunks.at(-1);\n if (finalHunk != null && !diff.isPartial) {\n pushCollapsedContextLines(\n resolvedDiff,\n deletionLines,\n additionLines,\n finalHunk.deletionLineIndex + finalHunk.deletionCount,\n finalHunk.additionLineIndex + finalHunk.additionCount,\n Math.min(\n deletionLines.length -\n (finalHunk.deletionLineIndex + finalHunk.deletionCount),\n additionLines.length -\n (finalHunk.additionLineIndex + finalHunk.additionCount)\n )\n );\n }\n\n resolvedDiff.splitLineCount = cursor.splitLineCount;\n resolvedDiff.unifiedLineCount = cursor.unifiedLineCount;\n\n return resolvedDiff;\n}\n\nfunction pushCollapsedContextLines(\n diff: FileDiffMetadata,\n deletionLines: string[],\n additionLines: string[],\n deletionLineIndex: number,\n additionLineIndex: number,\n lineCount: number\n) {\n for (let index = 0; index < lineCount; index++) {\n const deletionLine = deletionLines[deletionLineIndex + index];\n const additionLine = additionLines[additionLineIndex + index];\n if (deletionLine == null || additionLine == null) {\n throw new Error(\n 'pushCollapsedContextLines: missing collapsed context line'\n );\n }\n diff.deletionLines.push(deletionLine);\n diff.additionLines.push(additionLine);\n }\n}\n\n// Partial patches track omitted context in `collapsedBefore`, but those lines do\n// not exist in the diff's line arrays. Keep the virtual row counts and file\n// positions in sync without inventing hidden lines.\nfunction processCollapsedContext(\n sourceDiff: FileDiffMetadata,\n resolvedDiff: FileDiffMetadata,\n cursor: CursorState,\n deletionLineIndex: number,\n additionLineIndex: number,\n lineCount: number,\n shouldProcessContent: boolean\n) {\n if (lineCount <= 0) {\n return;\n }\n\n if (shouldProcessContent) {\n pushCollapsedContextLines(\n resolvedDiff,\n sourceDiff.deletionLines,\n sourceDiff.additionLines,\n deletionLineIndex,\n additionLineIndex,\n lineCount\n );\n cursor.nextAdditionLineIndex += lineCount;\n cursor.nextDeletionLineIndex += lineCount;\n }\n\n cursor.nextAdditionStart += lineCount;\n cursor.nextDeletionStart += lineCount;\n cursor.splitLineCount += lineCount;\n cursor.unifiedLineCount += lineCount;\n}\n\nfunction pushContentLinesToDiff(\n content: ContextContent | ChangeContent,\n diff: FileDiffMetadata,\n deletionLines: string[],\n additionLines: string[]\n) {\n if (content.type === 'context') {\n for (let i = 0; i < content.lines; i++) {\n const line = additionLines[content.additionLineIndex + i];\n if (line == null) {\n console.error({ additionLines, content, i });\n throw new Error('pushContentLinesToDiff: Context line does not exist');\n }\n diff.deletionLines.push(line);\n diff.additionLines.push(line);\n }\n } else {\n const len = Math.max(content.deletions, content.additions);\n for (let i = 0; i < len; i++) {\n if (i < content.deletions) {\n const line = deletionLines[content.deletionLineIndex + i];\n if (line == null) {\n console.error({ deletionLines, content, i });\n throw new Error(\n 'pushContentLinesToDiff: Deletion line does not exist'\n );\n }\n diff.deletionLines.push(line);\n }\n if (i < content.additions) {\n const line = additionLines[content.additionLineIndex + i];\n if (line == null) {\n console.error({ additionLines, content, i });\n throw new Error(\n 'pushContentLinesToDiff: Addition line does not exist'\n );\n }\n diff.additionLines.push(line);\n }\n }\n }\n}\n\nfunction pushResolveLinesToDiff(\n resolution: 'deletions' | 'additions' | 'both',\n content: ChangeContent,\n diff: FileDiffMetadata,\n deletionLines: string[],\n additionLines: string[]\n) {\n if (resolution === 'deletions' || resolution === 'both') {\n for (let i = 0; i < content.deletions; i++) {\n const line = deletionLines[content.deletionLineIndex + i];\n if (line == null) {\n console.error({ deletionLines, content, i });\n throw new Error('pushResolveLinesToDiff: Deletion line does not exist');\n }\n diff.deletionLines.push(line);\n diff.additionLines.push(line);\n }\n }\n if (resolution === 'additions' || resolution === 'both') {\n for (let i = 0; i < content.additions; i++) {\n const line = additionLines[content.additionLineIndex + i];\n if (line == null) {\n console.error({ additionLines, content, i });\n throw new Error('pushResolveLinesToDiff: Addition line does not exist');\n }\n diff.deletionLines.push(line);\n diff.additionLines.push(line);\n }\n }\n}\n\nfunction advanceCursor(\n content: ChangeContent | ContextContent,\n cursor: CursorState,\n hunk: Hunk\n) {\n if (content.type === 'context') {\n cursor.nextAdditionLineIndex += content.lines;\n cursor.nextDeletionLineIndex += content.lines;\n cursor.nextAdditionStart += content.lines;\n cursor.nextDeletionStart += content.lines;\n cursor.splitLineCount += content.lines;\n cursor.unifiedLineCount += content.lines;\n\n hunk.additionCount += content.lines;\n hunk.deletionCount += content.lines;\n hunk.splitLineCount += content.lines;\n hunk.unifiedLineCount += content.lines;\n } else {\n cursor.nextAdditionLineIndex += content.additions;\n cursor.nextDeletionLineIndex += content.deletions;\n cursor.nextAdditionStart += content.additions;\n cursor.nextDeletionStart += content.deletions;\n cursor.splitLineCount += Math.max(content.deletions, content.additions);\n cursor.unifiedLineCount += content.deletions + content.additions;\n\n hunk.deletionCount += content.deletions;\n hunk.deletionLines += content.deletions;\n hunk.additionCount += content.additions;\n hunk.additionLines += content.additions;\n hunk.splitLineCount += Math.max(content.deletions, content.additions);\n hunk.unifiedLineCount += content.deletions + content.additions;\n }\n}\n"],"mappings":";AAwBA,SAAgB,cACd,MACA,QACkB;CAClB,MAAM,EACJ,YACA,WACA,mBACA,iBACA,kCAAkB,IAAI,IAAI,MACxB;CACJ,MAAM,cAAc,KAAK,MAAM;CAC/B,IAAI,eAAe,MAAM;EACvB,QAAQ,MAAM;GAAE;GAAM;EAAU,CAAC;EACjC,MAAM,IAAI,MAAM,sCAAsC,WAAW;CACnE;CAEA,IACE,oBAAoB,KACpB,mBAAmB,YAAY,YAAY,UAC3C,oBAAoB,iBAEpB,MAAM,IAAI,MACR,yCAAyC,kBAAkB,IAAI,iBACjE;CAGF,MAAM,EAAE,OAAO,eAAe,kBAAkB;CAChD,MAAM,eAAiC;EACrC,GAAG;EACH,OAAO,CAAC;EACR,eAAe,CAAC;EAChB,eAAe,CAAC;EAChB,gBAAgB;EAChB,kBAAkB;EAClB,UACE,KAAK,YAAY,OACb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,kBAAkB,KAAK,IAAI,QAAQ,WAAW,QAAQ,SAAS;EACpE,KAAK,oBAAoB,QAAQ,YAAY,QAAQ;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"resolveRegion.js","names":[],"sources":["../../src/utils/resolveRegion.ts"],"sourcesContent":["import type {\n ChangeContent,\n ContextContent,\n FileDiffMetadata,\n Hunk,\n} from '../types';\nimport {\n getHunkSideEndBoundary,\n getHunkSideStartBoundary,\n} from './getHunkSideBoundaries';\n\ninterface RegionResolutionTarget {\n hunkIndex: number;\n startContentIndex: number;\n endContentIndex: number;\n resolution: 'deletions' | 'additions' | 'both';\n indexesToDelete?: Set<number>;\n}\n\ninterface CursorState {\n nextAdditionLineIndex: number;\n nextDeletionLineIndex: number;\n nextAdditionStart: number;\n nextDeletionStart: number;\n splitLineCount: number;\n unifiedLineCount: number;\n}\n\nexport function resolveRegion(\n diff: FileDiffMetadata,\n target: RegionResolutionTarget\n): FileDiffMetadata {\n const {\n resolution,\n hunkIndex,\n startContentIndex,\n endContentIndex,\n indexesToDelete = new Set(),\n } = target;\n const currentHunk = diff.hunks[hunkIndex];\n if (currentHunk == null) {\n console.error({ diff, hunkIndex });\n throw new Error(`resolveRegion: Invalid hunk index: ${hunkIndex}`);\n }\n\n if (\n startContentIndex < 0 ||\n endContentIndex >= currentHunk.hunkContent.length ||\n startContentIndex > endContentIndex\n ) {\n throw new Error(\n `resolveRegion: Invalid content range, ${startContentIndex}, ${endContentIndex}`\n );\n }\n\n const { hunks, additionLines, deletionLines } = diff;\n const resolvedDiff: FileDiffMetadata = {\n ...diff,\n hunks: [],\n deletionLines: [],\n additionLines: [],\n splitLineCount: 0,\n unifiedLineCount: 0,\n cacheKey:\n diff.cacheKey != null\n ? `${diff.cacheKey}:${resolution[0]}-${hunkIndex}:${startContentIndex}-${endContentIndex}`\n : undefined,\n };\n\n const cursor: CursorState = {\n nextAdditionLineIndex: 0,\n nextDeletionLineIndex: 0,\n nextAdditionStart: 1,\n nextDeletionStart: 1,\n splitLineCount: 0,\n unifiedLineCount: 0,\n };\n const updatesEOFState =\n hunkIndex === hunks.length - 1 &&\n endContentIndex === currentHunk.hunkContent.length - 1;\n const shouldProcessCollapsedContext = !diff.isPartial;\n\n for (const [index, hunk] of hunks.entries()) {\n processCollapsedContext(\n diff,\n resolvedDiff,\n cursor,\n getHunkSideStartBoundary(hunk.deletionStart, hunk.deletionCount) -\n hunk.collapsedBefore,\n getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount) -\n hunk.collapsedBefore,\n hunk.collapsedBefore,\n shouldProcessCollapsedContext\n );\n\n const newHunk: Hunk = {\n ...hunk,\n hunkContent: [],\n additionStart: cursor.nextAdditionStart,\n deletionStart: cursor.nextDeletionStart,\n additionLineIndex: cursor.nextAdditionLineIndex,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionCount: 0,\n deletionCount: 0,\n deletionLines: 0,\n additionLines: 0,\n splitLineStart: cursor.splitLineCount,\n unifiedLineStart: cursor.unifiedLineCount,\n splitLineCount: 0,\n unifiedLineCount: 0,\n };\n\n for (const [contentIndex, content] of hunk.hunkContent.entries()) {\n // If we are outside of the targeted hunk or content region\n if (\n index !== hunkIndex ||\n contentIndex < startContentIndex ||\n contentIndex > endContentIndex\n ) {\n pushContentLinesToDiff(\n content,\n resolvedDiff,\n deletionLines,\n additionLines\n );\n const newContent = {\n ...content,\n additionLineIndex: cursor.nextAdditionLineIndex,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n };\n newHunk.hunkContent.push(newContent);\n advanceCursor(newContent, cursor, newHunk);\n }\n // If we are at an index to delete, replace with an empty context node\n else if (indexesToDelete.has(contentIndex)) {\n newHunk.hunkContent.push({\n type: 'context',\n lines: 0,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionLineIndex: cursor.nextAdditionLineIndex,\n });\n }\n // There's nothing to `resolve` with context nodes, so just push them as\n // they are\n else if (content.type === 'context') {\n pushContentLinesToDiff(\n content,\n resolvedDiff,\n deletionLines,\n additionLines\n );\n const newContent: ContextContent = {\n ...content,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionLineIndex: cursor.nextAdditionLineIndex,\n };\n newHunk.hunkContent.push(newContent);\n advanceCursor(newContent, cursor, newHunk);\n }\n // Looks like we have a change to resolve and push\n else {\n pushResolveLinesToDiff(\n resolution,\n content,\n resolvedDiff,\n deletionLines,\n additionLines\n );\n const newContent: ContextContent = {\n type: 'context',\n lines:\n resolution === 'deletions'\n ? content.deletions\n : resolution === 'additions'\n ? content.additions\n : content.deletions + content.additions,\n deletionLineIndex: cursor.nextDeletionLineIndex,\n additionLineIndex: cursor.nextAdditionLineIndex,\n };\n newHunk.hunkContent.push(newContent);\n advanceCursor(newContent, cursor, newHunk);\n }\n }\n\n if (index === hunkIndex && updatesEOFState) {\n const noEOFCR =\n resolution === 'deletions'\n ? hunk.noEOFCRDeletions\n : hunk.noEOFCRAdditions;\n newHunk.noEOFCRAdditions = noEOFCR;\n newHunk.noEOFCRDeletions = noEOFCR;\n }\n\n if (newHunk.additionCount === 0) {\n newHunk.additionStart--;\n if (!diff.isPartial) {\n newHunk.additionLineIndex--;\n }\n }\n if (newHunk.deletionCount === 0) {\n newHunk.deletionStart--;\n if (!diff.isPartial) {\n newHunk.deletionLineIndex--;\n }\n }\n\n resolvedDiff.hunks.push(newHunk);\n }\n\n const finalHunk = hunks.at(-1);\n if (finalHunk != null && !diff.isPartial) {\n const finalDeletionEnd = getHunkSideEndBoundary(\n finalHunk.deletionStart,\n finalHunk.deletionCount\n );\n const finalAdditionEnd = getHunkSideEndBoundary(\n finalHunk.additionStart,\n finalHunk.additionCount\n );\n const trailingContext = Math.min(\n deletionLines.length - finalDeletionEnd,\n additionLines.length - finalAdditionEnd\n );\n pushCollapsedContextLines(\n resolvedDiff,\n deletionLines,\n additionLines,\n finalDeletionEnd,\n finalAdditionEnd,\n trailingContext\n );\n cursor.splitLineCount += trailingContext;\n cursor.unifiedLineCount += trailingContext;\n }\n\n resolvedDiff.splitLineCount = cursor.splitLineCount;\n resolvedDiff.unifiedLineCount = cursor.unifiedLineCount;\n\n return resolvedDiff;\n}\n\nfunction pushCollapsedContextLines(\n diff: FileDiffMetadata,\n deletionLines: string[],\n additionLines: string[],\n deletionLineIndex: number,\n additionLineIndex: number,\n lineCount: number\n) {\n for (let index = 0; index < lineCount; index++) {\n const deletionLine = deletionLines[deletionLineIndex + index];\n const additionLine = additionLines[additionLineIndex + index];\n if (deletionLine == null || additionLine == null) {\n throw new Error(\n 'pushCollapsedContextLines: missing collapsed context line'\n );\n }\n diff.deletionLines.push(deletionLine);\n diff.additionLines.push(additionLine);\n }\n}\n\n// Partial patches track omitted context in `collapsedBefore`, but those lines do\n// not exist in the diff's line arrays. Keep the virtual row counts and file\n// positions in sync without inventing hidden lines.\nfunction processCollapsedContext(\n sourceDiff: FileDiffMetadata,\n resolvedDiff: FileDiffMetadata,\n cursor: CursorState,\n deletionLineIndex: number,\n additionLineIndex: number,\n lineCount: number,\n shouldProcessContent: boolean\n) {\n if (lineCount <= 0) {\n return;\n }\n\n if (shouldProcessContent) {\n pushCollapsedContextLines(\n resolvedDiff,\n sourceDiff.deletionLines,\n sourceDiff.additionLines,\n deletionLineIndex,\n additionLineIndex,\n lineCount\n );\n cursor.nextAdditionLineIndex += lineCount;\n cursor.nextDeletionLineIndex += lineCount;\n }\n\n cursor.nextAdditionStart += lineCount;\n cursor.nextDeletionStart += lineCount;\n cursor.splitLineCount += lineCount;\n cursor.unifiedLineCount += lineCount;\n}\n\nfunction pushContentLinesToDiff(\n content: ContextContent | ChangeContent,\n diff: FileDiffMetadata,\n deletionLines: string[],\n additionLines: string[]\n) {\n if (content.type === 'context') {\n for (let i = 0; i < content.lines; i++) {\n const line = additionLines[content.additionLineIndex + i];\n if (line == null) {\n console.error({ additionLines, content, i });\n throw new Error('pushContentLinesToDiff: Context line does not exist');\n }\n diff.deletionLines.push(line);\n diff.additionLines.push(line);\n }\n } else {\n const len = Math.max(content.deletions, content.additions);\n for (let i = 0; i < len; i++) {\n if (i < content.deletions) {\n const line = deletionLines[content.deletionLineIndex + i];\n if (line == null) {\n console.error({ deletionLines, content, i });\n throw new Error(\n 'pushContentLinesToDiff: Deletion line does not exist'\n );\n }\n diff.deletionLines.push(line);\n }\n if (i < content.additions) {\n const line = additionLines[content.additionLineIndex + i];\n if (line == null) {\n console.error({ additionLines, content, i });\n throw new Error(\n 'pushContentLinesToDiff: Addition line does not exist'\n );\n }\n diff.additionLines.push(line);\n }\n }\n }\n}\n\nfunction pushResolveLinesToDiff(\n resolution: 'deletions' | 'additions' | 'both',\n content: ChangeContent,\n diff: FileDiffMetadata,\n deletionLines: string[],\n additionLines: string[]\n) {\n if (resolution === 'deletions' || resolution === 'both') {\n for (let i = 0; i < content.deletions; i++) {\n const line = deletionLines[content.deletionLineIndex + i];\n if (line == null) {\n console.error({ deletionLines, content, i });\n throw new Error('pushResolveLinesToDiff: Deletion line does not exist');\n }\n diff.deletionLines.push(line);\n diff.additionLines.push(line);\n }\n }\n if (resolution === 'additions' || resolution === 'both') {\n for (let i = 0; i < content.additions; i++) {\n const line = additionLines[content.additionLineIndex + i];\n if (line == null) {\n console.error({ additionLines, content, i });\n throw new Error('pushResolveLinesToDiff: Addition line does not exist');\n }\n diff.deletionLines.push(line);\n diff.additionLines.push(line);\n }\n }\n}\n\nfunction advanceCursor(\n content: ChangeContent | ContextContent,\n cursor: CursorState,\n hunk: Hunk\n) {\n if (content.type === 'context') {\n cursor.nextAdditionLineIndex += content.lines;\n cursor.nextDeletionLineIndex += content.lines;\n cursor.nextAdditionStart += content.lines;\n cursor.nextDeletionStart += content.lines;\n cursor.splitLineCount += content.lines;\n cursor.unifiedLineCount += content.lines;\n\n hunk.additionCount += content.lines;\n hunk.deletionCount += content.lines;\n hunk.splitLineCount += content.lines;\n hunk.unifiedLineCount += content.lines;\n } else {\n cursor.nextAdditionLineIndex += content.additions;\n cursor.nextDeletionLineIndex += content.deletions;\n cursor.nextAdditionStart += content.additions;\n cursor.nextDeletionStart += content.deletions;\n cursor.splitLineCount += Math.max(content.deletions, content.additions);\n cursor.unifiedLineCount += content.deletions + content.additions;\n\n hunk.deletionCount += content.deletions;\n hunk.deletionLines += content.deletions;\n hunk.additionCount += content.additions;\n hunk.additionLines += content.additions;\n hunk.splitLineCount += Math.max(content.deletions, content.additions);\n hunk.unifiedLineCount += content.deletions + content.additions;\n }\n}\n"],"mappings":";;AA4BA,SAAgB,cACd,MACA,QACkB;CAClB,MAAM,EACJ,YACA,WACA,mBACA,iBACA,kCAAkB,IAAI,IAAI,MACxB;CACJ,MAAM,cAAc,KAAK,MAAM;CAC/B,IAAI,eAAe,MAAM;EACvB,QAAQ,MAAM;GAAE;GAAM;EAAU,CAAC;EACjC,MAAM,IAAI,MAAM,sCAAsC,WAAW;CACnE;CAEA,IACE,oBAAoB,KACpB,mBAAmB,YAAY,YAAY,UAC3C,oBAAoB,iBAEpB,MAAM,IAAI,MACR,yCAAyC,kBAAkB,IAAI,iBACjE;CAGF,MAAM,EAAE,OAAO,eAAe,kBAAkB;CAChD,MAAM,eAAiC;EACrC,GAAG;EACH,OAAO,CAAC;EACR,eAAe,CAAC;EAChB,eAAe,CAAC;EAChB,gBAAgB;EAChB,kBAAkB;EAClB,UACE,KAAK,YAAY,OACb,GAAG,KAAK,SAAS,GAAG,WAAW,GAAG,GAAG,UAAU,GAAG,kBAAkB,GAAG,oBACvE,KAAA;CACR;CAEA,MAAM,SAAsB;EAC1B,uBAAuB;EACvB,uBAAuB;EACvB,mBAAmB;EACnB,mBAAmB;EACnB,gBAAgB;EAChB,kBAAkB;CACpB;CACA,MAAM,kBACJ,cAAc,MAAM,SAAS,KAC7B,oBAAoB,YAAY,YAAY,SAAS;CACvD,MAAM,gCAAgC,CAAC,KAAK;CAE5C,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GAAG;EAC3C,wBACE,MACA,cACA,QACA,yBAAyB,KAAK,eAAe,KAAK,aAAa,IAC7D,KAAK,iBACP,yBAAyB,KA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1
|
-
import {
|
|
1
|
+
import { InteractionManagerMode, OnTokenEventProps } from "../managers/InteractionManager.js";
|
|
2
2
|
|
|
3
3
|
//#region src/utils/shouldUseTokenTransformer.d.ts
|
|
4
|
-
|
|
4
|
+
interface ShouldUseTokenTransformerProps<TMode extends InteractionManagerMode> {
|
|
5
|
+
onTokenClick?(props: OnTokenEventProps<TMode>, event: MouseEvent): unknown;
|
|
6
|
+
onTokenEnter?(props: OnTokenEventProps<TMode>, event: PointerEvent): unknown;
|
|
7
|
+
onTokenLeave?(props: OnTokenEventProps<TMode>, event: PointerEvent): unknown;
|
|
5
8
|
useTokenTransformer?: boolean;
|
|
6
|
-
}
|
|
9
|
+
}
|
|
10
|
+
declare function shouldUseTokenTransformer<TMode extends 'file' | 'diff' = 'file'>(options: ShouldUseTokenTransformerProps<TMode> | undefined): boolean;
|
|
7
11
|
//#endregion
|
|
8
12
|
export { shouldUseTokenTransformer };
|
|
9
13
|
//# sourceMappingURL=shouldUseTokenTransformer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shouldUseTokenTransformer.d.ts","names":[],"sources":["../../src/utils/shouldUseTokenTransformer.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"shouldUseTokenTransformer.d.ts","names":[],"sources":["../../src/utils/shouldUseTokenTransformer.ts"],"mappings":";;;UAKU,8BAAA,eAA6C,sBAAA;EACrD,YAAA,EAAc,KAAA,EAAO,iBAAA,CAAkB,KAAA,GAAQ,KAAA,EAAO,UAAA;EACtD,YAAA,EAAc,KAAA,EAAO,iBAAA,CAAkB,KAAA,GAAQ,KAAA,EAAO,YAAA;EACtD,YAAA,EAAc,KAAA,EAAO,iBAAA,CAAkB,KAAA,GAAQ,KAAA,EAAO,YAAA;EACtD,mBAAA;AAAA;AAAA,iBAKc,yBAAA,yCAEd,OAAA,EAAS,8BAA8B,CAAC,KAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/utils/shouldUseTokenTransformer.ts
|
|
2
2
|
function shouldUseTokenTransformer(options) {
|
|
3
|
-
return options
|
|
3
|
+
return options?.useTokenTransformer === true || options?.onTokenClick != null || options?.onTokenEnter != null || options?.onTokenLeave != null;
|
|
4
4
|
}
|
|
5
5
|
//#endregion
|
|
6
6
|
export { shouldUseTokenTransformer };
|