GitHubivarvong

ply

main
ply6 git calls96 ms35 KiB3 cachedprotocol v2
454 lines44 KiBRaw
1// Merging, decided by git: fast-forward / up-to-date / merge-commit / conflict outcomes against `git merge-tree
2// --write-tree` (the merged tree oid) and `git merge` in a clone (the commit), over hand-built cases and a seeded
3// property run of random three-way edits. Branch create via editFile `base`, and delete, round-trip through receive-pack.
4import { test, beforeAll as before, afterAll as after } from 'vitest';
5import assert from 'node:assert/strict';
6import { join } from 'node:path';
7import { mkdirSync, writeFileSync, rmSync, mkdtempSync } from 'node:fs';
8import { spawnSync } from 'node:child_process';
9import { tmpdir } from 'node:os';
10import { git, tmpRoot, makeBareRepo, startGitServer, commitFiles, fsckProblems, initRepo } from './server.js';
11import { Rng } from './fuzz/prng.js';
12import { oracleRediff } from './gitversion.js';
13const rediff = oracleRediff();
14import { editFile } from '../src/edit.js';
15import { rebaseBranch } from '../src/rebase.js';
16import { mergeBranch, deleteRef, threeWay, bestBases, mergeMode, uniqueObjects, mergeBase } from '../src/merge.js';
17import { DEFAULT_LIMITS, WORKER_LIMITS } from '../src/limits.js';
18import { attributesFor } from '../src/attributes.js';
19import { createTransport as createTransportR } from '../src/http.js';
20import { GitHttp } from '../src/client.js';
21import { Tracer, arrayExporter, flattenLine } from '../src/otel.js';
22import { unwrapAsync } from './unwrap.js';
24import { unwrap } from './unwrap.js';
25// Throwing adapters over the Result API (0.2.0): the assertions below are about the throw.
26const createTransport = (...a) => unwrap(createTransportR(...a));
27// the empty tree as attr.tree: git reads no .gitattributes (our default) whatever its version's bare-repo default is
28const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
29let root, cleanup, srv, n = 0;
30const author = { name: 'merger', email: 'merger@x' };
31before(async () => { ({ root, cleanup } = tmpRoot()); srv = await startGitServer(root); });
32after(async () => { await srv.close(); cleanup(); });
34const ENV = { ...process.env, GIT_AUTHOR_NAME: 'w', GIT_AUTHOR_EMAIL: 'w@x', GIT_COMMITTER_NAME: 'w', GIT_COMMITTER_EMAIL: 'w@x', GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'commit.gpgsign', GIT_CONFIG_VALUE_0: 'false' };
35const sh = (cwd, args, input) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', env: ENV, input });
36const repo = () => { const name = `m${n++}`; const bare = makeBareRepo(root, name); const work = join(root, `w${name}`); mkdirSync(work); initRepo(work); return { name, bare, work, url: `${srv.url}/${name}.git` }; };
37// write files on a branch in the work repo and push it
38const branchCommit = (r, branch, from, files, msg) => {
39 // the bare repo is the truth (our pushes move it); start from its current state of `from`, not the work repo's stale copy
40 let start = from;
41 if (!/^[0-9a-f]{40}/.test(from)) { const f = sh(r.work, ['fetch', '-q', r.bare, `refs/heads/${from}`]); assert.equal(f.status, 0, f.stderr); start = 'FETCH_HEAD'; }
42 sh(r.work, ['checkout', '-q', '-B', branch, start]);
43 for (const [p, v] of Object.entries(files)) { if (v === null) { rmSync(join(r.work, p), { force: true }); continue; } mkdirSync(join(r.work, p, '..'), { recursive: true }); writeFileSync(join(r.work, p), v); }
44 sh(r.work, ['add', '-A']); const c = sh(r.work, ['commit', '-q', '--allow-empty', '-m', msg]); assert.equal(c.status, 0, c.stderr);
45 const p = sh(r.work, ['push', '-q', r.bare, `HEAD:refs/heads/${branch}`]); assert.equal(p.status, 0, p.stderr);
46 return sh(r.work, ['rev-parse', 'HEAD']).stdout.trim();
47};
48// git's answers
49// --name-only output: <tree>\n<conflicted paths…>\n\n<informational messages>; exit 0 clean, 1 conflicts
50const gitMergeTree = (bare, ours, theirs, attrTree = EMPTY_TREE) => { const r = sh(bare, ['-c', `attr.tree=${attrTree}`, 'merge-tree', '--write-tree', '--name-only', ours, theirs]); assert.ok(r.status === 0 || r.status === 1, r.stderr); const [head] = r.stdout.split('\n\n'); const lines = head.split('\n'); return { clean: r.status === 0, tree: lines[0].trim(), conflicts: lines.slice(1).filter(Boolean), info: r.stdout.split('\n\n').slice(1).join(' ').trim() }; };
51const gitMerge = (bare, ref, from) => { const d = mkdtempSync(join(tmpdir(), 'gm-')); try { sh(d, ['clone', '-q', bare, '.']); sh(d, ['checkout', '-q', ref]); const m = sh(d, ['merge', '--no-edit', `origin/${from}`]); return { clean: m.status === 0, tree: sh(d, ['rev-parse', 'HEAD^{tree}']).stdout.trim(), parents: sh(d, ['rev-list', '--parents', '-n1', 'HEAD']).stdout.trim().split(' ').slice(1) }; } finally { rmSync(d, { recursive: true, force: true }); } };
52const merge = (r, opts = {}, ex = arrayExporter()) => unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author, ...opts }, { tracer: new Tracer({ exporter: ex }), rediff }));
54test('threeWay: the trivial-merge rules, one directory', () => {
55 const e = (name, oid, mode = '100644') => ({ name, oid, mode });
56 const A = 'a'.repeat(40), B = 'b'.repeat(40), C = 'c'.repeat(40);
57 const r = threeWay([e('same', A), e('ours-changed', A), e('theirs-changed', A), e('both-same', A), e('both-diff', A), e('theirs-deleted', A), e('ours-deleted', A), e('dir', A, '40000'), e('both-deleted', A)],
58 [e('same', A), e('ours-changed', B), e('theirs-changed', A), e('both-same', B), e('both-diff', B), e('theirs-deleted', A), e('dir', B, '40000'), e('ours-added', A)],
59 [e('same', A), e('ours-changed', A), e('theirs-changed', B), e('both-same', B), e('both-diff', C), e('ours-deleted', A), e('dir', C, '40000'), e('theirs-added', A), e('both-added-diff', A)]);
60 const got = Object.fromEntries(r.entries.map(x => [x.name, x.oid]));
61 assert.deepEqual(got, { same: A, 'ours-changed': B, 'theirs-changed': B, 'both-same': B, 'ours-added': A, 'theirs-added': A, 'both-added-diff': A });
62 assert.deepEqual(r.recurse, ['dir']); assert.deepEqual(r.conflicts, []); assert.deepEqual(r.content, ['both-diff'], 'a regular file both sides changed goes to the line merge');
63 assert.deepEqual(threeWay([e('d', A, '40000')], [], [e('d', B, '40000')]).recurse, ['d'], 'directory deleted on one side, changed on the other → per-file decision');
64 assert.deepEqual(threeWay([e('d', A)], [e('d', B, '40000')], [e('d', C)]).conflicts, ['d'], 'file vs directory is a conflict');
65 // delete vs modify is a conflict; add/add different is a conflict; mode change vs content change is a content merge (mode from one side)
66 assert.deepEqual(threeWay([e('f', A)], [e('f', B)], []).conflicts, ['f']);
67 assert.deepEqual(threeWay([], [e('f', A)], [e('f', B)]).conflicts, ['f']);
68 assert.deepEqual(threeWay([e('f', A)], [e('f', A, '100755')], [e('f', B)]).content, ['f']);
69 assert.equal(mergeMode('100644', '100755', '100644'), '100755'); assert.equal(mergeMode('100644', '100755', '120000'), null);
70 // bestBases: git merge-base --all over a known commit graph (child → parents)
71 const G = edges => new Map(Object.entries(edges).map(([c, parents]) => [c, { parents }]));
72 assert.deepEqual(bestBases(G({ a: ['m'], b: ['m'], m: ['r'], r: [] }), 'a', 'b'), { best: ['m'], truncated: false });
73 // criss-cross: two best bases
74 assert.deepEqual(bestBases(G({ a: ['x', 'y'], b: ['y', 'x'], x: ['r'], y: ['r'], r: [] }), 'a', 'b').best, ['x', 'y']);
75 // the summed-distance trap: a's first parent is old r, but y (a descendant of r) is also common → y is the only best base
76 const trap = G({ a: ['r', 'p1'], p1: ['p2'], p2: ['p3'], p3: ['y'], b: ['y'], y: ['r'], r: [] });
77 assert.deepEqual(bestBases(trap, 'a', 'b').best, ['y'], 'r is common but an ancestor of y');
78 assert.deepEqual(bestBases(G({ a: ['r1'], r1: [], b: ['r2'], r2: [] }), 'a', 'b'), { best: [], truncated: false }, 'unrelated');
79 // truncated: b's side runs into a commit whose parents are unknown, outside everything settled → may hide a base
80 assert.equal(bestBases(G({ a: ['m'], b: ['q', 'm'], m: [] }), 'a', 'b').truncated, true);
81 assert.equal(bestBases(G({ a: ['m'], b: ['m'], m: [] }), 'a', 'b').truncated, false, 'a frontier under a common ancestor does not matter');
82 // #42: with two best bases, a cut inside the settled region may hide that one is below the other (z below c through x)
83 assert.deepEqual(bestBases(G({ a: ['c', 'z'], b: ['c', 'z'], c: ['x'], z: [] }), 'a', 'b'), { best: ['c', 'z'], truncated: true });
84 assert.deepEqual(bestBases(G({ a: ['c', 'z'], b: ['c', 'z'], c: ['x'], x: ['z'], z: [] }), 'a', 'b'), { best: ['c'], truncated: false });
85 assert.deepEqual(bestBases(G({ a: ['c'], b: ['c'], c: ['x'] }), 'a', 'b'), { best: ['c'], truncated: false }, 'one base over a settled cut is final');
86 // a pack must not carry an object twice (git: "tried to add buffer twice"); first occurrence wins, order kept
87 assert.deepEqual(uniqueObjects([{ oid: 'a', n: 1 }, { oid: 'b' }, { oid: 'a', n: 2 }]), [{ oid: 'a', n: 1 }, { oid: 'b' }]);
88});
90test('outcomes: up-to-date, fast-forward, ff-only refusal, no-ff merge commit, clean merge, conflict — each equal to git', async () => {
91 const r = repo();
92 const base = commitFiles(r.work, r.bare, { 'a.txt': 'a\n', 'd/x.txt': 'x\n', 'd/y.txt': 'y\n' }, 'base');
93 // branch ahead of main by one commit → fast-forward
94 const feat1 = branchCommit(r, 'feat', 'main', { 'b.txt': 'b\n' }, 'feat1');
95 assert.equal((await merge(r, { from: 'refs/heads/main' })).outcome, 'up_to_date', 'merging main into itself');
96 let m = await merge(r);
97 assert.equal(m.outcome, 'fast_forward'); assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), feat1);
98 assert.equal((await merge(r)).outcome, 'up_to_date');
99 // no-ff: a merge commit even when a fast-forward was possible
100 const feat2 = branchCommit(r, 'feat', 'feat', { 'c.txt': 'c\n' }, 'feat2');
101 const ex = arrayExporter();
102 m = await merge(r, { noFastForward: true }, ex);
103 assert.equal(m.outcome, 'merge'); assert.deepEqual(sh(r.bare, ['rev-list', '--parents', '-n1', 'main']).stdout.trim().split(' ').slice(1), [feat1, feat2]);
104 assert.equal(sh(r.bare, ['rev-parse', 'main^{tree}']).stdout.trim(), sh(r.bare, ['rev-parse', `${feat2}^{tree}`]).stdout.trim(), 'tree is theirs (ours unchanged)');
105 assert.equal(m.newTrees, 0, 'no new tree objects needed');
106 assert.match(sh(r.bare, ['log', '-1', '--format=%s', 'main']).stdout, /^Merge feat into main/);
107 // diverged, disjoint: ours touched a.txt and d/x.txt, theirs added e.txt and changed d/y.txt → clean merge, tree == git merge-tree
108 const ours3 = branchCommit(r, 'main', 'main', { 'a.txt': 'a2\n', 'd/x.txt': 'x2\n' }, 'ours3');
109 const theirs3 = branchCommit(r, 'feat', 'feat', { 'e.txt': 'e\n', 'd/y.txt': 'y2\n' }, 'theirs3');
110 await assert.rejects(merge(r, { fastForwardOnly: true }), e => e.code === 'not_fast_forward');
111 const gmt = gitMergeTree(r.bare, ours3, theirs3); assert.ok(gmt.clean);
112 const gm = gitMerge(r.bare, 'main', 'feat');
113 const ex3 = arrayExporter();
114 m = await merge(r, {}, ex3);
115 assert.equal(m.outcome, 'merge'); assert.equal(m.tree, gmt.tree, 'our merged tree == git merge-tree'); assert.equal(m.tree, gm.tree, '== git merge');
116 assert.deepEqual(sh(r.bare, ['rev-list', '--parents', '-n1', 'main']).stdout.trim().split(' ').slice(1), [ours3, theirs3]);
117 assert.equal(sh(r.bare, ['cat-file', '-p', 'main:d/y.txt']).stdout, 'y2\n'); assert.equal(sh(r.bare, ['cat-file', '-p', 'main:a.txt']).stdout, 'a2\n');
118 const rootSpan = ex3.lines.flatMap(flattenLine).find(s => s.name === 'git.merge');
119 assert.equal(rootSpan.attrs['git.merge.base'], feat2); assert.equal(m.newTrees, 2, 'root + d/ rewritten'); assert.ok(rootSpan.attrs['git.merge.trees.fetched'] <= 6, 'only differing directories fetched');
120 assert.deepEqual(fsckProblems(r.bare), []);
121 // conflict: both modify a.txt differently
122 const ours4 = branchCommit(r, 'main', 'main', { 'a.txt': 'a3\n' }, 'ours4');
123 const theirs4 = branchCommit(r, 'feat', 'feat', { 'a.txt': 'a4\n', 'f.txt': 'f\n' }, 'theirs4');
124 const gc = gitMergeTree(r.bare, ours4, theirs4); assert.equal(gc.clean, false); assert.deepEqual(gc.conflicts, ['a.txt']);
125 const ex4 = arrayExporter();
126 await assert.rejects(merge(r, {}, ex4), e => e.code === 'merge_conflict' && e.conflicts.length === 1 && e.conflicts[0] === 'a.txt');
127 assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), ours4, 'nothing pushed on conflict');
128 assert.deepEqual(ex4.lines.flatMap(flattenLine).find(s => s.name === 'git.merge').attrs['git.merge.conflicts'], ['a.txt']);
129 // unrelated histories
130 const r2 = repo(); commitFiles(r2.work, r2.bare, { 'z.txt': 'z\n' }, 'other root');
131 sh(r.work, ['remote', 'add', 'o2', r2.bare]); sh(r.work, ['fetch', '-q', 'o2']); sh(r.work, ['push', '-q', r.bare, 'o2/main:refs/heads/unrelated']);
132 await assert.rejects(merge(r, { from: 'refs/heads/unrelated' }), e => e.code === 'unrelated_histories');
133});
135test('line merge and renames, judged by git: disjoint edits to one file merge to git\'s bytes; same-line edits, binary, and rename shapes conflict', async () => {
136 const body = (n, k = 30) => Array.from({ length: k }, (_, i) => `line ${i} of ${n}\n`).join('');
137 const lines = body('a').split(/(?<=\n)/);
138 const cases = [
139 // [name, base files, ours files, theirs files, git clean?]
140 ['disjoint edits', { 'a.txt': body('a') }, { 'a.txt': ['TOP\n', ...lines.slice(1)].join('') }, { 'a.txt': [...lines.slice(0, -1), 'BOTTOM\n'].join('') }, true],
141 ['same line', { 'a.txt': body('a') }, { 'a.txt': ['OURS\n', ...lines.slice(1)].join('') }, { 'a.txt': ['THEIRS\n', ...lines.slice(1)].join('') }, false],
142 ['identical insertions', { 'a.txt': body('a') }, { 'a.txt': [...lines.slice(0, 5), 'SAME\n', ...lines.slice(5)].join('') }, { 'a.txt': [...lines.slice(0, 5), 'SAME\n', ...lines.slice(5), 'END\n'].join('') }, true],
143 ['no final newline', { 'a.txt': body('a') + 'tail' }, { 'a.txt': 'HEAD\n' + body('a').slice(lines[0].length) + 'tail' }, { 'a.txt': body('a') + 'tail2' }, true],
144 ['binary', { 'b.bin': 'x\0' + body('b') }, { 'b.bin': 'y\0' + body('b') }, { 'b.bin': 'x\0' + body('b') + 'z\n' }, false],
145 ['rename/rename(1to2)', { 'a.txt': body('a') }, { 'a.txt': null, 'b.txt': body('a') }, { 'a.txt': null, 'c.txt': body('a') }, false],
146 ['rename/delete', { 'a.txt': body('a') }, { 'a.txt': null, 'b.txt': body('a') }, { 'a.txt': null }, false],
147 ['dir rename + add', { 'd/x.txt': body('x'), 'd/y.txt': body('y') }, { 'd/x.txt': null, 'd/y.txt': null, 'e/x.txt': body('x'), 'e/y.txt': body('y') }, { 'd/new.txt': 'new\n' }, false],
148 ];
149 for (const [name, base, o, th, gitClean] of cases) {
150 const r = repo();
151 const b = commitFiles(r.work, r.bare, base, 'base');
152 const theirs = branchCommit(r, 'feat', b, th, 'theirs'); const ours = branchCommit(r, 'main', b, o, 'ours');
153 const g = gitMergeTree(r.bare, ours, theirs);
154 assert.equal(g.clean, gitClean, `${name}: the case means what it says (git ${g.clean ? 'clean' : 'conflicts'})`);
155 let m = null, err = null; try { m = await merge(r); } catch (e) { err = e; }
156 if (gitClean) { assert.ok(m, `${name}: git merges cleanly, so must we (${err?.message})`); assert.equal(m.tree, g.tree, `${name}: tree == git merge-tree`); assert.deepEqual(fsckProblems(r.bare), []); }
157 else assert.equal(err?.code, 'merge_conflict', `${name}: git conflicts, so must we`);
158 }
159});
161const pick = ({ base, depth, verdict }) => ({ base, depth, verdict: verdict.tag });
162test('limits: a file over maxMergeBlobBytes is a conflict with that reason (git would merge it: the cap is ours); merge-base search depth is bounded', async () => {
163 const r = repo();
164 const lines = Array.from({ length: 200 }, (_, i) => `line ${i}\n`);
165 const b = commitFiles(r.work, r.bare, { 'big.txt': lines.join('') }, 'base');
166 branchCommit(r, 'feat', b, { 'big.txt': [...lines.slice(0, -1), 'END\n'].join('') }, 'theirs');
167 const ours = branchCommit(r, 'main', b, { 'big.txt': ['TOP\n', ...lines.slice(1)].join('') }, 'ours');
168 const limits = { ...DEFAULT_LIMITS, maxMergeBlobBytes: 1000 };
169 await assert.rejects(unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer(), rediff, limits })), e => e.code === 'merge_conflict' && e.reasons['big.txt'] === 'too large to merge');
170 assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), ours, 'nothing pushed');
171 assert.equal((await merge(r)).outcome, 'merge', 'within the default cap the same merge is clean');
172 assert.equal(sh(r.bare, ['cat-file', '-p', 'main:big.txt']).stdout, ['TOP\n', ...lines.slice(1, -1), 'END\n'].join(''));
173 // two branches 10 commits from their common root, search capped at depth 8 → limit_exceeded (not a wrong answer)
174 const r2 = repo(); const root = commitFiles(r2.work, r2.bare, { 'x': '0\n' }, 'root');
175 let a = root, c = root; for (let i = 1; i <= 10; i++) { a = branchCommit(r2, 'a', a, { 'x': `a${i}\n` }, `a${i}`); c = branchCommit(r2, 'c', c, { 'x': `c${i}\n` }, `c${i}`); }
176 const t = createTransport(r2.url, { tracer: new Tracer() });
177 await assert.rejects(unwrapAsync(mergeBase(t, a, c, { maxDepth: 8 })), e => e.code === 'limit_exceeded');
178 assert.equal((await unwrapAsync(mergeBase(t, a, c, { maxDepth: 16 }))).base, root);
179 // #79: the doubling's last step is the cap itself. The root is 11 deep: cap 12 searches 8, then 12 (it stopped at 8
180 // and answered limit_exceeded); cap 11.5 searches whole commits; a cap under the first window searches the cap.
181 // At depth 10 the root is named by both sides' children without being fetched, which is an answer (#41); at 9 it is not.
182 for (const [maxDepth, depth] of [[12, 12], [11.5, 11], [11, 11], [10, 10]]) assert.deepEqual(pick(await unwrapAsync(mergeBase(t, a, c, { maxDepth }))), { base: root, depth, verdict: 'found' }, `cap ${maxDepth}`);
183 await assert.rejects(unwrapAsync(mergeBase(t, a, c, { maxDepth: 9 })), e => e.code === 'limit_exceeded' && e.max === 9);
184 const near = branchCommit(r2, 'n', root, { 'x': 'n\n' }, 'n'); const near2 = branchCommit(r2, 'n2', root, { 'x': 'n2\n' }, 'n2');
185 assert.deepEqual(pick(await unwrapAsync(mergeBase(t, near, near2, { maxDepth: 3 }))), { base: root, depth: 3, verdict: 'found' }, 'cap 3 < the first window of 8: one search of 3 (was limit_exceeded with no fetch)');
186});
188test('limits: a file whose line merge needs more than maxMergeWork steps is a conflict, too large to merge (git merges it: the budget is ours); a maxMergeWork that bounds nothing is refused', async () => {
189 const r = repo();
190 const lines = Array.from({ length: 200 }, (_, i) => `line ${i}\n`);
191 const b = commitFiles(r.work, r.bare, { 'big.txt': lines.join('') }, 'base');
192 branchCommit(r, 'feat', b, { 'big.txt': [...lines.slice(0, -1), 'END\n'].join('') }, 'theirs');
193 const ours = branchCommit(r, 'main', b, { 'big.txt': ['TOP\n', ...lines.slice(1)].join('') }, 'ours');
194 const go = limits => unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer(), rediff, limits }));
195 // Any diff of 200 lines against 200 reads every line of both at least once: 400 steps for base→ours alone, so a
196 // budget of 100 is passed whatever is counted. The presets carry the key as a number (the brand's contract).
197 assert.ok(Number.isFinite(DEFAULT_LIMITS.maxMergeWork) && DEFAULT_LIMITS.maxMergeWork > 400, `DEFAULT_LIMITS.maxMergeWork ${DEFAULT_LIMITS.maxMergeWork}`);
198 assert.ok(Number.isFinite(WORKER_LIMITS.maxMergeWork) && WORKER_LIMITS.maxMergeWork > 400 && WORKER_LIMITS.maxMergeWork <= DEFAULT_LIMITS.maxMergeWork, `WORKER_LIMITS.maxMergeWork ${WORKER_LIMITS.maxMergeWork}`);
199 await assert.rejects(go({ ...DEFAULT_LIMITS, maxMergeWork: 100 }), e => e.code === 'merge_conflict' && e.reasons['big.txt'] === 'too large to merge');
200 assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), ours, 'nothing pushed');
201 for (const bad of [NaN, Infinity, -1, '100']) {
202 await assert.rejects(go({ maxMergeWork: bad }), e => e.code === 'bad_request' && e.what === 'maxMergeWork' && Object.is(e.got, bad), String(bad));
203 assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), ours, 'nothing pushed');
204 }
205 assert.equal((await go({ ...WORKER_LIMITS })).outcome, 'merge', 'within the Worker budget the same merge is clean');
206 assert.equal(sh(r.bare, ['cat-file', '-p', 'main:big.txt']).stdout, ['TOP\n', ...lines.slice(1, -1), 'END\n'].join(''));
207});
209test('merge bases decided by git: criss-cross refuses (git builds a virtual base we do not), the summed-distance trap now picks git\'s base', async () => {
210 const run = (w, args) => { const x = sh(w, args); assert.equal(x.status, 0, `${args.join(' ')}: ${x.stderr}`); return x.stdout.trim(); };
211 const put = (w, p, v) => { writeFileSync(join(w, p), v); run(w, ['add', '-A']); };
212 // criss-cross where the first-parent base is the wrong one: main = merge(C1, A1) keeps f=a; feat = merge(A1, C1) reverts f
213 {
214 const r = repo(); const w = r.work;
215 put(w, 'f', 'x\n'); run(w, ['commit', '-qm', 'B']);
216 run(w, ['checkout', '-qb', 'side']); put(w, 'g', 'g\n'); run(w, ['commit', '-qm', 'C1']); const C1 = run(w, ['rev-parse', 'HEAD']);
217 run(w, ['checkout', '-q', 'main']); put(w, 'f', 'a\n'); run(w, ['commit', '-qm', 'A1']); const A1 = run(w, ['rev-parse', 'HEAD']);
218 run(w, ['checkout', '-q', '--detach', C1]); run(w, ['merge', '-q', '--no-edit', A1]); const M = run(w, ['rev-parse', 'HEAD']);
219 run(w, ['checkout', '-q', '--detach', A1]); sh(w, ['merge', '-q', '--no-commit', C1]); put(w, 'f', 'x\n'); run(w, ['commit', '-qm', 'F reverts f']); const F = run(w, ['rev-parse', 'HEAD']);
220 run(w, ['push', '-q', '-f', r.bare, `${M}:refs/heads/main`, `${F}:refs/heads/feat`]);
221 assert.equal(run(r.bare, ['merge-base', '--all', 'main', 'feat']).split('\n').length, 2);
222 const g = gitMergeTree(r.bare, M, F); assert.ok(g.clean); assert.equal(run(r.bare, ['cat-file', '-p', `${g.tree}:f`]), 'x', 'git: virtual base → f=x');
223 await assert.rejects(merge(r), e => e.code === 'merge_conflict' && e.bases.length === 2 && /criss-cross/.test(e.message));
224 assert.equal(run(r.bare, ['rev-parse', 'main']), M, 'nothing pushed');
225 await assert.rejects(unwrapAsync(rebaseBranch(r.url, { ref: 'refs/heads/feat', onto: 'refs/heads/main', committer: author }, { tracer: new Tracer() })), e => e.code === 'not_linear');
226 }
227 // the trap: main = merge(r, p3) with first parent the old root r, p3 ← … ← y ← r; feat ← y. Best base is y (r is its
228 // ancestor). main's merge reverted f to r's content; feat left y's. git: base y → f=r. Base r would give f=y.
229 {
230 const r = repo(); const w = r.work;
231 put(w, 'f', 'r\n'); run(w, ['commit', '-qm', 'r']); const R = run(w, ['rev-parse', 'HEAD']);
232 put(w, 'f', 'y\n'); run(w, ['commit', '-qm', 'y']); const Y = run(w, ['rev-parse', 'HEAD']);
233 run(w, ['checkout', '-qb', 'feat']); put(w, 'h', 'h\n'); run(w, ['commit', '-qm', 'feat']); const FT = run(w, ['rev-parse', 'HEAD']);
234 run(w, ['checkout', '-q', '--detach', Y]); for (let i = 1; i <= 3; i++) { put(w, `p${i}`, `${i}\n`); run(w, ['commit', '-qm', `p${i}`]); } const P3 = run(w, ['rev-parse', 'HEAD']);
235 run(w, ['checkout', '-q', '--detach', R]); sh(w, ['merge', '-q', '--no-ff', '--no-commit', P3]); put(w, 'f', 'r\n'); run(w, ['commit', '-qm', 'merge keeps r']); const MM = run(w, ['rev-parse', 'HEAD']);
236 run(w, ['push', '-q', '-f', r.bare, `${MM}:refs/heads/main`, `${FT}:refs/heads/feat`]);
237 assert.equal(run(r.bare, ['merge-base', '--all', 'main', 'feat']), Y);
238 const g = gitMergeTree(r.bare, MM, FT); assert.ok(g.clean);
239 const m = await merge(r); assert.equal(m.base, Y); assert.equal(m.tree, g.tree, 'tree == git merge-tree');
240 assert.equal(run(r.bare, ['cat-file', '-p', 'main:f']), 'r');
241 }
242});
244test('#42: a cut below two candidates is deepened, as git merge-base --all says (honest server), and merges as git does', async () => {
245 const run = (w, args, opts) => { const x = sh(w, args, opts); assert.equal(x.status, 0, `${args.join(' ')}: ${x.stderr}`); return x.stdout.trim(); };
246 const put = (w, p, v) => { writeFileSync(join(w, p), v); run(w, ['add', '-A']); };
247 // a,b → [c, z]; c → p1..p6 → x → z. The 8-deep window cuts x; over it z looks like a second best base (criss-cross,
248 // refused) where git has only c (z is below c through x). Must deepen and merge as git does.
249 const r = repo(); const w = r.work;
250 put(w, 'f', 'z\n'); run(w, ['commit', '-qm', 'z']); const Z = run(w, ['rev-parse', 'HEAD']);
251 put(w, 'f', 'x\n'); run(w, ['commit', '-qm', 'x']);
252 for (let i = 6; i >= 1; i--) { put(w, `p${i}`, `${i}\n`); run(w, ['commit', '-qm', `p${i}`]); }
253 put(w, 'f', 'c\n'); run(w, ['commit', '-qm', 'c']); const C = run(w, ['rev-parse', 'HEAD']);
254 // merge commits [C, Z] by hand: `git merge` would say "already up to date" (Z is below C), which is the point
255 put(w, 'ga', 'a\n'); const A = run(w, ['commit-tree', run(w, ['write-tree']), '-p', C, '-p', Z, '-m', 'a']);
256 run(w, ['checkout', '-q', '--detach', C]); put(w, 'gb', 'b\n'); const B = run(w, ['commit-tree', run(w, ['write-tree']), '-p', C, '-p', Z, '-m', 'b']);
257 run(w, ['push', '-q', '-f', r.bare, `${A}:refs/heads/main`, `${B}:refs/heads/feat`]);
258 assert.deepEqual(run(r.bare, ['rev-list', '--parents', '-n1', A]).split(' ').slice(1), [C, Z]);
259 assert.equal(run(r.bare, ['merge-base', '--all', A, B]), C, 'git: one base');
260 const mb = await unwrapAsync(mergeBase(createTransport(r.url, { tracer: new Tracer() }), A, B));
261 assert.deepEqual([mb.bases, mb.depth], [[C], 16], 'deepened past the cut; main answered [C, Z] at depth 8');
262 const g = gitMergeTree(r.bare, A, B); assert.ok(g.clean);
263 const m = await merge(r); assert.equal(m.outcome, 'merge'); assert.equal(m.base, C); assert.equal(m.tree, g.tree, 'tree == git merge-tree');
264 assert.deepEqual(run(r.bare, ['rev-list', '--parents', '-n1', 'main']).split(' ').slice(1), [A, B]);
265 assert.deepEqual(fsckProblems(r.bare), []);
266});
268test('.gitattributes merge drivers, judged by git (attr.tree): union, -merge, binary macro, nested override; each attribute source', async () => {
269 const L = n => Array.from({ length: n }, (_, i) => `entry ${i}\n`).join('');
270 const rootAttrs = 'CHANGELOG merge=union\n*.lock -merge\nnotes.txt binary\ndocs/** merge=union\n';
271 for (const [source, attrsOn] of [[null, null], ['ours', 'main'], ['theirs', 'feat'], ['base', 'base'], ['refs/heads/attrs', 'attrs']]) {
272 const r = repo();
273 // attributes live only where the case says, so each source gives a different verdict
274 const withAttrs = side => attrsOn === side || (attrsOn === 'attrs' && false);
275 const b = commitFiles(r.work, r.bare, { 'CHANGELOG': L(5), 'deps.lock': L(5), 'notes.txt': L(5), 'docs/a.md': L(5), 'plain.txt': L(5), ...(withAttrs('base') ? { '.gitattributes': rootAttrs, 'docs/.gitattributes': 'a.md -merge\n' } : {}) }, 'base');
276 const theirs = branchCommit(r, 'feat', b, { 'CHANGELOG': L(5) + 'theirs entry\n', 'deps.lock': 'T\n' + L(5).slice(8), 'notes.txt': L(5) + 'T\n', 'docs/a.md': L(5) + 'T\n', ...(withAttrs('feat') ? { '.gitattributes': rootAttrs, 'docs/.gitattributes': 'a.md -merge\n' } : {}) }, 'theirs');
277 const ours = branchCommit(r, 'main', b, { 'CHANGELOG': L(5) + 'ours entry\n', 'deps.lock': L(5) + 'O\n', 'notes.txt': 'O\n' + L(5).slice(8), 'docs/a.md': 'O\n' + L(5).slice(8), ...(withAttrs('main') ? { '.gitattributes': rootAttrs, 'docs/.gitattributes': 'a.md -merge\n' } : {}) }, 'ours');
278 let attrRev = { null: EMPTY_TREE, ours, theirs, base: b }[String(source)];
279 if (attrsOn === 'attrs') { attrRev = branchCommit(r, 'attrs', b, { '.gitattributes': rootAttrs, 'docs/.gitattributes': 'a.md -merge\n' }, 'attributes only'); }
280 const g = gitMergeTree(r.bare, ours, theirs, attrRev);
281 const ex = arrayExporter();
282 let m = null, err = null; try { m = await unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer({ exporter: ex }), rediff, attributes: source })); } catch (e) { err = e; }
283 const label = `attributes=${source}`;
284 if (g.clean) { assert.ok(m, `${label}: git clean, we ${err?.message}`); assert.equal(m.tree, g.tree, `${label}: tree == git`); }
285 else { assert.equal(err?.code, 'merge_conflict', `${label}: git conflicts on ${g.conflicts}`); for (const p of g.conflicts) assert.ok(err.conflicts.includes(p), `${label}: git conflicts on ${p}, we did not (${err.message})`); }
286 if (source === null) assert.deepEqual(g.conflicts.sort(), ['CHANGELOG'], 'no attributes: only the changelog conflicts (line-level clash), the rest line-merge');
287 else {
288 // with the attributes: the changelog unions, the lock and notes.txt (binary macro) and docs/a.md (nested -merge) conflict
289 assert.deepEqual(g.conflicts.sort(), ['deps.lock', 'docs/a.md', 'notes.txt'], `${label}: git's verdict is what the attributes say`);
290 assert.equal(err.reasons['deps.lock'], 'binary (merge attribute)');
291 assert.equal(ex.lines.flatMap(flattenLine).find(sp => sp.name === 'git.merge').attrs['git.merge.content.attr_binary'], 3);
292 }
293 }
294 // the union result itself, byte for byte: a merge where only the changelog clashes
295 const r = repo();
296 const b = commitFiles(r.work, r.bare, { 'CHANGELOG': L(3), '.gitattributes': 'CHANGELOG merge=union\n' }, 'base');
297 const theirs = branchCommit(r, 'feat', b, { 'CHANGELOG': L(3) + 'theirs 1\ntheirs 2' }, 'theirs'); // no final newline: union adds one between
298 const ours = branchCommit(r, 'main', b, { 'CHANGELOG': L(3) + 'ours 1\nours 2' }, 'ours');
299 const g = gitMergeTree(r.bare, ours, theirs, ours); assert.ok(g.clean);
300 const m = await unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer(), rediff, attributes: 'ours' }));
301 assert.equal(m.tree, g.tree);
302 assert.equal(sh(r.bare, ['cat-file', '-p', 'main:CHANGELOG']).stdout, L(3) + 'ours 1\nours 2\ntheirs 1\ntheirs 2');
303 await assert.rejects(unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer(), attributes: 'nope nope' })), e => e.code === 'bad_request');
304 await assert.rejects(unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer(), attributes: 42 })), e => e.code === 'bad_request');
305});
307test('names that are Object.prototype members (#16): a directory rename + add inside `constructor`/`__proto__`/…, a rename onto `__proto__`, a `__proto__` content conflict — each judged by git', async () => {
308 const body = (n, k = 30) => Array.from({ length: k }, (_, i) => `line ${i} of ${n}\n`).join('');
309 const lines = body('a').split(/(?<=\n)/);
310 // computed keys: a literal `__proto__:` key would set the prototype, not name a file
311 const cases = [];
312 for (const d of ['constructor', '__proto__', 'toString', 'hasOwnProperty']) {
313 cases.push([`dir rename + add in ${d}/`, { [`${d}/x.txt`]: body('x'), [`${d}/y.txt`]: body('y') }, { [`${d}/x.txt`]: null, [`${d}/y.txt`]: null, ['e/x.txt']: body('x'), ['e/y.txt']: body('y') }, { [`${d}/new.txt`]: 'new\n' }]);
314 cases.push([`dir rename + add in ${d}/ (theirs renames)`, { [`${d}/x.txt`]: body('x'), [`${d}/y.txt`]: body('y') }, { [`${d}/new.txt`]: 'new\n' }, { [`${d}/x.txt`]: null, [`${d}/y.txt`]: null, ['e/x.txt']: body('x'), ['e/y.txt']: body('y') }]);
315 }
316 cases.push(['rename/delete onto __proto__', { ['a.txt']: body('a') }, { ['a.txt']: null, ['__proto__']: body('a') }, { ['a.txt']: null }]);
317 cases.push(['same line in __proto__', { ['__proto__']: body('a') }, { ['__proto__']: ['OURS\n', ...lines.slice(1)].join('') }, { ['__proto__']: ['THEIRS\n', ...lines.slice(1)].join('') }]);
318 cases.push(['same line in constructor/__proto__', { ['constructor/__proto__']: body('a') }, { ['constructor/__proto__']: ['OURS\n', ...lines.slice(1)].join('') }, { ['constructor/__proto__']: ['THEIRS\n', ...lines.slice(1)].join('') }]);
319 for (const [name, base, o, th] of cases) {
320 const r = repo();
321 const b = commitFiles(r.work, r.bare, base, 'base');
322 const theirs = branchCommit(r, 'feat', b, th, 'theirs'); const ours = branchCommit(r, 'main', b, o, 'ours');
323 const g = gitMergeTree(r.bare, ours, theirs);
324 assert.equal(g.clean, false, `${name}: git conflicts (the case means what it says)`);
325 let m = null, err = null; try { m = await merge(r); } catch (e) { err = e; }
326 assert.equal(err?.code, 'merge_conflict', `${name}: git conflicts on ${g.conflicts} (${g.info}), so must we — we merged to ${m?.tree}`);
327 for (const p of g.conflicts) assert.ok(err.conflicts.includes(p) || Object.values(err.reasons).some(x => /directory rename/.test(x)), `${name}: git conflicts on ${p}, we did not (${err.message})`);
328 for (const p of err.conflicts) assert.equal(typeof Object.getOwnPropertyDescriptor(err.reasons, p)?.value, 'string', `${name}: ${p} has its own reason (${err.message})`);
329 assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), ours, `${name}: nothing pushed on conflict`);
330 }
331});
333test('.gitattributes [:class:] names that are Object.prototype members (#16): attributes == git check-attr, merge drivers == git merge-tree, never an untyped error', async () => {
334 const L = n => Array.from({ length: n }, (_, i) => `entry ${i}\n`).join('');
335 const attrs = 'x[[:hasOwnProperty:]] -merge\n*[[:constructor:]]* -merge\n*[[:toString:]]* merge=union\n*[[:__proto__:]]* -merge\n*[[:valueOf:]] merge=union\n*[[:alpha:]].log merge=union\n';
336 const paths = ['a.txt', 'xy', 'x1', 'constructor', 'toString.md', 'b.log', '__proto__', 'd/a.txt', 'd/x:'];
337 // check-attr: git's verdict for every path, against attributesFor
338 const r = repo();
339 const b = commitFiles(r.work, r.bare, { '.gitattributes': attrs, ...Object.fromEntries(paths.map(p => [p, L(5)])) }, 'base');
340 const res = sh(r.work, ['check-attr', `--source=${b}`, '-a', '-z', '--stdin'], paths.join('\0') + '\0');
341 assert.equal(res.status, 0, res.stderr);
342 const fields = res.stdout.split('\0'), want = new Map(paths.map(p => [p, []]));
343 for (let i = 0; i + 2 < fields.length; i += 3) want.get(fields[i]).push([fields[i + 1], fields[i + 2]]);
344 for (const p of paths) {
345 const ours = [...attributesFor(p, new Map([['', attrs]]))].filter(([, v]) => v !== null).map(([k, v]) => [k, v === true ? 'set' : v === false ? 'unset' : v]);
346 assert.deepEqual(ours.sort(), want.get(p).sort(), `${p}: attributes == git check-attr`);
347 }
348 assert.deepEqual(want.get('b.log'), [['merge', 'union']], 'a real class still matches');
349 // merge: every file changes the same line on both sides; only b.log (union) is clean in git
350 const theirs = branchCommit(r, 'feat', b, Object.fromEntries(paths.map(p => [p, L(5) + 'theirs\n'])), 'theirs');
351 const ours = branchCommit(r, 'main', b, Object.fromEntries(paths.map(p => [p, L(5) + 'ours\n'])), 'ours');
352 const g = gitMergeTree(r.bare, ours, theirs, ours);
353 let err = null; try { await unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer(), rediff, attributes: 'ours' })); } catch (e) { err = e; }
354 assert.equal(err?.code, 'merge_conflict', `git conflicts on ${g.conflicts}; we: ${err?.code} ${err?.message}`);
355 assert.deepEqual([...err.conflicts].sort(), [...g.conflicts].sort(), 'conflicts == git merge-tree');
356 for (const p of err.conflicts) assert.match(err.reasons[p], /^content/, `${p}: a text conflict, not -merge from a pattern git does not match`);
357});
359test('branch workflow: editFile creates the branch from main (CAS: must not exist), merge lands it, delete removes it', async () => {
360 const r = repo();
361 const base = commitFiles(r.work, r.bare, { 'README.md': 'hello MARK\n' }, 'base');
362 const e = await unwrapAsync(editFile(r.url, { path: 'README.md', find: 'MARK', replace: 'EDITED', ref: 'refs/heads/ply/edit-1', base: 'refs/heads/main', author, message: 'edit on a branch' }, { tracer: new Tracer() }));
363 assert.equal(e.oldCommit, base); assert.equal(sh(r.bare, ['rev-parse', 'refs/heads/ply/edit-1']).stdout.trim(), e.newCommit);
364 assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), base, 'main untouched');
365 assert.equal(sh(r.bare, ['rev-parse', `${e.newCommit}^`]).stdout.trim(), base, 'parent is main\'s head');
366 await assert.rejects(unwrapAsync(editFile(r.url, { path: 'README.md', find: 'MARK', replace: 'AGAIN', ref: 'refs/heads/ply/edit-1', base: 'refs/heads/main', author, message: 'm' }, { tracer: new Tracer() })), e => e.code === 'cas_conflict', 'branch exists → create refused');
367 const m = await unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/ply/edit-1', author }, { tracer: new Tracer() }));
368 assert.equal(m.outcome, 'fast_forward'); assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), e.newCommit);
369 assert.equal(sh(r.bare, ['cat-file', '-p', 'main:README.md']).stdout, 'hello EDITED\n');
370 const t = createTransport(r.url, { tracer: new Tracer() });
371 await unwrapAsync(deleteRef(t, { ref: 'refs/heads/ply/edit-1', oid: e.newCommit }));
372 assert.notEqual(sh(r.bare, ['show-ref', '--verify', 'refs/heads/ply/edit-1']).status, 0, 'branch gone');
373 // deleting with a stale oid is a CAS failure; deleting the current branch is refused by policy (receive.denyDeleteCurrent)
374 sh(r.work, ['push', '-q', r.bare, `${base}:refs/heads/tmp`]);
375 await assert.rejects(unwrapAsync(deleteRef(t, { ref: 'refs/heads/tmp', oid: e.newCommit })), e => e.code === 'cas_conflict', 'stale oid');
376 assert.equal(sh(r.bare, ['rev-parse', 'refs/heads/tmp']).stdout.trim(), base, 'tmp still there');
377 await assert.rejects(unwrapAsync(deleteRef(t, { ref: 'refs/heads/main', oid: e.newCommit })), e => e.code === 'push_rejected' && /current branch/.test(e.message));
378 assert.equal(sh(r.bare, ['rev-parse', 'main']).stdout.trim(), e.newCommit, 'main still there');
379 assert.deepEqual(fsckProblems(r.bare), []);
380});
382test('property: random three-way tree edits — clean merges equal git merge-tree; our conflicts ⊇ git\'s, and never a wrong tree', async () => {
383 const rng = new Rng(+(process.env.MERGE_SEED ?? 11));
384 const N = +(process.env.MERGE_CASES ?? 24);
385 const stats = { clean: 0, conflict: 0, conservative: 0, nonRename: 0, lineMerged: 0, criss: 0, shapes: [0, 0, 0], withAttrs: 0, unioned: 0, attrBinary: 0 };
386 for (let i = 0; i < N; i++) {
387 const r = repo();
388 const dirs = ['', 'a/', 'a/b/', 'c/']; const names = ['f1', 'f2', 'f3', 'f4'];
389 // multi-line files: line-level edits make both sides touch the same file in different places, so git (and we) line-merge
390 const body = p => Array.from({ length: 8 }, (_, j) => (j % 3 === 2 ? '}\n' : `${p} line ${j}\n`));
391 const files = {}; for (const d of dirs) for (const nm of names) if (rng.int(0, 2)) files[`${d}${nm}.txt`] = body(`${d}${nm}`).join('');
392 if (!Object.keys(files).length) files['f.txt'] = body('f').join('');
393 // .gitattributes at the root and in a/ (some cases), naming merge drivers for some of the files
394 const attrLine = () => `${rng.pick(['*.txt', 'f1.txt', 'f2.txt', '**/f3.txt', 'b/*', '/f4.txt', 'new*.txt'])} ${rng.pick(['merge=union', '-merge', 'binary', 'merge', 'merge=text', '!merge', 'merge=custom'])}\n`;
395 if (rng.int(0, 1)) files['.gitattributes'] = Array.from({ length: rng.int(1, 3) }, attrLine).join('');
396 if (rng.int(0, 2) === 0) files['a/.gitattributes'] = Array.from({ length: rng.int(1, 2) }, attrLine).join('');
397 const attrSource = rng.pick([null, null, 'ours', 'theirs', 'base']);
398 commitFiles(r.work, r.bare, files, 'base');
399 const lineEdit = p => { const ls = files[p].split(/(?<=\n)/); const at = rng.int(0, ls.length - 1); const k = rng.int(0, 2);
400 if (k === 0) ls[at] = `${p} edit ${rng.int(0, 9)}\n`; else if (k === 1) ls.splice(at, 1); else ls.splice(at, 0, rng.int(0, 1) ? '}\n' : `ins ${rng.int(0, 9)}\n`); return ls.join(''); };
401 const edit = () => { const ch = {}; for (const p of [...Object.keys(files), `${dirs[rng.int(0, 3)]}new${rng.int(0, 3)}.txt`]) { const k = rng.int(0, 7); if (k <= 1) ch[p] = files[p] ? lineEdit(p) : `${p} new ${rng.int(0, 9)}\n`; else if (k === 2 && files[p]) ch[p] = null; else if (k === 3 && files[p] && !rng.int(0, 3)) { ch[p] = null; ch[`${dirs[rng.int(0, 3)]}moved-${p.replace(/\//g, '_')}`] = lineEdit(p); } } return ch; };
402 const o = edit(), th = edit();
403 const base = sh(r.bare, ['rev-parse', 'main']).stdout.trim();
404 let theirs = Object.keys(th).length ? branchCommit(r, 'feat', base, th, 'theirs') : (sh(r.work, ['push', '-q', r.bare, `${base}:refs/heads/feat`]), base);
405 let ours = Object.keys(o).length ? branchCommit(r, 'main', base, o, 'ours') : base;
406 // history shapes: 0 plain; 1 main already merged feat once (merge commits in ours' history); 2 criss-cross (each side
407 // merged the other's tip); after 1 and 2 both sides edit again. A merge resolves content with -X ours|theirs and
408 // anything left (modify/delete) by taking the working tree as is.
409 const shape = ours !== base && theirs !== base ? rng.int(0, 2) : 0;
410 if (shape) {
411 const mergeAt = (branch, at, other, x) => {
412 sh(r.work, ['checkout', '-q', '--detach', at]);
413 if (sh(r.work, ['merge', '-q', '--no-ff', '--no-edit', `-X${x}`, other]).status !== 0) { sh(r.work, ['add', '-A']); sh(r.work, ['commit', '-qm', `merge ${other.slice(0, 7)}`]); }
414 const c = sh(r.work, ['rev-parse', 'HEAD']).stdout.trim(); sh(r.work, ['push', '-q', '-f', r.bare, `${c}:refs/heads/${branch}`]); return c;
415 };
416 const o0 = ours, t0 = theirs;
417 ours = mergeAt('main', o0, t0, rng.pick(['ours', 'theirs']));
418 let t1 = t0; if (shape === 2) t1 = mergeAt('feat', t0, o0, rng.pick(['ours', 'theirs']));
419 const o2 = edit(), t2 = edit();
420 if (Object.keys(o2).length) ours = branchCommit(r, 'main', ours, o2, 'ours again');
421 if (Object.keys(t2).length) t1 = branchCommit(r, 'feat', t1, t2, 'theirs again');
422 theirs = t1; stats.shapes[shape]++;
423 }
424 const nBases = sh(r.bare, ['merge-base', '--all', ours, theirs]).stdout.trim().split('\n').filter(Boolean).length;
425 const baseOid = sh(r.bare, ['merge-base', ours, theirs]).stdout.trim();
426 const g = gitMergeTree(r.bare, ours, theirs, attrSource === null ? EMPTY_TREE : { ours, theirs, base: baseOid }[attrSource]);
427 const ex = arrayExporter();
428 let m, err = null; try { m = await unwrapAsync(mergeBranch(r.url, { ref: 'refs/heads/main', from: 'refs/heads/feat', author }, { tracer: new Tracer({ exporter: ex }), rediff, attributes: attrSource })); } catch (e) { err = e; }
429 if (attrSource) stats.withAttrs++;
430 { const a = ex.lines.flatMap(flattenLine).find(sp => sp.name === 'git.merge')?.attrs ?? {}; stats.unioned += a['git.merge.content.unioned'] ?? 0; stats.attrBinary += a['git.merge.content.attr_binary'] ?? 0; }
431 stats.lineMerged += ex.lines.flatMap(flattenLine).find(s => s.name === 'git.merge')?.attrs['git.merge.content.merged'] ?? 0;
432 if (err && err.code !== 'merge_conflict') throw err;
433 if (!err) {
434 stats.clean++;
435 assert.ok(g.clean, `case ${i}: we merged cleanly but git conflicts on ${g.conflicts}`);
436 const tree = m.outcome === 'merge' ? m.tree : sh(r.bare, ['rev-parse', `${m.oid}^{tree}`]).stdout.trim();
437 assert.equal(tree, g.tree, `case ${i}: tree differs from git merge-tree (outcome ${m.outcome})`);
438 assert.deepEqual(fsckProblems(r.bare), []);
439 } else if (nBases > 1) {
440 // criss-cross: git merges the bases into a virtual one; we refuse, whatever git's verdict
441 assert.ok(err.bases?.length === nBases, `case ${i}: ${nBases} merge bases must be refused as such (${err.message})`); stats.criss++;
442 } else {
443 stats.conflict++;
444 // our conflicts are a superset of git's: where git is clean and we are not, that is the Myers-fallback abort
445 if (g.clean) { stats.conservative++; if (!Object.values(err.reasons ?? {}).some(x => /rename/.test(x))) stats.nonRename++; if (process.env.MERGE_DEBUG) console.log(` conservative ${i}: ${err.message}`); }
446 // per path: every path git conflicts on is one of ours — except a directory-rename target, a path git computes
447 // from the rename (G2 reports the added path instead, with its reason)
448 else for (const p of g.conflicts) assert.ok(err.conflicts.some(q => q === p || (q.endsWith('/') && p.startsWith(q))) || (/directory rename/.test(g.info) && Object.values(err.reasons ?? {}).some(x => /directory rename/.test(x))), `case ${i}: git conflicts on ${p}, we did not (ours: ${err.message}; git: ${g.conflicts} ${g.info ?? ''})`);
449 }
450 }
451 console.log(` ${N} cases (shapes plain/merged/criss-cross ${N - stats.shapes[1] - stats.shapes[2]}/${stats.shapes[1]}/${stats.shapes[2]}): clean=${stats.clean} conflict=${stats.conflict} criss-cross refused=${stats.criss} attr-source cases=${stats.withAttrs} (union-resolved files=${stats.unioned}, merge-attribute binary conflicts=${stats.attrBinary}) (conservative: ${stats.conservative}, not from a rename guard: ${stats.nonRename}) files line-merged: ${stats.lineMerged}`);
452 assert.ok(stats.clean > 0 && stats.conflict > 0 && stats.lineMerged > 0, 'the line merge was exercised');
453 assert.equal(stats.nonRename, 0, 'outside the rename guards, never conservative: the line merge is git\'s');
454});
Diagnostics6 git calls · 96 ms
CallStatusSizeTime096 ms
discover200191 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=191
git.server.agent=git/github-9922ec520325-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=191
git.pkt.payload.max=36
ls-refs20012 KiB2 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=11990
git.response.cache=UPDATING
git.response.duration_ms=2
git.protocol.version=2
git.pkt.frames=152
git.pkt.data=151
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=11990
git.pkt.payload.max=122
git.ls_refs.count=151
git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 102004.2 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=4347
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4347
git.pkt.payload.max=4247
git.sideband.band1.bytes=4247
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=10
git.pack.bytes=4247
git.pack.ofs_delta=0
git.pack.ref_delta=0
git.pack.chain.max=0
git.pack.trailer=a6caf8e129bea82c9bae4cbc7c130c9205add400
git.pack.full=10
Open pack map
fetchtree:0200919 B · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=919
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=800d30ba8923860bfc460ca884b7f9ba22083588
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=919
git.pkt.payload.max=892
git.sideband.band1.bytes=892
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=892
git.pack.trailer=5323b9266eea5ded637285d1c5320699f12be76e
Open pack map
fetchtree:02005.6 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=86
git.response.bytes=5724
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=58fabb6768b3f737ee9cd8bac647bdc27405fb4d
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=5724
git.pkt.payload.max=5697
git.sideband.band1.bytes=5697
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=5697
git.pack.trailer=be7e0453974a5fe832f9065a33bb7e3434c10e9b
Open pack map
fetch20012 KiB86 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=12438
git.response.cache=MISS
git.response.duration_ms=86
git.fetch.wants=f0a6dd817b571d811b0ff1c6a45e10abfbd4d429
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=5
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=12438
git.pkt.payload.max=8192
git.sideband.band1.bytes=12406
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://github.com/ivarvong/ply
Ref
refs/heads/main
Commit
19912563f540228593df0c489082e5e2508e21e4
cf-ray
a5e2bd6cb842cfc3
Request
2063665d…
Protocol
v2 · sha1
Agent
git/github-9922ec520325-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format