Skip to content

Commit

Permalink
fix: use native git command to get .git directory
Browse files Browse the repository at this point in the history
  • Loading branch information
iiroj committed Jun 11, 2024
1 parent e0386dc commit 119adb2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 30 deletions.
5 changes: 5 additions & 0 deletions .changeset/stale-ants-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'lint-staged': patch
---

Use native "git rev-parse" commands to determine git repo root directory and the .git config directory, instead of using custom logic. This hopefully makes path resolution more robust on non-POSIX systems.
34 changes: 4 additions & 30 deletions lib/resolveGitRepo.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,10 @@
import fs from 'node:fs/promises'
import path from 'node:path'

import debug from 'debug'

import { execGit } from './execGit.js'
import { readFile } from './file.js'
import { normalizePath } from './normalizePath.js'

const debugLog = debug('lint-staged:resolveGitRepo')

/**
* Resolve path to the .git directory, with special handling for
* submodules and worktrees
*/
const resolveGitConfigDir = async (gitDir) => {
// Get the real path in case it's a symlink
const defaultDir = path.join(gitDir, '.git')
const stats = await fs.lstat(defaultDir)

// If .git is a directory, use it
if (stats.isDirectory()) {
return defaultDir
}

// If .git is a symlink, return the real location
if (stats.isSymbolicLink()) {
return await fs.realpath(gitDir)
}

// Otherwise .git is a file containing path to real location
const file = (await readFile(defaultDir)).toString()
return path.resolve(gitDir, file.replace(/^gitdir: /, '')).trim()
}

/**
* Resolve git directory and possible submodule paths
*/
Expand All @@ -49,9 +21,11 @@ export const resolveGitRepo = async (cwd = process.cwd()) => {
const gitDir = normalizePath(
await execGit(['rev-parse', '--path-format=absolute', '--show-toplevel'], { cwd })
)
const gitConfigDir = normalizePath(await resolveGitConfigDir(gitDir))

debugLog('Resolved git directory to be `%s`', gitDir)

const gitConfigDir = normalizePath(
await execGit(['rev-parse', '--path-format=absolute', '--absolute-git-dir'], { cwd })
)
debugLog('Resolved git config directory to be `%s`', gitConfigDir)

return { gitDir, gitConfigDir }
Expand Down

0 comments on commit 119adb2

Please sign in to comment.