install-lefthook.spec.ts 36 KB

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