feat(git): safely apply individual diff hunks (#3443)

Resolve the Changes-view conflict without reverting branch or commit comparisons. Pair canonical action patches with displayed blob identities, refresh all path views after mutation, exclude historical snapshots, and reject stale or multi-file patches at the server boundary.

Preserve CRLF bytes and make long hunk menus keyboard-reachable. Workspace type-check, lint and build passed; focused parser, menu, view and real Git regressions passed.
This commit is contained in:
Bohdan Triapitsyn
2026-09-09 19:39:28 +03:00
10 changed files with 662 additions and 72 deletions
+11 -2
View File
@@ -25,7 +25,7 @@ The following functions are exported and used by the web server:
### Status and Diff Operations
- `getStatus(directory)`: Get comprehensive Git status including current branch, tracking, ahead/behind, file changes, diff stats, merge/rebase state.
- `getDiff(directory, { path, staged, contextLines })`: Get diff output for files or entire working tree. Untracked symbolic links are represented as link entries without following their targets.
- `getDiff(directory, { path, staged, contextLines })`: Get diff output for files or entire working tree with full Git blob identities. Untracked symbolic links are represented as link entries without following their targets.
- `getRangeDiff(directory, { base, head, path, contextLines, includeWorkingTree })`: Compare the merge base of the exact selected refs with `head`. With `includeWorkingTree: true`, compare with the checked-out branch's current files instead, including committed, staged, unstaged, and untracked work in one net diff. This mode rejects a head that is not the checked-out branch. Exposed as `GET /api/git/range-diff`; omit `path` for the whole comparison.
- `getRangeFiles(directory, { base, head, includeWorkingTree })`: List changed paths using the same comparison as `getRangeDiff`. A successful empty list means the final files match the merge base, even if staging and working-tree changes cancel each other out.
- Both range operations honor refs literally. A local `main` is never replaced with `origin/main`, and an unavailable ref fails rather than choosing a different remote. The UI picker sends qualified refs to distinguish local and remote branches with matching display names.
@@ -37,7 +37,7 @@ The following functions are exported and used by the web server:
- `revertFile(directory, filePath, options)`: Revert a file. Default scope `all` discards staged and working-tree changes; scope `working` discards only unstaged/working-tree changes.
- `stageFile(directory, filePath)`: Add one file path to the index.
- `unstageFile(directory, filePath)`: Remove one file path from the index while preserving working-tree content.
- `applyHunk(directory, filePath, options)`: Apply a single-hunk patch via `git apply`. `options.action` is `stage` (`git apply --cached`), `unstage` (`git apply --cached --reverse`), or `discard` (`git apply --reverse` in the working tree). The patch is written to a temp file; a `--check` runs first so a stale hunk fails with a clear "refresh and try again" error instead of a partial mutation. The patch target path must match the requested file.
- `applyHunk(directory, filePath, options)`: Apply a single-hunk patch via `git apply`. `options.action` is `stage` (`git apply --cached`), `unstage` (`git apply --cached --reverse`), or `discard` (`git apply --reverse` in the working tree). Inside the index mutation queue, the server verifies that the complete patch exactly matches one current three-context-line hunk for that file and scope, then runs `--check` before applying. Applicability alone cannot prove an unstaged change: old staged or committed hunks can reverse cleanly too. Stale, historical and multi-file patches fail with a refresh error. Temporary patch files are removed on success and failure; hunk content retains CRLF bytes.
### Branch Operations
- `getBranchBase(directory, branch)`: Read a named creation source from reflog. After a rebase, the creation source is no longer a current parent record, so return `null` and let the user choose a base. Explicit per-runtime, directory, and branch choices in the shared UI outrank detection.
@@ -137,6 +137,15 @@ The following functions are internal helpers used by exported functions:
- Commit comparison uses the same server boundary through optional `GitAPI.getGitCommitDiff`. Desktop Changes, mobile Changes, and the existing walkthrough surface share branch/commit comparison semantics. Mobile Changes uses the same selectors and `useGitComparison` file-list owner, with a read-only list-to-detail flow. VS Code keeps its existing modes because its Git bridge does not provide these comparison operations. The HTTP operations are available to web, Electron, hosted mobile, and Capacitor clients.
### Staged and unstaged change handling
- Desktop Changes keeps a canonical three-line-context action patch separate
from its full-file display patch. Multi-hunk actions require identical file
headers and full blob identities for the display/action pair, including cached
action patches; mismatch or missing identity leaves actions unavailable until
Retry obtains a matching pair. Successful file/hunk mutations invalidate
every mounted view of that path through `sessionEvents.requestGitRefresh`.
Actions remain unavailable until the refresh succeeds. Last turn, Branch and
Commit snapshots never expose hunk mutations. Mobile uses its separate Changes
surface and VS Code does not mount this menu.
- Untracked patches from `getDiff` and `getUntrackedDiffs` use `git diff --no-index` with separate stdout, stderr, and process exit status. Exit codes 0 and 1 return stdout only, so line-ending warnings never become patch text or request failures. Other exits and process failures reject the single-file request; the batch keeps an empty entry for the failed path and preserves the other results.
- `status.files` exposes both `index` and `working_dir` codes. Shared UI uses these as separate scopes: staged rows are derived from non-empty `index` statuses, while unstaged rows are derived from `working_dir` statuses and untracked files.
- A file with both staged and unstaged changes can appear in both UI sections. Staged rows request diffs with `staged: true`; unstaged rows request normal working-tree diffs.
+21 -7
View File
@@ -2466,7 +2466,7 @@ export async function getStatus(directory, options = {}) {
}
const getNoIndexDiff = async (repoRoot, repoPath, contextLines) => {
const args = ['diff', '--no-color'];
const args = ['diff', '--no-color', '--full-index'];
if (Number.isFinite(contextLines)) {
args.push(`-U${Math.max(0, contextLines)}`);
}
@@ -2484,7 +2484,7 @@ export async function getDiff(directory, { path: filePath, staged = false, conte
const { directoryPath, directoryGit, repoRoot, git } = await createRepositoryGitContext(directory);
try {
const args = ['diff', '--no-color'];
const args = ['diff', '--no-color', '--full-index'];
const fileContext = filePath ? await resolveGitFileContext(directoryPath, directoryGit, filePath, repoRoot) : null;
if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
@@ -3099,11 +3099,13 @@ const normalizePatchTargetPath = (value) => {
};
const extractPatchTargetPath = (patch) => {
const matches = [...patch.matchAll(/^(?:-{3}|\+{3})\s+.+$/gm)];
const firstHunk = patch.search(/^@@\s/m);
const header = firstHunk < 0 ? patch : patch.slice(0, firstHunk);
const matches = [...header.matchAll(/^(?:-{3}|\+{3})\s+.+$/gm)];
const realTargets = matches
.map((match) => normalizePatchTargetPath(parsePatchPathToken(match[0])))
.filter(Boolean);
return realTargets[0] || null;
return realTargets.at(-1) || null;
};
const writeTempPatchFile = async (patch) => {
@@ -3131,9 +3133,21 @@ export async function applyHunk(directory, filePath, options = {}) {
const fileContext = await resolveGitFileContext(directoryPath, directoryGit, filePath, repoRoot);
validateRepositoryFilePaths(repoRoot, [fileContext.repoPath]);
const targetPath = extractPatchTargetPath(patch);
if (targetPath && targetPath !== fileContext.repoPath && targetPath !== filePath) {
throw new Error('patch target path does not match the requested file');
// Applicability alone is insufficient: a previously staged or committed
// hunk may still reverse cleanly against the working tree. Accept only a
// canonical hunk from this file's current working/index diff.
const current = await getDiff(directory, { path: filePath, staged: action === 'unstage', contextLines: 3 });
const starts = [...current.matchAll(/^@@\s/gm)].map((match) => match.index);
const header = current.slice(0, starts[0] ?? 0);
const isCurrentHunk = starts.some((start, index) => (
header + current.slice(start, starts[index + 1] ?? current.length) === patch
));
if (!isCurrentHunk) {
const targetPath = extractPatchTargetPath(patch);
if (targetPath && targetPath !== fileContext.repoPath && targetPath !== filePath) {
throw new Error('patch target path does not match the requested file');
}
throw new Error('Hunk no longer applies — refresh and try again.');
}
const flags = HUNK_ACTION_FLAGS[action];
+75 -19
View File
@@ -231,22 +231,8 @@ describe.runIf(canRunGit())('setLocalIdentity', () => {
// applyHunk (per-hunk stage / unstage / discard)
// ---------------------------------------------------------------------------
/** Minimal unified-diff splitter: returns standalone per-hunk patches. */
const splitHunks = (patch) => {
const lines = patch.split(/\r?\n/);
const headerEnd = lines.findIndex((line) => /^@@\s/.test(line));
if (headerEnd === -1) return [];
const header = lines.slice(0, headerEnd);
const hunks = [];
for (let i = headerEnd; i < lines.length; i += 1) {
const line = lines[i];
if (/^@@\s/.test(line)) hunks.push([...header, line]);
else if (hunks.length > 0) hunks[hunks.length - 1].push(line);
}
return hunks.map((hunk) => hunk.join('\n'))
.filter((hunk) => hunk.trim().length > 0)
.map((hunk) => (hunk.endsWith('\n') ? hunk : `${hunk}\n`));
};
// Exercise the actual client splitter against the server apply boundary.
import { splitPatchIntoHunks as splitHunks } from '../../../../ui/src/lib/diff/patchFileDiff.ts';
const writeFile = (repo, name, contents) =>
fs.promises.writeFile(path.join(repo, name), contents, 'utf8');
@@ -262,6 +248,77 @@ const readWorking = (repo) => fs.promises.readFile(path.join(repo, 'file.txt'),
const readStaged = async (git) => (await git.raw(['show', ':file.txt'])).replace(/\r\n/g, '\n');
describe('applyHunk', () => {
it('stages successive hunks and never discards a stale staged or committed patch', async () => {
if (!canRunGit()) return;
const { tmpDir, git } = await createTempRepo();
const original = Array.from({ length: 60 }, (_, index) => `line${index}`);
const changed = [...original];
changed[1] = 'FIRST'; changed[25] = 'SECOND'; changed[50] = 'THIRD';
await writeFile(tmpDir, 'file.txt', original.join('\n') + '\n');
await git.add('file.txt'); await git.commit('Initial');
await writeFile(tmpDir, 'file.txt', changed.join('\n') + '\n');
const historical = splitHunks(await getDiff(tmpDir, { path: 'file.txt' }));
expect(historical).toHaveLength(3);
await applyHunk(tmpDir, 'file.txt', { patch: historical[0], action: 'stage' });
const remaining = splitHunks(await getDiff(tmpDir, { path: 'file.txt' }));
expect(remaining).toHaveLength(2);
await applyHunk(tmpDir, 'file.txt', { patch: remaining[0], action: 'stage' });
const stalePath = path.join(tmpDir, 'stale.patch');
await fs.promises.writeFile(stalePath, historical[0]);
// Git's reverse applicability check accepts it, but it is no longer an
// unstaged hunk. The server must reject it before touching the working file.
await git.raw(['apply', '--reverse', '--check', stalePath]);
await expect(applyHunk(tmpDir, 'file.txt', { patch: historical[0], action: 'discard' })).rejects.toThrow('refresh and try again');
expect(await readWorking(tmpDir)).toBe(changed.join('\n') + '\n');
const last = splitHunks(await getDiff(tmpDir, { path: 'file.txt' }));
expect(last).toHaveLength(1);
await applyHunk(tmpDir, 'file.txt', { patch: last[0], action: 'discard' });
changed[50] = original[50];
expect(await readWorking(tmpDir)).toBe(changed.join('\n') + '\n');
expect(await readStaged(git)).toBe(changed.join('\n') + '\n');
const staged = splitHunks(await getDiff(tmpDir, { path: 'file.txt', staged: true }));
await applyHunk(tmpDir, 'file.txt', { patch: staged[0], action: 'unstage' });
expect(await readWorking(tmpDir)).toBe(changed.join('\n') + '\n');
await git.add('file.txt'); await git.commit('Committed changes');
await expect(applyHunk(tmpDir, 'file.txt', { patch: historical[0], action: 'discard' })).rejects.toThrow('refresh and try again');
});
it.each(['crlf', 'mixed'])('preserves %s file bytes through stage, unstage and discard', async (endings) => {
if (!canRunGit()) return;
const { tmpDir, git } = await createTempRepo();
await git.addConfig('core.autocrlf', 'false');
const serialize = (first, last) => Array.from({ length: 30 }, (_, index) => {
const text = index === 0 ? first : index === 29 ? last : `line${index}`;
return text + (endings === 'crlf' || index % 2 === 0 ? '\r\n' : '\n');
}).join('');
const original = serialize('first', 'last');
const edited = serialize('FIRST', 'LAST');
await writeFile(tmpDir, 'file.txt', original);
await git.add('file.txt'); await git.commit('Initial');
await writeFile(tmpDir, 'file.txt', edited);
const hunks = splitHunks(await getDiff(tmpDir, { path: 'file.txt' }));
await applyHunk(tmpDir, 'file.txt', { patch: hunks[0], action: 'stage' });
expect(await git.raw(['show', ':file.txt'])).toBe(serialize('FIRST', 'last'));
const staged = splitHunks(await getDiff(tmpDir, { path: 'file.txt', staged: true }));
await applyHunk(tmpDir, 'file.txt', { patch: staged[0], action: 'unstage' });
expect(await git.raw(['show', ':file.txt'])).toBe(original);
const working = splitHunks(await getDiff(tmpDir, { path: 'file.txt' }));
await applyHunk(tmpDir, 'file.txt', { patch: working[0], action: 'discard' });
expect(await fs.promises.readFile(path.join(tmpDir, 'file.txt'), 'utf8')).toBe(serialize('first', 'LAST'));
});
it('rejects extra files hidden before the requested patch', async () => {
if (!canRunGit()) return;
const { tmpDir, git } = await createTempRepo();
for (const name of ['file.txt', 'other.txt']) await writeFile(tmpDir, name, ORIGINAL_FILE);
await git.add('.'); await git.commit('Initial');
for (const name of ['file.txt', 'other.txt']) await writeFile(tmpDir, name, EDITED_FILE);
const other = splitHunks(await getDiff(tmpDir, { path: 'other.txt' }))[0];
const requested = splitHunks(await getDiff(tmpDir, { path: 'file.txt' }))[0];
await expect(applyHunk(tmpDir, 'file.txt', { patch: requested + other, action: 'stage' })).rejects.toThrow('refresh and try again');
expect(await git.raw(['diff', '--cached'])).toBe('');
});
it('rejects an invalid action or a patch without a hunk header', async () => {
const { tmpDir } = await createTempRepo();
await expect(applyHunk(tmpDir, 'file.txt', { patch: '@@ -1 +1 @@\n a\n', action: 'bogus' })).rejects.toThrow(
@@ -344,10 +401,9 @@ describe('applyHunk', () => {
);
});
it('accepts hunk patches for files with spaces in their path', async () => {
it.each(['file name.txt', 'зміни.txt'])('accepts hunk patches for %s', async (filePath) => {
if (!canRunGit()) return;
const { tmpDir, git } = await createTempRepo();
const filePath = 'file name.txt';
await writeFile(tmpDir, filePath, ORIGINAL_FILE);
await git.add(filePath);
await git.commit('Initial');
@@ -374,7 +430,7 @@ describe.runIf(canRunGit())('untracked diffs', () => {
// Confirm this fixture produces a real diff exit, including stderr in the warning case.
let expectedPatch;
try {
runGit(tmpDir, ['diff', '--no-color', '--no-index', '--', '/dev/null', 'new file.txt']);
runGit(tmpDir, ['diff', '--no-color', '--full-index', '--no-index', '--', '/dev/null', 'new file.txt']);
throw new Error('Expected git diff to exit with differences');
} catch (error) {
expect(error.status).toBe(1);