Skip to content

Commit b4c2d5c

Browse files
committed
add .git to regex to get git project root from worktree directory
1 parent d65a692 commit b4c2d5c

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

simple-git-hooks.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ function getGitProjectRoot(directory=process.cwd()) {
5959
if (fs.existsSync(fullPath)) {
6060
if(!fs.lstatSync(fullPath).isDirectory()) {
6161
let content = fs.readFileSync(fullPath, { encoding: 'utf-8' })
62-
let match = /^gitdir: (.*)\s*$/.exec(content)
62+
let match = /^gitdir: (.*\.git)((\/.*)|(\s*))/.exec(content)
6363
if (match) {
6464
return path.normalize(match[1])
6565
}

simple-git-hooks.test.js

+30
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ const path = require("path")
44

55
const { version: packageVersion } = require('./package.json');
66

7+
// eslint-disable-next-line no-unused-vars
8+
const fsMock = jest.mock('fs')
79

810
// Get project root directory
911

@@ -44,6 +46,34 @@ test('get git root works from any file', () => {
4446
})
4547

4648

49+
function mockFsImplementation(gitdir){
50+
const mocks = [
51+
jest.spyOn(fs, 'existsSync').mockImplementation(()=>true),
52+
jest.spyOn(fs, 'lstatSync').mockImplementation(()=>({
53+
isDirectory: jest.fn(()=>false)
54+
})),
55+
jest.spyOn(fs, 'readFileSync').mockImplementation(()=>gitdir)
56+
]
57+
return ()=> mocks.forEach(mock=>mock.mockRestore())
58+
}
59+
60+
const gitRoot = '/home/user/projects/simple-git-hooks/.git';
61+
const workTreePath = '/home/user/projects/worktree1';
62+
const workTreeTestFilePath = '/home/user/projects/worktree1/simple-git-hooks.test.js';
63+
64+
test('get git root works from worktree directory', () => {
65+
const clearMocks = mockFsImplementation('gitdir: /home/user/projects/simple-git-hooks/.git/worktrees/worktree1')
66+
expect(spc.getGitProjectRoot(workTreePath)).toBe(gitRoot);
67+
clearMocks();
68+
})
69+
70+
test('get git root works from any file', () => {
71+
const clearMocks = mockFsImplementation('gitdir: /home/user/projects/simple-git-hooks/.git/worktrees/worktree1')
72+
expect(spc.getGitProjectRoot(workTreeTestFilePath)).toBe(gitRoot);
73+
clearMocks();
74+
})
75+
76+
4777
// Check if simple-pre-commit is in devDependencies or dependencies in package json
4878

4979
const correctPackageJsonProjectPath = path.normalize(path.join(process.cwd(), '_tests', 'project_with_simple_pre_commit_in_deps'))

0 commit comments

Comments
 (0)