translation-pairing-git.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. /** Git-blob operations owned by the bilingual pairing workflow. */
  2. import { spawnSync } from 'node:child_process'
  3. import { createHash } from 'node:crypto'
  4. const SNAPSHOT_REF_PREFIX = 'refs/dsh/translation-pairing/snapshots'
  5. /** Maximum buffered stdout or stderr for repository-owned Git subprocesses. */
  6. export const GIT_COMMAND_MAX_BUFFER = 1 << 26
  7. /** Full SHA-1 Git blob hash (the 40-hex format used by pairing records). */
  8. export function gitBlobHash(content: Buffer): string {
  9. const hash = createHash('sha1')
  10. hash.update(`blob ${content.byteLength}\0`)
  11. hash.update(content)
  12. return hash.digest('hex')
  13. }
  14. /**
  15. * Run one Git subprocess and return its exact stdout bytes.
  16. *
  17. * @param root - Repository root used as Git's working directory.
  18. * @param args - Arguments following the `git` executable.
  19. * @param operation - Human-readable operation for failure diagnostics.
  20. * @param input - Optional stdin bytes.
  21. * @returns Exact stdout bytes.
  22. * @throws Error when Git cannot start or exits unsuccessfully.
  23. */
  24. export function runGit(root: string, args: string[], operation: string, input?: Buffer): Buffer {
  25. const result = spawnSync('git', ['-C', root, ...args], {
  26. input,
  27. maxBuffer: GIT_COMMAND_MAX_BUFFER,
  28. })
  29. if (result.error) {
  30. throw new Error(`${operation} failed: ${result.error.message}`, { cause: result.error })
  31. }
  32. if (result.status !== 0) {
  33. throw new Error(`${operation} failed with status ${String(result.status)}: ${result.stderr.toString('utf8').trim()}`)
  34. }
  35. return result.stdout
  36. }
  37. /** One regular stage-zero Git index entry and its exact blob bytes. */
  38. export interface GitIndexBlob {
  39. objectId: string
  40. content: Buffer
  41. }
  42. /** Every stage-zero path currently present in the Git index. */
  43. export function gitIndexPaths(root: string): Set<string> {
  44. const paths = new Set<string>()
  45. const entries = runGit(root, ['ls-files', '--stage', '-z'], 'listing Git index paths')
  46. .toString('utf8')
  47. .split('\0')
  48. .filter(Boolean)
  49. for (const entry of entries) {
  50. const match = /^\d+ [0-9a-f]+ ([0-3])\t([\s\S]+)$/.exec(entry)
  51. if (!match?.[1] || match[2] === undefined) throw new Error('git ls-files --stage returned a malformed entry')
  52. if (match[1] === '0') paths.add(match[2])
  53. }
  54. return paths
  55. }
  56. /**
  57. * Paths visible to a custom merge driver from the current index plus every
  58. * merge head Git advertises through `GITHEAD_<oid>` environment entries.
  59. *
  60. * Git invokes custom drivers before it writes clean additions from the other
  61. * heads into stage zero. The explicit post-conflict resolver has no GITHEAD
  62. * entries and therefore uses the already-merged index alone.
  63. */
  64. export function gitMergeInputPaths(root: string, environment: NodeJS.ProcessEnv = process.env): Set<string> {
  65. const paths = gitIndexPaths(root)
  66. const heads = Object.keys(environment)
  67. .flatMap(key => /^GITHEAD_([0-9a-f]{40})$/.exec(key)?.[1] ?? [])
  68. .sort()
  69. for (const head of heads) {
  70. const files = runGit(root, ['ls-tree', '-r', '--name-only', '-z', head], `listing merge-head ${head} paths`)
  71. .toString('utf8')
  72. .split('\0')
  73. .filter(Boolean)
  74. for (const file of files) paths.add(file)
  75. }
  76. return paths
  77. }
  78. /**
  79. * Read one path from the Git index without consulting working-tree bytes.
  80. *
  81. * @param root - Repository root.
  82. * @param path - Repository-relative path.
  83. * @returns The stage-zero blob, or `undefined` when the path is absent.
  84. * @throws Error when the path is unmerged or its index entries are not a valid merge state.
  85. */
  86. export function readGitIndexBlob(root: string, path: string): GitIndexBlob | undefined {
  87. const output = runGit(
  88. root,
  89. ['ls-files', '--stage', '-z', '--', path],
  90. `git ls-files --stage for ${path}`,
  91. ).toString('utf8')
  92. const entries = output.split('\0').filter(Boolean)
  93. if (entries.length === 0) return undefined
  94. if (entries.length !== 1) throw new Error(`${path} does not have exactly one resolved index entry`)
  95. const match = /^(?:\d+) ([0-9a-f]+) 0\t[\s\S]+$/.exec(entries[0] ?? '')
  96. if (!match?.[1]) throw new Error(`${path} remains unmerged or has an invalid index entry`)
  97. return {
  98. objectId: match[1],
  99. content: runGit(root, ['cat-file', 'blob', match[1]], `reading staged ${path}`),
  100. }
  101. }
  102. /**
  103. * Persist exact working-tree bytes so a pairing record can later recover them
  104. * with `git cat-file`, even when they have never appeared in the index or a
  105. * commit. The returned object ID is checked against the pairing format's own
  106. * content hash before the caller writes a sidecar.
  107. */
  108. export function storeGitBlob(root: string, content: Buffer): string {
  109. const expected = gitBlobHash(content)
  110. const stored = runGit(root, ['hash-object', '-w', '--stdin'], 'git hash-object -w --stdin', content)
  111. .toString('utf8')
  112. .trim()
  113. if (stored !== expected) {
  114. throw new Error(`git hash-object -w --stdin returned unexpected object ID ${JSON.stringify(stored)}; expected ${expected}`)
  115. }
  116. runGit(
  117. root,
  118. ['update-ref', `${SNAPSHOT_REF_PREFIX}/${stored}`, stored],
  119. 'git update-ref for translation snapshot',
  120. )
  121. return stored
  122. }