// Landing a branch, with git operations only: fast-forward, a merge commit from a three-way tree merge, branch delete. // // mergeBranch(ref ← from): ls-refs both, find the merge base (commit-only fetches, tree:0, doubling depth), then // - ours == base → fast-forward: push the branch head to ref, empty pack (the server has every object) // - theirs == base → nothing to do // - else → three-way merge of the two trees against the base tree, directory by directory, fetching only the // subtrees that differ; a commit with parents [ours, theirs]; push the commit + the new trees and // merged blobs. A regular file both sides changed is merged line by line with a port of git's xdiff // (linemerge.js: histogram diff, compaction, zealous conflict refinement) — clean exactly where git is // clean and byte-identical, else `merge_conflict` with the paths and a reason per path. Our conflicts // are a superset of git's: the rename guards below, and the rare file where git's diff falls back to // classic Myers, which we do not port (test/fuzz/linemerge.mjs measures it). Where we succeed, the // tree is what `git merge-tree --write-tree` produces (test/merge.test.js). // The pure parts: decidePath / threeWay (one directory), mergeMode, bestBases (git merge-base --all over known commits), // searchStep (the merge-base search's transition), decideMerge (what a verdict means for the branch), uniqueObjects; // linemerge.js. The effects: lsRefs, fetchObject, push. Every step that can fail returns a Result, the entry points // (mergeBranch, mergeBase, mergeTrees, attributeTree) included. /* oxlint-disable import/max-dependencies -- a merge drives ls-refs, fetch, push, the object codecs and the line merge */ /* oxlint-disable eslint/require-await, typescript/promise-function-async -- each function keeps its async-ness (a sync throw stays sync); together the two rules forbid a function that forwards a promise */ import type { ValidatedIdent } from './validate.js'; import type { CheckedLimits } from './limits.js'; import type { Driver, Rediff } from './linemerge.js'; import type { ErrorOf, Extra, Miss, PlyError } from './errors.js'; import type { Err, Ok, Option, Result } from './result.js'; import type { Input } from './absent.js'; import type { LsRefsResult } from './lsrefs.js'; import type { OperationOpts, Outcome } from './operation.js'; import { fail } from './errors.js'; import { andThen, assertNever, err, getOrElse, isNone, isSome, map, mapOption, none, ok, some } from './result.js'; import { at, fromNullable, fromNullish, mapGet, withDefaults } from './absent.js'; import { lsRefs } from './lsrefs.js'; import { fetchObject, objectAt, treeEntries } from './fetch.js'; import { fetchPackTree0 } from './fetchpack.js'; import { push, ZERO_OID } from './push.js'; import { parseOid, type Oid } from './oid.js'; import { operation, verifyRef } from './operation.js'; import { parseTree, encodeEntries, parseCommit, encodeCommitOf, hashObject, ident, TYPE, type Mode } from './objects.js'; import { validateRef, validatePushRef, validateMessage } from './validate.js'; import { signCommit } from './sign.js'; import { mergeLines } from './linemerge.js'; import { attributeOf, attributesFor, bytesToStr, popLast, utf8ToStr } from './attributes.js'; import { short, commitAt, commitBytesAt, isOid, givenOid, assertCommit, stamp } from './mergeio.js'; import { checkLimit, limitError, lowered } from './limits.js'; // A merge_conflict's payload: Detail carries `conflicts`; reasons and bases are extras (errors.ts is shared; additive // detail is the steward's call). type ConflictDetail = Extra & { readonly conflicts: readonly string[] }; // The shapes this module reads from other modules (objects, transport, operation, push, ls-refs); their own modules // own the full types. export type TreeEntry = { readonly mode: Mode; readonly name: string; readonly oid: Oid }; export type Commit = { readonly tree: Oid; readonly parents: readonly Oid[]; readonly author: string; readonly committer: string; readonly encoding: string | null; readonly message: string | null; readonly extra: readonly string[]; }; export type PackObject = { readonly type: number; readonly data: Uint8Array; readonly oid: string }; // the transport every operation runs on (src/transport.ts); re-exported for rebase.ts export type { Transport } from './transport.js'; import type { Transport } from './transport.js'; // the span every operation records on (src/otel.js); re-exported for rebase.ts export type { Span } from './otel.js'; import type { Span } from './otel.js'; export type { Outcome } from './operation.js'; export type OpContext = { readonly t: Transport; readonly root: Span; readonly outcome: Outcome; readonly limits: CheckedLimits }; export type PushResult = { readonly packBytes: number }; // a commit stamp: `time` (unix seconds) defaults to the operation's `time`, `tz` (+HHMM / -HHMM) to +0000 export type Author = { readonly name: string; readonly email: string } & Input<{ readonly tz: string; readonly time: number }>; // a commit signer (src/sign.ts); re-exported for rebase.ts export type { Signer } from './sign.js'; import type { Signer } from './sign.js'; export type TreeCache = Map; export type PushObject = { readonly type: number; readonly data: Uint8Array }; const EMPTY: readonly TreeEntry[] = []; const NO_PARENTS: readonly never[] = []; const isTreeEntry = (e: TreeEntry): boolean => e.mode === '40000'; // An entry absent on a side is None. type Entry = Option; const same = (a: Entry, b: Entry): boolean => (a.tag === 'none' || b.tag === 'none' ? a.tag === b.tag : a.value.mode === b.value.mode && a.value.oid === b.value.oid); const isTree = (e: Entry): boolean => e.tag === 'some' && isTreeEntry(e.value); const isFile = (e: Entry): boolean => e.tag === 'some' && (e.value.mode === '100644' || e.value.mode === '100755'); // directory vs directory, or a directory one side deleted/added: recurse so the conflict (if any) is per file, // and untouched files inside a directory the other side deleted go away, as git does const treeish = (e: Entry): boolean => e.tag === 'none' || isTree(e); const recurses = (O: Entry, T: Entry): boolean => treeish(O) && treeish(T) && (isTree(O) || isTree(T)); const byName = (list: readonly TreeEntry[]): Map => new Map(list.map(e => [e.name, e])); // Pure: what a three-way merge does with one name of a directory, git's trivial-merge rules at tree level: same on both // sides → that; unchanged on one side → the other side's (an absent result drops the name); both trees → recurse; both // regular files changed differently over a regular base → content (a line merge may resolve it); otherwise → conflict. export type PathDecision = | { readonly kind: 'take'; readonly entry: TreeEntry } | { readonly kind: 'drop' } | { readonly kind: 'recurse' } | { readonly kind: 'content' } | { readonly kind: 'conflict' }; const DROP: PathDecision = { kind: 'drop' }; const RECURSE: PathDecision = { kind: 'recurse' }; const CONTENT: PathDecision = { kind: 'content' }; const CONFLICT: PathDecision = { kind: 'conflict' }; const taken = (e: Entry): PathDecision => (e.tag === 'some' ? { kind: 'take', entry: e.value } : DROP); function decidePath(B: Entry, O: Entry, T: Entry): PathDecision { if (same(O, T) || same(B, T)) return taken(O); if (same(B, O)) return taken(T); if (recurses(O, T)) return RECURSE; if (isFile(B) && isFile(O) && isFile(T)) return CONTENT; return CONFLICT; } // Pure: three-way merge of one directory's entries, as lists by decision: { entries (resolved, in no particular order), // recurse: [name], conflicts: [name], content: [name], deletedBoth, addedOurs, addedTheirs }. deletedBoth is the names // base holds and neither side does, in this one directory. The added lists feed the directory-rename guard in mergeTrees // (G2). The rename guard G1 does not read deletedBoth: what both sides lost is decided over the three trees (deletedOnBoth). export type ThreeWay = { readonly entries: TreeEntry[]; readonly recurse: string[]; readonly conflicts: string[]; readonly content: string[]; readonly deletedBoth: string[]; readonly addedOurs: string[]; readonly addedTheirs: string[]; }; export function threeWay(base: readonly TreeEntry[], ours: readonly TreeEntry[], theirs: readonly TreeEntry[]): ThreeWay { const b = byName(base); const o = byName(ours); const t = byName(theirs); const names = new Set([...b.keys(), ...o.keys(), ...t.keys()]); const entries: TreeEntry[] = []; const recurse: string[] = []; const conflicts: string[] = []; const content: string[] = []; const deletedBoth: string[] = []; const addedOurs: string[] = []; const addedTheirs: string[] = []; for (const name of names) { const B = mapGet(b, name); const O = mapGet(o, name); const T = mapGet(t, name); if (B.tag === 'some' && O.tag === 'none' && T.tag === 'none') deletedBoth.push(name); if (B.tag === 'none' && O.tag === 'some') addedOurs.push(name); if (B.tag === 'none' && T.tag === 'some') addedTheirs.push(name); const d = decidePath(B, O, T); switch (d.kind) { case 'take': entries.push(d.entry); continue; case 'drop': continue; case 'recurse': recurse.push(name); continue; case 'content': content.push(name); continue; case 'conflict': conflicts.push(name); continue; } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check assertNever(d); } return { entries, recurse, conflicts, content, deletedBoth, addedOurs, addedTheirs }; } // Pure: git's mode merge for a regular file both sides touched: equal → that; one side unchanged → the other's; null: // both changed it, differently (a conflict). export const mergeMode = (b: M, o: M, t: M): M | null => { if (o === t || b === t) return o; if (b === o) return t; return null; }; // Pure: git's merge bases — the best common ancestors of `a` and `b` (common ancestors that are not ancestors of another // common ancestor; git merge-base --all), over the commits known so far (oid → { parents }). A commit named as a parent // but not in the map is a cut: its ancestry is unknown. `truncated` says the answer may change once the cuts are fetched: // - a cut reachable from a or b outside the settled region (common ancestors and everything below them) may hide a // best base — any best base outside what we know is an ancestor of a or b that is not an ancestor of a known common // ancestor, so it lies beyond exactly such a cut; // - with more than one best base, a cut inside the settled region may hide that one of them is an ancestor of // another (through the cut), so the set would shrink: {c, z} where z is below c through a cut x is not criss-cross, // it is {c} (#42). Only a cut that some best base reaches and another does not can do that: z below c through a // cut k means k is an ancestor of c and z an ancestor of k, so k cannot also be an ancestor of z (a cycle). A cut // every best base reaches (deep shared history under a true criss-cross) changes nothing, and deepening for it // would walk to the root or the cap (limit_exceeded where git answers two bases). // A single best base over a graph whose only cuts are settled is final, and the rule says so without a special case: // every settled commit is the base or below it, so the one base reaches every settled cut. // The graph is over node names K: mergeBase walks Oids (K = Oid, so every base it answers is one); a caller's own graph // may name its nodes with any strings, since nothing here reads a name but to compare it. export type Parents = { readonly parents: readonly K[] }; // a known commit's parents; a cut has none known const parentsIn = (commits: ReadonlyMap>, c: K): readonly K[] => getOrElse(mapOption(mapGet(commits, c), x => x.parents), NO_PARENTS); export function bestBases(commits: ReadonlyMap>, a: K, b: K): { best: K[]; truncated: boolean } { // the commits reachable from `starts`, not walking into `stop` (a commit not in the map is reached, not walked) const closure = (starts: readonly K[], stop: ReadonlySet = new Set()): Set => { const seen = new Set(); const st = [...starts]; for (let c = popLast(st); c.tag === 'some'; c = popLast(st)) { if (seen.has(c.value) || stop.has(c.value)) continue; seen.add(c.value); for (const p of parentsIn(commits, c.value)) st.push(p); } return seen; }; const A = closure([a]); const B = closure([b]); const common = [...A].filter(c => B.has(c)); const below = closure(common.flatMap(c => parentsIn(commits, c))); // proper ancestors of common ancestors const best = common.filter(c => !below.has(c)).toSorted(); const settled = new Set([...common, ...below]); const cut = (c: K): boolean => !commits.has(c); // a cut reachable from a or b outside the settled region, or a settled cut some best base reaches and another does not const between = (): boolean => { const reach = best.map(c => closure([c])); return [...settled].some(k => cut(k) && reach.some(r => !r.has(k))); }; return { best, truncated: [...closure([a, b], settled)].some(c => cut(c)) || between() }; } // Effect: the ancestors of `head` within `depth`, via a commit-only pack (tree:0 keeps trees and blobs out). // The pack is held to the deepen contract (shallow-info, protocol v2): `head` is in it as a commit, every commit in it is // an ancestor of `head` through it, and a commit whose parent it lacks is one the server named `shallow`. Commits are // hash-verified, so ancestry cannot be forged, only withheld; a server that withholds it without saying so would make // bestBases answer over a cut graph that looks whole (#18), so that is `pack_corrupt` here. git's upload-pack keeps the // contract (the boundary of the depth and of a shallow server repository are both reported). // The answer is keyed by the ids the walk reached (head and the parents named in parsed commits), so every key is an Oid // parsed once (by parseOid and parseCommit), not the pack's own keys. export async function ancestors(t: Transport, head: Oid, depth: number): Promise, PlyError>> { const got = await fetchPackTree0(t, { wants: [head], filter: 'tree:0', deepen: depth }); if (!got.ok) return got; const r = got.value; const sent = new Map(); const objects = fromNullish(r.objects); if (objects.tag === 'some') for (const [oid, o] of objects.value) if (o.type === TYPE.COMMIT) { const c = parseCommit(o.data, t.limits); if (!c.ok) return c; sent.set(oid, c.value); } if (!sent.has(head)) return fail('pack_corrupt', `commit ${head} not in the pack that wanted it`); const commits = new Map(); const seen = new Set([head]); // seen grows while it is walked: every commit reachable from head through the pack for (const c of seen) { const known = mapGet(sent, c); if (known.tag === 'some') { commits.set(c, known.value); for (const p of known.value.parents) seen.add(p); } } const shallow = new Set(r.shallow); const reached = new Set(commits.keys()); for (const [oid, c] of sent) { if (!reached.has(oid)) return fail('pack_corrupt', `commit ${oid} sent but not an ancestor of ${head}`); const missing = shallow.has(oid) ? none : fromNullable(c.parents.find(p => !sent.has(p))); if (missing.tag === 'some') return fail('pack_corrupt', `parent ${missing.value} of ${oid} withheld and ${oid} not reported shallow`); } return ok(commits); } // The merge-base search as a machine. It starts searching a window of 8 commits a side and, while the window's graph // is truncated (bestBases), doubles it, the last step clamped to the cap (#79: cap 100 searches 64 and then 100, not // 64 alone). A graph that is not truncated is the verdict: one base, several (criss-cross), or none (unrelated). A // truncated graph at the cap is `capped`: limit_exceeded, never an answer over a cut graph. `searchStep` is pure; the // driver in mergeBase is the only part that fetches. export type Search = | { readonly tag: 'searching'; readonly depth: number } | { readonly tag: 'found'; readonly depth: number; readonly base: K; readonly bases: K[] } | { readonly tag: 'criss-cross'; readonly depth: number; readonly bases: K[] } | { readonly tag: 'unrelated'; readonly depth: number; readonly bases: K[] } | { readonly tag: 'capped'; readonly depth: number }; export type Verdict = Extract, { readonly tag: 'found' | 'criss-cross' | 'unrelated' }>; // `depth` is the window searched (commits a side, the tip at 1); `cap` counts whole commits (mergeBase rounds a limit // down); bases is git merge-base --all on every verdict. The first state is searching(min(8, cap)); a cap under 1 is // capped before any search. export function searchStep(depth: number, cap: number, commits: ReadonlyMap>, a: K, b: K): Search { const { best, truncated } = bestBases(commits, a, b); // Both sides complete and still truncated cannot happen (ancestors refuses a parent withheld without a shallow line); // it used to be accepted (#18). if (truncated) return depth < cap ? { tag: 'searching', depth: Math.min(depth * 2, cap) } : { tag: 'capped', depth }; const first = at(best, 0); if (first.tag === 'none') return { tag: 'unrelated', depth, bases: best }; return best.length > 1 ? { tag: 'criss-cross', depth, bases: best } : { tag: 'found', depth, base: first.value, bases: best }; } // base is the verdict's one base, or null export type MergeBase = { readonly base: Oid | null; readonly bases: Oid[]; readonly depth: number; readonly commits: Map; readonly verdict: Verdict }; // maxDepth: the search cap in commits a side; null (the default) reads the transport's limits.maxMergeDepth. export type MergeBaseConfig = { readonly maxDepth: number | null }; export type MergeBaseOptions = Input; // mergeBase of parsed ids: mergeBranch and rebaseBranch, which hold Oids, start here. export async function mergeBaseOf(t: Transport, a: Oid, b: Oid, options: MergeBaseOptions = {}): Promise> { const { maxDepth } = withDefaults(options, { maxDepth: null }); const capped = maxDepth === null ? ok(t.limits.maxMergeDepth) : checkLimit(maxDepth, 'maxMergeDepth'); if (!capped.ok) return capped; const cap = capped.value; const top = Math.floor(cap); let s: Search = top < 1 ? { tag: 'capped', depth: 0 } : { tag: 'searching', depth: Math.min(8, top) }; let commits = new Map(); while (s.tag === 'searching') { const depth: number = s.depth; // oxlint-disable-next-line eslint/no-await-in-loop -- each round deepens from what the last one found const [A, B] = await Promise.all([ancestors(t, a, depth), ancestors(t, b, depth)]); if (!A.ok) return A; if (!B.ok) return B; commits = new Map([...B.value, ...A.value]); s = searchStep(depth, top, commits, a, b); } switch (s.tag) { case 'capped': { const attempted = s.depth === 0 ? 1 : s.depth * 2; return err(limitError('merge-base search depth', attempted, cap)); } case 'found': return ok({ base: s.base, bases: s.bases, depth: s.depth, commits, verdict: s }); case 'criss-cross': case 'unrelated': return ok({ base: null, bases: s.bases, depth: s.depth, commits, verdict: s }); } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(s); } // The caller's two ids are parsed once, here (parseOid: bad_request, what `oid`), before any fetch. export async function mergeBase(t: Transport, a: string, b: string, options: MergeBaseOptions = {}): Promise> { const ia = parseOid(a); if (!ia.ok) return ia; const ib = parseOid(b); if (!ib.ok) return ib; return mergeBaseOf(t, ia.value, ib.value, options); } // Effect: a tree's entries, from the oid → bytes cache or fetched into it (`onFetch` counts a fetch) const NO_COUNT = (): void => { /* not counted */ }; // oxlint-disable-next-line eslint/max-params -- the transport, the cache, the oid and the counter const cachedTree = async (t: Transport, cache: TreeCache, oid: string, onFetch: () => void = NO_COUNT): Promise> => { const held = mapGet(cache, oid); if (held.tag === 'some') return parseTree(held.value, t.limits); const got = await fetchObject(t, { oid, expectType: TYPE.TREE }); if (!got.ok) return got; cache.set(oid, got.value.data); onFetch(); // the fetch's check parsed it (#208) return treeEntries(got.value, t.limits); }; const subtree = (e: Entry): Oid | null => (e.tag === 'some' && isTreeEntry(e.value) ? e.value.oid : null); // a tree by oid; null is the empty tree type ReadTree = (oid: Oid | null) => Promise>; // Effect: what `side` adds relative to `base` (both tree oids), recursing only into differing subtrees; a directory new // on `side` is one entry, 'dir/', standing for everything inside it, so it carries the directory's tree id: two sides // added the same things there only if they added the same tree. type Added = { readonly path: string; readonly oid: Oid }; async function addedPaths(read: ReadTree, base: Oid | null, side: Oid | null, prefix = ''): Promise> { if (base === side) return ok([]); const [B, S] = await Promise.all([read(base), read(side)]); if (!B.ok) return B; if (!S.ok) return S; const b = byName(B.value); const out: Added[] = []; for (const e of S.value) { const was = mapGet(b, e.name); // new, or a file where a directory was (or the reverse): added if (was.tag === 'none' || isTreeEntry(e) !== isTreeEntry(was.value)) out.push({ path: prefix + e.name + (isTreeEntry(e) ? '/' : ''), oid: e.oid }); else if (isTreeEntry(e) && was.value.oid !== e.oid) { // oxlint-disable-next-line eslint/no-await-in-loop -- one subtree at a time, as before const inner = await addedPaths(read, was.value.oid, e.oid, `${prefix}${e.name}/`); if (!inner.ok) return inner; out.push(...inner.value); } } return ok(out); } // a list of additions as one comparable value: each path with what was put there (paths hold no NUL) const changeSet = (l: readonly Added[]): string => l.map(a => `${a.path}\0${a.oid}`).toSorted().join('\0'); // a side still holds a base file as a file (a file replaced by a directory of its name is deleted there: the rename // detection ply stands in for counts anything but a tree as the file) const holdsFile = (e: Entry): boolean => e.tag === 'some' && !isTreeEntry(e.value); // Effect: the base paths neither side holds any more: every rename source both sides lost, which is what arms G1. It is // read off the three trees, not off the merge walk, because the walk does not visit every place a file can be lost on // both sides: a subtree that is the same tree on ours and theirs is taken whole, and a base file under a name where a // side now has a directory is merged as if the base were empty. Descends only where base differs from both sides (a // subtree one side left alone has no deletion on that side); a directory gone from both sides (absent, or a file now) // is one path. Where the sides differ the walk has been, so those reads are the tree cache's. A subtree ours and theirs // agree on and base does not is the only place this reads what the walk did not: base's copy and the sides' one copy, // each once. With `gate` given such a subtree is not entered but listed there, for the caller to enter only if the // merge can have a rename hazard (see mergeDir), and the directories exactly one side changed are counted (`lone`): // the two numbers say which of the gate's questions has fewer directories to read. type Shared = { readonly base: Oid; readonly side: Oid; readonly prefix: string }; type Gate = { readonly shared: Shared[]; lone: number }; // The gate reads sibling directories this many at a time, each up to two trees the walk did not read. const GATE_WIDTH = 8; // a base directory still a directory on both sides, changed by exactly one of them // oxlint-disable-next-line eslint/max-params -- base's tree and the two sides' const loneChange = (was: Oid, so: Oid | null, st: Oid | null): boolean => so !== null && st !== null && (so === was) !== (st === was); // oxlint-disable-next-line eslint/max-params -- the reader, the trees, where they are, the list filled and the gate's async function deletedOnBoth(read: ReadTree, { base, ours, theirs }: Trees, prefix: string, out: string[], gate: Gate | null): Promise> { if (base === null || base === ours || base === theirs) return ok(true); const [B, O, T] = await Promise.all([read(base), read(ours), read(theirs)]); if (!B.ok) return B; if (!O.ok) return O; if (!T.ok) return T; const o = byName(O.value); const t = byName(T.value); for (const e of B.value) { const eo = mapGet(o, e.name); const et = mapGet(t, e.name); if (!isTreeEntry(e)) { if (!holdsFile(eo) && !holdsFile(et)) out.push(prefix + e.name); continue; } const so = subtree(eo); const st = subtree(et); if (so === null && st === null) { out.push(prefix + e.name); continue; } if (gate !== null && so !== null && so === st && so !== e.oid) { gate.shared.push({ base: e.oid, side: so, prefix: `${prefix}${e.name}/` }); continue; } if (gate !== null && loneChange(e.oid, so, st)) gate.lone++; // oxlint-disable-next-line eslint/no-await-in-loop -- one subtree at a time, as addedPaths const inner = await deletedOnBoth(read, { base: e.oid, ours: so, theirs: st }, `${prefix}${e.name}/`, out, gate); if (!inner.ok) return inner; } return ok(true); } // One directory of oneSided: true when `side` added or removed a name here (a file where a directory was, or the // reverse, is both), else the subdirectories `side` changed, still to be looked at. type Level = { readonly base: Oid | null; readonly side: Oid | null; readonly other: Oid | null }; async function oneSidedAt(read: ReadTree, { base, side, other }: Level): Promise> { if (base === side || side === other) return ok([]); const [B, S, X] = await Promise.all([read(base), read(side), read(other)]); if (!B.ok) return B; if (!S.ok) return S; if (!X.ok) return X; const b = byName(B.value); const s = byName(S.value); const x = byName(X.value); for (const e of B.value) { const now = mapGet(s, e.name); if (now.tag === 'none' || isTreeEntry(now.value) !== isTreeEntry(e)) return ok(true); } const below: Level[] = []; for (const e of S.value) { const was = mapGet(b, e.name); if (was.tag === 'none') return ok(true); if (isTreeEntry(e) && was.value.oid !== e.oid) below.push({ base: was.value.oid, side: e.oid, other: subtree(mapGet(x, e.name)) }); } return ok(below); } // Effect: whether `side` added or removed a path relative to `base` anywhere outside the subtrees it shares with `other`. // Reads what the walk read, plus base's and the side's copy of each directory only that side changed: one depth at a // time, GATE_WIDTH sibling directories at once, stopping after the batch that holds an add or a removal. Inside a shared // subtree both sides added and removed the same things; if neither side added or removed anything outside them, the // two sides give rename detection the same sources and the same targets, so it pairs the same renames on both and // there is nothing for G1 to guard. // oxlint-disable-next-line eslint/max-params -- the reader and the three trees async function oneSided(read: ReadTree, base: Oid | null, side: Oid | null, other: Oid | null): Promise> { let level: Level[] = [{ base, side, other }]; while (level.length > 0) { const below: Level[] = []; for (let i = 0; i < level.length; i += GATE_WIDTH) { // oxlint-disable-next-line eslint/no-await-in-loop -- GATE_WIDTH directories at a time const found = await Promise.all(level.slice(i, i + GATE_WIDTH).map(async d => oneSidedAt(read, d))); for (const f of found) { if (!f.ok) return f; if (f.value === true) return ok(true); for (const d of f.value) below.push(d); } } level = below; } return ok(false); } export type DriverFor = (path: string) => Promise>; // Why a path conflicts. The text is the reason a caller reads in merge_conflict's `reasons`. export type ContentReason = | 'binary (merge attribute)' | 'too large to merge' | 'binary' | 'content (both sides changed the same lines)' | 'content (git would decide this with a classic-diff fallback ply does not implement)'; export type ConflictReason = | ContentReason | 'tree' // the sides disagree on what the path is (modify/delete, file/directory, add/add of different kinds, …) | 'mode' // both sides changed a file's mode, differently | 'content' // both sides changed a file and no line merge was given | 'possible directory rename (added inside a directory the other side removed)' | 'possible rename source (deleted on both sides while paths were added; ply does not detect renames)' | 'possible rename target (added while the merge has a deletion conflict)'; export type BlobSpec = { readonly base: Oid; readonly ours: Oid; readonly theirs: Oid; readonly path: string; readonly driverFor: DriverFor | null }; // A both-sides-changed file's content: one side's blob as it is (already on the server), a new merged blob (to push), // or a conflict with its reason. export type BlobMerge = | { readonly kind: 'existing'; readonly oid: Oid } | { readonly kind: 'merged'; readonly oid: Oid; readonly data: Uint8Array } | { readonly kind: 'conflict'; readonly reason: ContentReason }; export type MergeStats = { merged: number; undecided: number; unioned: number; attrBinary: number }; export type MergeBlob = ((spec: BlobSpec) => Promise>) & { stats: MergeStats }; export type Removed = 'ours' | 'theirs' | null; // The three trees by oid (null: the empty tree), the path prefix of this directory, which side removed the directory // being merged (null: neither), the line merge for a both-sides-changed file (null: such a file conflicts), and the // .gitattributes merge driver per path (null: text). export type MergeTreesConfig = { readonly base: string | null; readonly ours: string | null; readonly theirs: string | null; readonly prefix: string; readonly removed: Removed; readonly mergeBlob: MergeBlob | null; readonly driverFor: DriverFor | null; }; export type MergeTreesSpec = Input; // The same, the three tree ids parsed (mergeTrees' edge, or an Oid the caller already holds). type MergeDirConfig = Omit & Trees; // A reasons record with no prototype (Object.create's result is `any`). It has no keys, so it is any such record. // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- an empty null-prototype object: no key, no inherited key const noProtoReasons = (): Record => Object.create(null) as Record; // The accumulator one merge shares across its recursion. reasons is keyed by path and has no prototype. deletedOne: a // modify/delete conflict was seen. export type MergeAcc = { objects: PackObject[]; conflicts: string[]; fetched: number; deletedBoth: string[]; dirAdds: string[]; reasons: Record; contentMerged: number; deletedOne: boolean; }; // oid: the merged tree, or null when the merge conflicts or the tree is empty export type MergeTreesResult = MergeAcc & { readonly oid: Oid | null }; const mergeTreesDefaults = (): MergeTreesConfig => ({ base: null, ours: null, theirs: null, prefix: '', removed: null, mergeBlob: null, driverFor: null }); // Effect: merge three trees (by oid, any may be null = empty) into a new tree, returning its oid, the new objects to push // and conflicts as paths. Fetches only directories where the sides differ; `cache` is the oid → bytes tree cache. // `mergeBlob(base, ours, theirs, path)` resolves a path both sides changed (line merge); without it such paths conflict. // // Rename guards. merge-ort detects renames (and directory renames, as conflicts); we do not. Two shapes are where a // rename could make git conflict while a rename-blind merge is clean, so they are conflicts here (superset of git's): // G1 a path deleted on both sides while either side adds a path (rename/rename(1to2), rename/delete) — the deleted // paths and the added ones are reported, since git names the conflict at the rename target. "Deleted on both // sides" is decided over the whole of the three trees (deletedOnBoth), wherever the walk went // (G2's target is a path git computes from the directory rename; we report the added path and the reason.) // G2 a directory one side removed entirely, the other side adds inside it (directory rename + add) // A rename on one side with the other side untouched merges exactly as git does. /* oxlint-disable eslint/no-await-in-loop, eslint/complexity, eslint/max-params -- one path at a time (the merges share `out`, the cache and the fetch budget); the rename guards run once, at the top */ async function mergeDir(t: Transport, cache: TreeCache, { base, ours, theirs, prefix, removed, mergeBlob, driverFor }: MergeDirConfig, out: MergeAcc, top: boolean): Promise> { const conflict = (path: string, why: ConflictReason): void => { out.conflicts.push(path); out.reasons[path] = why; }; // A tree asked for again while its fetch is in flight is that fetch: two of the three trees can be one tree (a // subtree ours and theirs share), and no tree is fetched twice. const flying = new Map>>(); const read: ReadTree = async oid => { if (oid === null) return ok(EMPTY); const held = mapGet(flying, oid); if (held.tag === 'some') return held.value; const p = cachedTree(t, cache, oid, () => { out.fetched++; }); flying.set(oid, p); const got = await p; flying.delete(oid); return got; }; const [readB, readO, readT] = await Promise.all([read(base), read(ours), read(theirs)]); if (!readB.ok) return readB; if (!readO.ok) return readO; if (!readT.ok) return readT; const [B, O, T] = [readB.value, readO.value, readT.value]; const r = threeWay(B, O, T); const { entries } = r; // Names are the repository's: a Map, so a directory called `constructor` or `__proto__` is not Object.prototype's const b = byName(B); const o = byName(O); const th = byName(T); for (const name of r.conflicts) conflict(prefix + name, 'tree'); if (r.conflicts.some(name => b.has(name) && !(o.has(name) && th.has(name)))) out.deletedOne = true; // modify/delete if (removed === 'ours') for (const name of r.addedTheirs) out.dirAdds.push(prefix + name); if (removed === 'theirs') for (const name of r.addedOurs) out.dirAdds.push(prefix + name); for (const name of r.content) { // content names are files on all three sides (threeWay) const eb = mapGet(b, name); const eo = mapGet(o, name); const et = mapGet(th, name); if (eb.tag === 'none' || eo.tag === 'none' || et.tag === 'none') continue; const mode = mergeMode(eb.value.mode, eo.value.mode, et.value.mode); if (mode === null) { conflict(prefix + name, 'mode'); continue; } if (mergeBlob === null) { conflict(prefix + name, 'content'); continue; } const blobMerged = await mergeBlob({ base: eb.value.oid, ours: eo.value.oid, theirs: et.value.oid, path: prefix + name, driverFor }); if (!blobMerged.ok) return blobMerged; const blob = blobMerged.value; switch (blob.kind) { case 'conflict': conflict(prefix + name, blob.reason); continue; case 'existing': entries.push({ mode, name, oid: blob.oid }); out.contentMerged++; continue; case 'merged': entries.push({ mode, name, oid: blob.oid }); out.objects.push({ type: TYPE.BLOB, data: blob.data, oid: blob.oid }); out.contentMerged++; continue; } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check assertNever(blob); } for (const name of r.recurse) { const eb = mapGet(b, name); let sideRemoved = removed; if (sideRemoved === null && isTree(eb)) { if (!o.has(name)) sideRemoved = 'ours'; else if (!th.has(name)) sideRemoved = 'theirs'; } const sub = await mergeDir(t, cache, { base: subtree(eb), ours: subtree(mapGet(o, name)), theirs: subtree(mapGet(th, name)), prefix: `${prefix}${name}/`, removed: sideRemoved, mergeBlob, driverFor }, out, false); if (!sub.ok) return sub; if (sub.value.oid !== null) entries.push({ mode: '40000', name, oid: sub.value.oid }); // an empty merged subtree drops the directory, as git does } if (top) for (const p of out.dirAdds) if (!(p in out.reasons)) conflict(p, 'possible directory rename (added inside a directory the other side removed)'); const encoded = encodeEntries(entries); if (!encoded.ok) return encoded; const data: Uint8Array = encoded.value; const oid: Oid = hashObject('tree', data); // What both sides lost. Where the walk went this reads nothing new, and a merge with no shared subtree (one ours and // theirs changed identically) reads nothing here at all. With shared subtrees and no loss seen by the walk, G1 can // only fire if both hold: a path lost on both sides inside a shared subtree, and a path one side alone added or // removed (without one there is no rename for git to pair differently on the two sides). One "no" settles it, so the // question with fewer directories to read is asked first: the shared subtrees when they are fewer than the // directories one side alone changed, those directories otherwise. A "yes" asks the other question too, so what is // decided never depends on the order: the shared subtrees' losses arm G1 only when a side added or removed a path // of its own. const gate: Gate = { shared: [], lone: 0 }; // the paths both sides lost inside the shared subtrees, in the subtrees' order; each is entered once, GATE_WIDTH at a time const enter = async (): Promise> => { const subtrees = gate.shared.splice(0); const lost: string[] = []; for (let i = 0; i < subtrees.length; i += GATE_WIDTH) { const found = await Promise.all(subtrees.slice(i, i + GATE_WIDTH).map(async (s): Promise> => { const paths: string[] = []; const inner = await deletedOnBoth(read, { base: s.base, ours: s.side, theirs: s.side }, s.prefix, paths, null); return inner.ok ? ok(paths) : inner; })); for (const f of found) { if (!f.ok) return f; for (const p of f.value) lost.push(p); } } return ok(lost); }; // the shared subtrees' losses that arm G1: none unless a side added or removed a path of its own const armed = async (): Promise> => { const first = gate.shared.length < gate.lone ? await enter() : null; // null: the shared subtrees are not read yet if (first !== null && (!first.ok || first.value.length === 0)) return first; const mine = await oneSided(read, base, ours, theirs); if (!mine.ok) return mine; const yours = mine.value ? mine : await oneSided(read, base, theirs, ours); if (!yours.ok) return yours; if (!yours.value) return ok([]); return first === null ? enter() : first; }; if (top) { const lost = await deletedOnBoth(read, { base, ours, theirs }, prefix, out.deletedBoth, gate); if (!lost.ok) return lost; if (out.deletedBoth.length === 0 && !out.deletedOne && gate.shared.length > 0) { const hidden = await armed(); if (!hidden.ok) return hidden; for (const p of hidden.value) out.deletedBoth.push(p); } } // deletedOne is set only beside a conflict if (top && (out.deletedBoth.length > 0 || out.deletedOne)) { // Every path either side added, across the whole tree — the walk above skips directories only one side changed, and a // rename target can be anywhere. Fetched only when a deletion is in play. const addedOursR = await addedPaths(read, base, ours); if (!addedOursR.ok) return addedOursR; const addedTheirsR = await addedPaths(read, base, theirs); if (!addedTheirsR.ok) return addedTheirsR; const addedOurs = addedOursR.value; const addedTheirs = addedTheirsR.value; const added = [...new Set([...addedOurs, ...addedTheirs].map(a => a.path))]; // G1 stands down when the rename is already applied (#103): the rename-blind merge is ours' tree (every change theirs // made is in ours) and both sides added and deleted exactly the same things (a directory new on both sides is one // name, and the same addition only as the same tree), so git pairs the same renames on both // sides and finds nothing to conflict (a cherry-pick of it is empty). An add or delete on ours alone could let git // pair a different source or target there (rename/rename, rename/delete), so the guard stays. const sameChanges = async (): Promise> => { if (changeSet(addedOurs) !== changeSet(addedTheirs)) return ok(false); const removedOurs = await addedPaths(read, ours, base); if (!removedOurs.ok) return removedOurs; return map(await addedPaths(read, theirs, base), removedTheirs => changeSet(removedOurs.value) === changeSet(removedTheirs)); }; const unchanged = out.conflicts.length === 0 && oid === ours ? await sameChanges() : ok(false); if (!unchanged.ok) return unchanged; const applied = unchanged.value; // the refusal names every path both sides lost, the shared subtrees' too; a path the walk already conflicts on is // listed once and keeps the walk's reason if (added.length > 0 && !applied) { const entered = await enter(); if (!entered.ok) return entered; for (const p of entered.value) out.deletedBoth.push(p); } if (added.length > 0 && !applied) for (const p of out.deletedBoth) if (!(p in out.reasons)) conflict(p, 'possible rename source (deleted on both sides while paths were added; ply does not detect renames)'); // Naming: git reports a rename's conflict at the rename target (rename/delete, rename/rename, or a content conflict // after following a rename onto a modify/delete). When this merge conflicts with a deletion in play, every added path // is a possible target, so it is listed too. This adds names to a conflicting merge; it never makes one conflict. if (out.conflicts.length > 0) for (const p of added) if (!(p in out.reasons)) conflict(p, 'possible rename target (added while the merge has a deletion conflict)'); } if (out.conflicts.length > 0 || entries.length === 0) return ok({ oid: null, ...out }); if (oid !== ours && oid !== theirs && oid !== base) out.objects.push({ type: TYPE.TREE, data, oid }); cache.set(oid, data); return ok({ oid, ...out }); } /* oxlint-enable eslint/no-await-in-loop, eslint/complexity, eslint/max-params */ // A tree id as mergeTrees takes it: null is the empty tree; anything else is parsed once (parseOid: 40 lowercase hex, // what: 'oid') before any tree is read. const treeIdOf = (id: string | null): Result> => (id === null ? ok(null) : parseOid(id)); // The three trees parsed once, at the edge: base, then ours, then theirs. function parseTrees({ base, ours, theirs }: Pick): Result> { const b = treeIdOf(base); if (!b.ok) return b; const o = treeIdOf(ours); if (!o.ok) return o; const th = treeIdOf(theirs); if (!th.ok) return th; return ok({ base: b.value, ours: o.value, theirs: th.value }); } // mergeTrees of parsed tree ids: the merge and rebase entries, which hold Oids, start here. export async function mergeTreesOf(t: Transport, cache: TreeCache, spec: MergeDirConfig, into: MergeAcc | null = null): Promise> { const top = into === null; // reasons is keyed by path, so it has no prototype: a path named `__proto__` or `constructor` is recorded like any other const out: MergeAcc = into === null ? { objects: [], conflicts: [], fetched: 0, deletedBoth: [], dirAdds: [], reasons: noProtoReasons(), contentMerged: 0, deletedOne: false } : into; return mergeDir(t, cache, spec, out, top); } export async function mergeTrees(t: Transport, cache: TreeCache, spec: MergeTreesSpec, into: MergeAcc | null = null): Promise> { const config = withDefaults(spec, mergeTreesDefaults()); const trees = parseTrees(config); if (!trees.ok) return trees; // the parsed ids, and none of the caller's: past this line no tree id is a raw string const { prefix, removed, mergeBlob, driverFor } = config; return mergeTreesOf(t, cache, { prefix, removed, mergeBlob, driverFor, ...trees.value }, into); } // Effect: the merge driver for a path from the .gitattributes files of one tree (git's attr.tree / --attr-source, or the // worktree's — which is ours — for a non-bare `git merge`). Reads only the directories on the path, each once; returns // 'text' | 'union' | 'binary' as find_ll_merge_driver picks: merge set → text, -merge → binary, merge=binary|union|text // → that, any other name → text (a custom driver is server configuration we cannot see), unspecified → text. export function attributeDrivers(t: Transport, cache: TreeCache, treeOid: string): DriverFor { // Each directory's tree and .gitattributes text is looked up once and shared, while it is pending or once it has // succeeded. A lookup that fails (an Err, or a rejection) is forgotten as it fails, so the next path asks again (#79: // one transient failure poisoned every later lookup of that directory). type Look = Promise, PlyError>>; const memo = new Map([['/', Promise.resolve(ok(some(treeOid)))]]); const once = (key: string, look: () => Look): Look => { const known = mapGet(memo, key); if (known.tag === 'some') return known.value; const p = look(); memo.set(key, p); p.then(r => r.ok || memo.delete(key), () => memo.delete(key)).catch(() => false); return p; }; // the first entry of the tree `oid` that `keep` accepts const entryIn = async (oid: string, keep: (e: TreeEntry) => boolean): Promise, PlyError>> => map(await cachedTree(t, cache, oid), l => fromNullable(l.find(e => keep(e)))); // keys: '/' + dir for a directory's tree oid, dir alone for its .gitattributes text (a dir never starts with '/') const treeOf = (dir: string): Look => once(`/${dir}`, async () => { const cut = dir.lastIndexOf('/'); const p = await treeOf(cut < 0 ? '' : dir.slice(0, cut)); if (!p.ok || p.value.tag === 'none') return p; return map(await entryIn(p.value.value, e => e.name === dir.slice(cut + 1) && e.mode === '40000'), found => mapOption(found, e => e.oid)); }); // a .gitattributes entry's text const textOf = async (e: Option): Promise, PlyError>> => { if (e.tag === 'none') return ok(none); return map(await objectAt(t, e.value.oid, { expectType: TYPE.BLOB }), b => some(bytesToStr(b.data))); }; const fileOf = (dir: string): Look => once(dir, async () => { const oid = await treeOf(dir); if (!oid.ok || oid.value.tag === 'none') return oid; const e = await entryIn(oid.value.value, x => x.name === '.gitattributes' && x.mode !== '40000' && x.mode !== '160000'); if (!e.ok) return e; return textOf(e.value); }); return async path => { const dirs = ['']; for (let i = path.indexOf('/'); i >= 0; i = path.indexOf('/', i + 1)) dirs.push(path.slice(0, i)); const texts = await Promise.all(dirs.map(d => fileOf(d))); for (const r of texts) if (!r.ok) return r; const byDir = new Map(); for (const [i, d] of dirs.entries()) { const text = at(texts, i); if (text.tag === 'none' || !text.value.ok || text.value.value.tag === 'none') continue; const dir = utf8ToStr(d); if (!dir.ok) return dir; byDir.set(dir.value, text.value.value.value); } const file = utf8ToStr(path); if (!file.ok) return file; const v = attributeOf(attributesFor(file.value, byDir), 'merge'); if (v.tag === 'none') return ok('text'); if (v.value === false) return ok('binary'); if (v.value === 'binary' || v.value === 'union') return ok(v.value); return ok('text'); }; } const refused = (reason: ContentReason): Ok => ok({ kind: 'conflict', reason }); // A blob that could not be read: too large is a refusal (the merge goes on), anything else fails it. const lost = (r: Err): Result => (r.error.code === 'limit_exceeded' ? refused('too large to merge') : r); // Effect: the content half of a both-sides-changed file — git's shortcuts first (one side equal to base or both equal), // then the three blobs (bounded by maxMergeBlobBytes, their diff steps by maxMergeWork) through the ported xdiff merge. Shared by merge, rebase, // cherry-pick and revert. Refused (bad_request) before any merge: a rediff that is not one of the three, or a blob cap // that bounds nothing (the transport's object cap was checked where the transport was made). Blobs are read under the // lower of the two caps. export function blobMerger(t: Transport, maxMergeBlobBytes: unknown, rediff: Rediff): Result> { if (!['undecided', 'skip', 'myers'].includes(rediff)) return fail('bad_request', `rediff must be 'undecided', 'skip' or 'myers', not ${JSON.stringify(rediff)}`); const blobCapped = checkLimit(maxMergeBlobBytes, 'maxMergeBlobBytes'); if (!blobCapped.ok) return blobCapped; const stats: MergeStats = { merged: 0, undecided: 0, unioned: 0, attrBinary: 0 }; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Object.create returns any; the view is `t` with limits shadowed (as transport.ts withParent) const bounded = Object.create(t, { limits: { value: lowered(t.limits, 'maxObjectSize', blobCapped.value) } }) as Transport; // Blobs this merger produced exist only in the pending push (a rebase replays commit 2 onto commit 1's merged blob), so // they are served from here; the bytes are already held for the push, so this costs no extra memory. const made = new Map(); const get = async (oid: Oid): Promise> => { const held = mapGet(made, oid); return held.tag === 'some' ? ok(held.value) : map(await objectAt(bounded, oid, { expectType: TYPE.BLOB }), b => b.data); }; const f = async ({ base, ours, theirs, path, driverFor }: BlobSpec): Promise> => { if (ours === theirs || theirs === base) return ok({ kind: 'existing', oid: ours }); if (ours === base) return ok({ kind: 'existing', oid: theirs }); // the merge attribute (when an attribute source was given): binary/-merge conflicts without reading the blobs const driven = driverFor === null ? ok('text') : await driverFor(path); if (!driven.ok) return driven; const driver = driven.value; if (driver === 'binary') { stats.attrBinary++; return refused('binary (merge attribute)'); } const [rB, rO, rT] = await Promise.all([get(base), get(ours), get(theirs)]); if (!rB.ok) return lost(rB); if (!rO.ok) return lost(rO); if (!rT.ok) return lost(rT); const [B, O, T] = [rB.value, rO.value, rT.value]; const m = mergeLines(B, O, T, { maxBytes: blobCapped.value, maxWork: t.limits.maxMergeWork, rediff, driver }); if (!m.clean) { if (m.reason === 'undecided') { stats.undecided++; return refused('content (git would decide this with a classic-diff fallback ply does not implement)'); } return refused(m.reason === 'content' ? 'content (both sides changed the same lines)' : m.reason); } stats.merged++; if ('unioned' in m) stats.unioned++; const oid: Oid = hashObject('blob', m.data); made.set(oid, m.data); return ok({ kind: 'merged', oid, data: m.data }); }; return ok(Object.assign(f, { stats })); } // Pure: one entry per oid, first wins. git's unpack-objects/index-pack refuse a pack that carries an object twice // ("tried to add buffer twice"), and a merge produces the same blob or tree at two paths, or in two replayed commits. // the set grows exactly when the oid is new export const uniqueObjects = (objects: readonly O[]): O[] => { const seen = new Set(); return objects.filter(o => seen.size < seen.add(o.oid).size); }; // Effect: the tree whose .gitattributes govern a merge. null → none (git ≥ 2.46 in a bare repository, unless attr.tree // is set); 'ours' | 'theirs' | 'base' → that side's tree ('ours' is what `git merge` in a worktree reads, and git // 2.43–2.45 in a bare repository whose HEAD is the target branch); a ref name or commit oid → its tree (attr.tree=). // 'ours' | 'theirs' | 'base', a ref name or a commit oid, or null export type AttributeSource = string | null; // A caller's attributes option, checked (a JS caller's missing value is null). export const validateAttributes = (a: unknown): Result> => { const given = fromNullish(a); if (given.tag === 'none') return ok(null); const v = given.value; if (typeof v !== 'string') return fail('bad_request', 'attributes must be null, ours, theirs, base, a ref or a commit oid'); if (v === 'ours' || v === 'theirs' || v === 'base' || isOid(v)) return ok(v); return map(validateRef(v), () => v); }; // The three sides' trees (null: the empty tree, or a side not in play). // The three trees of a merge, parsed (null: the empty tree). export type Trees = { readonly base: Oid | null; readonly ours: Oid | null; readonly theirs: Oid | null }; export const NO_TREES: Trees = { base: null, ours: null, theirs: null }; const refMiss = (ref: string): Miss => ({ kind: 'ref', ref, candidates: [ref] }); // a ref's oid in an ls-refs answer export const refOid = (refs: LsRefsResult['refs'], ref: string): Option => mapOption(mapGet(refs, ref), r => r.oid); // The tree whose .gitattributes apply; a JS caller's missing tree is null. export async function attributeTree(t: Transport, attributes: AttributeSource, given: Input): Promise> { const trees = withDefaults(given, { ...NO_TREES }); if (attributes === null) return ok(null); if (attributes === 'ours' || attributes === 'theirs' || attributes === 'base') return ok(trees[attributes]); // validateAttributes ran first (mergeBranch, rebaseBranch, pickCommit): a ref name or an oid, parsed once here const id = parseOid(attributes); let oid: Oid; if (id.ok) oid = id.value; else { const named = validateRef(attributes); if (!named.ok) return named; const listed = await lsRefs(t, [attributes]); if (!listed.ok) return listed; const found = refOid(listed.value.refs, attributes); if (found.tag === 'none') return fail('not_found', `attributes ref ${attributes} not found`, { miss: { kind: 'ref', ref: attributes, candidates: [attributes] } }); oid = found.value; } return map(await commitAt(t, oid), c => c.tree); } // Fast-forward `ref` to `to`, expecting it to be at `from` (CAS). Empty pack: the server already has the objects. export async function fastForward(t: Transport, { ref, from, to }: { readonly ref: string; readonly from: string; readonly to: string }): Promise> { return push(t, { ref, oldOid: from, newOid: to, objects: [] }); } // Delete `ref` on a transport the caller holds, expecting it at `oid` (CAS). By URL, with the tip read for you: // refops.ts deleteBranch. export async function deleteRef(t: Transport, { ref, oid }: { readonly ref: string; readonly oid: string }): Promise> { return push(t, { ref, oldOid: oid, newOid: ZERO_OID, objects: [] }); } // What a merge-base verdict means for landing `theirs` on `ours`, before any tree is read: nothing to do, a // fast-forward, or a three-way merge over the one base. Criss-cross history is refused (git merges the bases into a // virtual one, recursively; a single base can give a clean result that differs from git's, so we refuse rather than // guess), as are unrelated histories and, when only a fast-forward is allowed, a merge commit. type Landing = | { readonly kind: 'up_to_date'; readonly base: Oid } | { readonly kind: 'fast_forward'; readonly base: Oid } | { readonly kind: 'three_way'; readonly base: Oid }; type LandingFlags = { readonly ref: string; readonly from: string; readonly fastForwardOnly: boolean; readonly noFastForward: boolean }; function decideMerge(verdict: Verdict, ours: Oid, theirs: Oid, { ref, from, fastForwardOnly, noFastForward }: LandingFlags): Result { switch (verdict.tag) { case 'criss-cross': return fail('merge_conflict', `${ref} and ${from} have ${verdict.bases.length} merge bases (criss-cross history); ply does not build git's virtual merge base`, { conflicts: [], reasons: noProtoReasons(), bases: verdict.bases } as ConflictDetail); case 'unrelated': return fail('unrelated_histories', `${ref} and ${from} share no common ancestor within the search depth`); case 'found': { const { base } = verdict; if (base === theirs) return ok({ kind: 'up_to_date', base }); if (base === ours && !noFastForward) return ok({ kind: 'fast_forward', base }); if (fastForwardOnly) return fail('not_fast_forward', `${ref} has moved past the merge base; a merge commit would be needed`); return ok({ kind: 'three_way', base }); } } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(verdict); } export type MergeSpecConfig = { readonly ref: string; readonly author: Author | null; // null: the author (one identity, one time, as before) readonly committer: Author | null; readonly message: string | null; readonly time: number; readonly fastForwardOnly: boolean; readonly noFastForward: boolean; }; export type MergeSpec = Input & { readonly from: string }; const mergeSpecDefaults = (): MergeSpecConfig => ({ ref: 'refs/heads/main', author: null, committer: null, message: null, time: Math.floor(Date.now() / 1000), fastForwardOnly: false, noFastForward: false }); // The operation options (auth, tracer, limits, …) pass through to operation(); these are the ones merge reads. export type MergeConfig = { readonly cache: TreeCache; readonly signer: Signer | null; readonly verify: boolean; readonly rediff: Rediff; readonly attributes: AttributeSource; }; export type MergeOptions = Input & Readonly>; const mergeDefaults = (): MergeConfig => ({ cache: new Map(), signer: null, verify: false, rediff: 'myers', attributes: null }); type Sides = { readonly ref: string; readonly oid: string; readonly ours: string; readonly theirs: string }; export type MergeOutcome = | Sides & { readonly outcome: 'up_to_date' | 'fast_forward'; readonly base: string } | Sides & { readonly outcome: 'merge'; readonly tree: string; readonly base: string; readonly pushBytes: number; readonly newTrees: number; readonly contentMerged: number }; // The entry options as operation() takes them, with the operation's attributes. The tracer is the caller's, required at // run time (operation starts the root span on it), as for every entry (boundary.ts EntryOptions). export const operationOpts = (options: Readonly>, attrs: Readonly>): OperationOpts => ({ ...options, attrs }); // an annotated tag's peeled commit, as ls-refs reports it const peeledOf = (refs: LsRefsResult['refs'], ref: string): Option => { const r = mapGet(refs, ref); return r.tag === 'none' ? none : fromNullish(r.value.peeled); }; // Effect: a landing that writes no merge commit: nothing to do, or the fast-forward push. type Quick = Exclude; async function landWithoutMerge(t: Transport, outcome: Outcome, land: Quick, { ref, ours, theirs }: { readonly ref: string; readonly ours: string; readonly theirs: string }): Promise> { switch (land.kind) { case 'up_to_date': return outcome('up_to_date', { outcome: 'up_to_date', ref, oid: ours, ours, theirs, base: land.base }); case 'fast_forward': { const r = await fastForward(t, { ref, from: ours, to: theirs }); if (!r.ok) return r; return outcome('fast_forward', { outcome: 'fast_forward', ref, oid: theirs, ours, theirs, base: land.base }, { 'git.merge.push.bytes': r.value.packBytes }); } } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(land); } // A stamp, or None when none was given. const stampOf = (p: Author | null, time: number): Result, PlyError> => (p === null ? ok(none) : map(stamp(p, time), some)); // The inputs are checked before any I/O; a refusal returns before the operation starts. The body's refusals keep the // names the decision inventory knows them by (mergeBranch#…), and the operation records an Err's code on the root span. /* oxlint-disable eslint/complexity -- one operation's steps in order: refs, merge base, landing, tree merge, commit, push */ export async function mergeBranch(url: string, spec: MergeSpec, options: MergeOptions = {}): Promise> { const { ref, author, committer, message, time, fastForwardOnly, noFastForward } = withDefaults(spec, mergeSpecDefaults()); const { from } = spec; const { cache, signer, verify, rediff, attributes: attributesGiven } = withDefaults(options, mergeDefaults()); const pushRef = validatePushRef(ref, false); if (!pushRef.ok) return pushRef; const given = givenOid(from, 'from'); if (!given.ok) return given; const fromOid = given.value; const authorStamp = stampOf(author, time); if (!authorStamp.ok) return authorStamp; const committerStamp = committer === null ? authorStamp : stampOf(committer, time); if (!committerStamp.ok) return committerStamp; const person = authorStamp.value; const committerPerson = committerStamp.value; if (message !== null && message !== '') { const checked = validateMessage(message); if (!checked.ok) return checked; } const attributesChecked = validateAttributes(attributesGiven); if (!attributesChecked.ok) return attributesChecked; const attributes = attributesChecked.value; return operation('merge', url, operationOpts(options, { 'git.merge.ref': ref, 'git.merge.from': from, 'git.merge.ff_only': fastForwardOnly, 'git.merge.no_ff': noFastForward }), async ({ t, root, outcome }: OpContext): Promise> => { const listed = await lsRefs(t, isNone(fromOid) ? [ref, from] : [ref]); if (!listed.ok) return listed; const { refs } = listed.value; const oursAt = refOid(refs, ref); const theirsAt = isSome(fromOid) ? fromOid : refOid(refs, from); if (oursAt.tag === 'none') return fail('not_found', `ref ${ref} not found`, { miss: refMiss(ref) }); if (theirsAt.tag === 'none') return fail('not_found', `ref ${from} not found`, { miss: refMiss(from) }); const ours = oursAt.value; const theirs = theirsAt.value; // ls-refs names an annotated tag's object, not a commit; `git merge ` records the tag in a mergetag header, which // ply does not write. Refused by name (it read as a missing commit, pack_corrupt, before #43's matrix ran it). for (const r of [ref, from]) { const peeled = peeledOf(refs, r); if (peeled.tag === 'some') return fail('unsupported', `${r} is an annotated tag (git merge writes a mergetag header ply does not); merge its commit ${peeled.value}`, { what: r === ref ? 'ref' : 'from' }); } if (fromOid.tag === 'some') { const c = await assertCommit(t, fromOid.value, 'from'); if (!c.ok) return c; } root.set({ 'git.merge.ours': ours, 'git.merge.theirs': theirs }); const upToDate = (base: string): Ok => outcome('up_to_date', { outcome: 'up_to_date', ref, oid: ours, ours, theirs, base }); if (ours === theirs) return upToDate(ours); const found = await mergeBaseOf(t, ours, theirs); if (!found.ok) return found; const { base: one, bases, depth, verdict } = found.value; root.set({ 'git.merge.base': one === null ? '' : one, 'git.merge.bases': bases.length, 'git.merge.base.depth': depth }); const landing = decideMerge(verdict, ours, theirs, { ref, from, fastForwardOnly, noFastForward }); if (!landing.ok) return landing; const land = landing.value; if (land.kind !== 'three_way') return landWithoutMerge(t, outcome, land, { ref, ours, theirs }); const { base } = land; // three-way: commits for the three trees (the commit-only packs from mergeBase did not carry trees) const [cB, cO, cT] = await Promise.all([commitBytesAt(t, base), commitBytesAt(t, ours), commitBytesAt(t, theirs)]); const tree = (c: Result<{ readonly data: Uint8Array }, PlyError>): Result => andThen(c, b => map(parseCommit(b.data, t.limits), x => x.tree)); const tB = tree(cB); if (!tB.ok) return tB; const tO = tree(cO); if (!tO.ok) return tO; const tT = tree(cT); if (!tT.ok) return tT; const trees: Trees = { base: tB.value, ours: tO.value, theirs: tT.value }; const merger = blobMerger(t, t.limits.maxMergeBlobBytes, rediff); if (!merger.ok) return merger; const mergeBlob = merger.value; const attrTree = await attributeTree(t, attributes, trees); if (!attrTree.ok) return attrTree; root.set({ 'git.merge.attributes': attributes === null ? '' : attributes }); const treesMerged = await mergeTreesOf(t, cache, { ...trees, prefix: '', removed: null, mergeBlob, driverFor: attrTree.value === null ? null : attributeDrivers(t, cache, attrTree.value) }); if (!treesMerged.ok) return treesMerged; const merged = treesMerged.value; const newTrees = merged.objects.filter(o => o.type === TYPE.TREE).length; root.set({ 'git.merge.content.merged': merged.contentMerged, 'git.merge.content.undecided': mergeBlob.stats.undecided, 'git.merge.content.unioned': mergeBlob.stats.unioned, 'git.merge.content.attr_binary': mergeBlob.stats.attrBinary, 'git.merge.trees.fetched': merged.fetched, 'git.merge.trees.new': newTrees, 'git.merge.conflicts': merged.conflicts.slice(0, 64), 'git.merge.conflicts.count': merged.conflicts.length }); if (merged.conflicts.length > 0) return fail('merge_conflict', `conflicts: ${merged.conflicts.slice(0, 8).map(p => `${p} (${merged.reasons[p]})`).join(', ')}${merged.conflicts.length > 8 ? '…' : ''}`, { conflicts: merged.conflicts, reasons: merged.reasons } as ConflictDetail); const emptyTree = encodeEntries([]); if (!emptyTree.ok) return emptyTree; const treeOid: Oid = merged.oid === null ? hashObject('tree', emptyTree.value) : merged.oid; if (person.tag === 'none' || committerPerson.tag === 'none') return fail('bad_request', 'author is required for a merge commit'); const authorLine = ident(person.value); if (!authorLine.ok) return authorLine; const committerLine = ident(committerPerson.value); if (!committerLine.ok) return committerLine; const encoded = encodeCommitOf({ tree: treeOid, parents: [ours, theirs], author: authorLine.value, committer: committerLine.value, message: (message === null ? `Merge ${short(from)} into ${short(ref)}` : message).replace(/\n?$/u, '\n') }); if (!encoded.ok) return encoded; let commitData = encoded.value; if (signer) { const signed = await signCommit(commitData, signer); if (!signed.ok) return signed; commitData = signed.value; } const oid: string = hashObject('commit', commitData); const objects = uniqueObjects([{ type: TYPE.COMMIT, data: commitData, oid }, ...(merged.oid === null ? [{ type: TYPE.TREE, data: emptyTree.value, oid: treeOid }] : []), ...merged.objects]).map(o => ({ type: o.type, data: o.data })); const pushed = await push(t, { ref, oldOid: ours, newOid: oid, objects }); if (!pushed.ok) return pushed; const r = pushed.value; if (verify) { const seen = await verifyRef(t, root, 'git.merge', ref, oid); if (!seen.ok) return seen; } return outcome('merge', { outcome: 'merge', ref, oid, tree: treeOid, ours, theirs, base, pushBytes: r.packBytes, newTrees, contentMerged: merged.contentMerged }, { 'git.merge.commit': oid, 'git.merge.tree': treeOid, 'git.merge.push.bytes': r.packBytes }); }); } /* oxlint-enable eslint/complexity */