section 11: Phase 11 — Diff sources: contract and git reader

This commit is contained in:
Chris Scott committed 2026-10-08 15:53:27 -04:00
1 parent df1891a52d
commit 11c23da67e
7 files changed
+750 -7

No files matched your search

@@ -0,0 +1,8 @@
import { ServiceError } from '../utils/service-error'
export class ChangeWalkthroughError extends ServiceError {
constructor(message: string, status: number, options?: { code?: string; details?: unknown }) {
super(message, status, options)
this.name = 'ChangeWalkthroughError'
}
}
+2 -6
View File
@@ -34,6 +34,7 @@ import { mapWithConcurrency } from '../utils/concurrency'
import { logger } from '../utils/logger'
import { GenerateTextTimeoutError, generateTextWithTimeout } from './opencode/generate-text'
import type { OpenCodeClient } from './opencode/client'
import { ChangeWalkthroughError } from './change-walkthrough-error'
import { readSessionChanges } from './session-changes'
import type { SettingsService } from './settings'
import type { SSEEvent } from './sse-aggregator'
@@ -108,12 +109,7 @@ export interface ChangeWalkthroughServiceOptions {
timeoutMs?: number
}
export class ChangeWalkthroughError extends ServiceError {
constructor(message: string, status: number, options?: { code?: string; details?: unknown }) {
super(message, status, options)
this.name = 'ChangeWalkthroughError'
}
}
export { ChangeWalkthroughError } from './change-walkthrough-error'
export function computeChangesHash(changes: FileDiffInfo[]): string {
const hash = createHash('sha256')
+165
View File
@@ -0,0 +1,165 @@
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { splitUnifiedDiffByFile } from '@opencode-manager/shared/utils'
import { getErrorMessage } from '../utils/error-utils'
import { executeCommand } from '../utils/process'
import { ChangeWalkthroughError } from './change-walkthrough-error'
import type { OpenCodeClient } from './opencode/client'
import { readSessionChanges } from './session-changes'
export interface ReadWalkthroughChangesOptions {
client: OpenCodeClient
session: SessionInfo
source: WalkthroughSource
gitEnv?: Record<string, string>
}
type GitWalkthroughSource = Exclude<WalkthroughSource, { kind: 'session' }>
interface CommandResult {
exitCode: number
stdout: string
stderr: string
}
function commandResult(result: string | CommandResult): CommandResult {
return typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
}
export async function readWalkthroughChanges({
client,
session,
source,
gitEnv,
}: ReadWalkthroughChangesOptions): Promise<FileDiffInfo[]> {
if (source.kind === 'session') {
return readSessionChanges(client, session.id)
}
return readGitChanges(session.location.directory, source, gitEnv)
}
async function readGitChanges(
directory: string,
source: GitWalkthroughSource,
gitEnv?: Record<string, string>,
): Promise<FileDiffInfo[]> {
await assertGitRepository(directory, gitEnv)
switch (source.kind) {
case 'uncommitted':
return collectChanges(directory, await uncommittedRevision(directory, gitEnv), true, gitEnv)
case 'staged':
return collectChanges(directory, ['--cached'], false, gitEnv)
case 'unstaged':
return collectChanges(directory, await unstagedRevision(directory, gitEnv), true, gitEnv)
case 'branch': {
const base = await resolveBaseBranch(directory, source.base, gitEnv)
return collectChanges(directory, [`${base}...HEAD`], false, gitEnv)
}
case 'pullRequest': {
const base = await resolveBaseBranch(directory, source.base, gitEnv)
const ref = `refs/ocm-walkthrough/pr/${source.number}`
try {
await runGit(directory, ['fetch', '--no-tags', 'origin', `+refs/pull/${source.number}/head:${ref}`], gitEnv)
} catch (error) {
throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to fetch the pull request', 502, {
code: 'WALKTHROUGH_SOURCE_UNAVAILABLE',
})
}
return collectChanges(directory, [`${base}...${ref}`], false, gitEnv)
}
}
}
async function uncommittedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
return (await headExists(directory, gitEnv)) ? ['HEAD'] : ['--cached']
}
async function unstagedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
return (await headExists(directory, gitEnv)) ? [] : ['--cached']
}
async function collectChanges(
directory: string,
revisionArgs: string[],
includeUntracked: boolean,
gitEnv?: Record<string, string>,
): Promise<FileDiffInfo[]> {
const tracked = await runGit(directory, ['diff', '--no-color', '--no-ext-diff', '-U3', ...revisionArgs], gitEnv)
if (!includeUntracked) {
return splitUnifiedDiffByFile(tracked)
}
const untracked = await readUntrackedDiffs(directory, gitEnv)
return splitUnifiedDiffByFile([tracked, ...untracked].join(''))
}
async function readUntrackedDiffs(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
const output = await runGit(directory, ['ls-files', '--others', '--exclude-standard', '-z'], gitEnv)
const paths = output.split('\0').filter((entry) => entry.length > 0).sort()
const diffs: string[] = []
for (const filePath of paths) {
const result = commandResult(await executeCommand(
['git', '-C', directory, 'diff', '--no-color', '--no-index', '--', '/dev/null', filePath],
{ env: gitEnv, silent: true, ignoreExitCode: true },
))
diffs.push(result.stdout)
}
return diffs
}
async function assertGitRepository(directory: string, gitEnv?: Record<string, string>): Promise<void> {
let insideWorkTree = false
try {
insideWorkTree = (await runGit(directory, ['rev-parse', '--is-inside-work-tree'], gitEnv)).trim() === 'true'
} catch {
insideWorkTree = false
}
if (!insideWorkTree) {
throw new ChangeWalkthroughError('Not a git repository', 409, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
}
}
async function headExists(directory: string, gitEnv?: Record<string, string>): Promise<boolean> {
const result = commandResult(await executeCommand(
['git', '-C', directory, 'rev-parse', '--verify', '--quiet', 'HEAD'],
{ env: gitEnv, silent: true, ignoreExitCode: true },
))
return result.exitCode === 0
}
async function resolveBaseBranch(
directory: string,
base: string | undefined,
gitEnv?: Record<string, string>,
): Promise<string> {
if (base) {
return base
}
const originHead = await tryGit(directory, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], gitEnv)
if (originHead) {
return originHead.trim()
}
for (const candidate of ['main', 'master']) {
const resolved = await tryGit(directory, ['rev-parse', '--verify', '--quiet', candidate], gitEnv)
if (resolved) {
return candidate
}
}
throw new ChangeWalkthroughError('No base branch found', 409, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
}
async function tryGit(directory: string, args: string[], gitEnv?: Record<string, string>): Promise<string | null> {
const result = commandResult(await executeCommand(['git', '-C', directory, ...args], {
env: gitEnv,
silent: true,
ignoreExitCode: true,
}))
return result.exitCode === 0 ? result.stdout : null
}
async function runGit(directory: string, args: string[], gitEnv?: Record<string, string>): Promise<string> {
return executeCommand(['git', '-C', directory, ...args], { env: gitEnv, silent: true })
}
@@ -0,0 +1,206 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterAll, describe, expect, it, vi } from 'vitest'
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import {
DEFAULT_WALKTHROUGH_SOURCE,
parseWalkthroughSourceKey,
walkthroughSourceKey,
} from '@opencode-manager/shared/schemas'
import { ChangeWalkthroughError } from '../../src/services/change-walkthrough-error'
import { readWalkthroughChanges } from '../../src/services/walkthrough-sources'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { cloneOrigin, createCommittedRepo, createOrigin, git, uniqueName } from '../helpers/git-fixtures'
const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'walkthrough-sources-'))
process.env.GIT_CONFIG_NOSYSTEM = '1'
process.env.GIT_CONFIG_GLOBAL = '/dev/null'
const GIT_ENV = { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0' }
afterAll(() => {
rmSync(workspaceRoot, { recursive: true, force: true })
})
function repoPath(prefix: string): string {
return path.join(workspaceRoot, uniqueName(prefix))
}
function sessionAt(directory: string): SessionInfo {
return { id: 'ses_test', title: 'Test', location: { directory } } as SessionInfo
}
function readAt(directory: string, source: WalkthroughSource): Promise<FileDiffInfo[]> {
return readWalkthroughChanges({
client: {} as OpenCodeClient,
session: sessionAt(directory),
source,
gitEnv: GIT_ENV,
})
}
describe('readWalkthroughChanges', () => {
it('delegates the session source to the session diff', async () => {
const changes: FileDiffInfo[] = [
{ file: 'src/a.ts', patch: '@@ -1 +1 @@\n-a\n+b', additions: 1, deletions: 1, status: 'modified' },
]
const client = {
api: {
message: { list: vi.fn(async () => ({ data: [{ id: 'msg-1' }], cursor: {} })) },
session: { diff: vi.fn(async () => changes) },
},
} as unknown as OpenCodeClient
const result = await readWalkthroughChanges({
client,
session: sessionAt('/not/a/repo'),
source: DEFAULT_WALKTHROUGH_SOURCE,
gitEnv: GIT_ENV,
})
expect(result).toEqual(changes)
})
it('reports staged-only edits only in staged', async () => {
const repo = repoPath('staged')
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'a.txt'), 'one\n')
git(['add', 'a.txt'], repo)
git(['commit', '-m', 'add a'], repo)
writeFileSync(path.join(repo, 'a.txt'), 'two\n')
git(['add', 'a.txt'], repo)
const staged = await readAt(repo, { kind: 'staged' })
const unstaged = await readAt(repo, { kind: 'unstaged' })
const uncommitted = await readAt(repo, { kind: 'uncommitted' })
expect(staged.map((entry) => entry.file)).toEqual(['a.txt'])
expect(staged[0]?.status).toBe('modified')
expect(unstaged).toEqual([])
expect(uncommitted.map((entry) => entry.file)).toEqual(['a.txt'])
})
it('reports an untracked file as added in uncommitted and unstaged', async () => {
const repo = repoPath('untracked')
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'new.txt'), 'hello\n')
const uncommitted = await readAt(repo, { kind: 'uncommitted' })
const unstaged = await readAt(repo, { kind: 'unstaged' })
expect(uncommitted).toHaveLength(1)
expect(uncommitted[0]).toMatchObject({ file: 'new.txt', status: 'added', additions: 1, deletions: 0 })
expect(unstaged.map((entry) => entry.file)).toEqual(['new.txt'])
expect(unstaged[0]?.status).toBe('added')
})
it('parses untracked paths with spaces and non-ASCII characters', async () => {
const repo = repoPath('special-names')
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'my file.txt'), 'hello\n')
writeFileSync(path.join(repo, 'é.txt'), 'bonjour\n')
const unstaged = await readAt(repo, { kind: 'unstaged' })
expect(unstaged.map((entry) => entry.file).sort()).toEqual(['my file.txt', 'é.txt'])
})
it('reports branch commits against the base', async () => {
const repo = repoPath('branch')
createCommittedRepo(repo, 'main')
git(['checkout', '-b', 'feature'], repo)
writeFileSync(path.join(repo, 'feature.txt'), 'feature\n')
git(['add', 'feature.txt'], repo)
git(['commit', '-m', 'feature'], repo)
const explicit = await readAt(repo, { kind: 'branch', base: 'main' })
const resolved = await readAt(repo, { kind: 'branch' })
expect(explicit.map((entry) => entry.file)).toEqual(['feature.txt'])
expect(explicit[0]?.status).toBe('added')
expect(resolved.map((entry) => entry.file)).toEqual(['feature.txt'])
})
it('reports a pull request ref pushed to the origin', async () => {
const origin = repoPath('origin')
const work = repoPath('work')
const clone = repoPath('clone')
createOrigin(origin, work)
cloneOrigin(origin, clone)
git(['checkout', '-b', 'feature'], clone)
writeFileSync(path.join(clone, 'pr.txt'), 'pr\n')
git(['add', 'pr.txt'], clone)
git(['commit', '-m', 'pr'], clone)
git(['push', 'origin', 'HEAD:refs/pull/1/head'], clone)
const changes = await readAt(clone, { kind: 'pullRequest', number: 1, base: 'main' })
expect(changes.map((entry) => entry.file)).toEqual(['pr.txt'])
expect(changes[0]?.status).toBe('added')
})
it('excludes untracked files from staged and branch sources', async () => {
const repo = repoPath('not-untracked')
createCommittedRepo(repo, 'main')
git(['checkout', '-b', 'feature'], repo)
writeFileSync(path.join(repo, 'feature.txt'), 'feature\n')
git(['add', 'feature.txt'], repo)
git(['commit', '-m', 'feature'], repo)
writeFileSync(path.join(repo, 'loose.txt'), 'loose\n')
const staged = await readAt(repo, { kind: 'staged' })
const branch = await readAt(repo, { kind: 'branch', base: 'main' })
expect(staged).toEqual([])
expect(branch.map((entry) => entry.file)).toEqual(['feature.txt'])
})
it('rejects a non-git directory with a 409 source error', async () => {
const dir = repoPath('plain')
mkdirSync(dir, { recursive: true })
const error = await readAt(dir, { kind: 'staged' }).catch((thrown) => thrown)
expect(error).toBeInstanceOf(ChangeWalkthroughError)
expect(error).toMatchObject({ status: 409, code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
})
it('rejects a branch source when no base branch exists', async () => {
const repo = repoPath('nobase')
createCommittedRepo(repo, 'trunk')
const error = await readAt(repo, { kind: 'branch' }).catch((thrown) => thrown)
expect(error).toBeInstanceOf(ChangeWalkthroughError)
expect(error).toMatchObject({ status: 409, code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
})
})
describe('walkthroughSourceKey', () => {
it('round-trips every source kind', () => {
const sources: WalkthroughSource[] = [
{ kind: 'session' },
{ kind: 'uncommitted' },
{ kind: 'staged' },
{ kind: 'unstaged' },
{ kind: 'branch' },
{ kind: 'branch', base: 'develop' },
{ kind: 'pullRequest', number: 12 },
{ kind: 'pullRequest', number: 12, base: 'develop' },
]
for (const source of sources) {
expect(parseWalkthroughSourceKey(walkthroughSourceKey(source))).toEqual(source)
}
})
it('rejects invalid keys', () => {
expect(parseWalkthroughSourceKey('branch:-x')).toBeNull()
expect(parseWalkthroughSourceKey('pr:0:')).toBeNull()
expect(parseWalkthroughSourceKey('pr:abc:main')).toBeNull()
expect(parseWalkthroughSourceKey('nonsense')).toBeNull()
})
})
+159 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { parseDiffLines, splitDiffHunks } from '@opencode-manager/shared/utils';
import { parseDiffLines, splitDiffHunks, splitUnifiedDiffByFile } from '@opencode-manager/shared/utils';
const DIFF = [
'diff --git a/src/app.ts b/src/app.ts',
@@ -117,3 +117,161 @@ describe('splitDiffHunks', () => {
expect(splitDiffHunks('')).toEqual([]);
});
});
describe('splitUnifiedDiffByFile', () => {
it('splits a modified file and counts additions and removals', () => {
const result = splitUnifiedDiffByFile(DIFF);
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({ file: 'src/app.ts', status: 'modified', additions: 3, deletions: 2 });
expect(result[0]!.patch.startsWith('diff --git a/src/app.ts b/src/app.ts')).toBe(true);
});
it('reads an added file from the new side', () => {
const diff = [
'diff --git a/src/new.ts b/src/new.ts',
'new file mode 100644',
'index 0000000..1111111',
'--- /dev/null',
'+++ b/src/new.ts',
'@@ -0,0 +1,2 @@',
'+one',
'+two',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'src/new.ts', status: 'added', additions: 2, deletions: 0 });
});
it('reads a deleted file from the old side', () => {
const diff = [
'diff --git a/src/old.ts b/src/old.ts',
'deleted file mode 100644',
'index 1111111..0000000',
'--- a/src/old.ts',
'+++ /dev/null',
'@@ -1,2 +0,0 @@',
'-one',
'-two',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'src/old.ts', status: 'deleted', additions: 0, deletions: 2 });
});
it('reads a renamed file with no content changes', () => {
const diff = [
'diff --git a/src/old.ts b/src/new.ts',
'similarity index 100%',
'rename from src/old.ts',
'rename to src/new.ts',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'src/new.ts', status: 'modified', additions: 0, deletions: 0 });
});
it('keeps a binary block with no hunks', () => {
const diff = [
'diff --git a/assets/logo.png b/assets/logo.png',
'index 1111111..2222222 100644',
'Binary files a/assets/logo.png and b/assets/logo.png differ',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'assets/logo.png', status: 'modified' });
expect(file!.patch).not.toContain('@@');
});
it('splits multiple files', () => {
const diff = [
DIFF,
'',
'diff --git a/src/other.ts b/src/other.ts',
'--- a/src/other.ts',
'+++ b/src/other.ts',
'@@ -1 +1 @@',
'-a',
'+b',
].join('\n');
expect(splitUnifiedDiffByFile(diff).map((entry) => entry.file)).toEqual(['src/app.ts', 'src/other.ts']);
});
it('parses a path containing a space with the trailing tab git appends', () => {
const diff = [
'diff --git a/my file.txt b/my file.txt',
'index 5626abf..f719efd 100644',
'--- a/my file.txt\t',
'+++ b/my file.txt\t',
'@@ -1 +1 @@',
'-one',
'+two',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'my file.txt', status: 'modified' });
});
it('decodes a C-quoted octal UTF-8 path', () => {
const diff = [
'diff --git "a/\\303\\251.txt" "b/\\303\\251.txt"',
'index 587be6b..ccc9bd6 100644',
'--- "a/\\303\\251.txt"',
'+++ "b/\\303\\251.txt"',
'@@ -1 +1 @@',
'-x',
'+xx',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'é.txt', status: 'modified' });
});
it('decodes a quoted rename target', () => {
const diff = [
'diff --git "a/\\303\\251.txt" "b/\\303\\251 renamed.txt"',
'similarity index 100%',
'rename from "\\303\\251.txt"',
'rename to "\\303\\251 renamed.txt"',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'é renamed.txt', status: 'modified' });
});
it('decodes a quoted path in the header fallback', () => {
const diff = [
'diff --git "a/\\303\\251.bin" "b/\\303\\251.bin"',
'index 1111111..2222222 100644',
'Binary files "a/\\303\\251.bin" and "b/\\303\\251.bin" differ',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'é.bin', status: 'modified' });
});
it('decodes a quoted header path when only the new side is quoted', () => {
const diff = [
'diff --git a/plain.bin "b/\\303\\251.bin"',
'index 1111111..2222222 100644',
'Binary files a/plain.bin and "b/\\303\\251.bin" differ',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'é.bin', status: 'modified' });
});
it('returns an empty list for an empty diff', () => {
expect(splitUnifiedDiffByFile('')).toEqual([]);
});
});
+57
View File
@@ -74,3 +74,60 @@ export const GenerateChangeWalkthroughRequestSchema = z.object({
});
export type GenerateChangeWalkthroughRequest = z.infer<typeof GenerateChangeWalkthroughRequestSchema>;
export const GitRefSchema = z.string().trim().min(1).max(200).regex(/^[^-\s][^\s]*$/)
export const WalkthroughSourceSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('session') }),
z.object({ kind: z.literal('uncommitted') }),
z.object({ kind: z.literal('staged') }),
z.object({ kind: z.literal('unstaged') }),
z.object({ kind: z.literal('branch'), base: GitRefSchema.optional() }),
z.object({ kind: z.literal('pullRequest'), number: z.number().int().positive(), base: GitRefSchema.optional() }),
])
export type WalkthroughSource = z.infer<typeof WalkthroughSourceSchema>
export const DEFAULT_WALKTHROUGH_SOURCE: WalkthroughSource = { kind: 'session' }
export function walkthroughSourceKey(source: WalkthroughSource): string {
switch (source.kind) {
case 'session':
case 'uncommitted':
case 'staged':
case 'unstaged':
return source.kind
case 'branch':
return `branch:${source.base ?? ''}`
case 'pullRequest':
return `pr:${source.number}:${source.base ?? ''}`
}
}
export function parseWalkthroughSourceKey(key: string): WalkthroughSource | null {
if (key === 'session' || key === 'uncommitted' || key === 'staged' || key === 'unstaged') {
return { kind: key }
}
if (key.startsWith('branch:')) {
const base = key.slice('branch:'.length)
return parseWalkthroughSourceCandidate(base ? { kind: 'branch', base } : { kind: 'branch' })
}
if (key.startsWith('pr:')) {
const rest = key.slice('pr:'.length)
const separator = rest.indexOf(':')
if (separator < 0) {
return null
}
const number = Number(rest.slice(0, separator))
const base = rest.slice(separator + 1)
return parseWalkthroughSourceCandidate(
base ? { kind: 'pullRequest', number, base } : { kind: 'pullRequest', number },
)
}
return null
}
function parseWalkthroughSourceCandidate(candidate: unknown): WalkthroughSource | null {
const parsed = WalkthroughSourceSchema.safeParse(candidate)
return parsed.success ? parsed.data : null
}
+153
View File
@@ -115,3 +115,156 @@ export function splitDiffHunks(patch: string): DiffHunk[] {
function toHunk(lines: string[]): DiffHunk {
return { header: lines[0]!, text: lines.join("\n") };
}
export interface UnifiedFileDiff {
file: string;
status: "added" | "deleted" | "modified";
patch: string;
additions: number;
deletions: number;
}
export function splitUnifiedDiffByFile(diff: string): UnifiedFileDiff[] {
const blocks: string[][] = [];
for (const line of diff.split("\n")) {
if (line.startsWith("diff --git ")) {
blocks.push([line]);
} else if (blocks.length > 0) {
blocks[blocks.length - 1]!.push(line);
}
}
return blocks.map((lines) => toUnifiedFileDiff(lines));
}
function toUnifiedFileDiff(lines: string[]): UnifiedFileDiff {
const header = lines[0]!;
const newPath = lines.find((line) => line.startsWith("+++ "));
const oldPath = lines.find((line) => line.startsWith("--- "));
const renameTo = lines.find((line) => line.startsWith("rename to "));
let file = "";
let status: UnifiedFileDiff["status"] = "modified";
let additions = 0;
let deletions = 0;
if (newPath && newPath.slice(4) !== "/dev/null") {
file = parseDiffPathToken(newPath.slice(4), "b/");
} else if (oldPath && oldPath.slice(4) !== "/dev/null") {
file = parseDiffPathToken(oldPath.slice(4), "a/");
} else if (renameTo) {
file = parseDiffPathToken(renameTo.slice("rename to ".length), "");
} else {
file = newPathFromDiffHeader(header);
}
for (const line of lines) {
if (line.startsWith("new file mode")) {
status = "added";
} else if (line.startsWith("deleted file mode")) {
status = "deleted";
}
if (line.startsWith("+++") || line.startsWith("---")) {
continue;
}
if (line.startsWith("+")) {
additions++;
} else if (line.startsWith("-")) {
deletions++;
}
}
return { file, status, patch: lines.join("\n"), additions, deletions };
}
function stripDiffPathPrefix(path: string, prefix: string): string {
return path.startsWith(prefix) ? path.slice(prefix.length) : path;
}
const GIT_C_ESCAPES: Record<string, number> = {
a: 0x07,
b: 0x08,
f: 0x0c,
n: 0x0a,
r: 0x0d,
t: 0x09,
v: 0x0b,
"\\": 0x5c,
'"': 0x22,
};
function parseDiffPathToken(raw: string, prefix: string): string {
const token = raw.startsWith('"') ? decodeGitQuotedPath(raw) : raw.split("\t")[0]!;
return stripDiffPathPrefix(token, prefix);
}
function decodeGitQuotedPath(raw: string): string {
const bytes: number[] = [];
const encoder = new TextEncoder();
let index = 1;
while (index < raw.length) {
const char = raw[index]!;
if (char === '"') {
break;
}
if (char === "\\") {
const octal = /^[0-7]{1,3}/.exec(raw.slice(index + 1));
if (octal) {
bytes.push(parseInt(octal[0]!, 8) & 0xff);
index += 1 + octal[0]!.length;
continue;
}
const next = raw[index + 1];
if (next === undefined) {
break;
}
const escaped = GIT_C_ESCAPES[next];
bytes.push(...(escaped === undefined ? encoder.encode(next) : [escaped]));
index += 2;
continue;
}
bytes.push(...encoder.encode(char));
index += 1;
}
return new TextDecoder().decode(new Uint8Array(bytes));
}
function newPathFromDiffHeader(header: string): string {
const rest = header.slice("diff --git ".length);
if (rest.startsWith('"')) {
const end = findClosingQuote(rest);
if (end >= 0) {
let index = end + 1;
while (rest[index] === " ") {
index += 1;
}
return parseDiffPathToken(rest.slice(index), "b/");
}
}
const quoted = rest.indexOf(' "');
if (quoted >= 0) {
return parseDiffPathToken(rest.slice(quoted + 1), "b/");
}
const index = rest.lastIndexOf(" b/");
return index >= 0 ? parseDiffPathToken(rest.slice(index + 1), "b/") : "";
}
function findClosingQuote(raw: string): number {
for (let index = 1; index < raw.length; index += 1) {
if (raw[index] === "\\") {
index += 1;
continue;
}
if (raw[index] === '"') {
return index;
}
}
return -1;
}