install-lefthook.spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. import { spawn, spawnSync } from 'node:child_process'
  2. import {
  3. chmodSync,
  4. existsSync,
  5. linkSync,
  6. mkdirSync,
  7. mkdtempSync,
  8. lstatSync,
  9. readFileSync,
  10. renameSync,
  11. rmSync,
  12. symlinkSync,
  13. writeFileSync,
  14. } from 'node:fs'
  15. import { tmpdir } from 'node:os'
  16. import { dirname, isAbsolute, join, resolve } from 'node:path'
  17. import { fileURLToPath } from 'node:url'
  18. import { afterEach, describe, expect, it } from 'vitest'
  19. const installer = fileURLToPath(new URL('./install-lefthook.mjs', import.meta.url))
  20. const fixtures: string[] = []
  21. interface Fixture {
  22. container: string
  23. env: NodeJS.ProcessEnv
  24. linked: string
  25. main: string
  26. }
  27. interface CommandResult {
  28. status: number | null
  29. stderr: string
  30. stdout: string
  31. }
  32. afterEach(() => {
  33. for (const fixture of fixtures.splice(0)) rmSync(fixture, { recursive: true, force: true })
  34. })
  35. function commandResult(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv): CommandResult {
  36. const result = spawnSync(command, args, { cwd, encoding: 'utf8', env })
  37. return { status: result.status, stderr: result.stderr, stdout: result.stdout }
  38. }
  39. function gitResult(fixture: Fixture, cwd: string, args: string[]): CommandResult {
  40. return commandResult('git', args, cwd, fixture.env)
  41. }
  42. function git(fixture: Fixture, cwd: string, args: string[]): string {
  43. const result = gitResult(fixture, cwd, args)
  44. if (result.status !== 0) {
  45. throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`)
  46. }
  47. return result.stdout.trim()
  48. }
  49. function write(path: string, content: string, mode?: number): void {
  50. mkdirSync(dirname(path), { recursive: true })
  51. writeFileSync(path, content, mode === undefined ? undefined : { mode })
  52. }
  53. function fakeLefthookSource(): string {
  54. return `#!/usr/bin/env node
  55. import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
  56. import { execFileSync } from 'node:child_process'
  57. import { join } from 'node:path'
  58. if (process.argv.slice(2).join(' ') !== 'install --force') process.exit(64)
  59. const rootOutput = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' })
  60. const root = rootOutput.endsWith('\\n') ? rootOutput.slice(0, -1) : rootOutput
  61. const forbiddenConfigKey = process.env.DSH_TEST_FORBIDDEN_GIT_CONFIG_KEY
  62. if (forbiddenConfigKey !== undefined) {
  63. try {
  64. execFileSync('git', ['config', '--get', forbiddenConfigKey], { encoding: 'utf8' })
  65. process.exit(92)
  66. } catch (error) {
  67. if (error === null || typeof error !== 'object' || !('status' in error) || error.status !== 1) throw error
  68. }
  69. }
  70. const hooksPath = execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim()
  71. mkdirSync(hooksPath, { recursive: true })
  72. const running = join(hooksPath, '.fake-lefthook-running')
  73. try {
  74. writeFileSync(running, String(process.pid), { flag: 'wx' })
  75. } catch {
  76. process.exit(91)
  77. }
  78. const delay = Number(process.env.DSH_TEST_LEFTHOOK_DELAY_MS ?? 0)
  79. if (delay > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay)
  80. const shouldFail = process.env.DSH_TEST_LEFTHOOK_FAIL === '1'
  81. if (!shouldFail) {
  82. const binary = join(root, 'node_modules', '.bin', process.platform === 'win32' ? 'lefthook.cmd' : 'lefthook')
  83. const config = readFileSync(join(root, 'lefthook.yml'), 'utf8').trim()
  84. const hook = \`#!/bin/sh\\n# root=\${root}\\n# binary=\${binary}\\n# config=\${config}\\nexit 0\\n\`
  85. for (const name of ['pre-commit', 'pre-push']) writeFileSync(join(hooksPath, name), hook, { mode: 0o755 })
  86. }
  87. if (existsSync(running)) unlinkSync(running)
  88. if (process.env.DSH_TEST_LEFTHOOK_BREAK_WORKTREE_CONFIG === '1') {
  89. const configPath = execFileSync('git', ['rev-parse', '--git-path', 'config.worktree'], { encoding: 'utf8' }).trim()
  90. writeFileSync(configPath, '[invalid\\n')
  91. }
  92. if (shouldFail) process.exit(77)
  93. `
  94. }
  95. function installFakeLefthook(root: string): void {
  96. const binDirectory = join(root, 'node_modules/.bin')
  97. mkdirSync(binDirectory, { recursive: true })
  98. writeFileSync(join(binDirectory, 'fake-lefthook.mjs'), fakeLefthookSource())
  99. if (process.platform === 'win32') {
  100. writeFileSync(
  101. join(binDirectory, 'lefthook.cmd'),
  102. `@echo off\r\n"${process.execPath}" "%~dp0\\fake-lefthook.mjs" %*\r\n`,
  103. )
  104. return
  105. }
  106. const shim = join(binDirectory, 'lefthook')
  107. writeFileSync(shim, `#!/bin/sh\nexec "${process.execPath}" "$(dirname "$0")/fake-lefthook.mjs" "$@"\n`)
  108. chmodSync(shim, 0o755)
  109. }
  110. function createFixture(names: { main?: string; linked?: string } = {}): Fixture {
  111. const container = mkdtempSync(join(tmpdir(), 'dsh-lefthook-'))
  112. fixtures.push(container)
  113. const main = join(container, names.main ?? 'main')
  114. const linked = join(container, names.linked ?? 'linked')
  115. const env: NodeJS.ProcessEnv = {
  116. ...process.env,
  117. CI: 'false',
  118. GITHUB_ACTIONS: 'false',
  119. GIT_AUTHOR_EMAIL: 'hooks@example.test',
  120. GIT_AUTHOR_NAME: 'Hooks Test',
  121. GIT_COMMITTER_EMAIL: 'hooks@example.test',
  122. GIT_COMMITTER_NAME: 'Hooks Test',
  123. GIT_CONFIG_GLOBAL: join(container, 'global.gitconfig'),
  124. GIT_CONFIG_NOSYSTEM: '1',
  125. HOME: container,
  126. XDG_CONFIG_HOME: join(container, '.config'),
  127. }
  128. const fixture = { container, env, linked, main }
  129. mkdirSync(main)
  130. git(fixture, container, ['init', main])
  131. write(join(main, 'README.md'), '# fixture\n')
  132. git(fixture, main, ['add', 'README.md'])
  133. git(fixture, main, ['commit', '-m', 'fixture'])
  134. git(fixture, main, ['worktree', 'add', '-b', 'linked', linked])
  135. write(join(main, 'lefthook.yml'), 'main-worktree-config\n')
  136. write(join(linked, 'lefthook.yml'), 'linked-worktree-config\n')
  137. installFakeLefthook(main)
  138. installFakeLefthook(linked)
  139. return fixture
  140. }
  141. function gitDirectory(fixture: Fixture, root: string): string {
  142. return git(fixture, root, ['rev-parse', '--absolute-git-dir'])
  143. }
  144. function commonDirectory(fixture: Fixture): string {
  145. const output = git(fixture, fixture.main, ['rev-parse', '--git-common-dir'])
  146. return isAbsolute(output) ? output : resolve(fixture.main, output)
  147. }
  148. function hooksPath(fixture: Fixture, root: string): string {
  149. return join(gitDirectory(fixture, root), 'dsh-hooks')
  150. }
  151. function installLockPath(fixture: Fixture): string {
  152. return join(commonDirectory(fixture), 'dsh-lefthook-install.lock')
  153. }
  154. async function waitForPath(path: string): Promise<void> {
  155. const deadline = Date.now() + 5_000
  156. while (!existsSync(path)) {
  157. if (Date.now() >= deadline) throw new Error(`timed out waiting for ${path}`)
  158. await new Promise(resolveWait => setTimeout(resolveWait, 10))
  159. }
  160. }
  161. function runInstaller(
  162. fixture: Fixture,
  163. root: string,
  164. extraEnv: NodeJS.ProcessEnv = {},
  165. ): Promise<CommandResult> {
  166. return new Promise((resolveResult, reject) => {
  167. const child = spawn(process.execPath, [installer], {
  168. cwd: root,
  169. env: { ...fixture.env, ...extraEnv },
  170. stdio: ['ignore', 'pipe', 'pipe'],
  171. })
  172. let stdout = ''
  173. let stderr = ''
  174. child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
  175. child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
  176. child.on('error', reject)
  177. child.on('close', (status) => { resolveResult({ status, stderr, stdout }) })
  178. })
  179. }
  180. describe('worktree-local Lefthook installer', () => {
  181. for (const [label, extraEnv] of [
  182. ['CI', { CI: 'true' }],
  183. ['GitHub Actions', { GITHUB_ACTIONS: 'true' }],
  184. ] satisfies [string, NodeJS.ProcessEnv][]) {
  185. it(`skips hook installation when ${label} marks an automated job`, async () => {
  186. const fixture = createFixture()
  187. const common = commonDirectory(fixture)
  188. const missingInclude = join(fixture.container, 'missing-ci-credentials.gitconfig')
  189. git(fixture, fixture.main, [
  190. 'config',
  191. '--local',
  192. 'includeIf.gitdir:/github/workspace/.git.path',
  193. missingInclude,
  194. ])
  195. const result = await runInstaller(fixture, fixture.main, extraEnv)
  196. expect(result.status, result.stderr).toBe(0)
  197. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  198. expect(git(fixture, fixture.main, ['config', '--get', 'core.repositoryFormatVersion'])).toBe('0')
  199. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  200. expect(existsSync(join(common, 'config.worktree'))).toBe(false)
  201. })
  202. }
  203. it('isolates main and linked worktrees without changing legacy common hooks', async () => {
  204. const fixture = createFixture()
  205. const common = commonDirectory(fixture)
  206. const legacyHook = join(common, 'hooks/pre-commit')
  207. write(legacyHook, '#!/bin/sh\n# legacy hook\n', 0o755)
  208. const mainInstall = await runInstaller(fixture, fixture.main)
  209. const linkedInstall = await runInstaller(fixture, fixture.linked)
  210. expect(mainInstall.status, mainInstall.stderr).toBe(0)
  211. expect(linkedInstall.status, linkedInstall.stderr).toBe(0)
  212. const mainHooks = hooksPath(fixture, fixture.main)
  213. const linkedHooks = hooksPath(fixture, fixture.linked)
  214. expect(mainHooks).not.toBe(linkedHooks)
  215. expect(git(fixture, fixture.main, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(mainHooks)
  216. expect(git(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(linkedHooks)
  217. const mainHook = readFileSync(join(mainHooks, 'pre-commit'), 'utf8')
  218. const linkedHook = readFileSync(join(linkedHooks, 'pre-commit'), 'utf8')
  219. const canonicalMain = git(fixture, fixture.main, ['rev-parse', '--show-toplevel'])
  220. const canonicalLinked = git(fixture, fixture.linked, ['rev-parse', '--show-toplevel'])
  221. expect(mainHook).toContain(`# root=${canonicalMain}`)
  222. expect(mainHook).toContain('# config=main-worktree-config')
  223. expect(mainHook).not.toContain(canonicalLinked)
  224. expect(linkedHook).toContain(`# root=${canonicalLinked}`)
  225. expect(linkedHook).toContain('# config=linked-worktree-config')
  226. expect(linkedHook).not.toContain(canonicalMain)
  227. expect(readFileSync(legacyHook, 'utf8')).toBe('#!/bin/sh\n# legacy hook\n')
  228. const commonConfig = join(common, 'config')
  229. expect(git(fixture, fixture.main, ['config', '--file', commonConfig, '--get', 'core.repositoryFormatVersion'])).toBe('1')
  230. expect(git(fixture, fixture.main, ['config', '--file', commonConfig, '--get', 'extensions.worktreeConfig'])).toBe('true')
  231. expect(gitResult(fixture, fixture.main, ['config', '--file', commonConfig, '--get', 'core.bare']).status).toBe(1)
  232. const mainHookBeforeRemoval = readFileSync(join(mainHooks, 'pre-commit'), 'utf8')
  233. git(fixture, fixture.main, ['worktree', 'remove', '--force', fixture.linked])
  234. expect(readFileSync(join(mainHooks, 'pre-commit'), 'utf8')).toBe(mainHookBeforeRemoval)
  235. expect(readFileSync(legacyHook, 'utf8')).toBe('#!/bin/sh\n# legacy hook\n')
  236. })
  237. it('replaces the owned hook path Git copies into a newly added worktree', async () => {
  238. const fixture = createFixture()
  239. const mainInstall = await runInstaller(fixture, fixture.main)
  240. expect(mainInstall.status, mainInstall.stderr).toBe(0)
  241. const mainHooks = hooksPath(fixture, fixture.main)
  242. const mainHookBefore = readFileSync(join(mainHooks, 'pre-commit'), 'utf8')
  243. const lateLinked = join(fixture.container, 'late-linked')
  244. git(fixture, fixture.main, ['worktree', 'add', '-b', 'late-linked', lateLinked])
  245. write(join(lateLinked, 'lefthook.yml'), 'late-linked-worktree-config\n')
  246. installFakeLefthook(lateLinked)
  247. expect(git(fixture, lateLinked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(mainHooks)
  248. const linkedInstall = await runInstaller(fixture, lateLinked)
  249. expect(linkedInstall.status, linkedInstall.stderr).toBe(0)
  250. const linkedHooks = hooksPath(fixture, lateLinked)
  251. expect(linkedHooks).not.toBe(mainHooks)
  252. expect(git(fixture, lateLinked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(linkedHooks)
  253. expect(readFileSync(join(linkedHooks, 'pre-commit'), 'utf8')).toContain(
  254. '# config=late-linked-worktree-config',
  255. )
  256. expect(readFileSync(join(mainHooks, 'pre-commit'), 'utf8')).toBe(mainHookBefore)
  257. })
  258. it('serializes concurrent installs and keeps repeated output stable', async () => {
  259. const fixture = createFixture()
  260. const delayed = { DSH_TEST_LEFTHOOK_DELAY_MS: '150' }
  261. const first = await Promise.all([
  262. runInstaller(fixture, fixture.main, delayed),
  263. runInstaller(fixture, fixture.linked, delayed),
  264. ])
  265. for (const result of first) expect(result.status, result.stderr).toBe(0)
  266. const mainHookPath = join(hooksPath(fixture, fixture.main), 'pre-push')
  267. const initialHook = readFileSync(mainHookPath, 'utf8')
  268. const repeated = await Promise.all([
  269. runInstaller(fixture, fixture.main, delayed),
  270. runInstaller(fixture, fixture.main, delayed),
  271. ])
  272. for (const result of repeated) expect(result.status, result.stderr).toBe(0)
  273. expect(readFileSync(mainHookPath, 'utf8')).toBe(initialHook)
  274. expect(existsSync(join(commonDirectory(fixture), 'dsh-lefthook-install.lock'))).toBe(false)
  275. expect(existsSync(join(hooksPath(fixture, fixture.main), '.fake-lefthook-running'))).toBe(false)
  276. })
  277. it('repairs its owned absolute hook path after the checkout moves', async () => {
  278. const fixture = createFixture()
  279. const oldRoot = fixture.main
  280. const first = await runInstaller(fixture, oldRoot)
  281. expect(first.status, first.stderr).toBe(0)
  282. const oldHooks = hooksPath(fixture, oldRoot)
  283. const movedRoot = join(fixture.container, 'moved-main')
  284. renameSync(oldRoot, movedRoot)
  285. const moved = await runInstaller(fixture, movedRoot)
  286. expect(moved.status, moved.stderr).toBe(0)
  287. const movedHooks = hooksPath(fixture, movedRoot)
  288. expect(movedHooks).not.toBe(oldHooks)
  289. expect(git(fixture, movedRoot, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(movedHooks)
  290. const canonicalMoved = git(fixture, movedRoot, ['rev-parse', '--show-toplevel'])
  291. expect(readFileSync(join(movedHooks, 'pre-commit'), 'utf8')).toContain(`# root=${canonicalMoved}`)
  292. expect(readFileSync(join(movedHooks, '.dsh-lefthook-owned'), 'utf8')).toContain(
  293. JSON.stringify(movedHooks),
  294. )
  295. })
  296. it.skipIf(process.platform === 'win32')('refuses a multiply linked ownership marker before relocation rewrites it', async () => {
  297. const fixture = createFixture()
  298. const oldRoot = fixture.main
  299. const first = await runInstaller(fixture, oldRoot)
  300. expect(first.status, first.stderr).toBe(0)
  301. const oldHooks = hooksPath(fixture, oldRoot)
  302. const markerName = '.dsh-lefthook-owned'
  303. const externalMarker = join(fixture.container, 'external-marker')
  304. linkSync(join(oldHooks, markerName), externalMarker)
  305. const externalContent = readFileSync(externalMarker, 'utf8')
  306. const movedRoot = join(fixture.container, 'moved-main')
  307. renameSync(oldRoot, movedRoot)
  308. const result = await runInstaller(fixture, movedRoot)
  309. expect(result.status).toBe(1)
  310. expect(result.stderr).toContain('invalid ownership marker')
  311. expect(readFileSync(externalMarker, 'utf8')).toBe(externalContent)
  312. })
  313. it.skipIf(process.platform === 'win32')('refuses aliased generated hooks before Lefthook can overwrite their targets', async () => {
  314. for (const kind of ['symlink', 'hardlink'] as const) {
  315. const fixture = createFixture()
  316. const first = await runInstaller(fixture, fixture.main)
  317. expect(first.status, first.stderr).toBe(0)
  318. const hook = join(hooksPath(fixture, fixture.main), 'pre-commit')
  319. const externalHook = join(fixture.container, `${kind}-external-hook`)
  320. rmSync(hook)
  321. write(externalHook, `external ${kind} target\n`)
  322. if (kind === 'symlink') symlinkSync(externalHook, hook)
  323. else linkSync(externalHook, hook)
  324. const externalContent = readFileSync(externalHook, 'utf8')
  325. const result = await runInstaller(fixture, fixture.main)
  326. expect(result.status).toBe(1)
  327. expect(result.stderr).toContain('non-regular or multiply linked hook entry')
  328. expect(readFileSync(externalHook, 'utf8')).toBe(externalContent)
  329. }
  330. })
  331. it('restores the marker-backed stale hook path when relocation reinstall fails', async () => {
  332. const fixture = createFixture()
  333. const oldRoot = fixture.main
  334. const first = await runInstaller(fixture, oldRoot)
  335. expect(first.status, first.stderr).toBe(0)
  336. const oldHooks = hooksPath(fixture, oldRoot)
  337. const markerName = '.dsh-lefthook-owned'
  338. const previousMarker = readFileSync(join(oldHooks, markerName), 'utf8')
  339. const movedRoot = join(fixture.container, 'moved-main')
  340. renameSync(oldRoot, movedRoot)
  341. const failed = await runInstaller(fixture, movedRoot, { DSH_TEST_LEFTHOOK_FAIL: '1' })
  342. expect(failed.status).toBe(1)
  343. expect(failed.stderr).toContain('exit status 77')
  344. const movedHooks = hooksPath(fixture, movedRoot)
  345. expect(git(fixture, movedRoot, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(oldHooks)
  346. expect(readFileSync(join(movedHooks, markerName), 'utf8')).toBe(previousMarker)
  347. })
  348. it('refuses dormant repository extensions before upgrading the repository format', async () => {
  349. const fixture = createFixture()
  350. const commonConfig = join(commonDirectory(fixture), 'config')
  351. git(fixture, fixture.main, ['config', 'extensions.dshUnknown', 'true'])
  352. expect(gitResult(fixture, fixture.main, ['status', '--porcelain']).status).toBe(0)
  353. const result = await runInstaller(fixture, fixture.main)
  354. expect(result.status).toBe(1)
  355. expect(result.stderr).toContain('dormant repository extension extensions.dshunknown')
  356. expect(git(fixture, fixture.main, [
  357. 'config', '--file', commonConfig, '--get', 'core.repositoryFormatVersion',
  358. ])).toBe('0')
  359. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  360. expect(gitResult(fixture, fixture.main, ['status', '--porcelain']).status).toBe(0)
  361. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  362. })
  363. it('refuses direct core.worktree before enabling worktree config', async () => {
  364. const fixture = createFixture()
  365. const commonConfig = join(commonDirectory(fixture), 'config')
  366. git(fixture, fixture.main, ['config', '--file', commonConfig, 'core.worktree', fixture.main])
  367. const result = await runInstaller(fixture, fixture.linked)
  368. expect(result.status).toBe(1)
  369. expect(result.stderr).toContain('core.worktree is in the common config')
  370. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  371. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  372. })
  373. it.skipIf(process.platform === 'win32')('refuses a symlinked common repository config before writing through it', async () => {
  374. const fixture = createFixture()
  375. const commonConfig = join(commonDirectory(fixture), 'config')
  376. const externalConfig = join(fixture.container, 'external-common.gitconfig')
  377. renameSync(commonConfig, externalConfig)
  378. symlinkSync(externalConfig, commonConfig)
  379. const externalContent = readFileSync(externalConfig, 'utf8')
  380. const result = await runInstaller(fixture, fixture.main)
  381. expect(result.status).toBe(1)
  382. expect(result.stderr).toContain('common repository config')
  383. expect(result.stderr).toContain('not a regular file')
  384. expect(lstatSync(commonConfig).isSymbolicLink()).toBe(true)
  385. expect(readFileSync(externalConfig, 'utf8')).toBe(externalContent)
  386. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  387. })
  388. it('leaves stale installer locks for explicit recovery', async () => {
  389. const fixture = createFixture()
  390. const lockPath = installLockPath(fixture)
  391. const completed = spawnSync(process.execPath, ['-e', ''])
  392. expect(completed.status).toBe(0)
  393. const staleRecord = `${String(completed.pid)} 00000000-0000-4000-8000-000000000000\n`
  394. writeFileSync(lockPath, staleRecord)
  395. const results = await Promise.all(Array.from(
  396. { length: 4 },
  397. () => runInstaller(fixture, fixture.main),
  398. ))
  399. for (const result of results) {
  400. expect(result.status).toBe(1)
  401. expect(result.stderr).toContain('stale Lefthook installer lock')
  402. expect(result.stderr).toContain('remove it manually')
  403. }
  404. expect(readFileSync(lockPath, 'utf8')).toBe(staleRecord)
  405. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  406. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  407. })
  408. it('leaves invalid installer locks for explicit recovery', async () => {
  409. const fixture = createFixture()
  410. const lockPath = installLockPath(fixture)
  411. const invalidRecord = 'not an installer lock\n'
  412. writeFileSync(lockPath, invalidRecord)
  413. const result = await runInstaller(fixture, fixture.main)
  414. expect(result.status).toBe(1)
  415. expect(result.stderr).toContain('invalid Lefthook installer lock')
  416. expect(result.stderr).toContain('remove it manually')
  417. expect(readFileSync(lockPath, 'utf8')).toBe(invalidRecord)
  418. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  419. })
  420. it('does not release an installer lock whose ownership changed', async () => {
  421. const fixture = createFixture()
  422. const lockPath = installLockPath(fixture)
  423. const runningPath = join(hooksPath(fixture, fixture.main), '.fake-lefthook-running')
  424. const install = runInstaller(fixture, fixture.main, { DSH_TEST_LEFTHOOK_DELAY_MS: '250' })
  425. await waitForPath(runningPath)
  426. const replacementRecord = 'replacement owner\n'
  427. writeFileSync(lockPath, replacementRecord)
  428. const result = await install
  429. expect(result.status).toBe(1)
  430. expect(result.stderr).toContain('installer lock ownership changed')
  431. expect(readFileSync(lockPath, 'utf8')).toBe(replacementRecord)
  432. })
  433. it.skipIf(process.platform === 'win32')('preserves trailing spaces in worktree paths', async () => {
  434. const fixture = createFixture({ main: 'main ', linked: 'linked ' })
  435. for (const root of [fixture.main, fixture.linked]) {
  436. const result = await runInstaller(fixture, root)
  437. expect(result.status, result.stderr).toBe(0)
  438. expect(git(fixture, root, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(hooksPath(fixture, root))
  439. }
  440. })
  441. it('preserves user-owned hook paths unless an inherited value is explicitly overridden', async () => {
  442. const fixture = createFixture()
  443. const customHook = join(fixture.main, 'custom-hooks/pre-commit')
  444. write(customHook, '#!/bin/sh\n# custom hook\n', 0o755)
  445. git(fixture, fixture.main, ['config', 'core.hooksPath', 'custom-hooks'])
  446. const refused = await runInstaller(fixture, fixture.main)
  447. expect(refused.status).toBe(1)
  448. expect(refused.stderr).toContain('refusing to replace user-owned core.hooksPath')
  449. expect(refused.stderr).toContain('DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE=1')
  450. expect(git(fixture, fixture.main, ['config', '--get', 'core.hooksPath'])).toBe('custom-hooks')
  451. expect(readFileSync(customHook, 'utf8')).toBe('#!/bin/sh\n# custom hook\n')
  452. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  453. const optedIn = await runInstaller(fixture, fixture.main, {
  454. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  455. })
  456. expect(optedIn.status, optedIn.stderr).toBe(0)
  457. expect(git(fixture, fixture.main, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(hooksPath(fixture, fixture.main))
  458. expect(git(fixture, fixture.linked, ['config', '--get', 'core.hooksPath'])).toBe('custom-hooks')
  459. expect(gitResult(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath']).status).toBe(1)
  460. expect(readFileSync(customHook, 'utf8')).toBe('#!/bin/sh\n# custom hook\n')
  461. git(fixture, fixture.linked, ['config', '--worktree', 'core.hooksPath', 'linked-custom-hooks'])
  462. const explicitWorktreePath = await runInstaller(fixture, fixture.linked, {
  463. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  464. })
  465. expect(explicitWorktreePath.status).toBe(1)
  466. expect(git(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe('linked-custom-hooks')
  467. })
  468. it('does not trust an ownership marker outside a registered worktree hook path', async () => {
  469. const fixture = createFixture()
  470. const mainInstall = await runInstaller(fixture, fixture.main)
  471. expect(mainInstall.status, mainInstall.stderr).toBe(0)
  472. const externalHooks = join(fixture.container, 'external-owned-hooks')
  473. write(
  474. join(externalHooks, '.dsh-lefthook-owned'),
  475. `${JSON.stringify({
  476. version: 1,
  477. owner: 'deepseek-harness worktree-local lefthook hooks',
  478. hooksPath: externalHooks,
  479. })}\n`,
  480. 0o600,
  481. )
  482. git(fixture, fixture.linked, ['config', '--worktree', 'core.hooksPath', externalHooks])
  483. const result = await runInstaller(fixture, fixture.linked)
  484. expect(result.status).toBe(1)
  485. expect(result.stderr).toContain('worktree-scoped core.hooksPath')
  486. expect(git(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(externalHooks)
  487. expect(existsSync(hooksPath(fixture, fixture.linked))).toBe(false)
  488. })
  489. it('refuses to activate a sibling worktree dormant hook path', async () => {
  490. const fixture = createFixture()
  491. const linkedConfig = join(gitDirectory(fixture, fixture.linked), 'config.worktree')
  492. const linkedHooks = join(fixture.linked, 'custom-hooks')
  493. git(fixture, fixture.main, ['config', '--file', linkedConfig, 'core.hooksPath', linkedHooks])
  494. expect(gitResult(fixture, fixture.linked, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  495. const result = await runInstaller(fixture, fixture.main)
  496. expect(result.status).toBe(1)
  497. expect(result.stderr).toContain('sibling dormant worktree config')
  498. expect(result.stderr).toContain(linkedConfig)
  499. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  500. expect(gitResult(fixture, fixture.linked, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  501. expect(git(fixture, fixture.main, ['config', '--file', linkedConfig, '--get', 'core.hooksPath'])).toBe(linkedHooks)
  502. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  503. })
  504. it.skipIf(process.platform === 'win32')('refuses an active symlinked worktree config before writing through it', async () => {
  505. const fixture = createFixture()
  506. const commonConfig = join(commonDirectory(fixture), 'config')
  507. const worktreeConfig = join(gitDirectory(fixture, fixture.main), 'config.worktree')
  508. const externalConfig = join(fixture.container, 'external.gitconfig')
  509. const externalContent = '[user]\n\tname = External owner\n'
  510. write(externalConfig, externalContent)
  511. git(fixture, fixture.main, ['config', '--file', commonConfig, 'core.repositoryFormatVersion', '1'])
  512. git(fixture, fixture.main, ['config', '--file', commonConfig, 'extensions.worktreeConfig', 'true'])
  513. symlinkSync(externalConfig, worktreeConfig)
  514. const result = await runInstaller(fixture, fixture.main)
  515. expect(result.status).toBe(1)
  516. expect(result.stderr).toContain('active worktree config')
  517. expect(result.stderr).toContain('not a regular file')
  518. expect(lstatSync(worktreeConfig).isSymbolicLink()).toBe(true)
  519. expect(readFileSync(externalConfig, 'utf8')).toBe(externalContent)
  520. expect(gitResult(fixture, fixture.main, [
  521. 'config', '--file', externalConfig, '--get', 'core.hooksPath',
  522. ]).status).toBe(1)
  523. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  524. })
  525. for (const includeKey of ['include.path', 'includeIf.onbranch:conditional.path']) {
  526. for (const key of ['core.worktree', 'core.bare', 'extensions.dshunknown']) {
  527. it(`ignores ${key} loaded through ${includeKey}`, async () => {
  528. const fixture = createFixture()
  529. const commonConfig = join(commonDirectory(fixture), 'config')
  530. const includedConfig = join(fixture.container, `${includeKey.split('.')[0]}-${key.replace('.', '-')}.gitconfig`)
  531. const value = key === 'core.worktree' ? fixture.main : 'true'
  532. git(fixture, fixture.main, ['config', '--file', includedConfig, key, value])
  533. git(fixture, fixture.main, ['config', '--file', commonConfig, includeKey, includedConfig])
  534. const result = await runInstaller(fixture, fixture.linked)
  535. expect(result.status, result.stderr).toBe(0)
  536. expect(git(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(
  537. hooksPath(fixture, fixture.linked),
  538. )
  539. expect(existsSync(join(hooksPath(fixture, fixture.linked), 'pre-commit'))).toBe(true)
  540. })
  541. }
  542. }
  543. it('ignores an inactive global includeIf that provides a hook path for another repository', async () => {
  544. const fixture = createFixture()
  545. const globalConfig = fixture.env.GIT_CONFIG_GLOBAL
  546. if (globalConfig === undefined) throw new Error('fixture global config path is missing')
  547. const includedConfig = join(fixture.container, 'other-repository.gitconfig')
  548. const includedHooks = join(fixture.container, 'other-repository-hooks')
  549. git(fixture, fixture.main, ['config', '--file', includedConfig, 'core.hooksPath', includedHooks])
  550. git(fixture, fixture.main, [
  551. 'config',
  552. '--file',
  553. globalConfig,
  554. `includeIf.gitdir:${join(fixture.container, 'other')}/.path`,
  555. includedConfig,
  556. ])
  557. const result = await runInstaller(fixture, fixture.linked)
  558. expect(result.status, result.stderr).toBe(0)
  559. expect(git(fixture, fixture.linked, ['config', '--get', 'core.hooksPath'])).toBe(hooksPath(fixture, fixture.linked))
  560. })
  561. it('never overrides a command-scoped hook path', async () => {
  562. const fixture = createFixture()
  563. const commandHooks = join(fixture.container, 'command-hooks')
  564. const sentinel = join(commandHooks, 'pre-commit')
  565. write(sentinel, '#!/bin/sh\n# command-scope sentinel\n', 0o755)
  566. const result = await runInstaller(fixture, fixture.main, {
  567. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  568. GIT_CONFIG_COUNT: '1',
  569. GIT_CONFIG_KEY_0: 'core.hooksPath',
  570. GIT_CONFIG_VALUE_0: commandHooks,
  571. })
  572. expect(result.status).toBe(1)
  573. expect(result.stderr).toContain('command-scoped core.hooksPath')
  574. expect(readFileSync(sentinel, 'utf8')).toBe('#!/bin/sh\n# command-scope sentinel\n')
  575. expect(gitResult(fixture, fixture.main, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  576. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  577. })
  578. it('does not pass unrelated command-scoped Git config to Lefthook', async () => {
  579. const fixture = createFixture()
  580. const result = await runInstaller(fixture, fixture.main, {
  581. DSH_TEST_FORBIDDEN_GIT_CONFIG_KEY: 'dsh.testSentinel',
  582. GIT_CONFIG_COUNT: '1',
  583. GIT_CONFIG_KEY_0: 'dsh.testSentinel',
  584. GIT_CONFIG_VALUE_0: 'must-not-reach-lefthook',
  585. })
  586. expect(result.status, result.stderr).toBe(0)
  587. expect(existsSync(join(hooksPath(fixture, fixture.main), 'pre-commit'))).toBe(true)
  588. })
  589. it('never overrides a hook path included by worktree config', async () => {
  590. const fixture = createFixture()
  591. const commonConfig = join(commonDirectory(fixture), 'config')
  592. const worktreeConfig = join(gitDirectory(fixture, fixture.main), 'config.worktree')
  593. const includedConfig = join(fixture.container, 'included-worktree.gitconfig')
  594. const includedHooks = join(fixture.container, 'included-hooks')
  595. const sentinel = join(includedHooks, 'pre-commit')
  596. write(sentinel, '#!/bin/sh\n# included-worktree sentinel\n', 0o755)
  597. git(fixture, fixture.main, ['config', '--file', includedConfig, 'core.hooksPath', includedHooks])
  598. git(fixture, fixture.main, ['config', '--file', commonConfig, 'core.repositoryFormatVersion', '1'])
  599. git(fixture, fixture.main, ['config', '--file', commonConfig, 'extensions.worktreeConfig', 'true'])
  600. git(fixture, fixture.main, ['config', '--file', worktreeConfig, 'include.path', includedConfig])
  601. const result = await runInstaller(fixture, fixture.main, {
  602. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  603. })
  604. expect(result.status).toBe(1)
  605. expect(result.stderr).toContain('worktree-scoped core.hooksPath')
  606. expect(git(fixture, fixture.main, ['config', '--get', 'core.hooksPath'])).toBe(includedHooks)
  607. expect(readFileSync(sentinel, 'utf8')).toBe('#!/bin/sh\n# included-worktree sentinel\n')
  608. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  609. })
  610. it('restores the previous hook lookup when Lefthook installation fails', async () => {
  611. const fixture = createFixture()
  612. const common = commonDirectory(fixture)
  613. const legacyHook = join(common, 'hooks/pre-push')
  614. write(legacyHook, '#!/bin/sh\n# legacy pre-push\n', 0o755)
  615. const result = await runInstaller(fixture, fixture.main, { DSH_TEST_LEFTHOOK_FAIL: '1' })
  616. expect(result.status).toBe(1)
  617. expect(result.stderr).toContain('exit status 77')
  618. expect(gitResult(fixture, fixture.main, ['config', '--worktree', '--get', 'core.hooksPath']).status).toBe(1)
  619. expect(gitResult(fixture, fixture.main, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  620. expect(readFileSync(legacyHook, 'utf8')).toBe('#!/bin/sh\n# legacy pre-push\n')
  621. })
  622. it('reports installation and hook-path rollback failures together', async () => {
  623. const fixture = createFixture()
  624. const result = await runInstaller(fixture, fixture.main, {
  625. DSH_TEST_LEFTHOOK_BREAK_WORKTREE_CONFIG: '1',
  626. DSH_TEST_LEFTHOOK_FAIL: '1',
  627. })
  628. expect(result.status).toBe(1)
  629. expect(result.stderr).toContain('Lefthook installation failed')
  630. expect(result.stderr).toContain('exit status 77')
  631. expect(result.stderr).toContain('worktree hook rollback also failed')
  632. expect(result.stderr).toContain('git config --worktree --unset-all core.hooksPath failed')
  633. })
  634. it('refuses an unowned directory at the reserved worktree hook path', async () => {
  635. const fixture = createFixture()
  636. const reservedHook = join(hooksPath(fixture, fixture.main), 'pre-commit')
  637. write(reservedHook, '#!/bin/sh\n# user content\n', 0o755)
  638. const result = await runInstaller(fixture, fixture.main)
  639. expect(result.status).toBe(1)
  640. expect(result.stderr).toContain('refusing to overwrite unowned hooks directory')
  641. expect(readFileSync(reservedHook, 'utf8')).toBe('#!/bin/sh\n# user content\n')
  642. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  643. })
  644. it.skipIf(process.platform === 'win32')('rejects Git without config-scope support before mutation', async () => {
  645. const fixture = createFixture()
  646. const realGit = commandResult('which', ['git'], fixture.main, fixture.env).stdout.trim()
  647. const fakeBin = join(fixture.container, 'fake-bin')
  648. const fakeGit = join(fakeBin, 'git')
  649. write(
  650. fakeGit,
  651. `#!/bin/sh\nif [ "$1" = "--version" ]; then echo "git version 2.25.0"; exit 0; fi\nexec "${realGit}" "$@"\n`,
  652. 0o755,
  653. )
  654. const result = await runInstaller(fixture, fixture.main, {
  655. PATH: `${fakeBin}:${fixture.env.PATH ?? ''}`,
  656. })
  657. expect(result.status).toBe(1)
  658. expect(result.stderr).toContain('Git 2.26 or newer is required')
  659. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  660. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  661. })
  662. })