| 1 | import { stat } from 'node:fs/promises'; |
| 2 | |
| 3 | import { alternatesEnv } |
| 4 | import { GitCommandFailedError } |
| 5 | import { runGit } |
| 6 | |
| 7 | export interface MergeContext |
| 8 | gitDir: string; |
| 9 | alternates?: string |
| 10 | } |
| 11 | |
| 12 | /** Merges two commits into a tree without a worktree or an index, so a bare cache can answer "does this conflict" and build the result from one call. Returns null when the merge conflicts. */ |
| 13 | export async function mergeTree |
| 14 | gitDir, |
| 15 | alternates, |
| 16 | base, |
| 17 | head, |
| 18 | }: MergeContext |
| 19 | try { |
| 20 | const raw = |
| 21 | args: ['merge-tree', |
| 22 | gitDir, |
| 23 | env: alternatesEnv(alternates |
| 24 | }); |
| 25 | return raw.split |
| 26 | } catch (error) |
| 27 | // A conflict and an unreadable commit both exit 1. Only the conflict keeps stderr empty, writing its tree and the conflicted paths to stdout, so a fork whose objects were never lent must not read as "merges cleanly". |
| 28 | if ( |
| 29 | error instanceof GitCommandFailedError |
| 30 | error.exitCode === |
| 31 | error.stderr === |
| 32 | ) { |
| 33 | return null; |
| 34 | } |
| 35 | throw error; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | export async function commitTree |
| 40 | gitDir, |
| 41 | alternates, |
| 42 | tree, |
| 43 | parents, |
| 44 | message, |
| 45 | author, |
| 46 | }: MergeContext |
| 47 | tree: string |
| 48 | parents: string |
| 49 | message: string |
| 50 | author: { |
| 51 | }): Promise<string |
| 52 | const raw = |
| 53 | args: [ |
| 54 | 'commit-tree', |
| 55 | tree, |
| 56 | ...parents.flatMap( |
| 57 | '-m', |
| 58 | message, |
| 59 | ], |
| 60 | gitDir, |
| 61 | env: { |
| 62 | ...alternatesEnv(alternates |
| 63 | // a bare cache has no configured identity, and git refuses to guess one |
| 64 | GIT_AUTHOR_NAME: author.name |
| 65 | GIT_AUTHOR_EMAIL: author.email |
| 66 | GIT_COMMITTER_NAME: author.name |
| 67 | GIT_COMMITTER_EMAIL: author.email |
| 68 | }, |
| 69 | }); |
| 70 | |
| 71 | return raw.trim |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * A packfile holding everything reachable from `include` that `exclude` does not already cover. |
| 76 | * |
| 77 | * `exclude` must be what the *target* log already holds, never the head commit: a fork's commits live in another repository's log, so excluding them would write an entry whose merge commit no node could ever replay. |
| 78 | */ |
| 79 | export async function packRange |
| 80 | gitDir, |
| 81 | alternates, |
| 82 | include, |
| 83 | exclude, |
| 84 | prefix, |
| 85 | }: MergeContext |
| 86 | include: string |
| 87 | exclude: string |
| 88 | prefix: string |
| 89 | }): Promise<{ |
| 90 | const name = |
| 91 | args: ['pack-objects', |
| 92 | gitDir, |
| 93 | env: alternatesEnv(alternates |
| 94 | input: Buffer.from |
| 95 | [include, ...exclude |
| 96 | 'utf8', |
| 97 | ), |
| 98 | }); |
| 99 | |
| 100 | const path = |
| 101 | return { path, |
| 102 | } |