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