ba1425315bdebffe04b6ec464e6593b241b9591651445305f29f2cda5f29aa62d48ae3f69176c9b199479f42d9c3f3624d3935723973c9271e1526bd3e741b 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict'
  2. const normalize = require('normalize-path')
  3. const debugLog = require('debug')('lint-staged:resolveGitRepo')
  4. const fs = require('fs')
  5. const path = require('path')
  6. const { promisify } = require('util')
  7. const execGit = require('./execGit')
  8. const { readFile } = require('./file')
  9. const fsLstat = promisify(fs.lstat)
  10. /**
  11. * Resolve path to the .git directory, with special handling for
  12. * submodules and worktrees
  13. */
  14. const resolveGitConfigDir = async (gitDir) => {
  15. const defaultDir = normalize(path.join(gitDir, '.git'))
  16. const stats = await fsLstat(defaultDir)
  17. // If .git is a directory, use it
  18. if (stats.isDirectory()) return defaultDir
  19. // Otherwise .git is a file containing path to real location
  20. const file = (await readFile(defaultDir)).toString()
  21. return path.resolve(gitDir, file.replace(/^gitdir: /, '')).trim()
  22. }
  23. /**
  24. * Resolve git directory and possible submodule paths
  25. */
  26. const resolveGitRepo = async (cwd) => {
  27. try {
  28. debugLog('Resolving git repo from `%s`', cwd)
  29. // Unset GIT_DIR before running any git operations in case it's pointing to an incorrect location
  30. debugLog('Unset GIT_DIR (was `%s`)', process.env.GIT_DIR)
  31. delete process.env.GIT_DIR
  32. debugLog('Unset GIT_WORK_TREE (was `%s`)', process.env.GIT_WORK_TREE)
  33. delete process.env.GIT_WORK_TREE
  34. const gitDir = normalize(await execGit(['rev-parse', '--show-toplevel'], { cwd }))
  35. const gitConfigDir = normalize(await resolveGitConfigDir(gitDir))
  36. debugLog('Resolved git directory to be `%s`', gitDir)
  37. debugLog('Resolved git config directory to be `%s`', gitConfigDir)
  38. return { gitDir, gitConfigDir }
  39. } catch (error) {
  40. debugLog('Failed to resolve git repo with error:', error)
  41. return { error, gitDir: null, gitConfigDir: null }
  42. }
  43. }
  44. module.exports = resolveGitRepo