install-lefthook.spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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', { timeout: 15_000 }, () => {
  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('waits for a concurrent installer to finish publishing its lock record', async () => {
  278. const fixture = createFixture()
  279. const lockPath = installLockPath(fixture)
  280. const publishing = runInstaller(fixture, fixture.main, {
  281. DSH_TEST_LEFTHOOK_LOCK_WRITE_DELAY_MS: '200',
  282. })
  283. await waitForPath(lockPath)
  284. expect(readFileSync(lockPath, 'utf8')).toBe('')
  285. const waiting = runInstaller(fixture, fixture.linked)
  286. const results = await Promise.all([publishing, waiting])
  287. for (const result of results) expect(result.status, result.stderr).toBe(0)
  288. expect(existsSync(lockPath)).toBe(false)
  289. })
  290. it('repairs its owned absolute hook path after the checkout moves', async () => {
  291. const fixture = createFixture()
  292. const oldRoot = fixture.main
  293. const first = await runInstaller(fixture, oldRoot)
  294. expect(first.status, first.stderr).toBe(0)
  295. const oldHooks = hooksPath(fixture, oldRoot)
  296. const movedRoot = join(fixture.container, 'moved-main')
  297. renameSync(oldRoot, movedRoot)
  298. const moved = await runInstaller(fixture, movedRoot)
  299. expect(moved.status, moved.stderr).toBe(0)
  300. const movedHooks = hooksPath(fixture, movedRoot)
  301. expect(movedHooks).not.toBe(oldHooks)
  302. expect(git(fixture, movedRoot, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(movedHooks)
  303. const canonicalMoved = git(fixture, movedRoot, ['rev-parse', '--show-toplevel'])
  304. expect(readFileSync(join(movedHooks, 'pre-commit'), 'utf8')).toContain(`# root=${canonicalMoved}`)
  305. expect(readFileSync(join(movedHooks, '.dsh-lefthook-owned'), 'utf8')).toContain(
  306. JSON.stringify(movedHooks),
  307. )
  308. })
  309. it.skipIf(process.platform === 'win32')('refuses a multiply linked ownership marker before relocation rewrites it', async () => {
  310. const fixture = createFixture()
  311. const oldRoot = fixture.main
  312. const first = await runInstaller(fixture, oldRoot)
  313. expect(first.status, first.stderr).toBe(0)
  314. const oldHooks = hooksPath(fixture, oldRoot)
  315. const markerName = '.dsh-lefthook-owned'
  316. const externalMarker = join(fixture.container, 'external-marker')
  317. linkSync(join(oldHooks, markerName), externalMarker)
  318. const externalContent = readFileSync(externalMarker, 'utf8')
  319. const movedRoot = join(fixture.container, 'moved-main')
  320. renameSync(oldRoot, movedRoot)
  321. const result = await runInstaller(fixture, movedRoot)
  322. expect(result.status).toBe(1)
  323. expect(result.stderr).toContain('invalid ownership marker')
  324. expect(readFileSync(externalMarker, 'utf8')).toBe(externalContent)
  325. })
  326. it.skipIf(process.platform === 'win32')('refuses aliased generated hooks before Lefthook can overwrite their targets', async () => {
  327. for (const kind of ['symlink', 'hardlink'] as const) {
  328. const fixture = createFixture()
  329. const first = await runInstaller(fixture, fixture.main)
  330. expect(first.status, first.stderr).toBe(0)
  331. const hook = join(hooksPath(fixture, fixture.main), 'pre-commit')
  332. const externalHook = join(fixture.container, `${kind}-external-hook`)
  333. rmSync(hook)
  334. write(externalHook, `external ${kind} target\n`)
  335. if (kind === 'symlink') symlinkSync(externalHook, hook)
  336. else linkSync(externalHook, hook)
  337. const externalContent = readFileSync(externalHook, 'utf8')
  338. const result = await runInstaller(fixture, fixture.main)
  339. expect(result.status).toBe(1)
  340. expect(result.stderr).toContain('non-regular or multiply linked hook entry')
  341. expect(readFileSync(externalHook, 'utf8')).toBe(externalContent)
  342. }
  343. })
  344. it('restores the marker-backed stale hook path when relocation reinstall fails', async () => {
  345. const fixture = createFixture()
  346. const oldRoot = fixture.main
  347. const first = await runInstaller(fixture, oldRoot)
  348. expect(first.status, first.stderr).toBe(0)
  349. const oldHooks = hooksPath(fixture, oldRoot)
  350. const markerName = '.dsh-lefthook-owned'
  351. const previousMarker = readFileSync(join(oldHooks, markerName), 'utf8')
  352. const movedRoot = join(fixture.container, 'moved-main')
  353. renameSync(oldRoot, movedRoot)
  354. const failed = await runInstaller(fixture, movedRoot, { DSH_TEST_LEFTHOOK_FAIL: '1' })
  355. expect(failed.status).toBe(1)
  356. expect(failed.stderr).toContain('exit status 77')
  357. const movedHooks = hooksPath(fixture, movedRoot)
  358. expect(git(fixture, movedRoot, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(oldHooks)
  359. expect(readFileSync(join(movedHooks, markerName), 'utf8')).toBe(previousMarker)
  360. })
  361. it('refuses dormant repository extensions before upgrading the repository format', async () => {
  362. const fixture = createFixture()
  363. const commonConfig = join(commonDirectory(fixture), 'config')
  364. git(fixture, fixture.main, ['config', 'extensions.dshUnknown', 'true'])
  365. expect(gitResult(fixture, fixture.main, ['status', '--porcelain']).status).toBe(0)
  366. const result = await runInstaller(fixture, fixture.main)
  367. expect(result.status).toBe(1)
  368. expect(result.stderr).toContain('dormant repository extension extensions.dshunknown')
  369. expect(git(fixture, fixture.main, [
  370. 'config', '--file', commonConfig, '--get', 'core.repositoryFormatVersion',
  371. ])).toBe('0')
  372. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  373. expect(gitResult(fixture, fixture.main, ['status', '--porcelain']).status).toBe(0)
  374. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  375. })
  376. it('refuses direct core.worktree before enabling worktree config', async () => {
  377. const fixture = createFixture()
  378. const commonConfig = join(commonDirectory(fixture), 'config')
  379. git(fixture, fixture.main, ['config', '--file', commonConfig, 'core.worktree', fixture.main])
  380. const result = await runInstaller(fixture, fixture.linked)
  381. expect(result.status).toBe(1)
  382. expect(result.stderr).toContain('core.worktree is in the common config')
  383. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  384. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  385. })
  386. it.skipIf(process.platform === 'win32')('refuses a symlinked common repository config before writing through it', async () => {
  387. const fixture = createFixture()
  388. const commonConfig = join(commonDirectory(fixture), 'config')
  389. const externalConfig = join(fixture.container, 'external-common.gitconfig')
  390. renameSync(commonConfig, externalConfig)
  391. symlinkSync(externalConfig, commonConfig)
  392. const externalContent = readFileSync(externalConfig, 'utf8')
  393. const result = await runInstaller(fixture, fixture.main)
  394. expect(result.status).toBe(1)
  395. expect(result.stderr).toContain('common repository config')
  396. expect(result.stderr).toContain('not a regular file')
  397. expect(lstatSync(commonConfig).isSymbolicLink()).toBe(true)
  398. expect(readFileSync(externalConfig, 'utf8')).toBe(externalContent)
  399. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  400. })
  401. it('leaves stale installer locks for explicit recovery', async () => {
  402. const fixture = createFixture()
  403. const lockPath = installLockPath(fixture)
  404. const completed = spawnSync(process.execPath, ['-e', ''])
  405. expect(completed.status).toBe(0)
  406. const staleRecord = `${String(completed.pid)} 00000000-0000-4000-8000-000000000000\n`
  407. writeFileSync(lockPath, staleRecord)
  408. const results = await Promise.all(Array.from(
  409. { length: 4 },
  410. () => runInstaller(fixture, fixture.main),
  411. ))
  412. for (const result of results) {
  413. expect(result.status).toBe(1)
  414. expect(result.stderr).toContain('stale Lefthook installer lock')
  415. expect(result.stderr).toContain('remove it manually')
  416. }
  417. expect(readFileSync(lockPath, 'utf8')).toBe(staleRecord)
  418. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  419. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  420. })
  421. it('leaves invalid installer locks for explicit recovery', async () => {
  422. const fixture = createFixture()
  423. const lockPath = installLockPath(fixture)
  424. const invalidRecord = 'not an installer lock\n'
  425. writeFileSync(lockPath, invalidRecord)
  426. const result = await runInstaller(fixture, fixture.main)
  427. expect(result.status).toBe(1)
  428. expect(result.stderr).toContain('invalid Lefthook installer lock')
  429. expect(result.stderr).toContain('remove it manually')
  430. expect(readFileSync(lockPath, 'utf8')).toBe(invalidRecord)
  431. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  432. })
  433. it('does not release an installer lock whose ownership changed', async () => {
  434. const fixture = createFixture()
  435. const lockPath = installLockPath(fixture)
  436. const runningPath = join(hooksPath(fixture, fixture.main), '.fake-lefthook-running')
  437. const install = runInstaller(fixture, fixture.main, { DSH_TEST_LEFTHOOK_DELAY_MS: '250' })
  438. await waitForPath(runningPath)
  439. const replacementRecord = 'replacement owner\n'
  440. writeFileSync(lockPath, replacementRecord)
  441. const result = await install
  442. expect(result.status).toBe(1)
  443. expect(result.stderr).toContain('installer lock ownership changed')
  444. expect(readFileSync(lockPath, 'utf8')).toBe(replacementRecord)
  445. })
  446. it.skipIf(process.platform === 'win32')('preserves trailing spaces in worktree paths', async () => {
  447. const fixture = createFixture({ main: 'main ', linked: 'linked ' })
  448. for (const root of [fixture.main, fixture.linked]) {
  449. const result = await runInstaller(fixture, root)
  450. expect(result.status, result.stderr).toBe(0)
  451. expect(git(fixture, root, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(hooksPath(fixture, root))
  452. }
  453. })
  454. it('preserves user-owned hook paths unless an inherited value is explicitly overridden', async () => {
  455. const fixture = createFixture()
  456. const customHook = join(fixture.main, 'custom-hooks/pre-commit')
  457. write(customHook, '#!/bin/sh\n# custom hook\n', 0o755)
  458. git(fixture, fixture.main, ['config', 'core.hooksPath', 'custom-hooks'])
  459. const refused = await runInstaller(fixture, fixture.main)
  460. expect(refused.status).toBe(1)
  461. expect(refused.stderr).toContain('refusing to replace user-owned core.hooksPath')
  462. expect(refused.stderr).toContain('DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE=1')
  463. expect(git(fixture, fixture.main, ['config', '--get', 'core.hooksPath'])).toBe('custom-hooks')
  464. expect(readFileSync(customHook, 'utf8')).toBe('#!/bin/sh\n# custom hook\n')
  465. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  466. const optedIn = await runInstaller(fixture, fixture.main, {
  467. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  468. })
  469. expect(optedIn.status, optedIn.stderr).toBe(0)
  470. expect(git(fixture, fixture.main, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(hooksPath(fixture, fixture.main))
  471. expect(git(fixture, fixture.linked, ['config', '--get', 'core.hooksPath'])).toBe('custom-hooks')
  472. expect(gitResult(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath']).status).toBe(1)
  473. expect(readFileSync(customHook, 'utf8')).toBe('#!/bin/sh\n# custom hook\n')
  474. git(fixture, fixture.linked, ['config', '--worktree', 'core.hooksPath', 'linked-custom-hooks'])
  475. const explicitWorktreePath = await runInstaller(fixture, fixture.linked, {
  476. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  477. })
  478. expect(explicitWorktreePath.status).toBe(1)
  479. expect(git(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe('linked-custom-hooks')
  480. })
  481. it('does not trust an ownership marker outside a registered worktree hook path', async () => {
  482. const fixture = createFixture()
  483. const mainInstall = await runInstaller(fixture, fixture.main)
  484. expect(mainInstall.status, mainInstall.stderr).toBe(0)
  485. const externalHooks = join(fixture.container, 'external-owned-hooks')
  486. write(
  487. join(externalHooks, '.dsh-lefthook-owned'),
  488. `${JSON.stringify({
  489. version: 1,
  490. owner: 'deepseek-harness worktree-local lefthook hooks',
  491. hooksPath: externalHooks,
  492. })}\n`,
  493. 0o600,
  494. )
  495. git(fixture, fixture.linked, ['config', '--worktree', 'core.hooksPath', externalHooks])
  496. const result = await runInstaller(fixture, fixture.linked)
  497. expect(result.status).toBe(1)
  498. expect(result.stderr).toContain('worktree-scoped core.hooksPath')
  499. expect(git(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(externalHooks)
  500. expect(existsSync(hooksPath(fixture, fixture.linked))).toBe(false)
  501. })
  502. it('refuses to activate a sibling worktree dormant hook path', async () => {
  503. const fixture = createFixture()
  504. const linkedConfig = join(gitDirectory(fixture, fixture.linked), 'config.worktree')
  505. const linkedHooks = join(fixture.linked, 'custom-hooks')
  506. git(fixture, fixture.main, ['config', '--file', linkedConfig, 'core.hooksPath', linkedHooks])
  507. expect(gitResult(fixture, fixture.linked, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  508. const result = await runInstaller(fixture, fixture.main)
  509. expect(result.status).toBe(1)
  510. expect(result.stderr).toContain('sibling dormant worktree config')
  511. expect(result.stderr).toContain(linkedConfig)
  512. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  513. expect(gitResult(fixture, fixture.linked, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  514. expect(git(fixture, fixture.main, ['config', '--file', linkedConfig, '--get', 'core.hooksPath'])).toBe(linkedHooks)
  515. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  516. })
  517. it.skipIf(process.platform === 'win32')('refuses an active symlinked worktree config before writing through it', async () => {
  518. const fixture = createFixture()
  519. const commonConfig = join(commonDirectory(fixture), 'config')
  520. const worktreeConfig = join(gitDirectory(fixture, fixture.main), 'config.worktree')
  521. const externalConfig = join(fixture.container, 'external.gitconfig')
  522. const externalContent = '[user]\n\tname = External owner\n'
  523. write(externalConfig, externalContent)
  524. git(fixture, fixture.main, ['config', '--file', commonConfig, 'core.repositoryFormatVersion', '1'])
  525. git(fixture, fixture.main, ['config', '--file', commonConfig, 'extensions.worktreeConfig', 'true'])
  526. symlinkSync(externalConfig, worktreeConfig)
  527. const result = await runInstaller(fixture, fixture.main)
  528. expect(result.status).toBe(1)
  529. expect(result.stderr).toContain('active worktree config')
  530. expect(result.stderr).toContain('not a regular file')
  531. expect(lstatSync(worktreeConfig).isSymbolicLink()).toBe(true)
  532. expect(readFileSync(externalConfig, 'utf8')).toBe(externalContent)
  533. expect(gitResult(fixture, fixture.main, [
  534. 'config', '--file', externalConfig, '--get', 'core.hooksPath',
  535. ]).status).toBe(1)
  536. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  537. })
  538. for (const includeKey of ['include.path', 'includeIf.onbranch:conditional.path']) {
  539. for (const key of ['core.worktree', 'core.bare', 'extensions.dshunknown']) {
  540. it(`ignores ${key} loaded through ${includeKey}`, async () => {
  541. const fixture = createFixture()
  542. const commonConfig = join(commonDirectory(fixture), 'config')
  543. const includedConfig = join(fixture.container, `${includeKey.split('.')[0]}-${key.replace('.', '-')}.gitconfig`)
  544. const value = key === 'core.worktree' ? fixture.main : 'true'
  545. git(fixture, fixture.main, ['config', '--file', includedConfig, key, value])
  546. git(fixture, fixture.main, ['config', '--file', commonConfig, includeKey, includedConfig])
  547. const result = await runInstaller(fixture, fixture.linked)
  548. expect(result.status, result.stderr).toBe(0)
  549. expect(git(fixture, fixture.linked, ['config', '--worktree', '--get', 'core.hooksPath'])).toBe(
  550. hooksPath(fixture, fixture.linked),
  551. )
  552. expect(existsSync(join(hooksPath(fixture, fixture.linked), 'pre-commit'))).toBe(true)
  553. })
  554. }
  555. }
  556. it('ignores an inactive global includeIf that provides a hook path for another repository', async () => {
  557. const fixture = createFixture()
  558. const globalConfig = fixture.env.GIT_CONFIG_GLOBAL
  559. if (globalConfig === undefined) throw new Error('fixture global config path is missing')
  560. const includedConfig = join(fixture.container, 'other-repository.gitconfig')
  561. const includedHooks = join(fixture.container, 'other-repository-hooks')
  562. git(fixture, fixture.main, ['config', '--file', includedConfig, 'core.hooksPath', includedHooks])
  563. git(fixture, fixture.main, [
  564. 'config',
  565. '--file',
  566. globalConfig,
  567. `includeIf.gitdir:${join(fixture.container, 'other')}/.path`,
  568. includedConfig,
  569. ])
  570. const result = await runInstaller(fixture, fixture.linked)
  571. expect(result.status, result.stderr).toBe(0)
  572. expect(git(fixture, fixture.linked, ['config', '--get', 'core.hooksPath'])).toBe(hooksPath(fixture, fixture.linked))
  573. })
  574. it('never overrides a command-scoped hook path', async () => {
  575. const fixture = createFixture()
  576. const commandHooks = join(fixture.container, 'command-hooks')
  577. const sentinel = join(commandHooks, 'pre-commit')
  578. write(sentinel, '#!/bin/sh\n# command-scope sentinel\n', 0o755)
  579. const result = await runInstaller(fixture, fixture.main, {
  580. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  581. GIT_CONFIG_COUNT: '1',
  582. GIT_CONFIG_KEY_0: 'core.hooksPath',
  583. GIT_CONFIG_VALUE_0: commandHooks,
  584. })
  585. expect(result.status).toBe(1)
  586. expect(result.stderr).toContain('command-scoped core.hooksPath')
  587. expect(readFileSync(sentinel, 'utf8')).toBe('#!/bin/sh\n# command-scope sentinel\n')
  588. expect(gitResult(fixture, fixture.main, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  589. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  590. })
  591. it('does not pass unrelated command-scoped Git config to Lefthook', async () => {
  592. const fixture = createFixture()
  593. const result = await runInstaller(fixture, fixture.main, {
  594. DSH_TEST_FORBIDDEN_GIT_CONFIG_KEY: 'dsh.testSentinel',
  595. GIT_CONFIG_COUNT: '1',
  596. GIT_CONFIG_KEY_0: 'dsh.testSentinel',
  597. GIT_CONFIG_VALUE_0: 'must-not-reach-lefthook',
  598. })
  599. expect(result.status, result.stderr).toBe(0)
  600. expect(existsSync(join(hooksPath(fixture, fixture.main), 'pre-commit'))).toBe(true)
  601. })
  602. it('never overrides a hook path included by worktree config', async () => {
  603. const fixture = createFixture()
  604. const commonConfig = join(commonDirectory(fixture), 'config')
  605. const worktreeConfig = join(gitDirectory(fixture, fixture.main), 'config.worktree')
  606. const includedConfig = join(fixture.container, 'included-worktree.gitconfig')
  607. const includedHooks = join(fixture.container, 'included-hooks')
  608. const sentinel = join(includedHooks, 'pre-commit')
  609. write(sentinel, '#!/bin/sh\n# included-worktree sentinel\n', 0o755)
  610. git(fixture, fixture.main, ['config', '--file', includedConfig, 'core.hooksPath', includedHooks])
  611. git(fixture, fixture.main, ['config', '--file', commonConfig, 'core.repositoryFormatVersion', '1'])
  612. git(fixture, fixture.main, ['config', '--file', commonConfig, 'extensions.worktreeConfig', 'true'])
  613. git(fixture, fixture.main, ['config', '--file', worktreeConfig, 'include.path', includedConfig])
  614. const result = await runInstaller(fixture, fixture.main, {
  615. DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE: '1',
  616. })
  617. expect(result.status).toBe(1)
  618. expect(result.stderr).toContain('worktree-scoped core.hooksPath')
  619. expect(git(fixture, fixture.main, ['config', '--get', 'core.hooksPath'])).toBe(includedHooks)
  620. expect(readFileSync(sentinel, 'utf8')).toBe('#!/bin/sh\n# included-worktree sentinel\n')
  621. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  622. })
  623. it('restores the previous hook lookup when Lefthook installation fails', async () => {
  624. const fixture = createFixture()
  625. const common = commonDirectory(fixture)
  626. const legacyHook = join(common, 'hooks/pre-push')
  627. write(legacyHook, '#!/bin/sh\n# legacy pre-push\n', 0o755)
  628. const result = await runInstaller(fixture, fixture.main, { DSH_TEST_LEFTHOOK_FAIL: '1' })
  629. expect(result.status).toBe(1)
  630. expect(result.stderr).toContain('exit status 77')
  631. expect(gitResult(fixture, fixture.main, ['config', '--worktree', '--get', 'core.hooksPath']).status).toBe(1)
  632. expect(gitResult(fixture, fixture.main, ['config', '--get', 'core.hooksPath']).status).toBe(1)
  633. expect(readFileSync(legacyHook, 'utf8')).toBe('#!/bin/sh\n# legacy pre-push\n')
  634. })
  635. it('reports installation and hook-path rollback failures together', async () => {
  636. const fixture = createFixture()
  637. const result = await runInstaller(fixture, fixture.main, {
  638. DSH_TEST_LEFTHOOK_BREAK_WORKTREE_CONFIG: '1',
  639. DSH_TEST_LEFTHOOK_FAIL: '1',
  640. })
  641. expect(result.status).toBe(1)
  642. expect(result.stderr).toContain('Lefthook installation failed')
  643. expect(result.stderr).toContain('exit status 77')
  644. expect(result.stderr).toContain('worktree hook rollback also failed')
  645. expect(result.stderr).toContain('git config --worktree --unset-all core.hooksPath failed')
  646. })
  647. it('refuses an unowned directory at the reserved worktree hook path', async () => {
  648. const fixture = createFixture()
  649. const reservedHook = join(hooksPath(fixture, fixture.main), 'pre-commit')
  650. write(reservedHook, '#!/bin/sh\n# user content\n', 0o755)
  651. const result = await runInstaller(fixture, fixture.main)
  652. expect(result.status).toBe(1)
  653. expect(result.stderr).toContain('refusing to overwrite unowned hooks directory')
  654. expect(readFileSync(reservedHook, 'utf8')).toBe('#!/bin/sh\n# user content\n')
  655. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  656. })
  657. it.skipIf(process.platform === 'win32')('rejects Git without config-scope support before mutation', async () => {
  658. const fixture = createFixture()
  659. const realGit = commandResult('which', ['git'], fixture.main, fixture.env).stdout.trim()
  660. const fakeBin = join(fixture.container, 'fake-bin')
  661. const fakeGit = join(fakeBin, 'git')
  662. write(
  663. fakeGit,
  664. `#!/bin/sh\nif [ "$1" = "--version" ]; then echo "git version 2.25.0"; exit 0; fi\nexec "${realGit}" "$@"\n`,
  665. 0o755,
  666. )
  667. const result = await runInstaller(fixture, fixture.main, {
  668. PATH: `${fakeBin}:${fixture.env.PATH ?? ''}`,
  669. })
  670. expect(result.status).toBe(1)
  671. expect(result.stderr).toContain('Git 2.26 or newer is required')
  672. expect(gitResult(fixture, fixture.main, ['config', '--get', 'extensions.worktreeConfig']).status).toBe(1)
  673. expect(existsSync(hooksPath(fixture, fixture.main))).toBe(false)
  674. })
  675. })