From b4c2d5c9701c58be1300101aa4459ba6a058542f Mon Sep 17 00:00:00 2001 From: Jimmy Rowland Date: Thu, 23 Jun 2022 14:19:01 -0700 Subject: [PATCH] add .git to regex to get git project root from worktree directory --- simple-git-hooks.js | 2 +- simple-git-hooks.test.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/simple-git-hooks.js b/simple-git-hooks.js index 6ac5e3f..0c54ae0 100644 --- a/simple-git-hooks.js +++ b/simple-git-hooks.js @@ -59,7 +59,7 @@ function getGitProjectRoot(directory=process.cwd()) { if (fs.existsSync(fullPath)) { if(!fs.lstatSync(fullPath).isDirectory()) { let content = fs.readFileSync(fullPath, { encoding: 'utf-8' }) - let match = /^gitdir: (.*)\s*$/.exec(content) + let match = /^gitdir: (.*\.git)((\/.*)|(\s*))/.exec(content) if (match) { return path.normalize(match[1]) } diff --git a/simple-git-hooks.test.js b/simple-git-hooks.test.js index 137891b..1dc6a8b 100644 --- a/simple-git-hooks.test.js +++ b/simple-git-hooks.test.js @@ -4,6 +4,8 @@ const path = require("path") const { version: packageVersion } = require('./package.json'); +// eslint-disable-next-line no-unused-vars +const fsMock = jest.mock('fs') // Get project root directory @@ -44,6 +46,34 @@ test('get git root works from any file', () => { }) +function mockFsImplementation(gitdir){ + const mocks = [ + jest.spyOn(fs, 'existsSync').mockImplementation(()=>true), + jest.spyOn(fs, 'lstatSync').mockImplementation(()=>({ + isDirectory: jest.fn(()=>false) + })), + jest.spyOn(fs, 'readFileSync').mockImplementation(()=>gitdir) + ] + return ()=> mocks.forEach(mock=>mock.mockRestore()) +} + +const gitRoot = '/home/user/projects/simple-git-hooks/.git'; +const workTreePath = '/home/user/projects/worktree1'; +const workTreeTestFilePath = '/home/user/projects/worktree1/simple-git-hooks.test.js'; + +test('get git root works from worktree directory', () => { + const clearMocks = mockFsImplementation('gitdir: /home/user/projects/simple-git-hooks/.git/worktrees/worktree1') + expect(spc.getGitProjectRoot(workTreePath)).toBe(gitRoot); + clearMocks(); +}) + +test('get git root works from any file', () => { + const clearMocks = mockFsImplementation('gitdir: /home/user/projects/simple-git-hooks/.git/worktrees/worktree1') + expect(spc.getGitProjectRoot(workTreeTestFilePath)).toBe(gitRoot); + clearMocks(); +}) + + // Check if simple-pre-commit is in devDependencies or dependencies in package json const correctPackageJsonProjectPath = path.normalize(path.join(process.cwd(), '_tests', 'project_with_simple_pre_commit_in_deps'))