git-command-manager.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import * as core from '@actions/core'
  2. import * as exec from '@actions/exec'
  3. import * as fshelper from './fs-helper'
  4. import * as io from '@actions/io'
  5. import * as path from 'path'
  6. import * as regexpHelper from './regexp-helper'
  7. import * as retryHelper from './retry-helper'
  8. import {GitVersion} from './git-version'
  9. // Auth header not supported before 2.9
  10. // Wire protocol v2 not supported before 2.18
  11. export const MinimumGitVersion = new GitVersion('2.18')
  12. export interface IGitCommandManager {
  13. branchDelete(remote: boolean, branch: string): Promise<void>
  14. branchExists(remote: boolean, pattern: string): Promise<boolean>
  15. branchList(remote: boolean): Promise<string[]>
  16. checkout(ref: string, startPoint: string): Promise<void>
  17. checkoutDetach(): Promise<void>
  18. config(
  19. configKey: string,
  20. configValue: string,
  21. globalConfig?: boolean
  22. ): Promise<void>
  23. configExists(configKey: string, globalConfig?: boolean): Promise<boolean>
  24. fetch(fetchDepth: number, refSpec: string[]): Promise<void>
  25. getWorkingDirectory(): string
  26. init(): Promise<void>
  27. isDetached(): Promise<boolean>
  28. lfsFetch(ref: string): Promise<void>
  29. lfsInstall(): Promise<void>
  30. log1(): Promise<void>
  31. remoteAdd(remoteName: string, remoteUrl: string): Promise<void>
  32. removeEnvironmentVariable(name: string): void
  33. setEnvironmentVariable(name: string, value: string): void
  34. setRemoteUrl(url: string): Promise<void>
  35. submoduleForeach(command: string, recursive: boolean): Promise<string>
  36. submoduleSync(recursive: boolean): Promise<void>
  37. submoduleUpdate(fetchDepth: number, recursive: boolean): Promise<void>
  38. tagExists(pattern: string): Promise<boolean>
  39. tryClean(): Promise<boolean>
  40. tryConfigUnset(configKey: string, globalConfig?: boolean): Promise<boolean>
  41. tryDisableAutomaticGarbageCollection(): Promise<boolean>
  42. tryGetRemoteUrl(): Promise<string>
  43. tryReset(): Promise<boolean>
  44. }
  45. export async function createCommandManager(
  46. workingDirectory: string,
  47. lfs: boolean
  48. ): Promise<IGitCommandManager> {
  49. return await GitCommandManager.createCommandManager(workingDirectory, lfs)
  50. }
  51. class GitCommandManager {
  52. private gitEnv = {
  53. GIT_TERMINAL_PROMPT: '0', // Disable git prompt
  54. GCM_INTERACTIVE: 'Never' // Disable prompting for git credential manager
  55. }
  56. private gitPath = ''
  57. private lfs = false
  58. private workingDirectory = ''
  59. // Private constructor; use createCommandManager()
  60. private constructor() {}
  61. async branchDelete(remote: boolean, branch: string): Promise<void> {
  62. const args = ['branch', '--delete', '--force']
  63. if (remote) {
  64. args.push('--remote')
  65. }
  66. args.push(branch)
  67. await this.execGit(args)
  68. }
  69. async branchExists(remote: boolean, pattern: string): Promise<boolean> {
  70. const args = ['branch', '--list']
  71. if (remote) {
  72. args.push('--remote')
  73. }
  74. args.push(pattern)
  75. const output = await this.execGit(args)
  76. return !!output.stdout.trim()
  77. }
  78. async branchList(remote: boolean): Promise<string[]> {
  79. const result: string[] = []
  80. // Note, this implementation uses "rev-parse --symbolic-full-name" because the output from
  81. // "branch --list" is more difficult when in a detached HEAD state.
  82. // Note, this implementation uses "rev-parse --symbolic-full-name" because there is a bug
  83. // in Git 2.18 that causes "rev-parse --symbolic" to output symbolic full names.
  84. const args = ['rev-parse', '--symbolic-full-name']
  85. if (remote) {
  86. args.push('--remotes=origin')
  87. } else {
  88. args.push('--branches')
  89. }
  90. const output = await this.execGit(args)
  91. for (let branch of output.stdout.trim().split('\n')) {
  92. branch = branch.trim()
  93. if (branch) {
  94. if (branch.startsWith('refs/heads/')) {
  95. branch = branch.substr('refs/heads/'.length)
  96. } else if (branch.startsWith('refs/remotes/')) {
  97. branch = branch.substr('refs/remotes/'.length)
  98. }
  99. result.push(branch)
  100. }
  101. }
  102. return result
  103. }
  104. async checkout(ref: string, startPoint: string): Promise<void> {
  105. const args = ['checkout', '--progress', '--force']
  106. if (startPoint) {
  107. args.push('-B', ref, startPoint)
  108. } else {
  109. args.push(ref)
  110. }
  111. await this.execGit(args)
  112. }
  113. async checkoutDetach(): Promise<void> {
  114. const args = ['checkout', '--detach']
  115. await this.execGit(args)
  116. }
  117. async config(
  118. configKey: string,
  119. configValue: string,
  120. globalConfig?: boolean
  121. ): Promise<void> {
  122. await this.execGit([
  123. 'config',
  124. globalConfig ? '--global' : '--local',
  125. configKey,
  126. configValue
  127. ])
  128. }
  129. async configExists(
  130. configKey: string,
  131. globalConfig?: boolean
  132. ): Promise<boolean> {
  133. const pattern = regexpHelper.escape(configKey)
  134. const output = await this.execGit(
  135. [
  136. 'config',
  137. globalConfig ? '--global' : '--local',
  138. '--name-only',
  139. '--get-regexp',
  140. pattern
  141. ],
  142. true
  143. )
  144. return output.exitCode === 0
  145. }
  146. async fetch(fetchDepth: number, refSpec: string[]): Promise<void> {
  147. const args = [
  148. '-c',
  149. 'protocol.version=2',
  150. 'fetch',
  151. '--no-tags',
  152. '--prune',
  153. '--progress',
  154. '--no-recurse-submodules'
  155. ]
  156. if (fetchDepth > 0) {
  157. args.push(`--depth=${fetchDepth}`)
  158. } else if (
  159. fshelper.fileExistsSync(
  160. path.join(this.workingDirectory, '.git', 'shallow')
  161. )
  162. ) {
  163. args.push('--unshallow')
  164. }
  165. args.push('origin')
  166. for (const arg of refSpec) {
  167. args.push(arg)
  168. }
  169. const that = this
  170. await retryHelper.execute(async () => {
  171. await that.execGit(args)
  172. })
  173. }
  174. getWorkingDirectory(): string {
  175. return this.workingDirectory
  176. }
  177. async init(): Promise<void> {
  178. await this.execGit(['init', this.workingDirectory])
  179. }
  180. async isDetached(): Promise<boolean> {
  181. // Note, "branch --show-current" would be simpler but isn't available until Git 2.22
  182. const output = await this.execGit(
  183. ['rev-parse', '--symbolic-full-name', '--verify', '--quiet', 'HEAD'],
  184. true
  185. )
  186. return !output.stdout.trim().startsWith('refs/heads/')
  187. }
  188. async lfsFetch(ref: string): Promise<void> {
  189. const args = ['lfs', 'fetch', 'origin', ref]
  190. const that = this
  191. await retryHelper.execute(async () => {
  192. await that.execGit(args)
  193. })
  194. }
  195. async lfsInstall(): Promise<void> {
  196. await this.execGit(['lfs', 'install', '--local'])
  197. }
  198. async log1(): Promise<void> {
  199. await this.execGit(['log', '-1'])
  200. }
  201. async remoteAdd(remoteName: string, remoteUrl: string): Promise<void> {
  202. await this.execGit(['remote', 'add', remoteName, remoteUrl])
  203. }
  204. removeEnvironmentVariable(name: string): void {
  205. delete this.gitEnv[name]
  206. }
  207. setEnvironmentVariable(name: string, value: string): void {
  208. this.gitEnv[name] = value
  209. }
  210. async setRemoteUrl(value: string): Promise<void> {
  211. await this.config('git.remote.url', value)
  212. }
  213. async submoduleForeach(command: string, recursive: boolean): Promise<string> {
  214. const args = ['submodule', 'foreach']
  215. if (recursive) {
  216. args.push('--recursive')
  217. }
  218. args.push(command)
  219. const output = await this.execGit(args)
  220. return output.stdout
  221. }
  222. async submoduleSync(recursive: boolean): Promise<void> {
  223. const args = ['submodule', 'sync']
  224. if (recursive) {
  225. args.push('--recursive')
  226. }
  227. await this.execGit(args)
  228. }
  229. async submoduleUpdate(fetchDepth: number, recursive: boolean): Promise<void> {
  230. const args = ['-c', 'protocol.version=2']
  231. args.push('submodule', 'update', '--init', '--force')
  232. if (fetchDepth > 0) {
  233. args.push(`--depth=${fetchDepth}`)
  234. }
  235. if (recursive) {
  236. args.push('--recursive')
  237. }
  238. await this.execGit(args)
  239. }
  240. async tagExists(pattern: string): Promise<boolean> {
  241. const output = await this.execGit(['tag', '--list', pattern])
  242. return !!output.stdout.trim()
  243. }
  244. async tryClean(): Promise<boolean> {
  245. const output = await this.execGit(['clean', '-ffdx'], true)
  246. return output.exitCode === 0
  247. }
  248. async tryConfigUnset(
  249. configKey: string,
  250. globalConfig?: boolean
  251. ): Promise<boolean> {
  252. const output = await this.execGit(
  253. [
  254. 'config',
  255. globalConfig ? '--global' : '--local',
  256. '--unset-all',
  257. configKey
  258. ],
  259. true
  260. )
  261. return output.exitCode === 0
  262. }
  263. async tryDisableAutomaticGarbageCollection(): Promise<boolean> {
  264. const output = await this.execGit(
  265. ['config', '--local', 'gc.auto', '0'],
  266. true
  267. )
  268. return output.exitCode === 0
  269. }
  270. async tryGetRemoteUrl(): Promise<string> {
  271. const output = await this.execGit(
  272. ['config', '--local', '--get', 'remote.origin.url'],
  273. true
  274. )
  275. if (output.exitCode !== 0) {
  276. return ''
  277. }
  278. const stdout = output.stdout.trim()
  279. if (stdout.includes('\n')) {
  280. return ''
  281. }
  282. return stdout
  283. }
  284. async tryReset(): Promise<boolean> {
  285. const output = await this.execGit(['reset', '--hard', 'HEAD'], true)
  286. return output.exitCode === 0
  287. }
  288. static async createCommandManager(
  289. workingDirectory: string,
  290. lfs: boolean
  291. ): Promise<GitCommandManager> {
  292. const result = new GitCommandManager()
  293. await result.initializeCommandManager(workingDirectory, lfs)
  294. return result
  295. }
  296. private async execGit(
  297. args: string[],
  298. allowAllExitCodes = false
  299. ): Promise<GitOutput> {
  300. fshelper.directoryExistsSync(this.workingDirectory, true)
  301. const result = new GitOutput()
  302. const env = {}
  303. for (const key of Object.keys(process.env)) {
  304. env[key] = process.env[key]
  305. }
  306. for (const key of Object.keys(this.gitEnv)) {
  307. env[key] = this.gitEnv[key]
  308. }
  309. const stdout: string[] = []
  310. const options = {
  311. cwd: this.workingDirectory,
  312. env,
  313. ignoreReturnCode: allowAllExitCodes,
  314. listeners: {
  315. stdout: (data: Buffer) => {
  316. stdout.push(data.toString())
  317. }
  318. }
  319. }
  320. result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options)
  321. result.stdout = stdout.join('')
  322. return result
  323. }
  324. private async initializeCommandManager(
  325. workingDirectory: string,
  326. lfs: boolean
  327. ): Promise<void> {
  328. this.workingDirectory = workingDirectory
  329. // Git-lfs will try to pull down assets if any of the local/user/system setting exist.
  330. // If the user didn't enable `LFS` in their pipeline definition, disable LFS fetch/checkout.
  331. this.lfs = lfs
  332. if (!this.lfs) {
  333. this.gitEnv['GIT_LFS_SKIP_SMUDGE'] = '1'
  334. }
  335. this.gitPath = await io.which('git', true)
  336. // Git version
  337. core.debug('Getting git version')
  338. let gitVersion = new GitVersion()
  339. let gitOutput = await this.execGit(['version'])
  340. let stdout = gitOutput.stdout.trim()
  341. if (!stdout.includes('\n')) {
  342. const match = stdout.match(/\d+\.\d+(\.\d+)?/)
  343. if (match) {
  344. gitVersion = new GitVersion(match[0])
  345. }
  346. }
  347. if (!gitVersion.isValid()) {
  348. throw new Error('Unable to determine git version')
  349. }
  350. // Minimum git version
  351. if (!gitVersion.checkMinimum(MinimumGitVersion)) {
  352. throw new Error(
  353. `Minimum required git version is ${MinimumGitVersion}. Your git ('${this.gitPath}') is ${gitVersion}`
  354. )
  355. }
  356. if (this.lfs) {
  357. // Git-lfs version
  358. core.debug('Getting git-lfs version')
  359. let gitLfsVersion = new GitVersion()
  360. const gitLfsPath = await io.which('git-lfs', true)
  361. gitOutput = await this.execGit(['lfs', 'version'])
  362. stdout = gitOutput.stdout.trim()
  363. if (!stdout.includes('\n')) {
  364. const match = stdout.match(/\d+\.\d+(\.\d+)?/)
  365. if (match) {
  366. gitLfsVersion = new GitVersion(match[0])
  367. }
  368. }
  369. if (!gitLfsVersion.isValid()) {
  370. throw new Error('Unable to determine git-lfs version')
  371. }
  372. // Minimum git-lfs version
  373. // Note:
  374. // - Auth header not supported before 2.1
  375. const minimumGitLfsVersion = new GitVersion('2.1')
  376. if (!gitLfsVersion.checkMinimum(minimumGitLfsVersion)) {
  377. throw new Error(
  378. `Minimum required git-lfs version is ${minimumGitLfsVersion}. Your git-lfs ('${gitLfsPath}') is ${gitLfsVersion}`
  379. )
  380. }
  381. }
  382. // Set the user agent
  383. const gitHttpUserAgent = `git/${gitVersion} (github-actions-checkout)`
  384. core.debug(`Set git useragent to: ${gitHttpUserAgent}`)
  385. this.gitEnv['GIT_HTTP_USER_AGENT'] = gitHttpUserAgent
  386. }
  387. }
  388. class GitOutput {
  389. stdout = ''
  390. exitCode = 0
  391. }