GitHubivarvong
ply
main
1// Rebase, squash, cherry-pick, revert: each is the three-way tree merge from merge.js with different arguments and a
2// different commit on top (see the table in README). All are git operations over receive-pack; the branch update after a
3// rebase is a non-fast-forward push with the old tip as the CAS.
4//
5// op base ours theirs commit
6// rebase commit's parent tree new tip commit tree parent [new tip], author+message kept, committer now
7// squash merge-base tree target branch tip tree parent [target]
8// cherry-pick commit's parent tree target commit tree parent [target], author+message kept
9// (a root's parent is the empty tree)
10// revert commit tree target commit's parent tree parent [target]
11// (a root's parent is the empty tree)
12//
13// Every step that can fail returns a Result, the entry points (rebaseBranch, pickCommit, cherryPick, revertCommit,
14// linearChain) included.
15/* oxlint-disable import/max-dependencies -- a replay drives ls-refs, the merge-base search, the tree merge, the object codecs and push */
16/* 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 */
17import type { ValidatedIdent } from './validate.js';
18import type { ErrorOf, Extra, Miss, PlyError } from './errors.js';
19import type { Option, Result } from './result.js';
20import type { Input } from './absent.js';
21import type { Rediff } from './linemerge.js';
22import type { AttributeSource, Author, Commit, MergeBase, MergeBlob, OpContext, PackObject, Parents, Search, Signer, Transport, TreeCache, Trees } from './merge.js';
23import { parseOid, type Oid } from './oid.js';
24import { fail } from './errors.js';
25import { assertNever, err, getOrElse, map, mapOption, none, ok, some } from './result.js';
26import { at, mapGet, withDefaults } from './absent.js';
27import { lsRefs } from './lsrefs.js';
28import { push } from './push.js';
29import { operation } from './operation.js';
30import { ancestors, searchStep, mergeTreesOf, blobMerger, uniqueObjects, attributeTree, attributeDrivers, validateAttributes, operationOpts, refOid, NO_TREES } from './merge.js';
31import { encodeCommitOf, hashObject, ident, TYPE } from './objects.js';
32import { validatePushRef, validateMessage } from './validate.js';
33import { signCommit } from './sign.js';
34import { short, commitAt, givenOid, assertCommit, stamp } from './mergeio.js';
35import { limitError, LIMIT_REBASE_COMMITS } from './limits.js';
37const refMiss = (ref: string): Miss => ({ kind: 'ref', ref, candidates: [ref] });
40// A merge_conflict's payload: Detail carries `conflicts`; reasons, commit and replayed are extras.
41type ConflictDetail = Extra & { readonly conflicts: readonly string[] };
43// Pure: headers to carry over when a commit is re-created. A signature does not survive a new tree/parent (git drops it).
44export function carriedExtra(extra: readonly string[]): string[] {
45 const out: string[] = []; let dropping = false;
46 for (const l of extra) { if (l.startsWith('gpgsig')) { dropping = true; continue; } if (dropping && l.startsWith(' ')) continue; dropping = false; out.push(l); }
47 return out;
48}
50// Pure: the default message of a squash, from the replayed commits' messages oldest first: each without its trailing
51// newlines, the empty ones left out, joined by one blank line, ending in one newline. For messages git itself cleaned
52// up (`git commit`), that is the message `git rebase -i` writes for pick, squash, squash, ... byte for byte.
53// A message is written by whoever can push the branch, so the strip is a scan from the end, one step per newline
54// removed: `/\n+$/` retries a run of newlines from each newline in it, which is quadratic in a run that is not last.
55export function squashMessage(messages: ReadonlyArray<string | null>): string {
56 const parts: string[] = [];
57 for (const m of messages) {
58 if (m === null) continue;
59 let end = m.length;
60 while (end > 0 && m.codePointAt(end - 1) === 10) end--;
61 if (end > 0) parts.push(m.slice(0, end));
62 }
63 return `${parts.join('\n\n')}\n`;
64}
66// a walk that reached every parent it names: deepening it fetches nothing new
67const whole = (m: ReadonlyMap<Oid, Commit>): boolean => { for (const c of m.values()) for (const p of c.parents) if (!m.has(p)) return false; return true; };
68// Pure: the single-parent commits from `tip` that walk A holds and walk B does not, counted no further than max + 1
69const chainOutside = (A: ReadonlyMap<Oid, Commit>, B: ReadonlyMap<Oid, Commit>, tip: Oid, max: number): number => {
70 let over = 0;
71 let id: Oid = tip;
72 for (let c = mapGet(A, id); c.tag === 'some' && c.value.parents.length === 1 && !B.has(id) && over <= max; over++) { id = getOrElse(at(c.value.parents, 0), id); c = mapGet(A, id); }
73 return over;
74};
75// Pure: a walk's commits as parent lists only, what the windowed branch walk keeps of a window
76const parentsOf = (m: ReadonlyMap<Oid, Commit>): Map<Oid, readonly Oid[]> => { const o = new Map<Oid, readonly Oid[]>(); for (const [k, c] of m) o.set(k, c.parents); return o; };
77// Effect: the single-parent chain from `tip`, counted by position (the tip at 1), through `first` and then windows of
78// at most `window` commits fetched from the frontier, one held at a time as parent lists. It stops at a commit of the
79// onto walk (hit), at a merge or root (break), or past capA commits (cap).
80async function chainWindows(t: Transport, from: { readonly first: Map<Oid, readonly Oid[]>; readonly inOnto: ReadonlySet<Oid>; readonly tip: Oid }, capA: number, window: number): Promise<Result<{ readonly end: 'hit' | 'break' | 'cap'; readonly pos: number }, PlyError>> {
81 const { inOnto, tip } = from;
82 // a window is cleared before the next is fetched (the first one too, which the caller still names): one is live
83 let held = from.first;
84 let id: Oid = tip; let pos = 1;
85 for (;;) {
86 if (inOnto.has(id)) return ok({ end: 'hit', pos });
87 if (pos > capA) return ok({ end: 'cap', pos });
88 const c = mapGet(held, id);
89 if (c.tag === 'none') {
90 held.clear();
91 // oxlint-disable-next-line eslint/no-await-in-loop -- each window starts at the last one's frontier
92 const got = await ancestors(t, id, Math.min(window, capA - pos + 1));
93 if (!got.ok) return got;
94 held = parentsOf(got.value); continue;
95 }
96 if (c.value.length !== 1) return ok({ end: 'break', pos });
97 id = getOrElse(at(c.value, 0), id); pos++;
98 }
99}
100// Effect: the merge base of a rebase. Two walks, each under its own limit: the branch walk (from the tip) is the chain
101// walk, to maxRebaseCommits + 2 commits (the base of a chain of n commits is n + 1 from the tip, and one more shows a
102// chain one over the limit) or to maxMergeDepth where that is deeper; the onto walk is the merge-base search, to
103// maxMergeDepth, as mergeBranch's. Both double
104// from 8 to maxMergeDepth; a walk that is whole or at its cap is not fetched again. A branch cap more than twice
105// maxMergeDepth is walked on in windows of maxMergeDepth commits (chainWindows, one held at a time as parent lists),
106// and the search with full commits resumes only where the chain ends within the cap: a refusal under DEFAULT_LIMITS
107// is 17 + 9 window requests (26, test/rebase.test.js). When neither walk can go deeper and the graph is
108// still cut, the chain is known to be over its limit only if the onto walk is whole: every commit it does not hold is
109// then outside onto's history, so more than maxRebaseCommits single-parent commits from the tip are `rebase chain`
110// (got = max + 1: the search stops one past the limit, it does not count the chain). With the onto walk cut, a commit
111// of the branch walk may be an ancestor of onto beyond the cut (a short branch far behind onto looks the same as a
112// long one), and no request is spent to tell: the refusal is `merge-base search depth` against maxMergeDepth, with the
113// fields mergeBaseOf reports (got: twice the depth searched). Every max is a field of the caller's limits.
114type Settled = Exclude<Search<Oid>, { readonly tag: 'searching' }>;
115export async function rebaseBaseOf(t: Transport, tip: Oid, target: Oid): Promise<Result<MergeBase, PlyError>> {
116 const { maxRebaseCommits, maxMergeDepth } = t.limits;
117 const capB = Math.floor(maxMergeDepth);
118 // maxMergeDepth under 1 allows no search, as in mergeBase: refused before any fetch
119 if (capB < 1) return err(limitError('merge-base search depth', 1, maxMergeDepth));
120 // never shallower than the merge-base search (mergeBaseOf walks both sides to maxMergeDepth): a base that search
121 // finds is found here, so a chain over its limit is named wherever it was, and raising maxMergeDepth settles a cut
122 const capA = Math.max(Math.floor(maxRebaseCommits) + 2, capB);
123 const top = Math.max(capA, capB);
124 let A = new Map<Oid, Commit>(); let B = new Map<Oid, Commit>();
125 let atA = 0; let atB = 0;
126 let commits = new Map<Oid, Commit>();
127 // the merge-base search, the branch walk to capOfA; resumable at a depth
128 const search = async (start: number, capOfA: number): Promise<Result<Settled, PlyError>> => {
129 let st: Search<Oid> = { tag: 'searching', depth: start };
130 while (st.tag === 'searching') {
131 const depth: number = st.depth;
132 const wantA = Math.min(depth, capOfA); const wantB = Math.min(depth, capB);
133 const heldA = A; const heldB = B;
134 // oxlint-disable-next-line eslint/no-await-in-loop -- each round deepens from what the last one found
135 const [ra, rb] = await Promise.all([
136 wantA === atA || (atA > 0 && whole(heldA)) ? ok(heldA) : ancestors(t, tip, wantA),
137 wantB === atB || (atB > 0 && whole(heldB)) ? ok(heldB) : ancestors(t, target, wantB),
138 ]);
139 if (!ra.ok) return ra;
140 if (!rb.ok) return rb;
141 A = ra.value; B = rb.value; atA = wantA; atB = wantB;
142 commits = new Map([...B, ...A]);
143 st = searchStep(depth, capOfA === capA ? top : Math.max(capOfA, capB), commits, tip, target);
144 }
145 return ok(st);
146 };
147 // A branch cap within one doubling of maxMergeDepth is searched whole, as before (the chain walk holds at most twice
148 // the merge-base search). A deeper one is first walked to maxMergeDepth, as mergeBaseOf: what main holds.
149 const windowed = capA > capB * 2;
150 const first = await search(Math.min(8, top), windowed ? capB : capA);
151 if (!first.ok) return first;
152 let s: Settled = first.value;
153 if (s.tag === 'capped' && windowed) {
154 // Past maxMergeDepth the branch walk holds no more than the merge-base search did: from the cut frontier, in
155 // windows of maxMergeDepth commits (one window held at a time), it keeps the position along the single-parent
156 // chain, the frontier and whether a commit is in the onto walk. The chain's commits are fetched for the replay
157 // only once the base is found within capA.
158 const window = capB;
159 // onto-membership only: the onto walk's commits are dropped for the windows (refetched if the search goes on)
160 const ontoWhole = whole(B);
161 const inOnto: ReadonlySet<Oid> = new Set(B.keys());
162 const firstWindow = parentsOf(A);
163 A = new Map(); B = new Map(); atB = 0; commits = new Map();
164 const walked = await chainWindows(t, { first: firstWindow, inOnto, tip }, capA, window);
165 if (!walked.ok) return walked;
166 const { end, pos } = walked.value;
167 if (end === 'cap') {
168 // capA single-parent commits from the tip, none in the onto walk
169 if (ontoWhole) return err(limitError('rebase chain', Math.floor(maxRebaseCommits) + 1, maxRebaseCommits));
170 return err(limitError('merge-base search depth', capB * 2, maxMergeDepth));
171 }
172 // the chain reaches a commit of the onto walk at pos: a chain of pos - 1, over the limit when pos - 1 > max
173 if (end === 'hit' && pos - 1 > maxRebaseCommits) return err(limitError('rebase chain', Math.floor(maxRebaseCommits) + 1, maxRebaseCommits));
174 // the base within the limit, or a merge or root on the way: the search goes on as it did, with full commits
175 let d = capB; while (d < capA && d < pos + 1) d = Math.min(d * 2, capA);
176 atA = 0;
177 const rest = await search(d, capA);
178 if (!rest.ok) return rest;
179 s = rest.value;
180 }
181 switch (s.tag) {
182 case 'capped': {
183 const over = whole(B) ? chainOutside(A, B, tip, maxRebaseCommits) : 0;
184 if (over > maxRebaseCommits) return err(limitError('rebase chain', over, maxRebaseCommits));
185 return err(limitError('merge-base search depth', capB * 2, maxMergeDepth));
186 }
187 case 'found': return ok({ base: s.base, bases: s.bases, depth: s.depth, commits, verdict: s });
188 case 'criss-cross':
189 case 'unrelated': return ok({ base: null, bases: s.bases, depth: s.depth, commits, verdict: s });
190 }
191 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
192 return assertNever(s);
193}
195export type ChainCommit = Commit & { readonly oid: Oid };
196// Pure: the linear chain of commits from `base` (exclusive) to `tip`, oldest first; a merge commit in it is not_linear.
197// Over node names K, as bestBases: rebaseBranch walks mergeBase's Oids, and the chain's ids are those Oids.
198export function linearChain<K extends string, C extends Parents<K>>(commits: ReadonlyMap<K, C>, tip: K, base: K | null, max: number = LIMIT_REBASE_COMMITS): Result<Array<C & { readonly oid: K }>, PlyError> {
199 const chain: Array<C & { readonly oid: K }> = [];
200 // a commit in the chain has exactly one parent: the fallback (the commit itself) never stands
201 for (let c = tip; c !== base;) {
202 const info = mapGet(commits, c);
203 if (info.tag === 'none') return fail('internal', `commit ${c} not in the fetched history`);
204 const { parents } = info.value;
205 if (parents.length !== 1) return fail('not_linear', `${c} has ${parents.length} parents; only linear branches are rebased`);
206 chain.push({ oid: c, ...info.value });
207 if (chain.length > max) return err(limitError('rebase chain', chain.length, max));
208 c = getOrElse(at(parents, 0), c);
209 }
210 return ok(chain.toReversed());
211}
213// What one rebase or pick shares across its transplants: the trees fetched, the attribute tree of a fixed source (a ref
214// or an oid, resolved once), the line merger (built once), the files merged by content.
215type Replay = {
216 fetched: number;
217 readonly rediff: Rediff;
218 readonly attributes: AttributeSource;
219 attrTree: Option<string | null>;
220 mergeBlob: Option<MergeBlob>;
221 contentMerged: number;
222};
223const replay = (rediff: Rediff, attributes: AttributeSource): Replay => ({ fetched: 0, rediff, attributes, attrTree: none, mergeBlob: none, contentMerged: 0 });
224type NewCommit = { readonly parent: Oid; readonly author: string; readonly committer: string; readonly message: string | null; readonly encoding: string | null; readonly extra: readonly string[] };
225// One transplant: the commit written on the merged tree, or the merge's conflicts.
226type Transplant =
227 | { readonly kind: 'written'; readonly oid: Oid; readonly data: Uint8Array; readonly treeOid: Oid; readonly objects: PackObject[] }
228 | { readonly kind: 'conflict'; readonly conflicts: string[]; readonly reasons: Record<string, string> };
230// The attribute tree for one transplant: 'ours' is the tree being built on (what a worktree rebase/cherry-pick reads);
231// a ref or an oid resolves once per replay.
232async function attributeTreeFor(t: Transport, out: Replay, trees: Trees): Promise<Result<string | null, PlyError>> {
233 const fixed = out.attributes !== null && !['ours', 'theirs', 'base'].includes(out.attributes);
234 if (!fixed) return attributeTree(t, out.attributes, trees);
235 if (out.attrTree.tag === 'some') return ok(out.attrTree.value);
236 const r = await attributeTree(t, out.attributes, NO_TREES);
237 if (r.ok) out.attrTree = some(r.value);
238 return r;
239}
240// The replay's line merger, built on first use.
241function mergerFor(t: Transport, out: Replay): Result<MergeBlob, PlyError> {
242 if (out.mergeBlob.tag === 'some') return ok(out.mergeBlob.value);
243 const m = blobMerger(t, t.limits.maxMergeBlobBytes, out.rediff);
244 if (m.ok) out.mergeBlob = some(m.value);
245 return m;
246}
248// Effect: one transplant — three-way tree merge then a commit on `parent`.
249// oxlint-disable-next-line eslint/max-params -- the merge sides, the commit, the signer and the shared replay state
250async function transplant(t: Transport, cache: TreeCache, trees: Trees, { parent, author, committer, message, encoding, extra }: NewCommit, signer: Signer | null, out: Replay): Promise<Result<Transplant, PlyError>> {
251 const attrTree = await attributeTreeFor(t, out, trees);
252 if (!attrTree.ok) return attrTree;
253 const mergeBlob = mergerFor(t, out);
254 if (!mergeBlob.ok) return mergeBlob;
255 const merged = await mergeTreesOf(t, cache, { ...trees, prefix: '', removed: null, mergeBlob: mergeBlob.value, driverFor: attrTree.value === null ? null : attributeDrivers(t, cache, attrTree.value) });
256 if (!merged.ok) return merged;
257 const m = merged.value;
258 out.fetched += m.fetched;
259 if (m.conflicts.length > 0) return ok({ kind: 'conflict', conflicts: m.conflicts, reasons: m.reasons });
260 const treeOid: Oid = m.oid === null ? hashObject('tree', new Uint8Array(0)) : m.oid;
261 const encoded = encodeCommitOf({ tree: treeOid, parents: [parent], author, committer, encoding, message, extra });
262 if (!encoded.ok) return encoded;
263 let data = encoded.value;
264 if (signer) { const signed = await signCommit(data, signer); if (!signed.ok) return signed; data = signed.value; }
265 const oid: Oid = hashObject('commit', data);
266 out.contentMerged += m.contentMerged;
267 return ok({ kind: 'written', oid, data, treeOid, objects: [...(m.oid === null ? [{ type: TYPE.TREE, data: new Uint8Array(0), oid: treeOid }] : []), ...m.objects, { type: TYPE.COMMIT, data, oid }] });
268}
270export type RebaseSpecConfig = {
271 readonly onto: string;
272 readonly committer: Author | null;
273 readonly author: Author | null;
274 readonly time: number;
275 readonly squash: boolean;
276 readonly message: string | null;
277};
278export type RebaseSpec = Input<RebaseSpecConfig> & { readonly ref: string };
279const rebaseSpecDefaults = (): RebaseSpecConfig => ({ onto: 'refs/heads/main', committer: null, author: null, time: Math.floor(Date.now() / 1000), squash: false, message: null });
280// The operation options (auth, tracer, limits, …) pass through to operation(); these are the ones a replay reads.
281export type RebaseConfig = {
282 readonly cache: TreeCache;
283 readonly signer: Signer | null;
284 readonly rediff: Rediff;
285 readonly attributes: AttributeSource;
286};
287export type RebaseOptions = Input<RebaseConfig> & Readonly<Record<string, unknown>>;
288const rebaseDefaults = (): RebaseConfig => ({ cache: new Map(), signer: null, rediff: 'myers', attributes: null });
289export type Replayed = { readonly from: string; readonly to: string; readonly tree: string };
290export type RebaseOutcome =
291 | { readonly outcome: 'up_to_date' | 'fast_forward'; readonly ref: string; readonly oid: string; readonly commits: 0 }
292 | {
293 readonly outcome: 'rebase' | 'squash';
294 readonly ref: string;
295 readonly oid: string;
296 readonly oldTip: string;
297 readonly onto: string;
298 readonly base: string;
299 readonly commits: number;
300 readonly replayed: Replayed[];
301 readonly dropped: string[];
302 readonly pushBytes: number;
303 };
304// Rebase `ref` onto `onto`'s head (or squash it into one commit). The branch is force-updated (CAS on its old tip).
305// The inputs are checked before any I/O; a refusal returns before the operation starts. The body's refusals keep the
306// names the decision inventory knows them by (rebaseBranch#…), and the operation records an Err's code on the root span.
307/* oxlint-disable eslint/complexity -- one operation's steps in order: refs, merge base, chain, replay, push */
308export async function rebaseBranch(url: string, spec: RebaseSpec, options: RebaseOptions = {}): Promise<Result<RebaseOutcome, PlyError>> {
309 const { onto, committer, author, time, squash, message } = withDefaults(spec, rebaseSpecDefaults());
310 const { ref } = spec;
311 const { cache, signer, rediff, attributes: attributesGiven } = withDefaults(options, rebaseDefaults());
312 const attributesChecked = validateAttributes(attributesGiven); if (!attributesChecked.ok) return attributesChecked;
313 const attributes = attributesChecked.value;
314 const pushRef = validatePushRef(ref, false); if (!pushRef.ok) return pushRef;
315 const given = givenOid(onto, 'onto'); if (!given.ok) return given;
316 const ontoOid = given.value;
317 const committerStamp = stamp(committer, time); if (!committerStamp.ok) return committerStamp;
318 const committerPerson: ValidatedIdent = committerStamp.value;
319 const authorStamp = author === null ? ok(none) : map(stamp(author, time), some); if (!authorStamp.ok) return authorStamp;
320 const authorPerson: Option<ValidatedIdent> = authorStamp.value;
321 if (message !== null) { const checked = validateMessage(message); if (!checked.ok) return checked; }
322 return operation('rebase', url, operationOpts(options, { 'git.rebase.ref': ref, 'git.rebase.onto': onto, 'git.rebase.squash': squash }), async ({ t, root, outcome, limits }: OpContext): Promise<Result<RebaseOutcome, PlyError>> => {
323 const listed = await lsRefs(t, ontoOid.tag === 'none' ? [ref, onto] : [ref]); if (!listed.ok) return listed;
324 const { refs } = listed.value;
325 const tipAt = refOid(refs, ref);
326 const targetAt = ontoOid.tag === 'some' ? ontoOid : refOid(refs, onto);
327 if (tipAt.tag === 'none') return fail('not_found', `ref ${ref} not found`, { miss: refMiss(ref) });
328 if (targetAt.tag === 'none') return fail('not_found', `ref ${onto} not found`, { miss: refMiss(onto) });
329 const tip = tipAt.value;
330 const target = targetAt.value;
331 if (ontoOid.tag === 'some') { const c = await assertCommit(t, ontoOid.value, 'onto'); if (!c.ok) return c; }
332 root.set({ 'git.rebase.tip': tip, 'git.rebase.target': target });
333 const found = await rebaseBaseOf(t, tip, target);
334 if (!found.ok) return found;
335 const { bases, commits, verdict } = found.value;
336 // several merge bases mean the branch contains a merge of its own (the commit joining the bases is not in onto),
337 // so its chain is not linear
338 if (verdict.tag !== 'found') {
339 switch (verdict.tag) {
340 case 'criss-cross': return fail('not_linear', `${ref} and ${onto} have ${bases.length} merge bases (criss-cross history); rebase needs a linear branch`, { bases } as Extra & { readonly bases: readonly string[] });
341 case 'unrelated': return fail('unrelated_histories', `${ref} and ${onto} share no common ancestor within the search depth`);
342 }
343 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
344 return assertNever(verdict);
345 }
346 const { base } = verdict;
347 root.set({ 'git.rebase.base': base });
348 if (base === target) return outcome('up_to_date', { outcome: 'up_to_date', ref, oid: tip, commits: 0 });
349 if (base === tip) { // the branch is behind: rebasing nothing onto target makes the branch equal to target
350 const pushed = await push(t, { ref, oldOid: tip, newOid: target, objects: [] });
351 if (!pushed.ok) return pushed;
352 return outcome('fast_forward', { outcome: 'fast_forward', ref, oid: target, commits: 0 });
353 }
354 const chained = linearChain(commits, tip, base, limits.maxRebaseCommits);
355 if (!chained.ok) return chained;
356 const chain = chained.value;
357 root.set({ 'git.rebase.commits': chain.length });
358 // The base may sit exactly at the window's cut: named by its children on both sides, never fetched (mergeBase needs
359 // no more than that; #41). Its tree is the first replay's base, so fetch it; every chain commit is above it and in hand.
360 if (!commits.has(base)) { const b = await commitAt(t, base); if (!b.ok) return b; commits.set(base, b.value); }
361 const targetCommit = await commitAt(t, target); if (!targetCommit.ok) return targetCommit;
362 const targetTree: Oid = targetCommit.value.tree;
363 const committerLine = ident(committerPerson); if (!committerLine.ok) return committerLine;
364 const who: string = committerLine.value;
365 // a commit's tree by oid, among those in hand; a chain commit's one parent is in hand (linearChain)
366 const treeOf = (oid: Oid): Oid | null => getOrElse(mapOption(mapGet(commits, oid), c => c.tree), null);
367 const parentTree = (c: Commit): Oid | null => getOrElse(mapOption(at(c.parents, 0), treeOf), null);
368 const out = replay(rediff, attributes); const objects: PackObject[] = []; let cur: Oid = target; let curTree = targetTree; const replayed: Replayed[] = []; const dropped: string[] = [];
369 // tip !== base, so the chain has a commit
370 const first = at(chain, 0);
371 const last = at(chain, chain.length - 1);
372 if (squash && first.tag === 'some' && last.tag === 'some') {
373 const authorLine = authorPerson.tag === 'some' ? ident(authorPerson.value) : ok(first.value.author); if (!authorLine.ok) return authorLine;
374 const r = await transplant(t, cache, { base: treeOf(base), ours: targetTree, theirs: last.value.tree }, { parent: target, author: authorLine.value, committer: who, message: message === null ? squashMessage(chain.map(c => c.message)) : message, encoding: null, extra: [] }, signer, out);
375 if (!r.ok) return r;
376 const w = r.value;
377 if (w.kind === 'conflict') return fail('merge_conflict', `squash of ${short(ref)} onto ${short(onto)} conflicts: ${w.conflicts.slice(0, 8).join(', ')}`, { conflicts: w.conflicts, reasons: w.reasons } as ConflictDetail);
378 objects.push(...w.objects); cur = w.oid; replayed.push({ from: last.value.oid, to: w.oid, tree: w.treeOid });
379 } else {
380 for (const c of chain) {
381 // oxlint-disable-next-line eslint/no-await-in-loop -- each commit replays onto the one before it
382 const r = await transplant(t, cache, { base: parentTree(c), ours: curTree, theirs: c.tree }, { parent: cur, author: c.author, committer: who, message: c.message, encoding: c.encoding, extra: carriedExtra(c.extra) }, signer, out);
383 if (!r.ok) return r;
384 const w = r.value;
385 if (w.kind === 'conflict') return fail('merge_conflict', `replaying ${c.oid.slice(0, 8)} onto ${short(onto)} conflicts: ${w.conflicts.slice(0, 8).map(p => `${p} (${w.reasons[p]})`).join(', ')}`, { conflicts: w.conflicts, reasons: w.reasons, commit: c.oid, replayed } as ConflictDetail);
386 // git rebase --empty=drop (the default): a commit that did not start empty but becomes empty is dropped
387 if (w.treeOid === curTree && c.tree !== parentTree(c)) { dropped.push(c.oid); continue; }
388 objects.push(...w.objects); replayed.push({ from: c.oid, to: w.oid, tree: w.treeOid }); cur = w.oid; curTree = w.treeOid;
389 }
390 }
391 root.set({ 'git.rebase.trees.fetched': out.fetched, 'git.rebase.objects': objects.length, 'git.rebase.dropped': dropped.length });
392 const pushedR = await push(t, { ref, oldOid: tip, newOid: cur, objects: uniqueObjects(objects) }); // non-fast-forward: the old tip is the CAS
393 if (!pushedR.ok) return pushedR;
394 const pushed = pushedR.value;
395 return outcome(squash ? 'squash' : 'rebase', { outcome: squash ? 'squash' : 'rebase', ref, oid: cur, oldTip: tip, onto: target, base, commits: chain.length, replayed, dropped, pushBytes: pushed.packBytes }, { 'git.rebase.new_tip': cur, 'git.rebase.push.bytes': pushed.packBytes });
396 });
397}
398/* oxlint-enable eslint/complexity */
400// What to do when the transplanted tree is the target's tree. 'stop' is git's default (report empty, write nothing).
401// 'keep' is `git cherry-pick --keep-redundant-commits` (implies `--allow-empty`): write the commit on that tree.
402// One policy covers both kinds git distinguishes — a commit that was empty, and one that became empty because the
403// change is already applied — because both are the same tree here. git 2.43's `revert` has no `--allow-empty`; the
404// commit it would write is what `git commit --allow-empty --no-edit` writes from the message revert prepared.
405export type EmptyPolicy = 'stop' | 'keep';
406export type PickSpecConfig = {
407 readonly ref: string;
408 readonly committer: Author | null;
409 // a revert's author (git: the one reverting); null: the committer. A cherry-pick keeps the commit's author.
410 readonly author: Author | null;
411 readonly time: number;
412 readonly revert: boolean;
413 readonly message: string | null;
414 readonly empty: EmptyPolicy;
415};
416export type PickSpec = Input<PickSpecConfig> & { readonly commit: string };
417const pickSpecDefaults = (): PickSpecConfig => ({ ref: 'refs/heads/main', committer: null, author: null, time: Math.floor(Date.now() / 1000), revert: false, message: null, empty: 'stop' });
418type PickWritten = {
419 readonly ref: string;
420 readonly oid: string;
421 readonly tree: string;
422 readonly onto: string;
423 readonly pushBytes: number;
424};
425export type PickEmpty = { readonly outcome: 'empty'; readonly ref: string; readonly oid: string };
426export type PickKept = { readonly outcome: 'kept_empty' } & PickWritten;
427export type PickOk = { readonly outcome: 'ok' } & PickWritten;
428// 'stop' cannot keep, and 'keep' cannot stop: the policy is part of the result.
429export type PickOutcome<E extends EmptyPolicy = EmptyPolicy> =
430 [E] extends ['keep'] ? PickKept | PickOk : [E] extends ['stop'] ? PickEmpty | PickOk : PickEmpty | PickKept | PickOk;
431// The spec with the default policy: empty left out, or 'stop'.
432type Stopping<S> = Omit<S, 'empty'> & Input<{ readonly empty: 'stop' }>;
434// A caller's empty policy, checked (a JS caller may pass anything).
435function emptyPolicy(value: unknown): Result<EmptyPolicy, ErrorOf<'bad_request'>> {
436 if (value === 'stop') return ok('stop');
437 if (value === 'keep') return ok('keep');
438 // Own decision point: a three-statement function whose fail() uses its parameter is recorded as a wrapper, and the
439 // call site would be the decision instead of this check.
440 const got = value;
441 return fail('bad_request', "empty must be 'stop' or 'keep'", { what: 'empty', got });
442}
444// A root's missing parent is the empty tree (mergeTrees' null). git's first parent of a parentless commit.
445// The commit `ref` points at, or not_found.
446async function refTip(t: Transport, ref: string): Promise<Result<Oid, PlyError>> {
447 const listed = await lsRefs(t, [ref]); if (!listed.ok) return listed;
448 const tip = refOid(listed.value.refs, ref);
449 return tip.tag === 'some' ? ok(tip.value) : fail('not_found', `ref ${ref} not found`, { miss: refMiss(ref) });
450}
451async function parentTreeAt(t: Transport, parents: readonly Oid[]): Promise<Result<Oid | null, PlyError>> {
452 const parentOid = at(parents, 0);
453 if (parentOid.tag === 'none') return ok(null);
454 return map(await commitAt(t, parentOid.value), c => c.tree);
455}
457// 'stop' reports empty and writes nothing. 'keep' writes that same tree (`kept_empty`). A different tree is `ok`.
458function writtenKind(sameTree: boolean, empty: EmptyPolicy): 'empty' | 'kept_empty' | 'ok' {
459 if (!sameTree) return 'ok';
460 if (empty === 'stop') return 'empty';
461 return 'kept_empty';
462}
464// Cherry-pick (`revert: false`) or revert (`revert: true`) one commit onto `ref`'s head.
465// A root commit has no parent: git diffs it against the empty tree (mergeTrees' null), and revert does the same in
466// reverse. A merge commit is refused; git cherry-picks one only with `-m` (a mainline ply does not take).
467// The inputs are checked before any I/O, as rebaseBranch's are.
468export function pickCommit(url: string, spec: PickSpec & { readonly empty: 'keep' }, ...options: [] | [RebaseOptions]): Promise<Result<PickKept | PickOk, PlyError>>;
469export function pickCommit(url: string, spec: Stopping<PickSpec>, ...options: [] | [RebaseOptions]): Promise<Result<PickEmpty | PickOk, PlyError>>;
470export function pickCommit(url: string, spec: PickSpec, ...options: [] | [RebaseOptions]): Promise<Result<PickOutcome, PlyError>>;
471export async function pickCommit(url: string, spec: PickSpec, options: RebaseOptions = {}): Promise<Result<PickOutcome, PlyError>> {
472 const { ref, committer, author, time, revert, message, empty: emptyGiven } = withDefaults(spec, pickSpecDefaults());
473 const { commit } = spec;
474 const { cache, signer, rediff, attributes: attributesGiven } = withDefaults(options, rebaseDefaults());
475 const attributesChecked = validateAttributes(attributesGiven); if (!attributesChecked.ok) return attributesChecked;
476 const attributes = attributesChecked.value;
477 const pushRef = validatePushRef(ref, false); if (!pushRef.ok) return pushRef;
478 const policy = emptyPolicy(emptyGiven); if (!policy.ok) return policy;
479 const empty = policy.value;
480 const committerStamp = stamp(committer, time); if (!committerStamp.ok) return committerStamp;
481 const committerPerson: ValidatedIdent = committerStamp.value;
482 const authorStamp = author === null ? ok(committerPerson) : stamp(author, time); if (!authorStamp.ok) return authorStamp;
483 const revertAuthor: ValidatedIdent = authorStamp.value;
484 if (message !== null) { const checked = validateMessage(message); if (!checked.ok) return checked; }
485 // parsed once, here
486 const pickedId = parseOid(commit);
487 if (!pickedId.ok) return fail('bad_request', 'commit must be a 40-hex oid');
488 const op = revert ? 'revert' : 'cherry_pick';
489 const name = `git.${op}`;
490 return operation(op, url, operationOpts(options, { [`${name}.ref`]: ref, [`${name}.commit`]: commit, [`${name}.empty`]: empty }), async ({ t, outcome }: OpContext): Promise<Result<PickOutcome, PlyError>> => {
491 const tipNow = await refTip(t, ref); if (!tipNow.ok) return tipNow;
492 const target = tipNow.value;
493 const [targetCommit, picked] = await Promise.all([commitAt(t, target), commitAt(t, pickedId.value)]);
494 if (!targetCommit.ok) return targetCommit;
495 if (!picked.ok) return picked;
496 const tInfo: Commit = targetCommit.value;
497 const c: Commit = picked.value;
498 if (c.parents.length > 1) return fail('not_linear', `${commit} has ${c.parents.length} parents; only single-parent commits are picked`);
499 const parentTreeR = await parentTreeAt(t, c.parents); if (!parentTreeR.ok) return parentTreeR;
500 const parentTree = parentTreeR.value;
501 const committerLine = ident(committerPerson); if (!committerLine.ok) return committerLine;
502 const who: string = committerLine.value;
503 const out = replay(rediff, attributes);
504 const subject = getOrElse(at((c.message === null ? '' : c.message).split('\n'), 0), '');
505 // the message git writes when none is given: revert's, or the picked commit's own
506 const ownMessage = revert ? `Revert "${subject}"\n\nThis reverts commit ${commit}.\n` : c.message;
507 const authorLine = revert ? ident(revertAuthor) : ok(c.author); if (!authorLine.ok) return authorLine;
508 const r = await transplant(t, cache,
509 revert ? { base: c.tree, ours: tInfo.tree, theirs: parentTree } : { base: parentTree, ours: tInfo.tree, theirs: c.tree },
510 { parent: target, author: authorLine.value, committer: who, message: message === null ? ownMessage : message, encoding: revert ? null : c.encoding, extra: revert ? [] : carriedExtra(c.extra) }, signer, out);
511 if (!r.ok) return r;
512 const w = r.value;
513 if (w.kind === 'conflict') return fail('merge_conflict', `${revert ? 'revert' : 'cherry-pick'} of ${commit.slice(0, 8)} onto ${short(ref)} conflicts: ${w.conflicts.slice(0, 8).join(', ')}`, { conflicts: w.conflicts, reasons: w.reasons } as ConflictDetail);
514 const kind = writtenKind(w.treeOid === tInfo.tree, empty);
515 if (kind === 'empty') return outcome('empty', { outcome: 'empty', ref, oid: target });
516 const pushedR = await push(t, { ref, oldOid: target, newOid: w.oid, objects: uniqueObjects(w.objects) });
517 if (!pushedR.ok) return pushedR;
518 const pushed = pushedR.value;
519 return outcome(kind, { outcome: kind, ref, oid: w.oid, tree: w.treeOid, onto: target, pushBytes: pushed.packBytes }, { [`${name}.new`]: w.oid, [`${name}.tree`]: w.treeOid, [`${name}.trees.fetched`]: out.fetched, [`${name}.push.bytes`]: pushed.packBytes });
520 });
521}
522type CherrySpec = Omit<PickSpec, 'revert'>;
523export function cherryPick(url: string, spec: CherrySpec & { readonly empty: 'keep' }, ...options: [] | [RebaseOptions]): Promise<Result<PickKept | PickOk, PlyError>>;
524export function cherryPick(url: string, spec: Stopping<CherrySpec>, ...options: [] | [RebaseOptions]): Promise<Result<PickEmpty | PickOk, PlyError>>;
525export function cherryPick(url: string, spec: CherrySpec, ...options: [] | [RebaseOptions]): Promise<Result<PickOutcome, PlyError>>;
526export function cherryPick(url: string, spec: CherrySpec, ...options: [] | [RebaseOptions]): Promise<Result<PickOutcome, PlyError>> {
527 return pickCommit(url, { ...spec, revert: false }, ...options);
528}
529export function revertCommit(url: string, spec: CherrySpec & { readonly empty: 'keep' }, ...options: [] | [RebaseOptions]): Promise<Result<PickKept | PickOk, PlyError>>;
530export function revertCommit(url: string, spec: Stopping<CherrySpec>, ...options: [] | [RebaseOptions]): Promise<Result<PickEmpty | PickOk, PlyError>>;
531export function revertCommit(url: string, spec: CherrySpec, ...options: [] | [RebaseOptions]): Promise<Result<PickOutcome, PlyError>>;
532export function revertCommit(url: string, spec: CherrySpec, ...options: [] | [RebaseOptions]): Promise<Result<PickOutcome, PlyError>> {
533 return pickCommit(url, { ...spec, revert: true }, ...options);
534}
Diagnostics6 git calls · 133 ms
CallStatusSizeTime0133 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=2 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 KiB · hit2 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=HIT 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 · hit2 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=2 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=10Open 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=2 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=5323b9266eea5ded637285d1c5320699f12be76eOpen pack map
fetchtree:02002.4 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=124 git.response.bytes=2507 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=8f720d29ff85ce682ffdad9c393b04a3834c3203 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=2507 git.pkt.payload.max=2480 git.sideband.band1.bytes=2480 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=2480 git.pack.trailer=723b6bf1d4d6021fe5eb940c622b9ff00ee4a381Open pack map
fetch20011 KiB125 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=11061 git.response.cache=MISS git.response.duration_ms=125 git.fetch.wants=7f60637836137597d67ef45a133ada8483843db7 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=11061 git.pkt.payload.max=8192 git.sideband.band1.bytes=11029 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
- a5e0f8484f06332c
- Request
- 4ebe2c7a…
- 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