Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276/** * GitRepositoryResolver tests (saga j8dtju.5 — phase 1). * * Real-git coverage against fixtures (main repo, linked worktree sharing repository identity, * detached HEAD, path with spaces, symlink spelling, non-Git cwd, merged vs unmerged ancestry, * hostile ref input) PLUS injected-runner hermetic coverage of ref validation and the * option-injection-safe argument positioning (`--end-of-options`). */import { describe, expect, it } from 'bun:test';import { join } from 'node:path';import { GitRepositoryResolver, type GitRunner, type GitRunOptions, type GitRunOutcome } from '@/core/git';import { buildMainRepo, addLinkedWorktree, detachHead, buildRepoWithSpaceInPath, makeSymlink, dispose, freshTmp,} from '../../helpers/git-fixtures';
/** A scripted injected runner: keys on the first argv token or a custom predicate. */class ScriptRunner implements GitRunner { public calls: GitRunOptions[] = []; constructor( private readonly dispatch: (opts: GitRunOptions) => GitRunOutcome, private readonly record = true, ) {} async run(opts: GitRunOptions): Promise<GitRunOutcome> { if (this.record) this.calls.push(opts); return this.dispatch(opts); }}
describe('GitRepositoryResolver — real-git identity', () => { it('resolves a main checkout identity (HEAD + branch; commonDir === gitDir)', async () => { const repo = freshTmp('shard-resolver-main-'); try { const { defaultGitRunner } = await import('@/core/git'); const { head } = await buildMainRepo(repo); const resolver = new GitRepositoryResolver(defaultGitRunner); const out = await resolver.resolveIdentity(repo); expect(out.kind).toBe('ok'); if (out.kind !== 'ok') return; const { repository: { commonDir, commonDirFingerprint }, worktree: { toplevel, gitDir, toplevelFingerprint }, head: h, } = out.identity; expect(toplevel).toBe(repo); // Main checkout: the per-worktree git dir IS the common dir. expect(gitDir).toBe(commonDir); expect(commonDirFingerprint).toHaveLength(16); expect(toplevelFingerprint).toHaveLength(16); expect(h.commit).toBe(head); expect(h.branch).toBe('refs/heads/main'); } finally { dispose(repo); } });
it('a linked worktree shares the repository identity (commonDir) with the main checkout', async () => { const parent = freshTmp('shard-resolver-shared-'); const main = join(parent, 'main'); const linked = join(parent, 'linked'); try { const { defaultGitRunner } = await import('@/core/git'); await buildMainRepo(main); await addLinkedWorktree(main, linked, 'feature'); const resolver = new GitRepositoryResolver(defaultGitRunner);
const mainOut = await resolver.resolveIdentity(main); const linkedOut = await resolver.resolveIdentity(linked); expect(mainOut.kind).toBe('ok'); expect(linkedOut.kind).toBe('ok'); if (mainOut.kind !== 'ok' || linkedOut.kind !== 'ok') return; // Repository identity (common-dir) is shared across the two worktrees. expect(linkedOut.identity.repository.commonDir).toBe(mainOut.identity.repository.commonDir); expect(linkedOut.identity.repository.commonDirFingerprint).toBe( mainOut.identity.repository.commonDirFingerprint, ); // Worktree identity differs (different toplevels). expect(linkedOut.identity.worktree.toplevel).toBe(linked); expect(linkedOut.identity.worktree.gitDir).not.toBe(linkedOut.identity.repository.commonDir); } finally { dispose(parent); } });
it('resolves a detached HEAD with no attached branch', async () => { const repo = freshTmp('shard-resolver-detached-'); try { const { defaultGitRunner } = await import('@/core/git'); await buildMainRepo(repo); await detachHead(repo); const resolver = new GitRepositoryResolver(defaultGitRunner); const out = await resolver.resolveIdentity(repo); expect(out.kind).toBe('ok'); if (out.kind !== 'ok') return; expect(out.identity.head.branch).toBeUndefined(); expect(out.identity.head.commit).toMatch(/^[0-9a-f]{40}$/); } finally { dispose(repo); } });
it('handles a top-level path containing a space', async () => { const parent = freshTmp('shard-resolver-space-'); try { const { defaultGitRunner } = await import('@/core/git'); const repo = await buildRepoWithSpaceInPath(parent); const resolver = new GitRepositoryResolver(defaultGitRunner); const out = await resolver.resolveIdentity(repo); expect(out.kind).toBe('ok'); if (out.kind === 'ok') { expect(out.identity.worktree.toplevel).toBe(repo); expect(out.identity.head.branch).toBe('refs/heads/main'); } } finally { dispose(parent); } });
it('collapses a symlink spelling of the cwd to the same canonical identity', async () => { const parent = freshTmp('shard-resolver-symlink-'); const main = join(parent, 'main'); const link = join(parent, 'mainlink'); try { const { defaultGitRunner } = await import('@/core/git'); await buildMainRepo(main); makeSymlink(link, main); const resolver = new GitRepositoryResolver(defaultGitRunner);
const realOut = await resolver.resolveIdentity(main); const linkOut = await resolver.resolveIdentity(link); expect(realOut.kind).toBe('ok'); expect(linkOut.kind).toBe('ok'); if (realOut.kind !== 'ok' || linkOut.kind !== 'ok') return; // realpath resolves the symlink to the same canonical toplevel + commonDir. expect(linkOut.identity.worktree.toplevel).toBe(realOut.identity.worktree.toplevel); expect(linkOut.identity.repository.commonDirFingerprint).toBe( realOut.identity.repository.commonDirFingerprint, ); } finally { dispose(parent); } });
it('classifies a non-Git cwd as `non-git` (not `probe-failed`)', async () => { const dir = freshTmp('shard-resolver-nongit-'); try { const { defaultGitRunner } = await import('@/core/git'); const resolver = new GitRepositoryResolver(defaultGitRunner); const out = await resolver.resolveIdentity(dir); expect(out.kind).toBe('non-git'); } finally { dispose(dir); } });});
describe('GitRepositoryResolver — porcelain enumeration', () => { it('lists a main repo plus its linked worktree via porcelain -z', async () => { const parent = freshTmp('shard-resolver-list-'); const main = join(parent, 'main'); const linked = join(parent, 'linked'); try { const { defaultGitRunner } = await import('@/core/git'); await buildMainRepo(main); await addLinkedWorktree(main, linked, 'feature'); const resolver = new GitRepositoryResolver(defaultGitRunner); const res = await resolver.listWorktrees(main); expect(res.ok).toBe(true); if (!res.ok) return; expect(res.entries.length).toBeGreaterThanOrEqual(2); const paths = res.entries.map((e) => e.worktree).sort(); expect(paths).toContain(main); expect(paths).toContain(linked); } finally { dispose(parent); } });});
describe('GitRepositoryResolver — ref/branch validation + ancestry (injected runner)', () => { it('validates a well-formed branch name and rejects a malformed one', async () => { let last: GitRunOptions | undefined; const runner = new ScriptRunner((opts) => { last = opts; // Simulate git check-ref-format --branch <name>: exit 0 for `feature`, 128 for `-x`. const name = opts.argv[opts.argv.length - 1] ?? ''; const ok = name === 'feature'; return ok ? { ok: true, result: { stdout: name, stderr: '', exitCode: 0, durationMs: 1, truncated: false } } : { ok: false, error: { kind: 'nonzero-exit', message: 'bad name', exitCode: 128, stderr: `fatal: '${name}' is not a valid branch name` }, }; }); const resolver = new GitRepositoryResolver(runner); expect(await resolver.validateBranchName('/repo', 'feature')).toBe(true); expect(await resolver.validateBranchName('/repo', '-x')).toBe(false); // `--branch` consumes the name as its argument (argv position 2), NOT interpolated. expect(last?.argv).toEqual(['check-ref-format', '--branch', '-x']); });
it('resolves a ref with `--end-of-options` before the ref (no option injection)', async () => { const sha = '994f00717b8b2e12da57828f44648addcaccce3d'; const runner = new ScriptRunner((opts) => { // The ref must appear positioned AFTER --end-of-options. expect(opts.argv).toContain('--end-of-options'); const ref = opts.argv[opts.argv.indexOf('--end-of-options') + 1] ?? ''; // A hostile ref-like string arrives as a single literal token (spaces preserved, the // `^{commit}` suffix intact), never shell-split. expect(ref.startsWith('; rm -rf /')).toBe(true); expect(ref).toContain(' '); return { ok: true, result: { stdout: `${sha}\n`, stderr: '', exitCode: 0, durationMs: 1, truncated: false }, }; }); const resolver = new GitRepositoryResolver(runner); expect(await resolver.resolveRef('/repo', '; rm -rf /')).toBe(sha); });
it('returns undefined for an unresolvable ref', async () => { const runner = new ScriptRunner(() => ({ ok: false, error: { kind: 'nonzero-exit', message: 'bad rev', exitCode: 128, stderr: 'fatal: bad revision' }, })); const resolver = new GitRepositoryResolver(runner); expect(await resolver.resolveRef('/repo', 'does-not-exist')).toBeUndefined(); });
it('proves merged reachability via --is-ancestor exit 0, and reports unmerged via exit 1', async () => { const runner = new ScriptRunner((opts) => { // argv: [merge-base, --is-ancestor, --end-of-options, maybeAncestor, descendant] const tokens = opts.argv; const anc = tokens[tokens.length - 2] ?? ''; const dec = tokens[tokens.length - 1] ?? ''; // `merged` = anc === 'main' into 'feature' (ancestor). `unmerged` = anc === 'feature'. const isAncestor = anc === 'main' && dec === 'feature'; return { ok: true, result: { stdout: '', stderr: '', exitCode: isAncestor ? 0 : 1, durationMs: 1, truncated: false, }, }; }); const resolver = new GitRepositoryResolver(runner); expect(await resolver.isAncestor('/repo', 'main', 'feature')).toBe(true); expect(await resolver.isAncestor('/repo', 'feature', 'main')).toBe(false); });});
describe('GitRepositoryResolver — real-git ancestry', () => { it('main is an ancestor of feature (merged), feature is not an ancestor of main (unmerged)', async () => { const repo = freshTmp('shard-resolver-ancestry-'); try { const { defaultGitRunner } = await import('@/core/git'); const { head: mainCommit, feature } = await buildMainRepo(repo, { featureBranch: true }); const resolver = new GitRepositoryResolver(defaultGitRunner); // main is an ancestor of feature (feature branched from main + added a commit). expect(await resolver.isAncestor(repo, mainCommit, feature ?? '')).toBe(true); // feature is NOT an ancestor of main (the feature commit is ahead). expect(await resolver.isAncestor(repo, feature ?? '', mainCommit)).toBe(false); } finally { dispose(repo); } });});