Repository navigation
Handle jupyter removal - #88
Conversation
Co-authored-by: Avni2000 <[email protected]>
Co-authored-by: Avni2000 <[email protected]>
- Hack to fix json conflict by simply showing the status bar whenever any file has conflicts
- Shouldn't depend on user installing nbdime
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📝 WalkthroughWalkthroughAdds a workspace-level nbdime guard: a new CI workflow and test runner, extension refactor for background conflict monitoring and status-bar picker, comprehensive git-config detection/remediation with a public ensureSupportedMergeTool API and exported UnsupportedMergeToolError, plus extension-host tests for the guard. Changes
Sequence DiagramsequenceDiagram
participant User as User
participant Ext as Extension
participant GitInt as GitIntegration
participant GitCfg as GitConfig
participant UI as UI
User->>Ext: activate extension / trigger resolve
Ext->>GitInt: ensureSupportedMergeTool(gitRootOrPath)
GitInt->>GitCfg: listGitConfigEntries / detect incompatible keys
GitCfg-->>GitInt: incompatible entries?
alt incompatibilities found
GitInt->>UI: showUnsupportedMergeToolGuidance(context)
UI->>User: present actions (auto-fix / show commands)
User->>UI: select action
alt auto-fix
UI->>GitInt: request auto-fix
GitInt->>GitCfg: applyGitConfigFix(commands)
GitCfg-->>GitInt: confirmation
GitInt-->>Ext: resolved
else show commands
GitInt-->>UI: provide terminal commands
UI->>User: display commands
end
else no issues
GitInt-->>Ext: ok to proceed
end
Ext->>User: allow merge/resolution actions
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 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.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/gitIntegration.ts (2)
499-501:⚠️ Potential issue | 🟠 MajorClarify/expand unmerged status handling (UU-only vs all conflict codes).
Right now
isUnmergedStatus()returns true forUU,AA,DDonly. That’s either:
- too broad if you intend “semantic notebook conflicts” to be
UUonly, or- too narrow if you want to catch all unmerged conflict states (
AA, AU, UA, DD, DU, UD, UU).This affects workspace-wide conflict discovery.
Proposed diff (option A: UU-only)
function isUnmergedStatus(status: string): boolean { - return status === 'UU' || status === 'AA' || status === 'DD'; + return status === 'UU'; }Proposed diff (option B: all unmerged conflict codes)
function isUnmergedStatus(status: string): boolean { - return status === 'UU' || status === 'AA' || status === 'DD'; + return ( + status === 'DD' || + status === 'AU' || + status === 'UD' || + status === 'UA' || + status === 'DU' || + status === 'AA' || + status === 'UU' + ); }As per coding guidelines, “Detect merge conflicts using Git
UUstatus for semantic conflicts in notebooks.”
24-30:⚠️ Potential issue | 🔴 CriticalFix shell injection risk in
applyGitConfigFixand correct invalidpackage.jsontype.The optional VSCode import using
require()is compatible with your"module": "Node16"tsconfig target. However, two issues require immediate attention:
Critical: Shell injection vulnerability in
applyGitConfigFix(lines 237–257). Git config keys and section names must be quoted or escaped when passed to shell commands. Currently, commands like:git config --${scope} --unset-all ${key}will fail or inject commands if keys contain spaces, quotes, or special characters. Use
execFilewith argv arrays instead of shell command strings:await execFile('git', ['config', `--${scope}`, '--unset-all', key], { cwd: gitRoot })Major: Invalid
package.jsontype. The field"type": "git"is not a valid npm package type. It should be"type": "commonjs"(or"module"if switching to ESM). This may cause module resolution issues with bundling and require patterns.Additionally, the
isUnmergedStatusfunction (line 500) detectsAAandDDalongsideUU, but your guidelines emphasize "UU status for semantic conflicts." Clarify whether the intent is UU-only or all unmerged states.
🤖 Fix all issues with AI agents
In @.github/workflows/vscode-nbdime-guard.yml:
- Around line 1-36: Update the workflow's Node.js to an LTS release (change the
node-version under the "Use Node.js" step from 18 to 20 or 22) and add explicit
least-privilege workflow permissions at the top-level; also pin nbdime when
installing (e.g., in the "Install npm deps" step ensure nbdime is installed at a
fixed version instead of unpinned latest). Locate the job named "nbdime-guard"
and the steps labeled "Use Node.js" and "Install npm deps" to make the
node-version and nbdime pin changes, and add a top-level permissions block
granting only the minimum required permissions for the workflow.
In `@src/gitIntegration.ts`:
- Around line 360-369: The current "Show terminal fix commands" flow sends raw
multiline commands to the VS Code terminal using
terminal.sendText(terminalCommands.join('\n'), false), which can execute any
non-comment line; update the code that handles the terminal path (the block that
calls getNbdimeDisableCommands and then terminal.sendText, and the analogous
block around lines 263-267) to first transform terminalCommands into a safe
preview by commenting out any executable lines (e.g., map each line: if it's
non-empty and does not already start with '#' then prefix with '# ' while
preserving blank lines), optionally prepend a one-line header like "# Commands
(commented) — remove leading '# ' to run", and then call terminal.sendText on
that commentedCommands string so nothing runs unintentionally.
- Around line 585-646: The getUnmergedFiles function currently prints the full
`git status --porcelain` output and per-line parsing which is too noisy; change
logging to only emit minimal info by default and gate verbose logs behind an
environment flag (e.g. process.env.DEBUG_GIT_INTEGRATION). Specifically, in
getUnmergedFiles replace the unconditional console.log of stdout, the lines
count log, and the per-line debug logs (the logs that include line, status, path
and the "-> UNMERGED" messages) with a minimal log such as the gitRoot being
processed and a single summary of how many unmerged files were added; then wrap
the detailed logs (full stdout, lines array, and per-line parsing logs) in a
conditional if (process.env.DEBUG_GIT_INTEGRATION) block so they only run when
the flag is set; keep the error catch log intact so failures from execAsync are
still reported. Ensure you reference getUnmergedFiles, execAsync,
normalizeStatusPath and isUnmergedStatus when making these changes.
🧹 Nitpick comments (5)
src/extension.ts (2)
116-158: Status bar refresh versioning is good; consider debouncing to reduce git churn.
statusBarRefreshVersionavoids stale UI updates, but it doesn’t prevent multiple concurrent scans from being kicked off (editor changes + repo state changes can be frequent). A small debounce/throttle aroundupdateStatusBar()would reduce repeatedgit statuscalls in large workspaces.Also applies to: 219-229
383-427: File decoration provider may be too expensive if it hits Git per-decoration.
provideFileDecorationcallsgitIntegration.isUnmergedFile()which can cascade into workspace-widegit statuscalls. In repos with many notebooks (or frequent explorer refresh), this can become noticeable.Consider caching the last conflict set from
resolver.findNotebooksWithConflicts()/getUnmergedFiles()and serving decorations from memory, invalidating on the existing watchers.src/tests/nbdimeGuard.test.ts (1)
44-50: Optional: useexecFileSyncto avoid shell-quoting surprises in tests.Today it’s safe because the arguments are controlled, but switching to
execFileSync('git', args, ...)prevents issues if you later add args containing regex backslashes/spaces (e.g.,--get-regexp).Also applies to: 65-69
.github/workflows/vscode-nbdime-guard.yml (1)
37-45: Pinnbdimeto a specific version for reproducible CI.The repository does not currently pin
nbdimeanywhere, and the CI workflow installs the latest version. This can cause unexpected failures ifnbdimereleases a breaking change, even when the extension code hasn't changed. Pinning a version (e.g.,nbdime==4.0.2) ensures consistent test behavior across CI runs.Suggested change
- name: Install nbdime run: | python -m pip install --upgrade pip - python -m pip install nbdime + python -m pip install "nbdime==4.0.2" python - <<'PY' import nbdime print(nbdime.__version__) PYsrc/gitIntegration.ts (1)
131-154: UseexecFilefor git config operations to follow best practices, but note that git's built-in key validation mitigates the injection risk described.Lines 246, 255, and the command generation in
getNbdimeDisableCommands()(275, 278, 285, 288) currently interpolate${key}and${section}into shell commands viaexecAsync. While switching toexecFilewith an argv array is the correct approach for defense in depth, the actual vulnerability surface is limited: git config itself validates key names at the source and rejects keys containing spaces, quotes, or special shell metacharacters. The keys processed byapplyGitConfigFix()are further restricted to those matchingnotebookConfigPattern(jupyter/ipynb/nbdiff/nbdime) or the hardcodedtoolPointerKeysset (merge.tool, diff.tool).Adopting
execFileremains advisable for consistency, maintainability, and to avoid reliance on git's validation layer, but this is an optional refactoring rather than a critical security fix.
| name: VSCode Nbdime Guard Tests | ||
|
|
||
| on: | ||
| pull_request: | ||
| push: | ||
| branches: [main] | ||
| workflow_dispatch: | ||
|
|
||
| jobs: | ||
| nbdime-guard: | ||
| runs-on: ubuntu-24.04 | ||
| env: | ||
| VSCODE_VERSION: stable | ||
| CI: true | ||
| MERGENB_NBDIME_GUARD_CI: true | ||
|
|
||
| steps: | ||
| - name: Checkout | ||
| uses: actions/checkout@v4 | ||
|
|
||
| - name: Use Node.js | ||
| uses: actions/setup-node@v4 | ||
| with: | ||
| node-version: 18 | ||
|
|
||
| - name: Use Python | ||
| uses: actions/setup-python@v5 | ||
| with: | ||
| python-version: '3.12' | ||
|
|
||
| - name: Install system deps | ||
| run: sudo apt-get update && sudo apt-get install -y xvfb | ||
|
|
||
| - name: Install npm deps | ||
| run: npm ci | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== package.json engines & volta ==="
if [ -f package.json ]; then
head -50 package.json | grep -A5 -B2 '"engines"\|"volta"' || echo "No engines/volta found in first 50 lines"
fi
echo -e "\n=== .nvmrc and .node-version files ==="
fd -H '^\.(nvmrc|node-version)$' || echo "No .nvmrc or .node-version found"
echo -e "\n=== All GitHub workflows and their Node versions ==="
fd -H --glob '.github/workflows/*.yml' | while read -r file; do
echo "--- $file ---"
grep -A2 "setup-node" "$file" || echo " (no setup-node)"
done
echo -e "\n=== nbdime installation in this workflow ==="
grep -n "nbdime" .github/workflows/vscode-nbdime-guard.yml || echo "nbdime not mentioned in this workflow"
echo -e "\n=== Check if nbdime is listed in package.json ==="
if [ -f package.json ]; then
grep -i "nbdime" package.json || echo "nbdime not in package.json"
fiRepository: Avni2000/MergeNB
Length of output: 653
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== .github/workflows directory listing ==="
ls -la .github/workflows/ 2>/dev/null || echo "No .github/workflows directory"
echo -e "\n=== vscode-nbdime-guard.yml full content (lines 30-55) ==="
if [ -f .github/workflows/vscode-nbdime-guard.yml ]; then
sed -n '30,55p' .github/workflows/vscode-nbdime-guard.yml
fi
echo -e "\n=== Node 18 status (release date and support) ==="
echo "Node 18: LTS ended 2024-10-18, Maintenance until 2025-10-18"
echo "Current date: February 2026"
echo "Status: Node 18 is END OF LIFE"
echo -e "\n=== Check if Node 20 or 22 are LTS ==="
echo "Node 20: LTS until 2026-10-18 (current)"
echo "Node 22: LTS until 2027-10-18"
echo -e "\n=== Checking if there are any version constraints in repo ==="
find . -maxdepth 2 -type f \( -name ".npmrc" -o -name ".yarnrc" -o -name "pnpm-workspace.yaml" \) 2>/dev/null | xargs cat 2>/dev/null || echo "No npm/yarn/pnpm config found"Repository: Avni2000/MergeNB
Length of output: 1370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== vscode-integration-test.yml Node version and permissions ==="
cat .github/workflows/vscode-integration-test.yml
echo -e "\n=== Current permissions in any workflows ==="
grep -n "permissions:" .github/workflows/*.yml || echo "No explicit permissions found in workflows"Repository: Avni2000/MergeNB
Length of output: 5563
Update Node.js to LTS version and pin nbdime; add explicit workflow permissions.
Node 18 reached end-of-life on 2024-10-18 and is no longer receiving security updates—upgrade to Node 20 LTS (supported until 2026-10) or Node 22 LTS (2027-10). This is also used in the other workflow (vscode-integration-test.yml), so align both.
Pin the nbdime installation to a specific version to prevent unexpected CI failures from upstream changes:
- name: Install nbdime
run: |
python -m pip install --upgrade pip
- python -m pip install nbdime
+ python -m pip install nbdime==0.7.2
python - <<'PY'
import nbdime
print(nbdime.__version__)
PYAdd explicit least-privilege permissions:
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
+permissions:
+ contents: read
+
jobs:📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| name: VSCode Nbdime Guard Tests | |
| on: | |
| pull_request: | |
| push: | |
| branches: [main] | |
| workflow_dispatch: | |
| jobs: | |
| nbdime-guard: | |
| runs-on: ubuntu-24.04 | |
| env: | |
| VSCODE_VERSION: stable | |
| CI: true | |
| MERGENB_NBDIME_GUARD_CI: true | |
| steps: | |
| - name: Checkout | |
| uses: actions/checkout@v4 | |
| - name: Use Node.js | |
| uses: actions/setup-node@v4 | |
| with: | |
| node-version: 18 | |
| - name: Use Python | |
| uses: actions/setup-python@v5 | |
| with: | |
| python-version: '3.12' | |
| - name: Install system deps | |
| run: sudo apt-get update && sudo apt-get install -y xvfb | |
| - name: Install npm deps | |
| run: npm ci | |
| name: VSCode Nbdime Guard Tests | |
| on: | |
| pull_request: | |
| push: | |
| branches: [main] | |
| workflow_dispatch: | |
| permissions: | |
| contents: read | |
| jobs: | |
| nbdime-guard: | |
| runs-on: ubuntu-24.04 | |
| env: | |
| VSCODE_VERSION: stable | |
| CI: true | |
| MERGENB_NBDIME_GUARD_CI: true | |
| steps: | |
| - name: Checkout | |
| uses: actions/checkout@v4 | |
| - name: Use Node.js | |
| uses: actions/setup-node@v4 | |
| with: | |
| node-version: 18 | |
| - name: Use Python | |
| uses: actions/setup-python@v5 | |
| with: | |
| python-version: '3.12' | |
| - name: Install system deps | |
| run: sudo apt-get update && sudo apt-get install -y xvfb | |
| - name: Install npm deps | |
| run: npm ci |
🤖 Prompt for AI Agents
In @.github/workflows/vscode-nbdime-guard.yml around lines 1 - 36, Update the
workflow's Node.js to an LTS release (change the node-version under the "Use
Node.js" step from 18 to 20 or 22) and add explicit least-privilege workflow
permissions at the top-level; also pin nbdime when installing (e.g., in the
"Install npm deps" step ensure nbdime is installed at a fixed version instead of
unpinned latest). Locate the job named "nbdime-guard" and the steps labeled "Use
Node.js" and "Install npm deps" to make the node-version and nbdime pin changes,
and add a top-level permissions block granting only the minimum required
permissions for the workflow.
| if (selection === terminalChoice) { | ||
| const terminalCommands = getNbdimeDisableCommands(error); | ||
| options?.testHooks?.onTerminalCommands?.(terminalCommands); | ||
| if (!selectAction && vscode) { | ||
| const terminal = vscode.window.createTerminal({ name: 'MergeNB notebook config fix', cwd: error.gitRoot }); | ||
| terminal.show(true); | ||
| terminal.sendText(terminalCommands.join('\n'), false); | ||
| } | ||
| return false; | ||
| } |
There was a problem hiding this comment.
“Show terminal fix commands” currently executes commands immediately.
terminal.sendText(terminalCommands.join('\n'), false) will execute any non-comment line before the final line (newlines act like pressing Enter). That contradicts the “Show … commands” intent and can unexpectedly mutate git config.
Proposed diff (comment out executable lines before sending)
function getNbdimeDisableCommands(error: UnsupportedMergeToolError): string[] {
const commands: string[] = [
'# MergeNB detected incompatible Git notebook config (jupyter/ipynb/nbdiff/nbdime).',
- '# Review the commands below, then press Enter to run selected ones.'
+ '# Review the commands below. Uncomment any command you want to run.'
];
...
}
async function showUnsupportedMergeToolGuidance(
...
): Promise<boolean> {
...
if (selection === terminalChoice) {
const terminalCommands = getNbdimeDisableCommands(error);
options?.testHooks?.onTerminalCommands?.(terminalCommands);
if (!selectAction && vscode) {
const terminal = vscode.window.createTerminal({ name: 'MergeNB notebook config fix', cwd: error.gitRoot });
terminal.show(true);
- terminal.sendText(terminalCommands.join('\n'), false);
+ // Safety: avoid executing commands on paste; keep them commented out.
+ const safeLines = terminalCommands.map((line) => (line.startsWith('#') ? line : `# ${line}`));
+ terminal.sendText(safeLines.join('\n'), false);
}
return false;
}Also applies to: 263-267
🤖 Prompt for AI Agents
In `@src/gitIntegration.ts` around lines 360 - 369, The current "Show terminal fix
commands" flow sends raw multiline commands to the VS Code terminal using
terminal.sendText(terminalCommands.join('\n'), false), which can execute any
non-comment line; update the code that handles the terminal path (the block that
calls getNbdimeDisableCommands and then terminal.sendText, and the analogous
block around lines 263-267) to first transform terminalCommands into a safe
preview by commenting out any executable lines (e.g., map each line: if it's
non-empty and does not already start with '#' then prefix with '# ' while
preserving blank lines), optionally prepend a one-line header like "# Commands
(commented) — remove leading '# ' to run", and then call terminal.sendText on
that commentedCommands string so nothing runs unintentionally.
| export async function getUnmergedFiles(workspaceFolderOrPath?: any): Promise<GitFileStatus[]> { | ||
| try { | ||
| let gitRoot: string | undefined; | ||
|
|
||
| // Handle different argument types | ||
| if (typeof workspaceFolderOrPath === 'string') { | ||
| gitRoot = workspaceFolderOrPath; | ||
| } else if (workspaceFolderOrPath?.uri?.fsPath) { | ||
| // VSCode WorkspaceFolder | ||
| gitRoot = workspaceFolderOrPath.uri.fsPath; | ||
| } else if (vscode?.workspace?.workspaceFolders?.[0]?.uri?.fsPath) { | ||
| // Fallback to first VSCode workspace folder | ||
| gitRoot = vscode.workspace.workspaceFolders[0].uri.fsPath; | ||
| const candidateRoots = new Set<string>(); | ||
| if (typeof workspaceFolderOrPath === 'string') { | ||
| candidateRoots.add(workspaceFolderOrPath); | ||
| } else if (workspaceFolderOrPath?.uri?.fsPath) { | ||
| candidateRoots.add(workspaceFolderOrPath.uri.fsPath); | ||
| } else { | ||
| for (const folder of vscode?.workspace?.workspaceFolders ?? []) { | ||
| candidateRoots.add(folder.uri.fsPath); | ||
| } | ||
|
|
||
| console.log(`[GitIntegration] getUnmergedFiles: gitRoot = ${gitRoot}`); | ||
| if (!gitRoot) { | ||
| console.log(`[GitIntegration] getUnmergedFiles: no gitRoot, returning empty`); | ||
| return []; | ||
| } | ||
|
|
||
| if (candidateRoots.size === 0) { | ||
| console.log('[GitIntegration] getUnmergedFiles: no workspace roots found, returning empty'); | ||
| return []; | ||
| } | ||
|
|
||
| const gitRoots = new Set<string>(); | ||
| for (const candidate of candidateRoots) { | ||
| const gitRoot = await resolveGitRootForPath(candidate); | ||
| if (gitRoot) { | ||
| gitRoots.add(gitRoot); | ||
| } | ||
| } | ||
|
|
||
| const { stdout } = await execAsync('git status --porcelain', { cwd: gitRoot }); | ||
| console.log(`[GitIntegration] getUnmergedFiles git status output:\n${stdout}`); | ||
|
|
||
| const unmergedFiles: GitFileStatus[] = []; | ||
| const lines = stdout.split('\n').filter(line => line.trim()); | ||
| console.log(`[GitIntegration] getUnmergedFiles: ${lines.length} non-empty lines`); | ||
|
|
||
| for (const line of lines) { | ||
| const status = line.substring(0, 2); | ||
| const filePath = normalizeStatusPath(line.substring(3)); | ||
| console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`); | ||
|
|
||
| if (isUnmergedStatus(status)) { | ||
| const fullPath = path.join(gitRoot, filePath); | ||
| console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`); | ||
| unmergedFiles.push({ | ||
| path: fullPath, | ||
| repoPath: filePath, | ||
| status, | ||
| isUnmerged: true | ||
| }); | ||
| if (gitRoots.size === 0) { | ||
| console.log('[GitIntegration] getUnmergedFiles: no git roots found, returning empty'); | ||
| return []; | ||
| } | ||
|
|
||
| const unmergedFiles: GitFileStatus[] = []; | ||
| for (const gitRoot of gitRoots) { | ||
| try { | ||
| const { stdout } = await execAsync('git status --porcelain', { cwd: gitRoot }); | ||
| console.log(`[GitIntegration] getUnmergedFiles git status output for ${gitRoot}:\n${stdout}`); | ||
|
|
||
| const lines = stdout.split('\n').filter((line) => line.trim()); | ||
| console.log(`[GitIntegration] getUnmergedFiles: ${lines.length} non-empty lines in ${gitRoot}`); | ||
|
|
||
| for (const line of lines) { | ||
| const status = line.substring(0, 2); | ||
| const filePath = normalizeStatusPath(line.substring(3)); | ||
| console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`); | ||
|
|
||
| if (isUnmergedStatus(status)) { | ||
| const fullPath = path.join(gitRoot, filePath); | ||
| console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`); | ||
| unmergedFiles.push({ | ||
| path: fullPath, | ||
| repoPath: filePath, | ||
| status, | ||
| isUnmerged: true | ||
| }); | ||
| } | ||
| } | ||
| } catch (error) { | ||
| console.error(`[GitIntegration] Error getting unmerged files for ${gitRoot}:`, error); | ||
| } | ||
|
|
||
| return unmergedFiles; | ||
| } catch (error) { | ||
| console.error('Error getting unmerged files:', error); | ||
| return []; | ||
| } | ||
|
|
||
| return unmergedFiles; | ||
| } |
There was a problem hiding this comment.
getUnmergedFiles() logging is too verbose for production paths.
This now logs:
- full
git status --porcelainoutput, - count of lines,
- every line’s parsed status/path.
Given status bar updates + repo watchers, this can easily flood logs and slow down the extension.
Proposed diff (gate behind an env flag and remove per-line logs)
export async function getUnmergedFiles(workspaceFolderOrPath?: any): Promise<GitFileStatus[]> {
+ const debugGit = process.env.MERGENB_DEBUG_GIT === 'true';
...
for (const gitRoot of gitRoots) {
try {
const { stdout } = await execAsync('git status --porcelain', { cwd: gitRoot });
- console.log(`[GitIntegration] getUnmergedFiles git status output for ${gitRoot}:\n${stdout}`);
+ if (debugGit) {
+ console.log(`[GitIntegration] getUnmergedFiles git status output for ${gitRoot}:\n${stdout}`);
+ }
const lines = stdout.split('\n').filter((line) => line.trim());
- console.log(`[GitIntegration] getUnmergedFiles: ${lines.length} non-empty lines in ${gitRoot}`);
+ if (debugGit) {
+ console.log(`[GitIntegration] getUnmergedFiles: ${lines.length} non-empty lines in ${gitRoot}`);
+ }
for (const line of lines) {
const status = line.substring(0, 2);
const filePath = normalizeStatusPath(line.substring(3));
- console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`);
+ if (debugGit) {
+ console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`);
+ }
if (isUnmergedStatus(status)) {
const fullPath = path.join(gitRoot, filePath);
- console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`);
+ if (debugGit) {
+ console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`);
+ }
unmergedFiles.push({
...
});
}
}
} catch (error) {
console.error(`[GitIntegration] Error getting unmerged files for ${gitRoot}:`, error);
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export async function getUnmergedFiles(workspaceFolderOrPath?: any): Promise<GitFileStatus[]> { | |
| try { | |
| let gitRoot: string | undefined; | |
| // Handle different argument types | |
| if (typeof workspaceFolderOrPath === 'string') { | |
| gitRoot = workspaceFolderOrPath; | |
| } else if (workspaceFolderOrPath?.uri?.fsPath) { | |
| // VSCode WorkspaceFolder | |
| gitRoot = workspaceFolderOrPath.uri.fsPath; | |
| } else if (vscode?.workspace?.workspaceFolders?.[0]?.uri?.fsPath) { | |
| // Fallback to first VSCode workspace folder | |
| gitRoot = vscode.workspace.workspaceFolders[0].uri.fsPath; | |
| const candidateRoots = new Set<string>(); | |
| if (typeof workspaceFolderOrPath === 'string') { | |
| candidateRoots.add(workspaceFolderOrPath); | |
| } else if (workspaceFolderOrPath?.uri?.fsPath) { | |
| candidateRoots.add(workspaceFolderOrPath.uri.fsPath); | |
| } else { | |
| for (const folder of vscode?.workspace?.workspaceFolders ?? []) { | |
| candidateRoots.add(folder.uri.fsPath); | |
| } | |
| console.log(`[GitIntegration] getUnmergedFiles: gitRoot = ${gitRoot}`); | |
| if (!gitRoot) { | |
| console.log(`[GitIntegration] getUnmergedFiles: no gitRoot, returning empty`); | |
| return []; | |
| } | |
| if (candidateRoots.size === 0) { | |
| console.log('[GitIntegration] getUnmergedFiles: no workspace roots found, returning empty'); | |
| return []; | |
| } | |
| const gitRoots = new Set<string>(); | |
| for (const candidate of candidateRoots) { | |
| const gitRoot = await resolveGitRootForPath(candidate); | |
| if (gitRoot) { | |
| gitRoots.add(gitRoot); | |
| } | |
| } | |
| const { stdout } = await execAsync('git status --porcelain', { cwd: gitRoot }); | |
| console.log(`[GitIntegration] getUnmergedFiles git status output:\n${stdout}`); | |
| const unmergedFiles: GitFileStatus[] = []; | |
| const lines = stdout.split('\n').filter(line => line.trim()); | |
| console.log(`[GitIntegration] getUnmergedFiles: ${lines.length} non-empty lines`); | |
| for (const line of lines) { | |
| const status = line.substring(0, 2); | |
| const filePath = normalizeStatusPath(line.substring(3)); | |
| console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`); | |
| if (isUnmergedStatus(status)) { | |
| const fullPath = path.join(gitRoot, filePath); | |
| console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`); | |
| unmergedFiles.push({ | |
| path: fullPath, | |
| repoPath: filePath, | |
| status, | |
| isUnmerged: true | |
| }); | |
| if (gitRoots.size === 0) { | |
| console.log('[GitIntegration] getUnmergedFiles: no git roots found, returning empty'); | |
| return []; | |
| } | |
| const unmergedFiles: GitFileStatus[] = []; | |
| for (const gitRoot of gitRoots) { | |
| try { | |
| const { stdout } = await execAsync('git status --porcelain', { cwd: gitRoot }); | |
| console.log(`[GitIntegration] getUnmergedFiles git status output for ${gitRoot}:\n${stdout}`); | |
| const lines = stdout.split('\n').filter((line) => line.trim()); | |
| console.log(`[GitIntegration] getUnmergedFiles: ${lines.length} non-empty lines in ${gitRoot}`); | |
| for (const line of lines) { | |
| const status = line.substring(0, 2); | |
| const filePath = normalizeStatusPath(line.substring(3)); | |
| console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`); | |
| if (isUnmergedStatus(status)) { | |
| const fullPath = path.join(gitRoot, filePath); | |
| console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`); | |
| unmergedFiles.push({ | |
| path: fullPath, | |
| repoPath: filePath, | |
| status, | |
| isUnmerged: true | |
| }); | |
| } | |
| } | |
| } catch (error) { | |
| console.error(`[GitIntegration] Error getting unmerged files for ${gitRoot}:`, error); | |
| } | |
| return unmergedFiles; | |
| } catch (error) { | |
| console.error('Error getting unmerged files:', error); | |
| return []; | |
| } | |
| return unmergedFiles; | |
| } | |
| export async function getUnmergedFiles(workspaceFolderOrPath?: any): Promise<GitFileStatus[]> { | |
| const debugGit = process.env.MERGENB_DEBUG_GIT === 'true'; | |
| const candidateRoots = new Set<string>(); | |
| if (typeof workspaceFolderOrPath === 'string') { | |
| candidateRoots.add(workspaceFolderOrPath); | |
| } else if (workspaceFolderOrPath?.uri?.fsPath) { | |
| candidateRoots.add(workspaceFolderOrPath.uri.fsPath); | |
| } else { | |
| for (const folder of vscode?.workspace?.workspaceFolders ?? []) { | |
| candidateRoots.add(folder.uri.fsPath); | |
| } | |
| } | |
| if (candidateRoots.size === 0) { | |
| console.log('[GitIntegration] getUnmergedFiles: no workspace roots found, returning empty'); | |
| return []; | |
| } | |
| const gitRoots = new Set<string>(); | |
| for (const candidate of candidateRoots) { | |
| const gitRoot = await resolveGitRootForPath(candidate); | |
| if (gitRoot) { | |
| gitRoots.add(gitRoot); | |
| } | |
| } | |
| if (gitRoots.size === 0) { | |
| console.log('[GitIntegration] getUnmergedFiles: no git roots found, returning empty'); | |
| return []; | |
| } | |
| const unmergedFiles: GitFileStatus[] = []; | |
| for (const gitRoot of gitRoots) { | |
| try { | |
| const { stdout } = await execAsync('git status --porcelain', { cwd: gitRoot }); | |
| if (debugGit) { | |
| console.log(`[GitIntegration] getUnmergedFiles git status output for ${gitRoot}:\n${stdout}`); | |
| } | |
| const lines = stdout.split('\n').filter((line) => line.trim()); | |
| if (debugGit) { | |
| console.log(`[GitIntegration] getUnmergedFiles: ${lines.length} non-empty lines in ${gitRoot}`); | |
| } | |
| for (const line of lines) { | |
| const status = line.substring(0, 2); | |
| const filePath = normalizeStatusPath(line.substring(3)); | |
| if (debugGit) { | |
| console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`); | |
| } | |
| if (isUnmergedStatus(status)) { | |
| const fullPath = path.join(gitRoot, filePath); | |
| if (debugGit) { | |
| console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`); | |
| } | |
| unmergedFiles.push({ | |
| path: fullPath, | |
| repoPath: filePath, | |
| status, | |
| isUnmerged: true | |
| }); | |
| } | |
| } | |
| } catch (error) { | |
| console.error(`[GitIntegration] Error getting unmerged files for ${gitRoot}:`, error); | |
| } | |
| } | |
| return unmergedFiles; | |
| } |
🤖 Prompt for AI Agents
In `@src/gitIntegration.ts` around lines 585 - 646, The getUnmergedFiles function
currently prints the full `git status --porcelain` output and per-line parsing
which is too noisy; change logging to only emit minimal info by default and gate
verbose logs behind an environment flag (e.g.
process.env.DEBUG_GIT_INTEGRATION). Specifically, in getUnmergedFiles replace
the unconditional console.log of stdout, the lines count log, and the per-line
debug logs (the logs that include line, status, path and the "-> UNMERGED"
messages) with a minimal log such as the gitRoot being processed and a single
summary of how many unmerged files were added; then wrap the detailed logs (full
stdout, lines array, and per-line parsing logs) in a conditional if
(process.env.DEBUG_GIT_INTEGRATION) block so they only run when the flag is set;
keep the error catch log intact so failures from execAsync are still reported.
Ensure you reference getUnmergedFiles, execAsync, normalizeStatusPath and
isUnmergedStatus when making these changes.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/gitIntegration.ts (1)
237-261: Consider shell-escaping git config keys to prevent command injection.The
keyandsectionvariables are interpolated directly into shell commands. While git config keys typically have a restricted character set, a maliciously crafted config key with shell metacharacters could cause issues.Suggested defensive fix
for (const key of keys) { try { - await execAsync(`git config --${scope} --unset-all ${key}`, { cwd: gitRoot }); + await execAsync(`git config --${scope} --unset-all "${key}"`, { cwd: gitRoot }); } catch { // Key may already be unset; ignore. } } const notebookSections = getNotebookSections(keys); for (const section of notebookSections) { try { - await execAsync(`git config --${scope} --remove-section ${section}`, { cwd: gitRoot }); + await execAsync(`git config --${scope} --remove-section "${section}"`, { cwd: gitRoot }); } catch { // Section may not exist; ignore. } }
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/gitIntegration.ts (1)
215-235: Unconditionally adding default sections is safe but may be unnecessary.Lines 228-233 always add
mergetool.nbdimeanddifftool.nbdimesections regardless of whether they were actually detected. While the removal inapplyGitConfigFixhandles missing sections gracefully, this could generate unnecessary git commands.Consider only adding sections that match detected keys:
♻️ Suggested refinement
function getNotebookSections(keys: string[]): string[] { const sections = new Set<string>(); for (const key of keys) { const keyParts = key.split('.'); if (keyParts.length < 3) { continue; } const section = keyParts.slice(0, -1).join('.'); if (!notebookConfigPattern.test(section)) { continue; } sections.add(section); } - if (sections.has('mergetool.nbdime') === false) { - sections.add('mergetool.nbdime'); - } - if (sections.has('difftool.nbdime') === false) { - sections.add('difftool.nbdime'); - } return [...sections]; }
@coderabbitai can you write a low priority issue about this? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain
🏁 Script executed: Length of output: 45 🏁 Script executed: Length of output: 45
🧠 Learnings used |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (10)
src/tests/runNbdimeGuardTest.ts (1)
52-57: Consider adding--disable-gputo launch args for CI stability.Some CI environments (even with xvfb) can have GPU-related issues. Adding
'--disable-gpu'tolaunchArgsis a common hardening step for headless VS Code tests.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/runNbdimeGuardTest.ts` around lines 52 - 57, Add the Chromium GPU-disable flag to the test VS Code launch arguments: update the launchArgs array used in runNbdimeGuardTest (the launchArgs field shown in the diff) to include '--disable-gpu' alongside '--disable-extensions', '--skip-welcome', and '--skip-release-notes' so CI/headless runs avoid GPU-related failures.src/extension.ts (2)
383-406:provideFileDecorationcallsisUnmergedFileper.ipynbURI, spawning a git process each time.Every decoration request triggers
getUnmergedFiles→git status --porcelainfor the file's repo root. With many.ipynbfiles, this can become expensive. Consider caching the unmerged file set (perhaps refreshed on the same cadence as the status bar) and looking up URIs against the cached set rather than invoking git per file.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/extension.ts` around lines 383 - 406, provideFileDecoration currently calls gitIntegration.isUnmergedFile for every .ipynb URI which spawns a git process each time; instead introduce a cached Set (e.g., unmergedFilesCache) updated on the same cadence as the status bar or via the existing decorationChangeEmitter, and change provideFileDecoration to check uri.fsPath against unmergedFilesCache before falling back to a refresh only when needed; update the gitIntegration update routine (where getUnmergedFiles is used) to populate unmergedFilesCache and emit decorationChangeEmitter.fire() after refresh, and ensure provideFileDecoration and backgroundConflictMonitoringEnabled reference the cache rather than calling isUnmergedFile per file.
119-158:updateStatusBarlacks debouncing — rapid Git events can spawn many concurrentfindNotebooksWithConflictscalls.The version counter correctly discards stale results, but each call still executes
git status --porcelainfor every workspace root. With multiple Git state watchers, file watchers, and editor-change listeners all callingvoid updateStatusBar(), this can produce a burst of git processes. Consider debouncing (e.g., a simple timer that delays execution by ~300ms, resetting on each new call).Sketch
+let statusBarDebounceTimer: ReturnType<typeof setTimeout> | undefined; + +function scheduleStatusBarUpdate(): void { + if (statusBarDebounceTimer) { + clearTimeout(statusBarDebounceTimer); + } + statusBarDebounceTimer = setTimeout(() => { + statusBarDebounceTimer = undefined; + void updateStatusBar(); + }, 300); +}Then replace all
void updateStatusBar()calls (in watchers, event handlers) withscheduleStatusBarUpdate().🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/extension.ts` around lines 119 - 158, updateStatusBar currently runs immediately on each trigger and can spawn many concurrent findNotebooksWithConflicts/git processes; implement a debounced scheduler to coalesce rapid calls: add a module-scoped timer (e.g., statusBarUpdateTimer) and new helper scheduleStatusBarUpdate(delay = 300) that clears the timer and sets a new setTimeout to call updateStatusBar(); keep the existing statusBarRefreshVersion logic inside updateStatusBar, and replace all direct calls to updateStatusBar() (from watchers/event handlers) with scheduleStatusBarUpdate() so rapid events only run one refresh after the delay..github/workflows/vscode-nbdime-guard.yml (1)
1-7: Add explicit least-privilege workflow permissions.The workflow still lacks a top-level
permissionsblock. Addingpermissions: contents: readlimits the defaultGITHUB_TOKENscope and follows GitHub's security hardening best practices.Proposed fix
on: pull_request: push: branches: [main] workflow_dispatch: +permissions: + contents: read + jobs:🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/vscode-nbdime-guard.yml around lines 1 - 7, Add a top-level GitHub Actions permissions block to this workflow ("VSCode Nbdime Guard Tests") to restrict the GITHUB_TOKEN scope; specifically add a top-level permissions: contents: read entry in the workflow root so the default write permissions are removed and the token only has read access to repository contents.src/gitIntegration.ts (5)
400-420:ensureSupportedMergeToolthrows on first failing root, skipping remaining roots.If there are multiple git roots and the first one has issues the user dismisses, the error thrown at Line 417 aborts the loop without checking remaining roots. If partial checking is intentional, a comment clarifying that would help. Otherwise, consider collecting errors and reporting at the end.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 400 - 420, ensureSupportedMergeTool currently throws the first UnsupportedMergeToolError inside the loop, aborting checks for other git roots; instead collect errors for all roots and throw or report them after the loop. Modify ensureSupportedMergeTool to iterate all git roots (resolved by resolveGitRoots) and, when findIncompatibleGitConfig returns issues, call showUnsupportedMergeToolGuidance and if not fixed push a new UnsupportedMergeToolError(gitRoot, issues) into a local errors array; after the loop, if errors.length > 0, either throw an aggregate error (or throw the first with aggregated message) so all roots are checked before failing. Ensure behavior of options.suppressIfAlreadyShown and options.testHooks is preserved when calling showUnsupportedMergeToolGuidance.
215-235:getNotebookSectionsunconditionally addsmergetool.nbdimeanddifftool.nbdime.Lines 228-233 always inject these two sections regardless of whether the user's config actually contains them. This means
applyGitConfigFixwill attempt to remove sections that may never have existed. It's harmless due to the catch block, but it could cause confusing terminal commands (viagetNbdimeDisableCommands) suggesting removal of sections the user doesn't have. Consider gating the additions on whether any key inkeysactually falls under those sections.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 215 - 235, The function getNotebookSections currently always injects 'mergetool.nbdime' and 'difftool.nbdime'; change it to only add those two if any input key actually belongs to those sections: scan keys (using the same splitting/section logic or key.startsWith) to detect presence of 'mergetool.nbdime' or 'difftool.nbdime' before adding them to sections. Update getNotebookSections (and keep using notebookConfigPattern) so applyGitConfigFix and getNbdimeDisableCommands will only propose removals for sections that were present in the original keys.
237-261: Unsanitized keys/sections interpolated into shell commands.
keyandsectionare injected directly intoexecAsynccalls without quoting. While git config keys are constrained by format rules and the regex filters, a crafted.gitconfigcould still include shell metacharacters in values that end up as keys in edge cases. Prefer quoting interpolated arguments.Proposed fix
- await execAsync(`git config --${scope} --unset-all ${key}`, { cwd: gitRoot }); + await execAsync(`git config --${scope} --unset-all "${key}"`, { cwd: gitRoot });- await execAsync(`git config --${scope} --remove-section ${section}`, { cwd: gitRoot }); + await execAsync(`git config --${scope} --remove-section "${section}"`, { cwd: gitRoot });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 237 - 261, The code in applyGitConfigFix injects unescaped key and section into shell-interpolated execAsync calls (execAsync(`git config --${scope} --unset-all ${key}` / --remove-section ${section}`)), which can lead to shell injection; fix by invoking git with argv rather than a single shell string (e.g., call execAsync or a spawn/execFile variant with command 'git' and args ['config', `--${scope}`, '--unset-all', key] and similarly ['config', `--${scope}`, '--remove-section', section]), or else validate/sanitize key and section against the expected git config regex before use so only safe characters are passed; update both usages in applyGitConfigFix (the loops over keys and notebookSections) to use argument arrays or validated values.
33-35: Module-level mutable state (nbdimeWarningShownRoots) has no reset mechanism.This
Setpersists for the lifetime of the extension host. In long-running sessions, if a user fixes their config and then re-introduces an incompatible config, the suppression will prevent the warning from re-appearing for that root. Consider providing a way to clear this set (e.g., on a workspace change or as part of a test hook).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 33 - 35, The module-level Set nbdimeWarningShownRoots currently never resets; add a clear mechanism: export a function clearNbdimeWarningShownRoots() that calls nbdimeWarningShownRoots.clear() for tests and invoke that same clear inside a workspace lifecycle listener (e.g., vscode.workspace.onDidChangeWorkspaceFolders or onDidChangeConfiguration) so the set is cleared when workspace folders or relevant config change; update any initialization code to register that listener and ensure the Set is only mutated via its existing usage sites.
44-54:IncompatibleGitConfigIssueandEnsureSupportedMergeToolIssueare structurally identical.Both interfaces have the same
{ scope, key, value }shape. Consider exporting a single type and reusing it to reduce duplication.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 44 - 54, The two interfaces IncompatibleGitConfigIssue and EnsureSupportedMergeToolIssue are identical; replace them with a single exported interface (e.g., export interface GitConfigIssue { scope: GitConfigScope | 'local' | 'global'; key: string; value: string } or unify the scope types appropriately) and update all usages to reference the new GitConfigIssue type, removing the duplicate declaration; ensure the new type name and scope union (or a shared GitConfigScope) match existing references in functions or types that previously used IncompatibleGitConfigIssue and EnsureSupportedMergeToolIssue.src/tests/nbdimeGuard.test.ts (1)
44-50:githelper joins args with spaces — fragile if any arg contains whitespace.
args.join(' ')will break for arguments with spaces (e.g., config values containing spaces). This is fine for the current test usage but worth noting if the helper is reused with richer arguments.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/nbdimeGuard.test.ts` around lines 44 - 50, The git helper currently builds a single command string with args.join(' ') which breaks when an argument contains whitespace; change the implementation of the git function (named git) to invoke the child_process API that accepts an argv array (e.g., spawnSync or execFileSync) instead of execSync with a concatenated string, pass cwd and encoding/stdio options the same way, and return the trimmed stdout; this preserves proper argument quoting/whitespace handling for all args.
🤖 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/tests/nbdimeGuard.test.ts`:
- Around line 148-153: The test is missing an assertion to verify that the local
key nbdime.autoresolve was removed; add a call to
ensureKeyMissing(workspacePath, '--local', 'nbdime.autoresolve') alongside the
other cleanup assertions (after ensureSectionMissing calls) so the test verifies
the bare [nbdime] key is unset (this complements getNotebookSections behavior
which skips 2-part keys and relies on --unset-all to remove nbdime.autoresolve).
---
Duplicate comments:
In `@src/gitIntegration.ts`:
- Around line 360-371: The previous risk was that terminal.sendText could
execute commands unintentionally; ensure the code in the selection branch that
handles terminalChoice continues to create the terminal
(vscode.window.createTerminal), compute terminalCommands via
getNbdimeDisableCommands(error), map them to safeLines by prefixing non-comment
lines with "# " and then call terminal.sendText(safeLines.join('\n'), false) so
commands remain commented and not executed; keep the
options?.testHooks?.onTerminalCommands?.(terminalCommands) call and return false
afterward to preserve existing flow.
- Around line 617-648: The getUnmergedFiles function is logging the full git
output and detailed per-line parsing unconditionally; wrap those debug logs (the
console.log calls that print stdout, lines count, per-line parse and UNMERGED
notices) behind a debug flag or logger level check so they only run when verbose
debugging is enabled. Modify getUnmergedFiles to consult an existing debug
setting or a new boolean (e.g., a module-level debug constant or a
Logger.isDebug()) before calling console.log for the git status output,
lines.length, each parsed line, and the UNMERGED push message; keep error
logging via console.error (or Logger.error) unchanged and still emitted on
catch. Ensure you reference the logs near execAsync('git status --porcelain'),
the lines/for loop using normalizeStatusPath and isUnmergedStatus, and the
unmergedFiles.push so the gating covers all those console.log statements.
---
Nitpick comments:
In @.github/workflows/vscode-nbdime-guard.yml:
- Around line 1-7: Add a top-level GitHub Actions permissions block to this
workflow ("VSCode Nbdime Guard Tests") to restrict the GITHUB_TOKEN scope;
specifically add a top-level permissions: contents: read entry in the workflow
root so the default write permissions are removed and the token only has read
access to repository contents.
In `@src/extension.ts`:
- Around line 383-406: provideFileDecoration currently calls
gitIntegration.isUnmergedFile for every .ipynb URI which spawns a git process
each time; instead introduce a cached Set (e.g., unmergedFilesCache) updated on
the same cadence as the status bar or via the existing decorationChangeEmitter,
and change provideFileDecoration to check uri.fsPath against unmergedFilesCache
before falling back to a refresh only when needed; update the gitIntegration
update routine (where getUnmergedFiles is used) to populate unmergedFilesCache
and emit decorationChangeEmitter.fire() after refresh, and ensure
provideFileDecoration and backgroundConflictMonitoringEnabled reference the
cache rather than calling isUnmergedFile per file.
- Around line 119-158: updateStatusBar currently runs immediately on each
trigger and can spawn many concurrent findNotebooksWithConflicts/git processes;
implement a debounced scheduler to coalesce rapid calls: add a module-scoped
timer (e.g., statusBarUpdateTimer) and new helper scheduleStatusBarUpdate(delay
= 300) that clears the timer and sets a new setTimeout to call
updateStatusBar(); keep the existing statusBarRefreshVersion logic inside
updateStatusBar, and replace all direct calls to updateStatusBar() (from
watchers/event handlers) with scheduleStatusBarUpdate() so rapid events only run
one refresh after the delay.
In `@src/gitIntegration.ts`:
- Around line 400-420: ensureSupportedMergeTool currently throws the first
UnsupportedMergeToolError inside the loop, aborting checks for other git roots;
instead collect errors for all roots and throw or report them after the loop.
Modify ensureSupportedMergeTool to iterate all git roots (resolved by
resolveGitRoots) and, when findIncompatibleGitConfig returns issues, call
showUnsupportedMergeToolGuidance and if not fixed push a new
UnsupportedMergeToolError(gitRoot, issues) into a local errors array; after the
loop, if errors.length > 0, either throw an aggregate error (or throw the first
with aggregated message) so all roots are checked before failing. Ensure
behavior of options.suppressIfAlreadyShown and options.testHooks is preserved
when calling showUnsupportedMergeToolGuidance.
- Around line 215-235: The function getNotebookSections currently always injects
'mergetool.nbdime' and 'difftool.nbdime'; change it to only add those two if any
input key actually belongs to those sections: scan keys (using the same
splitting/section logic or key.startsWith) to detect presence of
'mergetool.nbdime' or 'difftool.nbdime' before adding them to sections. Update
getNotebookSections (and keep using notebookConfigPattern) so applyGitConfigFix
and getNbdimeDisableCommands will only propose removals for sections that were
present in the original keys.
- Around line 237-261: The code in applyGitConfigFix injects unescaped key and
section into shell-interpolated execAsync calls (execAsync(`git config
--${scope} --unset-all ${key}` / --remove-section ${section}`)), which can lead
to shell injection; fix by invoking git with argv rather than a single shell
string (e.g., call execAsync or a spawn/execFile variant with command 'git' and
args ['config', `--${scope}`, '--unset-all', key] and similarly ['config',
`--${scope}`, '--remove-section', section]), or else validate/sanitize key and
section against the expected git config regex before use so only safe characters
are passed; update both usages in applyGitConfigFix (the loops over keys and
notebookSections) to use argument arrays or validated values.
- Around line 33-35: The module-level Set nbdimeWarningShownRoots currently
never resets; add a clear mechanism: export a function
clearNbdimeWarningShownRoots() that calls nbdimeWarningShownRoots.clear() for
tests and invoke that same clear inside a workspace lifecycle listener (e.g.,
vscode.workspace.onDidChangeWorkspaceFolders or onDidChangeConfiguration) so the
set is cleared when workspace folders or relevant config change; update any
initialization code to register that listener and ensure the Set is only mutated
via its existing usage sites.
- Around line 44-54: The two interfaces IncompatibleGitConfigIssue and
EnsureSupportedMergeToolIssue are identical; replace them with a single exported
interface (e.g., export interface GitConfigIssue { scope: GitConfigScope |
'local' | 'global'; key: string; value: string } or unify the scope types
appropriately) and update all usages to reference the new GitConfigIssue type,
removing the duplicate declaration; ensure the new type name and scope union (or
a shared GitConfigScope) match existing references in functions or types that
previously used IncompatibleGitConfigIssue and EnsureSupportedMergeToolIssue.
In `@src/tests/nbdimeGuard.test.ts`:
- Around line 44-50: The git helper currently builds a single command string
with args.join(' ') which breaks when an argument contains whitespace; change
the implementation of the git function (named git) to invoke the child_process
API that accepts an argv array (e.g., spawnSync or execFileSync) instead of
execSync with a concatenated string, pass cwd and encoding/stdio options the
same way, and return the trimmed stdout; this preserves proper argument
quoting/whitespace handling for all args.
In `@src/tests/runNbdimeGuardTest.ts`:
- Around line 52-57: Add the Chromium GPU-disable flag to the test VS Code
launch arguments: update the launchArgs array used in runNbdimeGuardTest (the
launchArgs field shown in the diff) to include '--disable-gpu' alongside
'--disable-extensions', '--skip-welcome', and '--skip-release-notes' so
CI/headless runs avoid GPU-related failures.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/tests/nbdimeGuard.test.ts (1)
238-254: No-op verification reusespromptCallswithout resetting — works but is fragile.The no-op path relies on
promptCallsstill having length 1 from the auto-fix phase. If someone later adds another test step between auto-fix and no-op that pushes topromptCalls, this assertion silently becomes wrong. Consider using a fresh array or checking only the delta.Suggested approach
+ const noopPromptCalls: PromptCall[] = []; await withTimeout( gitIntegration.ensureSupportedMergeTool(workspacePath, { testHooks: { selectAction: async (context) => { - promptCalls.push({ + noopPromptCalls.push({ message: context.message, actions: context.actions }); return 'Auto-fix repo + global'; } } }), 10000, 'ensureSupportedMergeTool(no-op)' ); - assert(promptCalls.length === 1, 'Unexpected extra guidance prompt after auto-fix cleanup'); + assert(noopPromptCalls.length === 0, 'Unexpected guidance prompt on no-op path after auto-fix cleanup');🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/nbdimeGuard.test.ts` around lines 238 - 254, The test reuses the shared promptCalls array for both the auto-fix and no-op phases which makes the final assertion fragile; modify the test around ensureSupportedMergeTool (and its testHooks.selectAction) to either reset promptCalls to an empty array before invoking the no-op call or capture the initial length and assert only the delta (e.g., expect no new pushes after the no-op). Locate references to promptCalls and the two await calls to gitIntegration.ensureSupportedMergeTool and change the assertion to validate only the additional prompts (or use a fresh array) so the no-op verification cannot be invalidated by intervening steps.
🤖 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/tests/nbdimeGuard.test.ts`:
- Around line 166-170: The test is missing an assertion that the
mergetool.nbdime.keepBackup key remains unchanged after the "terminal guidance
only shows commands" block; update the test in src/tests/nbdimeGuard.test.ts to
call ensureKeyValue(workspacePath, '--local' or appropriate scope,
'mergetool.nbdime.keepBackup', '<expected-value>') alongside the other
ensureKeyValue assertions so that configureIncompatibleNotebookSettings' five
keys (as set in configureIncompatibleNotebookSettings) are all verified
immutably; locate the existing ensureKeyValue calls in the "terminal guidance
must not mutate config" section and add the missing mergetool.nbdime.keepBackup
check using the same pattern.
---
Nitpick comments:
In `@src/tests/nbdimeGuard.test.ts`:
- Around line 238-254: The test reuses the shared promptCalls array for both the
auto-fix and no-op phases which makes the final assertion fragile; modify the
test around ensureSupportedMergeTool (and its testHooks.selectAction) to either
reset promptCalls to an empty array before invoking the no-op call or capture
the initial length and assert only the delta (e.g., expect no new pushes after
the no-op). Locate references to promptCalls and the two await calls to
gitIntegration.ensureSupportedMergeTool and change the assertion to validate
only the additional prompts (or use a fresh array) so the no-op verification
cannot be invalidated by intervening steps.
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/gitIntegration.ts (3)
109-129:getUnmergedFilesduplicates the root-resolution logic fromresolveGitRoots.
resolveGitRoots(lines 109-129) already handles "given path → git root" and "no path → workspace folders → git roots".getUnmergedFilesreimplements the same pattern (lines 599-626). Consider reusingresolveGitRootsto reduce duplication.Sketch
export async function getUnmergedFiles(workspaceFolderOrPath?: any): Promise<GitFileStatus[]> { - const candidateRoots = new Set<string>(); - if (typeof workspaceFolderOrPath === 'string') { - candidateRoots.add(workspaceFolderOrPath); - } else if (workspaceFolderOrPath?.uri?.fsPath) { - candidateRoots.add(workspaceFolderOrPath.uri.fsPath); - } else { - for (const folder of vscode?.workspace?.workspaceFolders ?? []) { - candidateRoots.add(folder.uri.fsPath); - } - } - if (candidateRoots.size === 0) { ... } - - const gitRoots = new Set<string>(); - for (const candidate of candidateRoots) { - const gitRoot = await resolveGitRootForPath(candidate); - if (gitRoot) { gitRoots.add(gitRoot); } - } - if (gitRoots.size === 0) { ... } + const inputPath = typeof workspaceFolderOrPath === 'string' + ? workspaceFolderOrPath + : workspaceFolderOrPath?.uri?.fsPath; + const gitRoots = await resolveGitRoots(inputPath); + if (gitRoots.length === 0) { + console.log('[GitIntegration] getUnmergedFiles: no git roots found, returning empty'); + return []; + } ...Also applies to: 598-621
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 109 - 129, The getUnmergedFiles implementation duplicates root-resolution logic already in resolveGitRoots; update getUnmergedFiles to call resolveGitRoots(gitRootOrPath) to obtain the list of git roots instead of reimplementing path→root and workspace folder traversal, remove the duplicated Set/loop logic, and use the returned array of roots when iterating to collect unmerged files; ensure resolveGitRoots is awaited and that getUnmergedFiles preserves existing behavior for an empty result (no roots) and any error handling around resolveGitRoots.
411-431:ensureSupportedMergeToolstops at the first unfixed root.When multiple workspace roots have incompatible config, only the first unfixed root throws
UnsupportedMergeToolError. The remaining roots are never inspected. If this is a conscious fail-fast choice, consider documenting it; otherwise, collecting all errors and reporting them together would give users a complete picture in one pass.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 411 - 431, The function ensureSupportedMergeTool currently stops after throwing UnsupportedMergeToolError for the first git root that isn't fixed, leaving other roots uninspected; update ensureSupportedMergeTool to iterate all roots returned by resolveGitRoots, run findIncompatibleGitConfig and showUnsupportedMergeToolGuidance for each gitRoot, collect any UnsupportedMergeToolError instances (or their gitRoot+issues) when fixed is false, and after the loop either throw a single aggregated error (or a new AggregateUnsupportedMergeToolError) containing all failures or return a consolidated report; refer to ensureSupportedMergeTool, resolveGitRoots, findIncompatibleGitConfig, UnsupportedMergeToolError, and showUnsupportedMergeToolGuidance when making the change.
632-654: Consider using the structured logger fromsrc/logger.tsinstead of rawconsole.log/console.error.The codebase already has a
logger.error()(and presumably other levels) insrc/logger.tsthat prefixes[MergeNB]. The new code usesconsole.log/console.errorwith a[GitIntegration]prefix, creating an inconsistency in log formatting and making it harder to filter or control log levels.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/gitIntegration.ts` around lines 632 - 654, Replace console.log/console.error calls in getUnmergedFiles with the project's structured logger (imported from src/logger.ts) to keep consistent formatting and log levels; update the messages currently using console.log in the getUnmergedFiles function (including the debug lines that print stdout, lines length, each parsed Line/status/path and the UNMERGED notification) to use logger.debug or logger.info as appropriate, and replace the catch block console.error with logger.error while preserving the error object; ensure you reference normalizeStatusPath, isUnmergedStatus, unmergedFiles and the same message content (prefixed by whatever the project's logger already adds) so behavior and diagnostics remain unchanged.
🤖 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 248-271: The git config invocations in applyGitConfigFix
interpolate untrusted values (variables key and section) directly into shell
strings; update these calls to avoid shell injection by passing command and
arguments as an argv array (or properly shell-escaping/quoting the values) to
execAsync instead of interpolating, and do the same fixes in
getNbdimeDisableCommands where keys/sections are used (lines around 286, 289,
296, 299). Locate the execAsync invocations inside applyGitConfigFix and replace
patterns like execAsync(`git config --${scope} --unset-all ${key}`, { cwd:
gitRoot }) and execAsync(`git config --${scope} --remove-section ${section}`, {
cwd: gitRoot }) with safe argument-based calls (e.g., execAsync(['git','config',
`--${scope}`, '--unset-all', key], { cwd: gitRoot }) or equivalent API-supported
quoting) so key and section are never interpreted by the shell.
- Around line 628-656: The getUnmergedFiles loop is logging full git output and
per-line details unconditionally; remove or gate the verbose
console.log/console.error calls inside the for (const gitRoot of gitRoots) block
(the logs around execAsync('git status --porcelain'), lines/line parsing, and
UNMERGED detection) so normal operation doesn't flood logs — either delete those
console.log statements or wrap them behind a debug flag/config (e.g., a isDebug
or logger.debug check) and keep the catch only logging concise error info via
the existing logging facility; key symbols to edit: getUnmergedFiles, gitRoots,
execAsync('git status --porcelain'), normalizeStatusPath, isUnmergedStatus,
unmergedFiles.
---
Nitpick comments:
In `@src/gitIntegration.ts`:
- Around line 109-129: The getUnmergedFiles implementation duplicates
root-resolution logic already in resolveGitRoots; update getUnmergedFiles to
call resolveGitRoots(gitRootOrPath) to obtain the list of git roots instead of
reimplementing path→root and workspace folder traversal, remove the duplicated
Set/loop logic, and use the returned array of roots when iterating to collect
unmerged files; ensure resolveGitRoots is awaited and that getUnmergedFiles
preserves existing behavior for an empty result (no roots) and any error
handling around resolveGitRoots.
- Around line 411-431: The function ensureSupportedMergeTool currently stops
after throwing UnsupportedMergeToolError for the first git root that isn't
fixed, leaving other roots uninspected; update ensureSupportedMergeTool to
iterate all roots returned by resolveGitRoots, run findIncompatibleGitConfig and
showUnsupportedMergeToolGuidance for each gitRoot, collect any
UnsupportedMergeToolError instances (or their gitRoot+issues) when fixed is
false, and after the loop either throw a single aggregated error (or a new
AggregateUnsupportedMergeToolError) containing all failures or return a
consolidated report; refer to ensureSupportedMergeTool, resolveGitRoots,
findIncompatibleGitConfig, UnsupportedMergeToolError, and
showUnsupportedMergeToolGuidance when making the change.
- Around line 632-654: Replace console.log/console.error calls in
getUnmergedFiles with the project's structured logger (imported from
src/logger.ts) to keep consistent formatting and log levels; update the messages
currently using console.log in the getUnmergedFiles function (including the
debug lines that print stdout, lines length, each parsed Line/status/path and
the UNMERGED notification) to use logger.debug or logger.info as appropriate,
and replace the catch block console.error with logger.error while preserving the
error object; ensure you reference normalizeStatusPath, isUnmergedStatus,
unmergedFiles and the same message content (prefixed by whatever the project's
logger already adds) so behavior and diagnostics remain unchanged.
- Shell injection risk - Dedupe logic
Just checking nbdime test first
closes #48
closes #87
Summary by CodeRabbit
New Features
Tests
Chores (CI)