From a1904ec6a96b04cd93eeb622b04cf328a10083df Mon Sep 17 00:00:00 2001 From: Alexander Rinass Date: Fri, 12 Jun 2020 11:12:01 +0200 Subject: [PATCH] fix: Git directory is not correctly resolved if GIT_WORK_TREE is set to relative path (#887) Resolving the git directory failed if the environment variable `GIT_WORK_TREE` is set to a relative path and lint-staged is run from a subdirectory of a Git repository (e.g. multi-package repos). `GIT_WORK_TREE` can be used to set the worktree directory for a Git repo. `GIT_DIR` specifies only the `.git` directory path. `git rev-parse --show-toplevel` will return the Git worktree directory. If it is set to a relative path, it won't work when git commands are called from a subdirectory, as the relative path will fail to resolve correctly. While `GIT_DIR` is unset in `resolveGitRepo.js`, `GIT_WORK_TREE` was not. Unsetting `GIT_WORK_TREE` in the same place fixes the issue. --- lib/resolveGitRepo.js | 2 ++ test/resolveGitRepo.spec.js | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/lib/resolveGitRepo.js b/lib/resolveGitRepo.js index d194da039..a3e550998 100644 --- a/lib/resolveGitRepo.js +++ b/lib/resolveGitRepo.js @@ -35,6 +35,8 @@ const resolveGitRepo = async (cwd) => { // Unset GIT_DIR before running any git operations in case it's pointing to an incorrect location debugLog('Unset GIT_DIR (was `%s`)', process.env.GIT_DIR) delete process.env.GIT_DIR + debugLog('Unset GIT_WORK_TREE (was `%s`)', process.env.GIT_WORK_TREE) + delete process.env.GIT_WORK_TREE const gitDir = normalize(await execGit(['rev-parse', '--show-toplevel'], { cwd })) const gitConfigDir = normalize(await resolveGitConfigDir(gitDir)) diff --git a/test/resolveGitRepo.spec.js b/test/resolveGitRepo.spec.js index 11666bd95..46086ab41 100644 --- a/test/resolveGitRepo.spec.js +++ b/test/resolveGitRepo.spec.js @@ -34,6 +34,16 @@ describe('resolveGitRepo', () => { process.cwd = processCwdBkp }) + it('should resolve to the parent dir when .git is in the parent dir even when the GIT_WORK_TREE environment variable is set', async () => { + const expected = normalize(path.dirname(__dirname)) + const processCwdBkp = process.cwd + process.cwd = () => __dirname + process.env.GIT_WORK_TREE = './wrong/path/' + const { gitDir } = await resolveGitRepo() + expect(gitDir).toEqual(expected) + process.cwd = processCwdBkp + }) + it('should return null when not in a git directory', async () => { const { gitDir } = await resolveGitRepo({ cwd: '/' }) // assume root is not a git directory expect(gitDir).toEqual(null)