install-lefthook.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #!/usr/bin/env node
  2. import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
  3. import { spawnSync } from 'node:child_process'
  4. import { isAbsolute, join, resolve } from 'node:path'
  5. const MINIMUM_GIT = [2, 20, 0]
  6. const HOOKS_DIRECTORY = 'dsh-hooks'
  7. const OWNERSHIP_MARKER = '.dsh-lefthook-owned'
  8. const OWNERSHIP_MARKER_CONTENT = 'deepseek-harness worktree-local lefthook hooks\n'
  9. const INSTALL_LOCK = 'dsh-lefthook-install.lock'
  10. const INSTALL_LOCK_TIMEOUT_MS = 30_000
  11. const INSTALL_LOCK_POLL_MS = 50
  12. const ALLOW_HOOKS_PATH_OVERRIDE = 'DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE'
  13. function errorCode(error) {
  14. return typeof error === 'object' && error !== null && 'code' in error
  15. ? error.code
  16. : undefined
  17. }
  18. function commandFailure(command, args, result) {
  19. const stderr = typeof result.stderr === 'string' ? result.stderr.trim() : ''
  20. const detail = result.error?.message ?? (stderr || `exit status ${String(result.status)}`)
  21. return new Error(`${command} ${args.join(' ')} failed: ${detail}`)
  22. }
  23. function capture(command, args, options = {}) {
  24. const result = spawnSync(command, args, {
  25. cwd: options.cwd,
  26. encoding: 'utf8',
  27. env: process.env,
  28. })
  29. if (result.status !== 0 && !options.allowStatuses?.includes(result.status)) {
  30. throw commandFailure(command, args, result)
  31. }
  32. return result
  33. }
  34. function git(args, root, options = {}) {
  35. return capture('git', args, { ...options, cwd: root })
  36. }
  37. function nulValues(result) {
  38. if (result.status !== 0) return []
  39. if (result.stdout === '') return ['']
  40. const output = result.stdout.endsWith('\0') ? result.stdout.slice(0, -1) : result.stdout
  41. return output.split('\0')
  42. }
  43. function fileConfigValues(root, configPath, key) {
  44. return nulValues(git(
  45. ['config', '--file', configPath, '--null', '--get-all', key],
  46. root,
  47. { allowStatuses: [1] },
  48. ))
  49. }
  50. function effectiveConfigValue(root, key) {
  51. const values = nulValues(git(
  52. ['config', '--null', '--get', key],
  53. root,
  54. { allowStatuses: [1] },
  55. ))
  56. if (values.length > 1) throw new Error(`git config returned multiple effective values for ${key}`)
  57. return values[0]
  58. }
  59. function parseGitBoolean(value, key) {
  60. const normalized = value.toLowerCase()
  61. if (normalized === '' || normalized === 'true' || normalized === 'yes' || normalized === 'on' || normalized === '1') return true
  62. if (normalized === 'false' || normalized === 'no' || normalized === 'off' || normalized === '0') return false
  63. throw new Error(`invalid Boolean value for ${key}: ${JSON.stringify(value)}`)
  64. }
  65. function assertSingle(values, key) {
  66. if (values.length > 1) throw new Error(`multiple ${key} values are not supported`)
  67. return values[0]
  68. }
  69. function assertSupportedGit(root) {
  70. const version = git(['--version'], root).stdout.trim()
  71. const match = /git version (\d+)\.(\d+)(?:\.(\d+))?/.exec(version)
  72. if (match === null) throw new Error(`cannot determine Git version from ${JSON.stringify(version)}`)
  73. const actual = [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)]
  74. for (let index = 0; index < MINIMUM_GIT.length; index += 1) {
  75. if (actual[index] > MINIMUM_GIT[index]) return
  76. if (actual[index] < MINIMUM_GIT[index]) {
  77. throw new Error(`Git 2.20 or newer is required for worktree-local hooks; found ${version}`)
  78. }
  79. }
  80. }
  81. function ensureWorktreeConfig(root, commonConfigPath) {
  82. const versions = fileConfigValues(root, commonConfigPath, 'core.repositoryFormatVersion')
  83. const versionText = assertSingle(versions, 'core.repositoryFormatVersion')
  84. const version = Number(versionText)
  85. if (!Number.isInteger(version) || version < 0) {
  86. throw new Error(`unsupported core.repositoryFormatVersion: ${JSON.stringify(versionText)}`)
  87. }
  88. const worktrees = fileConfigValues(root, commonConfigPath, 'core.worktree')
  89. if (worktrees.length > 0) {
  90. throw new Error('cannot enable extensions.worktreeConfig while core.worktree is in the common config; move it to the main worktree config first')
  91. }
  92. const bareText = assertSingle(fileConfigValues(root, commonConfigPath, 'core.bare'), 'core.bare')
  93. const bare = bareText === undefined ? undefined : parseGitBoolean(bareText, 'core.bare')
  94. if (bare === true) {
  95. throw new Error('cannot enable extensions.worktreeConfig for a common config with core.bare=true')
  96. }
  97. const extensionText = assertSingle(
  98. fileConfigValues(root, commonConfigPath, 'extensions.worktreeConfig'),
  99. 'extensions.worktreeConfig',
  100. )
  101. const extensionEnabled = extensionText === undefined
  102. ? false
  103. : parseGitBoolean(extensionText, 'extensions.worktreeConfig')
  104. if (version === 0) {
  105. git(['config', '--file', commonConfigPath, 'core.repositoryFormatVersion', '1'], root)
  106. }
  107. if (!extensionEnabled) {
  108. git(['config', '--file', commonConfigPath, 'extensions.worktreeConfig', 'true'], root)
  109. }
  110. if (bare === false) {
  111. git(['config', '--file', commonConfigPath, '--unset-all', 'core.bare'], root)
  112. }
  113. }
  114. function lockOwnerIsAlive(lockPath) {
  115. let owner
  116. try {
  117. owner = Number(readFileSync(lockPath, 'utf8').trim())
  118. } catch (error) {
  119. if (errorCode(error) === 'ENOENT') return false
  120. throw error
  121. }
  122. if (!Number.isSafeInteger(owner) || owner <= 0) return true
  123. try {
  124. process.kill(owner, 0)
  125. return true
  126. } catch (error) {
  127. if (errorCode(error) === 'ESRCH') return false
  128. if (errorCode(error) === 'EPERM') return true
  129. throw error
  130. }
  131. }
  132. function removeStaleLock(lockPath) {
  133. try {
  134. unlinkSync(lockPath)
  135. } catch (error) {
  136. if (errorCode(error) !== 'ENOENT') throw error
  137. // Another waiting installer removed the same stale lock first.
  138. }
  139. }
  140. async function acquireInstallLock(commonDirectory) {
  141. const lockPath = join(commonDirectory, INSTALL_LOCK)
  142. const deadline = Date.now() + INSTALL_LOCK_TIMEOUT_MS
  143. while (true) {
  144. try {
  145. writeFileSync(lockPath, `${String(process.pid)}\n`, { flag: 'wx', mode: 0o600 })
  146. return () => removeStaleLock(lockPath)
  147. } catch (error) {
  148. if (errorCode(error) !== 'EEXIST') throw error
  149. if (!lockOwnerIsAlive(lockPath)) {
  150. removeStaleLock(lockPath)
  151. continue
  152. }
  153. if (Date.now() >= deadline) {
  154. throw new Error(`timed out waiting for Lefthook installer lock ${lockPath}`)
  155. }
  156. await new Promise(resolveWait => setTimeout(resolveWait, INSTALL_LOCK_POLL_MS))
  157. }
  158. }
  159. }
  160. function ensureOwnedHooksDirectory(hooksPath) {
  161. const markerPath = join(hooksPath, OWNERSHIP_MARKER)
  162. if (!existsSync(hooksPath)) {
  163. mkdirSync(hooksPath, { mode: 0o700 })
  164. writeFileSync(markerPath, OWNERSHIP_MARKER_CONTENT, { flag: 'wx', mode: 0o600 })
  165. return
  166. }
  167. const hooksStat = lstatSync(hooksPath)
  168. if (!hooksStat.isDirectory() || hooksStat.isSymbolicLink()) {
  169. throw new Error(`refusing to use non-directory or symlinked hooks path ${hooksPath}`)
  170. }
  171. if (!existsSync(markerPath)) {
  172. throw new Error(`refusing to overwrite unowned hooks directory ${hooksPath}`)
  173. }
  174. const markerStat = lstatSync(markerPath)
  175. if (!markerStat.isFile() || markerStat.isSymbolicLink() || readFileSync(markerPath, 'utf8') !== OWNERSHIP_MARKER_CONTENT) {
  176. throw new Error(`refusing to overwrite hooks directory with an invalid ownership marker: ${hooksPath}`)
  177. }
  178. }
  179. function runLefthook(root, lefthook) {
  180. const args = ['install', '--force']
  181. // Node refuses to spawn Windows `.cmd` shims directly; the quoted path is
  182. // re-parsed by cmd.exe, while POSIX can execute its extensionless shim.
  183. const result = process.platform === 'win32'
  184. ? spawnSync(`"${lefthook}"`, args, { cwd: root, stdio: 'inherit', shell: true })
  185. : spawnSync(lefthook, args, { cwd: root, stdio: 'inherit' })
  186. if (result.status !== 0) throw commandFailure(lefthook, args, result)
  187. }
  188. function refuseCustomHooksPath(root, hooksPath) {
  189. const origin = git(
  190. ['config', '--show-origin', '--get', 'core.hooksPath'],
  191. root,
  192. { allowStatuses: [1] },
  193. ).stdout.trim()
  194. const source = origin === '' ? hooksPath : origin
  195. throw new Error(
  196. `refusing to replace user-owned core.hooksPath (${source}). `
  197. + `Chain those hooks through lefthook.yml, or, if this inherited path may remain active only in other worktrees, `
  198. + `rerun with ${ALLOW_HOOKS_PATH_OVERRIDE}=1`,
  199. )
  200. }
  201. async function main() {
  202. const probe = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' })
  203. if (probe.status !== 0) return
  204. const root = probe.stdout.trim()
  205. const isWindows = process.platform === 'win32'
  206. const lefthook = join(root, 'node_modules', '.bin', isWindows ? 'lefthook.cmd' : 'lefthook')
  207. if (!existsSync(lefthook)) return
  208. assertSupportedGit(root)
  209. const gitDirectory = git(['rev-parse', '--absolute-git-dir'], root).stdout.trim()
  210. const commonOutput = git(['rev-parse', '--git-common-dir'], root).stdout.trim()
  211. const commonDirectory = isAbsolute(commonOutput) ? commonOutput : resolve(root, commonOutput)
  212. const commonConfigPath = join(commonDirectory, 'config')
  213. const worktreeConfigPath = join(gitDirectory, 'config.worktree')
  214. const hooksPath = join(gitDirectory, HOOKS_DIRECTORY)
  215. const releaseLock = await acquireInstallLock(commonDirectory)
  216. try {
  217. const worktreePath = assertSingle(
  218. fileConfigValues(root, worktreeConfigPath, 'core.hooksPath'),
  219. 'worktree core.hooksPath',
  220. )
  221. if (worktreePath !== undefined && worktreePath !== hooksPath) refuseCustomHooksPath(root, worktreePath)
  222. const effectivePath = effectiveConfigValue(root, 'core.hooksPath')
  223. const effectivePathIsOwned = effectivePath === hooksPath && worktreePath === hooksPath
  224. if (
  225. effectivePath !== undefined
  226. && !effectivePathIsOwned
  227. && process.env[ALLOW_HOOKS_PATH_OVERRIDE] !== '1'
  228. ) {
  229. refuseCustomHooksPath(root, effectivePath)
  230. }
  231. ensureOwnedHooksDirectory(hooksPath)
  232. ensureWorktreeConfig(root, commonConfigPath)
  233. let pathChanged = false
  234. try {
  235. git(['config', '--worktree', 'core.hooksPath', hooksPath], root)
  236. pathChanged = worktreePath === undefined
  237. runLefthook(root, lefthook)
  238. } catch (error) {
  239. if (pathChanged) {
  240. git(['config', '--worktree', '--unset-all', 'core.hooksPath'], root)
  241. }
  242. throw error
  243. }
  244. } finally {
  245. releaseLock()
  246. }
  247. }
  248. try {
  249. await main()
  250. } catch (error) {
  251. console.error(`[install-lefthook] ${error instanceof Error ? error.message : String(error)}`)
  252. process.exitCode = 1
  253. }