opts.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const fs = require('node:fs')
  2. const os = require('node:os')
  3. const path = require('node:path')
  4. const ini = require('ini')
  5. const gitConfigPath = path.join(os.homedir(), '.gitconfig')
  6. let cachedConfig = null
  7. // Function to load and cache the git config
  8. const loadGitConfig = () => {
  9. if (cachedConfig === null) {
  10. try {
  11. cachedConfig = {}
  12. if (fs.existsSync(gitConfigPath)) {
  13. const configContent = fs.readFileSync(gitConfigPath, 'utf-8')
  14. cachedConfig = ini.parse(configContent)
  15. }
  16. } catch (error) {
  17. cachedConfig = {}
  18. }
  19. }
  20. return cachedConfig
  21. }
  22. const checkGitConfigs = () => {
  23. const config = loadGitConfig()
  24. return {
  25. sshCommandSetInConfig: config?.core?.sshCommand !== undefined,
  26. askPassSetInConfig: config?.core?.askpass !== undefined,
  27. }
  28. }
  29. const sshCommandSetInEnv = process.env.GIT_SSH_COMMAND !== undefined
  30. const askPassSetInEnv = process.env.GIT_ASKPASS !== undefined
  31. const { sshCommandSetInConfig, askPassSetInConfig } = checkGitConfigs()
  32. // Values we want to set if they're not already defined by the end user
  33. // This defaults to accepting new ssh host key fingerprints
  34. const finalGitEnv = {
  35. ...(askPassSetInEnv || askPassSetInConfig ? {} : {
  36. GIT_ASKPASS: 'echo',
  37. }),
  38. ...(sshCommandSetInEnv || sshCommandSetInConfig ? {} : {
  39. GIT_SSH_COMMAND: 'ssh -oStrictHostKeyChecking=accept-new',
  40. }),
  41. }
  42. module.exports = (opts = {}) => ({
  43. stdioString: true,
  44. ...opts,
  45. shell: false,
  46. env: opts.env || { ...finalGitEnv, ...process.env },
  47. })
  48. // Export the loadGitConfig function for testing
  49. module.exports.loadGitConfig = loadGitConfig