Repository navigation
Handle all status codes - #135
Conversation
stageFile() now invalidates the snapshot/cache/index for the affected repository root so that subsequent getUnmergedFileStatus() calls return fresh data instead of stale pre-staging status. DU/UD test assertions now call refreshUnmergedFilesSnapshot() before querying getUnmergedFileStatus() to ensure the VS Code Git API state is re-read after the index has changed.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughBroadens conflict handling from UU-only to seven Git unmerged statuses (UU, AA, DD, AU, UA, DU, UD); rewrites gitIntegration to API-first with CLI fallbacks and per-root caching; adds add-only and delete‑vs‑modify resolver flows, API-based staging, test hooks, and multiple end-to-end regression tests. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Extension as VSCode Extension
participant GitLayer as Git API / CLI
participant Resolver as NotebookConflictResolver
participant FS as File System
User->>Extension: trigger findConflicts / resolve action
Extension->>GitLayer: check active file unmerged status (API or CLI)
GitLayer-->>Extension: GitUnmergedStatus (UU|AA|DD|AU|UA|DU|UD)
alt active file unmerged
Extension->>Resolver: resolve single file (status)
else scan workspace
Extension->>GitLayer: list unmerged files
GitLayer-->>Extension: unmerged files + statuses
Extension->>Resolver: discover & present conflicts
end
Resolver->>User: prompt (add-only / delete-vs-modify / 3-way)
User-->>Resolver: chosen action
Resolver->>FS: write or delete resolved notebook content
Resolver->>GitLayer: stageFile(path)
GitLayer-->>Resolver: stage result
Resolver-->>Extension: emit onDidResolveConflictWithDetails
Extension->>Extension: updateStatusBar()
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (9)
src/gitIntegration.ts (5)
1330-1332: Unusedcontentparameter inisSemanticConflict.The
contentparameter is accepted but never read — the function delegates entirely toisUnmergedFile(filePath). If callers are still passing content, it's dead code. Consider removing the parameter (breaking change) or adding a_prefix to signal intent.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 1330 - 1332, The isSemanticConflict function currently declares a second parameter content that is never used; either remove the parameter from isSemanticConflict signature and update all callers to stop passing content, or mark it intentionally unused by renaming it to _content (or prefix with _) in the isSemanticConflict(filePath: string, _content: string) declaration and update any lint exemptions; locate the function isSemanticConflict and the helper isUnmergedFile to apply the change and update call sites accordingly to avoid unused-parameter warnings or breaking changes.
621-656:getGitApi()promise is cached forever — no recovery if the extension activates later.Once
gitApiPromiseresolves tonull(e.g., the git extension wasn't active at first call), subsequent calls reuse the cachednullforever. If the git extension activates later in the session, the API will remain unavailable. For a long-lived extension this could be an issue.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 621 - 656, getGitApi currently stores whatever the inner promise resolves to in gitApiPromise, so a first call that resolves to null (git extension missing/inactive) is cached forever; change it so gitApiPromise is only retained when a valid GitAPI is obtained. Specifically, inside getGitApi's inner async function (the closure that references extension/isActive/activate and returns extension.exports?.getAPI(1) or null), ensure that if the result is null you clear/unset gitApiPromise before returning so future calls will retry activation/acquisition, but if a non-null GitAPI is returned keep the cache; also handle the activate()/getAPI() catch paths similarly (clear cache on failure) to allow recovery when the git extension becomes available later.
1353-1363: UseexecFileAsyncinstead ofexecAsyncto avoid shell interpolation.
mergeHeadis interpolated into a shell command string via template literal. Whilegit rev-parse MERGE_HEADnormally returns a hex SHA, usingexecFileAsyncwith an args array is safer and avoids any shell metacharacter risk.Proposed fix
- const { stdout } = await execAsync('git rev-parse MERGE_HEAD', { cwd: gitRoot }); + const { stdout } = await execFileAsync('git', ['rev-parse', 'MERGE_HEAD'], { cwd: gitRoot, encoding: 'utf8' }); const mergeHead = stdout.trim(); - try { - const { stdout: branchName } = await execAsync( - `git name-rev --name-only ${mergeHead}`, - { cwd: gitRoot } + const { stdout: branchName } = await execFileAsync( + 'git', ['name-rev', '--name-only', mergeHead], + { cwd: gitRoot, encoding: 'utf8' } );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 1353 - 1363, The code calls execAsync to run "git name-rev --name-only ${mergeHead}", interpolating mergeHead into a shell command; switch this to execFileAsync and pass the command and arguments as an array to avoid shell interpolation: call execFileAsync('git', ['name-rev', '--name-only', mergeHead], { cwd: gitRoot }) instead of execAsync with a template string, keeping the existing try/catch and fallback that returns mergeHead.substring(0, 7); also ensure execFileAsync is imported/available alongside execAsync in the module.
941-958: CLI always takes precedence over the API — API query results are effectively wasted when CLI succeeds.
queryUnmergedFilesForRootqueries both the API and CLI, but if CLI succeeds (the common case), the API results are discarded. The API query (and itscacheRepositoryside-effect) still runs, so it's not purely wasted, but the redundant work could be avoided by querying CLI first and only falling back to the API.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 941 - 958, queryUnmergedFilesForRoot currently always invokes the API path first and discards its results when the CLI succeeds; change it to call queryUnmergedFilesFromGitCli(gitRoot) first and if that returns a non-null result return it immediately, only then fall back to calling getRepositoryForPath(gitRoot) and queryUnmergedFilesFromRepository(repository) (and keep the warnApiStrictOnce(getGitRootCacheKey(...)) behavior when repository is missing). This avoids running the API/cacheRepository side-effects when the CLI is sufficient while preserving the existing fallback and warning logic.
591-597: Import theStatusenum instead of hardcoding numeric values.The numeric constants (12–18) are correct and match the VS Code Git extension's
Statusenum, but hardcoding creates fragility. Replace with enum member references: addStatusto the import from./typings/gitand useStatus.ADDED_BY_US,Status.BOTH_MODIFIED, etc., in themapGitStatusToUnmergedStatusfunction. This makes the mapping self-documenting and safeguards against future enum changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 591 - 597, Replace the hardcoded numeric git status constants with the Status enum: add Status to the import from ./typings/git and update mapGitStatusToUnmergedStatus to use Status.ADDED_BY_US, Status.ADDED_BY_THEM, Status.DELETED_BY_US, Status.DELETED_BY_THEM, Status.BOTH_ADDED, Status.BOTH_DELETED, and Status.BOTH_MODIFIED instead of the numeric constants (GIT_STATUS_*). Remove the now-unused numeric constants and ensure all switch/case or comparisons in mapGitStatusToUnmergedStatus reference the enum members so the mapping is self-documenting and resilient to enum changes.src/tests/unmergedStatusMatrix.test.ts (1)
77-90: Minor:\\nin source produces a literal backslash-n, not a newline.Line 86:
`${label}\\n`yields the two-character sequence\n, not an actual newline. Notebook cell source lines conventionally end with a real newline (\n). This doesn't impact the test's correctness (it's testing status detection, not content), but if any downstream assertion ever checks source normalization, it could be surprising.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/unmergedStatusMatrix.test.ts` around lines 77 - 90, The notebookContent helper is embedding a literal backslash-n in the cell source (`\`${label}\\n\``) instead of a real newline; update the source value in notebookContent so the string ends with an actual newline (e.g., use `${label}\n` or a template literal with a real newline) so the cells' source lines follow conventional newline termination while keeping the rest of notebookContent unchanged.src/resolver.ts (2)
298-310: Good: DD status correctly skipped in discovery, but consider logging the unmerged status for non-DD entries.The
hasSemanticConflictsexpression (file.status === 'UU' || file.status === 'AA' || file.status === 'AU' || file.status === 'UA') is repeated in three places (lines 253, 268, 308). Extracting a helper (e.g.,isSemanticCapableStatus(status)) would reduce duplication and make updates easier.Proposed helper
+const SEMANTIC_CAPABLE_STATUSES = new Set<gitIntegration.GitUnmergedStatus>(['UU', 'AA', 'AU', 'UA']); + +function isSemanticCapableStatus(status: gitIntegration.GitUnmergedStatus): boolean { + return SEMANTIC_CAPABLE_STATUSES.has(status); +}Then replace the repeated inline checks with
isSemanticCapableStatus(status)/isSemanticCapableStatus(file.status).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/resolver.ts` around lines 298 - 310, Extract the repeated status-check logic into a small helper like isSemanticCapableStatus(status) that returns true for 'UU','AA','AU','UA', then replace the three inline expressions that set hasSemanticConflicts (the checks against file.status currently used where withConflicts objects are created and the other two places in resolver.ts) with calls to isSemanticCapableStatus(file.status); ensure the helper is exported or defined near the top of resolver.ts and update all references to use it so the DD skip logic and unmergedStatus assignment remain unchanged.
518-528: Error-matching regex indeleteFileIfPresentis fragile.The pattern
/not.*found|entry.*not.*found/irelies on specific error message wording from VS Code's file system provider. Different providers (remote, virtual) may use different phrasing. Consider catching the error by its code (e.g.,FileSystemError.FileNotFoundorvscode.FileSystemErrorwithcode === 'FileNotFound') for more robust handling.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/resolver.ts` around lines 518 - 528, The current deleteFileIfPresent implementation uses a fragile regex on the error.message; update it to detect VS Code filesystem "not found" errors by checking the error type and code: when catching errors from vscode.workspace.fs.delete in deleteFileIfPresent, test if error is an instance of vscode.FileSystemError and whether error.code === 'FileNotFound' (or matches the FileNotFound sentinel on vscode.FileSystemError) and return in that case; otherwise rethrow the error. This replaces the /not.*found|entry.*not.*found/i message check and makes handling robust across providers.src/tests/duUdPickOneRegression.test.ts (1)
14-14: Remove the unusedGitStagetype.
GitStageis declared but never referenced in the file. It's dead code.🗑️ Proposed removal
-type GitStage = '1' | '2' | '3'; type DeleteConflictStatus = 'DU' | 'UD';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/duUdPickOneRegression.test.ts` at line 14, Remove the unused type declaration GitStage (type GitStage = '1' | '2' | '3';) from the test file since it is never referenced; delete that line and run TypeScript compile/tests to ensure no remaining references to GitStage remain.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/gitIntegration.ts`:
- Around line 1330-1332: The isSemanticConflict function currently declares a
second parameter content that is never used; either remove the parameter from
isSemanticConflict signature and update all callers to stop passing content, or
mark it intentionally unused by renaming it to _content (or prefix with _) in
the isSemanticConflict(filePath: string, _content: string) declaration and
update any lint exemptions; locate the function isSemanticConflict and the
helper isUnmergedFile to apply the change and update call sites accordingly to
avoid unused-parameter warnings or breaking changes.
- Around line 621-656: getGitApi currently stores whatever the inner promise
resolves to in gitApiPromise, so a first call that resolves to null (git
extension missing/inactive) is cached forever; change it so gitApiPromise is
only retained when a valid GitAPI is obtained. Specifically, inside getGitApi's
inner async function (the closure that references extension/isActive/activate
and returns extension.exports?.getAPI(1) or null), ensure that if the result is
null you clear/unset gitApiPromise before returning so future calls will retry
activation/acquisition, but if a non-null GitAPI is returned keep the cache;
also handle the activate()/getAPI() catch paths similarly (clear cache on
failure) to allow recovery when the git extension becomes available later.
- Around line 1353-1363: The code calls execAsync to run "git name-rev
--name-only ${mergeHead}", interpolating mergeHead into a shell command; switch
this to execFileAsync and pass the command and arguments as an array to avoid
shell interpolation: call execFileAsync('git', ['name-rev', '--name-only',
mergeHead], { cwd: gitRoot }) instead of execAsync with a template string,
keeping the existing try/catch and fallback that returns mergeHead.substring(0,
7); also ensure execFileAsync is imported/available alongside execAsync in the
module.
- Around line 941-958: queryUnmergedFilesForRoot currently always invokes the
API path first and discards its results when the CLI succeeds; change it to call
queryUnmergedFilesFromGitCli(gitRoot) first and if that returns a non-null
result return it immediately, only then fall back to calling
getRepositoryForPath(gitRoot) and queryUnmergedFilesFromRepository(repository)
(and keep the warnApiStrictOnce(getGitRootCacheKey(...)) behavior when
repository is missing). This avoids running the API/cacheRepository side-effects
when the CLI is sufficient while preserving the existing fallback and warning
logic.
- Around line 591-597: Replace the hardcoded numeric git status constants with
the Status enum: add Status to the import from ./typings/git and update
mapGitStatusToUnmergedStatus to use Status.ADDED_BY_US, Status.ADDED_BY_THEM,
Status.DELETED_BY_US, Status.DELETED_BY_THEM, Status.BOTH_ADDED,
Status.BOTH_DELETED, and Status.BOTH_MODIFIED instead of the numeric constants
(GIT_STATUS_*). Remove the now-unused numeric constants and ensure all
switch/case or comparisons in mapGitStatusToUnmergedStatus reference the enum
members so the mapping is self-documenting and resilient to enum changes.
In `@src/resolver.ts`:
- Around line 298-310: Extract the repeated status-check logic into a small
helper like isSemanticCapableStatus(status) that returns true for
'UU','AA','AU','UA', then replace the three inline expressions that set
hasSemanticConflicts (the checks against file.status currently used where
withConflicts objects are created and the other two places in resolver.ts) with
calls to isSemanticCapableStatus(file.status); ensure the helper is exported or
defined near the top of resolver.ts and update all references to use it so the
DD skip logic and unmergedStatus assignment remain unchanged.
- Around line 518-528: The current deleteFileIfPresent implementation uses a
fragile regex on the error.message; update it to detect VS Code filesystem "not
found" errors by checking the error type and code: when catching errors from
vscode.workspace.fs.delete in deleteFileIfPresent, test if error is an instance
of vscode.FileSystemError and whether error.code === 'FileNotFound' (or matches
the FileNotFound sentinel on vscode.FileSystemError) and return in that case;
otherwise rethrow the error. This replaces the /not.*found|entry.*not.*found/i
message check and makes handling robust across providers.
In `@src/tests/duUdPickOneRegression.test.ts`:
- Line 14: Remove the unused type declaration GitStage (type GitStage = '1' |
'2' | '3';) from the test file since it is never referenced; delete that line
and run TypeScript compile/tests to ensure no remaining references to GitStage
remain.
In `@src/tests/unmergedStatusMatrix.test.ts`:
- Around line 77-90: The notebookContent helper is embedding a literal
backslash-n in the cell source (`\`${label}\\n\``) instead of a real newline;
update the source value in notebookContent so the string ends with an actual
newline (e.g., use `${label}\n` or a template literal with a real newline) so
the cells' source lines follow conventional newline termination while keeping
the rest of notebookContent unchanged.
On Windows, resolveGitRootsForPathHint can discover the same git root under different path representations (API vs CLI, 8.3 short names vs long names). getUnmergedFiles now deduplicates by normalized real path to prevent the same file appearing twice. Also relax the status indicator test to accept any conflict count rather than exactly "1 conflict".
Adds regression test for AU (Added by Us) and UA (Added by Them) status codes, covering both apply-and-stage and cancel paths. Ensures that user confirmation is required before staging and that cancellation preserves the unmerged state.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/tests/auUaPickOneRegression.test.ts (1)
117-120: Prefer JSON-structure assertions over raw string equality for notebooks.The current assertion can miss structure-level issues and is formatting-sensitive. Parse both notebooks and compare objects (plus targeted checks on
cells[].source,cells[].outputs, andmetadata).As per coding guidelines: "Always parse raw JSON in .ipynb files; conflicts may be in cells[].source, cells[].outputs, or metadata—never assume they're only in code".💡 Suggested refactor
- const actual = fs.readFileSync(uri.fsPath, 'utf8'); - assert.strictEqual(actual, expectedContent, `Unexpected file content after apply-and-stage (${context})`); + const actualRaw = fs.readFileSync(uri.fsPath, 'utf8'); + const actualNotebook = JSON.parse(actualRaw); + const expectedNotebook = JSON.parse(expectedContent); + assert.deepStrictEqual( + actualNotebook, + expectedNotebook, + `Unexpected notebook JSON after apply-and-stage (${context})` + );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/auUaPickOneRegression.test.ts` around lines 117 - 120, Replace the raw string equality check for .ipynb files by parsing both the actual file content and expectedContent as JSON and comparing their structures: after reading actual (variable uri/fsPath -> actual) and having expectedContent, JSON.parse both, then assert deep-equality of the notebook objects and add targeted assertions for notebook.cells[].source, notebook.cells[].outputs and notebook.metadata to catch structural/format differences; keep the existing context variable for assertion messages and update the assertions around assert.strictEqual(actual, expectedContent, ...) and any use of actual to use the parsed objects instead.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/gitIntegration.ts`:
- Around line 1345-1348: getCurrentBranch currently returns null whenever
getRepositoryForPath/VS Code Git API is unavailable; restore a CLI fallback by
attempting to resolve the branch via the Git CLI when
repository?.state.HEAD?.name is falsy. Update getCurrentBranch to first try
repository.state.HEAD?.name (as it does) and if that yields null/undefined call
the existing git execution helper (or spawn git) to run a rev-parse/abbrev-ref
for the filePath dir, parse the output and return the branch name (or null on
error); reference getCurrentBranch and getRepositoryForPath to locate where to
add the fallback.
- Around line 621-656: getGitApi currently permanently caches a promise that may
resolve to null; change it so only successful non-null GitAPI results remain
cached: create a localPromise (e.g., const local = (async ()=>{ ... })()),
assign gitApiPromise = local, await the result (const api = await local), and if
api === null set gitApiPromise = undefined before returning; keep all existing
activation/try-catch logic inside the local async so you still return the same
types but allow retries on future calls when initial lookups fail.
---
Nitpick comments:
In `@src/tests/auUaPickOneRegression.test.ts`:
- Around line 117-120: Replace the raw string equality check for .ipynb files by
parsing both the actual file content and expectedContent as JSON and comparing
their structures: after reading actual (variable uri/fsPath -> actual) and
having expectedContent, JSON.parse both, then assert deep-equality of the
notebook objects and add targeted assertions for notebook.cells[].source,
notebook.cells[].outputs and notebook.metadata to catch structural/format
differences; keep the existing context variable for assertion messages and
update the assertions around assert.strictEqual(actual, expectedContent, ...)
and any use of actual to use the parsed objects instead.
ℹ️ Review info
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/gitIntegration.tssrc/tests/auUaPickOneRegression.test.tssrc/tests/registry.tssrc/tests/statusIndicatorsRegression.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/tests/statusIndicatorsRegression.test.ts
- This may not fix CI as intended - Coderabbit fixes - getGitApi null caching fix - getCurrentBranch: Restores the CLI fallback
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/gitIntegration.ts (2)
830-876: Consider settingmaxBufferfor large repositories.The
execFileAsynccall forgit statusdoesn't specifymaxBuffer. For repositories with many files, this could hit the default buffer limit (1MB in Node.js).💡 Suggested improvement
const { stdout } = await execFileAsync( 'git', ['status', '--porcelain', '-z', '--untracked-files=no'], - { cwd: gitRoot, encoding: 'utf8' } + { cwd: gitRoot, encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 } );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 830 - 876, The execFileAsync call in queryUnmergedFilesFromGitCli can overflow Node's default stdout buffer for large repos; update the execFileAsync invocation (the call that runs 'git status' inside queryUnmergedFilesFromGitCli) to pass an options object that includes a larger maxBuffer (e.g., increase from default to a safe size like 10MB or configurable via constant), preserving cwd and encoding, so the git status output won't cause a buffer overflow and the catch branch remains for other errors.
1408-1419: PreferexecFileAsyncoverexecAsyncfor Git commands with dynamic arguments.Using
execAsyncwith template literals (git name-rev --name-only ${mergeHead}) could theoretically be exploited ifmergeHeadcontained shell metacharacters. WhilemergeHeadcomes from trusted Git output, usingexecFileAsyncwith argument arrays is safer and more consistent with the rest of the codebase.🛡️ Suggested fix
const { stdout } = await execAsync('git rev-parse MERGE_HEAD', { cwd: gitRoot }); const mergeHead = stdout.trim(); try { - const { stdout: branchName } = await execAsync( - `git name-rev --name-only ${mergeHead}`, - { cwd: gitRoot } - ); + const { stdout: branchName } = await execFileAsync( + 'git', + ['name-rev', '--name-only', mergeHead], + { cwd: gitRoot, encoding: 'utf8' } + ); return branchName.trim();Also consider updating the
git rev-parse MERGE_HEADcall similarly:- const { stdout } = await execAsync('git rev-parse MERGE_HEAD', { cwd: gitRoot }); + const { stdout } = await execFileAsync('git', ['rev-parse', 'MERGE_HEAD'], { cwd: gitRoot, encoding: 'utf8' });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 1408 - 1419, Replace the execAsync calls that interpolate mergeHead with execFileAsync and pass git arguments as an array to avoid shell interpolation: capture MERGE_HEAD with execFileAsync (replace the `execAsync('git rev-parse MERGE_HEAD', { cwd: gitRoot })` call) and then call execFileAsync for name-rev using the args ['name-rev','--name-only', mergeHead] (replacing the `execAsync(\`git name-rev --name-only ${mergeHead}\`, { cwd: gitRoot })` call); keep the same trimming/error-handling logic around the branchName and mergeHead fallback in this block.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/gitIntegration.ts`:
- Around line 1369-1371: The function isSemanticConflict currently declares an
unused parameter content; remove the content parameter from the
isSemanticConflict signature so it only accepts filePath and returns
Promise<boolean> by delegating to isUnmergedFile(filePath). After changing the
signature, update all call sites that pass a content argument to stop passing it
(or pass only the filePath), and run type checks to fix any compilation errors
where the old two-arg signature was expected; leave isUnmergedFile usage
unchanged.
---
Nitpick comments:
In `@src/gitIntegration.ts`:
- Around line 830-876: The execFileAsync call in queryUnmergedFilesFromGitCli
can overflow Node's default stdout buffer for large repos; update the
execFileAsync invocation (the call that runs 'git status' inside
queryUnmergedFilesFromGitCli) to pass an options object that includes a larger
maxBuffer (e.g., increase from default to a safe size like 10MB or configurable
via constant), preserving cwd and encoding, so the git status output won't cause
a buffer overflow and the catch branch remains for other errors.
- Around line 1408-1419: Replace the execAsync calls that interpolate mergeHead
with execFileAsync and pass git arguments as an array to avoid shell
interpolation: capture MERGE_HEAD with execFileAsync (replace the
`execAsync('git rev-parse MERGE_HEAD', { cwd: gitRoot })` call) and then call
execFileAsync for name-rev using the args ['name-rev','--name-only', mergeHead]
(replacing the `execAsync(\`git name-rev --name-only ${mergeHead}\`, { cwd:
gitRoot })` call); keep the same trimming/error-handling logic around the
branchName and mergeHead fallback in this block.
| export async function isSemanticConflict(filePath: string, content: string): Promise<boolean> { | ||
| return await isUnmergedFile(filePath); | ||
| return isUnmergedFile(filePath); | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
rg -n "isSemanticConflict" --type ts -B2 -A2Repository: Avni2000/MergeNB
Length of output: 394
🏁 Script executed:
rg "isSemanticConflict\s*\(" --type tsRepository: Avni2000/MergeNB
Length of output: 177
🏁 Script executed:
rg "isSemanticConflict" --type-listRepository: Avni2000/MergeNB
Length of output: 449
🏁 Script executed:
rg "isSemanticConflict" -lRepository: Avni2000/MergeNB
Length of output: 81
🏁 Script executed:
rg "isSemanticConflict" -A5 -B5 --type ts --type tsxRepository: Avni2000/MergeNB
Length of output: 87
🏁 Script executed:
fd -e tsx -e ts | xargs rg "isSemanticConflict" 2>/dev/nullRepository: Avni2000/MergeNB
Length of output: 177
🏁 Script executed:
sed -n '1360,1380p' src/gitIntegration.tsRepository: Avni2000/MergeNB
Length of output: 662
🏁 Script executed:
find . -type d -name webviewRepository: Avni2000/MergeNB
Length of output: 42
🏁 Script executed:
ls -la src/ | head -20Repository: Avni2000/MergeNB
Length of output: 1172
🏁 Script executed:
rg "semantic" -i --type tsRepository: Avni2000/MergeNB
Length of output: 15726
Remove unused content parameter from isSemanticConflict.
The content parameter is declared but never used. The function only checks unmerged file status via isUnmergedFile(filePath) and does not inspect the content. Remove the parameter to avoid confusion about the function's actual behavior.
Suggested fix
-export async function isSemanticConflict(filePath: string, content: string): Promise<boolean> {
+export async function isSemanticConflict(filePath: string): Promise<boolean> {
return isUnmergedFile(filePath);
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/gitIntegration.ts` around lines 1369 - 1371, The function
isSemanticConflict currently declares an unused parameter content; remove the
content parameter from the isSemanticConflict signature so it only accepts
filePath and returns Promise<boolean> by delegating to isUnmergedFile(filePath).
After changing the signature, update all call sites that pass a content argument
to stop passing it (or pass only the filePath), and run type checks to fix any
compilation errors where the old two-arg signature was expected; leave
isUnmergedFile usage unchanged.
|
@coderabbitai Can you investigate why all of the tests - but only on ubuntu 22.04 with vscode 1.80 - are failing due to the websocket not starting? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain
🏁 Script executed: Length of output: 11886 🏁 Script executed: Length of output: 38182 🏁 Script executed: Length of output: 8295 🏁 Script executed: Length of output: 7405
ProblemCommit 187c47f added function resolveRealPath(p: string): string {
try {
return fs.realpathSync(p); // ← BLOCKING operation
} catch {
return p;
}
}Why it breaks WebSocket startupHere's the sequence that causes the failure:
On Ubuntu 22.04 with VSCode 1.80, the filesystem operations are likely slower or there are more files to process, making the blocking long enough to prevent the server from starting. SolutionReplace async function resolveRealPath(p: string): Promise<string> {
try {
return await fs.promises.realpath(p);
} catch {
return p;
}
}Then update const seenPaths = new Set<string>();
for (const files of unmergedFilesPerRoot) {
for (const file of files) {
const key = normalizeForComparison(await resolveRealPath(file.path));
if (seenPaths.has(key)) {
continue;
}
seenPaths.add(key);
unmergedFiles.push(file);
}
}This will prevent blocking the event loop and allow the WebSocket server to start properly on all platforms. 🐰 |
- unmergedStatusMatrix creates staged-only entries (status_*.ipynb) that don’t exist on disk. - realpath fails for those, so dedupe can fall back to differing absolute forms (short/long root, namespace-prefixed paths), producing duplicate rows (14 instead of 7).
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/gitIntegration.ts (1)
1439-1441:⚠️ Potential issue | 🟡 MinorUnused
contentparameter still present inisSemanticConflict.The
contentparameter is declared but not used - the function only delegates toisUnmergedFile(filePath). This was flagged in a previous review.💡 Suggested fix
-export async function isSemanticConflict(filePath: string, content: string): Promise<boolean> { +export async function isSemanticConflict(filePath: string): Promise<boolean> { return isUnmergedFile(filePath); }Note: You'll need to update any call sites that pass the
contentargument.
,🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 1439 - 1441, The isSemanticConflict function currently declares an unused parameter content and simply returns isUnmergedFile(filePath); remove the unused content parameter from the isSemanticConflict signature and all its call sites (and TypeScript types) so it becomes isSemanticConflict(filePath: string): Promise<boolean>, or if the intent was to use content implement the semantic-conflict check using content instead of delegating—ensure consistency between the function implementation, its exported type, and every caller (update imports/overloads/tests accordingly).
🧹 Nitpick comments (4)
src/gitIntegration.ts (4)
1279-1292: The root path calculation from depth is clever but warrants a comment.The logic computes the repository root by walking up
depthdirectories fromfile.pathbased on the number of path segments inrepoPath. This handles the case where the file doesn't exist on disk (staged-only). Consider adding a brief comment explaining the intent:// Prefer repoPath + canonical root to dedupe reliably even when the file // is staged-only and missing from the working tree (realpath would fail). if (file.repoPath && isRepoRelativePath(file.repoPath)) { const depth = splitPathSegments(file.repoPath).length; + // Compute root by walking up 'depth' directories from the full path const rootPath = depth > 0 ? path.resolve(file.path, ...Array(depth).fill('..')) : path.dirname(file.path);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 1279 - 1292, The rootPath calculation that walks up `depth` directories from `file.path` (using `splitPathSegments(file.repoPath)` to compute `depth` and building `rootPath` with `path.resolve(file.path, ...Array(depth).fill('..'))`) is subtle and needs a short clarifying comment; update the block in the function where `isRepoRelativePath(file.repoPath)` is checked (the variables `depth`, `rootPath`, and use of `resolveRealPathCached`/`normalizeForComparison`) to include a concise comment explaining that we walk up `depth` segments to compute the repository root for staged-only or missing-on-disk files so `realpath` can be resolved reliably and keys are deduplicated with `repoPath`.
473-496: Mixed sync/async realpath usage may still block the event loop in some code paths.While
resolveRealPath(async) was added to fix the WebSocket startup issue, several functions still useresolveRealPathSync:
gitRelativePath(line 495)getNormalizedPathInfo(line 541)pathsLikelySameFileToTarget(line 547)isPathWithinRoot(line 576)getGitRootCacheKey(line 626)getStagePathCandidates(lines 1175, 1182-1183)The critical
getUnmergedFilespath now uses async resolution (lines 1264-1273), which addresses the reported issue. However, if these sync helpers are called frequently elsewhere, they could still cause minor blocking.Consider documenting which functions are safe to call on hot paths vs. which are for one-off operations, or gradually migrating remaining sync usages to async equivalents.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 473 - 496, Several helpers still call the synchronous resolveRealPathSync causing potential event-loop blocking (e.g., gitRelativePath, getNormalizedPathInfo, pathsLikelySameFileToTarget, isPathWithinRoot, getGitRootCacheKey, getStagePathCandidates); replace these usages with the async resolveRealPath variant and make the hosting functions async (propagate Promise returns upward) or, if a function is truly one-off and non-hot-path, add a clear comment and keep sync; ensure callers of gitRelativePath and the listed functions are updated to await the async versions or are refactored to run off the main event loop (e.g., background task), and add tests to cover Windows short-path behavior after the change.
860-868: Porcelain format validation may be overly strict for some edge cases.The check
entry.length < 4 || entry[2] !== ' 'assumes standard "XY filename" format. However, for renamed files, Git uses "XY oldname\0newname" format with an extra null-separated field. While this may not apply to unmerged statuses, consider adding a comment explaining the expected format.for (const entry of entries) { + // Expected format: "XY filename" where XY is two-character status code + // and position 2 is a space separator if (entry.length < 4 || entry[2] !== ' ') { continue; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 860 - 868, The loop that parses git porcelain entries (the for ... of entries loop) currently uses the condition entry.length < 4 || entry[2] !== ' ' to validate the "XY filename" format before slicing statusCode via entry.slice(0, 2) and calling isUnmergedStatus; add a concise inline comment above that check explaining the expected porcelain format (XY<space>filename), note the edge-case where git uses a null-separated "XY oldname\0newname" form for renames, and state that this check is intentionally strict because we only need the first two status chars for unmerged detection (isUnmergedStatus). If you prefer to handle renames explicitly, mention how to detect the '\0' separator and still extract entry.slice(0,2) safely, but do not change the parsing logic unless necessary.
607-616: Import and use the Status enum from git.d.ts instead of hard-coded constants.The numeric constants (
GIT_STATUS_ADDED_BY_US = 12, etc.) duplicate values already defined in theStatusenum exported fromsrc/typings/git.d.ts. Instead of maintaining separate constants, importStatusfrom the type definitions and reference enum values directly (e.g.,Status.BOTH_MODIFIED). This eliminates duplication, ensures consistency if the enum changes, and makes the code more maintainable.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 607 - 616, Replace the hard-coded numeric constants (GIT_STATUS_ADDED_BY_US, GIT_STATUS_ADDED_BY_THEM, GIT_STATUS_DELETED_BY_US, GIT_STATUS_DELETED_BY_THEM, GIT_STATUS_BOTH_ADDED, GIT_STATUS_BOTH_DELETED, GIT_STATUS_BOTH_MODIFIED) with the Status enum from the typings (import Status from the git.d.ts export) and reference Status.BOTH_MODIFIED, Status.BOTH_ADDED, etc., wherever those constants are used; remove the redundant constant declarations and update UNMERGED_STATUSES to use the appropriate enum string values if needed, ensuring you add the import for Status at the top of gitIntegration.ts and replace all occurrences of the old constant names with the corresponding Status.<NAME> enum members.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/gitIntegration.ts`:
- Around line 1439-1441: The isSemanticConflict function currently declares an
unused parameter content and simply returns isUnmergedFile(filePath); remove the
unused content parameter from the isSemanticConflict signature and all its call
sites (and TypeScript types) so it becomes isSemanticConflict(filePath: string):
Promise<boolean>, or if the intent was to use content implement the
semantic-conflict check using content instead of delegating—ensure consistency
between the function implementation, its exported type, and every caller (update
imports/overloads/tests accordingly).
---
Nitpick comments:
In `@src/gitIntegration.ts`:
- Around line 1279-1292: The rootPath calculation that walks up `depth`
directories from `file.path` (using `splitPathSegments(file.repoPath)` to
compute `depth` and building `rootPath` with `path.resolve(file.path,
...Array(depth).fill('..'))`) is subtle and needs a short clarifying comment;
update the block in the function where `isRepoRelativePath(file.repoPath)` is
checked (the variables `depth`, `rootPath`, and use of
`resolveRealPathCached`/`normalizeForComparison`) to include a concise comment
explaining that we walk up `depth` segments to compute the repository root for
staged-only or missing-on-disk files so `realpath` can be resolved reliably and
keys are deduplicated with `repoPath`.
- Around line 473-496: Several helpers still call the synchronous
resolveRealPathSync causing potential event-loop blocking (e.g.,
gitRelativePath, getNormalizedPathInfo, pathsLikelySameFileToTarget,
isPathWithinRoot, getGitRootCacheKey, getStagePathCandidates); replace these
usages with the async resolveRealPath variant and make the hosting functions
async (propagate Promise returns upward) or, if a function is truly one-off and
non-hot-path, add a clear comment and keep sync; ensure callers of
gitRelativePath and the listed functions are updated to await the async versions
or are refactored to run off the main event loop (e.g., background task), and
add tests to cover Windows short-path behavior after the change.
- Around line 860-868: The loop that parses git porcelain entries (the for ...
of entries loop) currently uses the condition entry.length < 4 || entry[2] !== '
' to validate the "XY filename" format before slicing statusCode via
entry.slice(0, 2) and calling isUnmergedStatus; add a concise inline comment
above that check explaining the expected porcelain format (XY<space>filename),
note the edge-case where git uses a null-separated "XY oldname\0newname" form
for renames, and state that this check is intentionally strict because we only
need the first two status chars for unmerged detection (isUnmergedStatus). If
you prefer to handle renames explicitly, mention how to detect the '\0'
separator and still extract entry.slice(0,2) safely, but do not change the
parsing logic unless necessary.
- Around line 607-616: Replace the hard-coded numeric constants
(GIT_STATUS_ADDED_BY_US, GIT_STATUS_ADDED_BY_THEM, GIT_STATUS_DELETED_BY_US,
GIT_STATUS_DELETED_BY_THEM, GIT_STATUS_BOTH_ADDED, GIT_STATUS_BOTH_DELETED,
GIT_STATUS_BOTH_MODIFIED) with the Status enum from the typings (import Status
from the git.d.ts export) and reference Status.BOTH_MODIFIED, Status.BOTH_ADDED,
etc., wherever those constants are used; remove the redundant constant
declarations and update UNMERGED_STATUSES to use the appropriate enum string
values if needed, ensuring you add the import for Status at the top of
gitIntegration.ts and replace all occurrences of the old constant names with the
corresponding Status.<NAME> enum members.
New Features
Bug Fixes
Documentation
Tests