Skip to content

Commit

Permalink
fix: Git directory is not correctly resolved if GIT_WORK_TREE is set …
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
alexrinass authored Jun 12, 2020
1 parent 0daae61 commit a1904ec
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/resolveGitRepo.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
10 changes: 10 additions & 0 deletions test/resolveGitRepo.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit a1904ec

Please sign in to comment.