git-command-manager.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 {GitVersion} from './git-version'
  7. // Auth header not supported before 2.9
  8. // Wire protocol v2 not supported before 2.18
  9. export const MinimumGitVersion = new GitVersion('2.18')
  10. export interface IGitCommandManager {
  11. branchDelete(remote: boolean, branch: string): Promise<void>
  12. branchExists(remote: boolean, pattern: string): Promise<boolean>
  13. branchList(remote: boolean): Promise<string[]>
  14. checkout(ref: string, startPoint: string): Promise<void>
  15. checkoutDetach(): Promise<void>
  16. config(configKey: string, configValue: string): Promise<void>
  17. configExists(configKey: string): Promise<boolean>
  18. fetch(fetchDepth: number, refSpec: string[]): Promise<void>
  19. getWorkingDirectory(): string
  20. init(): Promise<void>
  21. isDetached(): Promise<boolean>
  22. lfsFetch(ref: string): Promise<void>
  23. lfsInstall(): Promise<void>
  24. log1(): Promise<void>
  25. remoteAdd(remoteName: string, remoteUrl: string): Promise<void>
  26. tagExists(pattern: string): Promise<boolean>
  27. tryClean(): Promise<boolean>
  28. tryConfigUnset(configKey: string): Promise<boolean>
  29. tryDisableAutomaticGarbageCollection(): Promise<boolean>
  30. tryGetFetchUrl(): Promise<string>
  31. tryReset(): Promise<boolean>
  32. }
  33. export async function CreateCommandManager(
  34. workingDirectory: string,
  35. lfs: boolean
  36. ): Promise<IGitCommandManager> {
  37. return await GitCommandManager.createCommandManager(workingDirectory, lfs)
  38. }
  39. class GitCommandManager {
  40. private gitEnv = {
  41. GIT_TERMINAL_PROMPT: '0', // Disable git prompt
  42. GCM_INTERACTIVE: 'Never' // Disable prompting for git credential manager
  43. }
  44. private gitPath = ''
  45. private lfs = false
  46. private workingDirectory = ''
  47. // Private constructor; use createCommandManager()
  48. private constructor() {}
  49. async branchDelete(remote: boolean, branch: string): Promise<void> {
  50. const args = ['branch', '--delete', '--force']
  51. if (remote) {
  52. args.push('--remote')
  53. }
  54. args.push(branch)
  55. await this.execGit(args)
  56. }
  57. async branchExists(remote: boolean, pattern: string): Promise<boolean> {
  58. const args = ['branch', '--list']
  59. if (remote) {
  60. args.push('--remote')
  61. }
  62. args.push(pattern)
  63. const output = await this.execGit(args)
  64. return !!output.stdout.trim()
  65. }
  66. async branchList(remote: boolean): Promise<string[]> {
  67. const result: string[] = []
  68. // Note, this implementation uses "rev-parse --symbolic" because the output from
  69. // "branch --list" is more difficult when in a detached HEAD state.
  70. const args = ['rev-parse', '--symbolic']
  71. if (remote) {
  72. args.push('--remotes=origin')
  73. } else {
  74. args.push('--branches')
  75. }
  76. const output = await this.execGit(args)
  77. for (let branch of output.stdout.trim().split('\n')) {
  78. branch = branch.trim()
  79. if (branch) {
  80. result.push(branch)
  81. }
  82. }
  83. return result
  84. }
  85. async checkout(ref: string, startPoint: string): Promise<void> {
  86. const args = ['checkout', '--progress', '--force']
  87. if (startPoint) {
  88. args.push('-B', ref, startPoint)
  89. } else {
  90. args.push(ref)
  91. }
  92. await this.execGit(args)
  93. }
  94. async checkoutDetach(): Promise<void> {
  95. const args = ['checkout', '--detach']
  96. await this.execGit(args)
  97. }
  98. async config(configKey: string, configValue: string): Promise<void> {
  99. await this.execGit(['config', configKey, configValue])
  100. }
  101. async configExists(configKey: string): Promise<boolean> {
  102. const pattern = configKey.replace(/[^a-zA-Z0-9_]/g, x => {
  103. return `\\${x}`
  104. })
  105. const output = await this.execGit(
  106. ['config', '--name-only', '--get-regexp', pattern],
  107. true
  108. )
  109. return output.exitCode === 0
  110. }
  111. async fetch(fetchDepth: number, refSpec: string[]): Promise<void> {
  112. const args = [
  113. '-c',
  114. 'protocol.version=2',
  115. 'fetch',
  116. '--no-tags',
  117. '--prune',
  118. '--progress',
  119. '--no-recurse-submodules'
  120. ]
  121. if (fetchDepth > 0) {
  122. args.push(`--depth=${fetchDepth}`)
  123. } else if (
  124. fshelper.fileExistsSync(
  125. path.join(this.workingDirectory, '.git', 'shallow')
  126. )
  127. ) {
  128. args.push('--unshallow')
  129. }
  130. args.push('origin')
  131. for (const arg of refSpec) {
  132. args.push(arg)
  133. }
  134. let attempt = 1
  135. const maxAttempts = 3
  136. while (attempt <= maxAttempts) {
  137. const allowAllExitCodes = attempt < maxAttempts
  138. const output = await this.execGit(args, allowAllExitCodes)
  139. if (output.exitCode === 0) {
  140. break
  141. }
  142. const seconds = this.getRandomIntInclusive(1, 10)
  143. core.warning(
  144. `Git fetch failed with exit code ${output.exitCode}. Waiting ${seconds} seconds before trying again.`
  145. )
  146. await this.sleep(seconds * 1000)
  147. attempt++
  148. }
  149. }
  150. getWorkingDirectory(): string {
  151. return this.workingDirectory
  152. }
  153. async init(): Promise<void> {
  154. await this.execGit(['init', this.workingDirectory])
  155. }
  156. async isDetached(): Promise<boolean> {
  157. // Note, this implementation uses "branch --show-current" because
  158. // "rev-parse --symbolic-full-name HEAD" can fail on a new repo
  159. // with nothing checked out.
  160. const output = await this.execGit(['branch', '--show-current'])
  161. return output.stdout.trim() === ''
  162. }
  163. async lfsFetch(ref: string): Promise<void> {
  164. const args = ['lfs', 'fetch', 'origin', ref]
  165. let attempt = 1
  166. const maxAttempts = 3
  167. while (attempt <= maxAttempts) {
  168. const allowAllExitCodes = attempt < maxAttempts
  169. const output = await this.execGit(args, allowAllExitCodes)
  170. if (output.exitCode === 0) {
  171. break
  172. }
  173. const seconds = this.getRandomIntInclusive(1, 10)
  174. core.warning(
  175. `Git lfs fetch failed with exit code ${output.exitCode}. Waiting ${seconds} seconds before trying again.`
  176. )
  177. await this.sleep(seconds * 1000)
  178. attempt++
  179. }
  180. }
  181. async lfsInstall(): Promise<void> {
  182. await this.execGit(['lfs', 'install', '--local'])
  183. }
  184. async log1(): Promise<void> {
  185. await this.execGit(['log', '-1'])
  186. }
  187. async remoteAdd(remoteName: string, remoteUrl: string): Promise<void> {
  188. await this.execGit(['remote', 'add', remoteName, remoteUrl])
  189. }
  190. async tagExists(pattern: string): Promise<boolean> {
  191. const output = await this.execGit(['tag', '--list', pattern])
  192. return !!output.stdout.trim()
  193. }
  194. async tryClean(): Promise<boolean> {
  195. const output = await this.execGit(['clean', '-ffdx'], true)
  196. return output.exitCode === 0
  197. }
  198. async tryConfigUnset(configKey: string): Promise<boolean> {
  199. const output = await this.execGit(
  200. ['config', '--unset-all', configKey],
  201. true
  202. )
  203. return output.exitCode === 0
  204. }
  205. async tryDisableAutomaticGarbageCollection(): Promise<boolean> {
  206. const output = await this.execGit(['config', 'gc.auto', '0'], true)
  207. return output.exitCode === 0
  208. }
  209. async tryGetFetchUrl(): Promise<string> {
  210. const output = await this.execGit(
  211. ['config', '--get', 'remote.origin.url'],
  212. true
  213. )
  214. if (output.exitCode !== 0) {
  215. return ''
  216. }
  217. const stdout = output.stdout.trim()
  218. if (stdout.includes('\n')) {
  219. return ''
  220. }
  221. return stdout
  222. }
  223. async tryReset(): Promise<boolean> {
  224. const output = await this.execGit(['reset', '--hard', 'HEAD'], true)
  225. return output.exitCode === 0
  226. }
  227. static async createCommandManager(
  228. workingDirectory: string,
  229. lfs: boolean
  230. ): Promise<GitCommandManager> {
  231. const result = new GitCommandManager()
  232. await result.initializeCommandManager(workingDirectory, lfs)
  233. return result
  234. }
  235. private async execGit(
  236. args: string[],
  237. allowAllExitCodes = false
  238. ): Promise<GitOutput> {
  239. fshelper.directoryExistsSync(this.workingDirectory, true)
  240. const result = new GitOutput()
  241. const env = {}
  242. for (const key of Object.keys(process.env)) {
  243. env[key] = process.env[key]
  244. }
  245. for (const key of Object.keys(this.gitEnv)) {
  246. env[key] = this.gitEnv[key]
  247. }
  248. const stdout: string[] = []
  249. const options = {
  250. cwd: this.workingDirectory,
  251. env,
  252. ignoreReturnCode: allowAllExitCodes,
  253. listeners: {
  254. stdout: (data: Buffer) => {
  255. stdout.push(data.toString())
  256. }
  257. }
  258. }
  259. result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options)
  260. result.stdout = stdout.join('')
  261. return result
  262. }
  263. private async initializeCommandManager(
  264. workingDirectory: string,
  265. lfs: boolean
  266. ): Promise<void> {
  267. this.workingDirectory = workingDirectory
  268. // Git-lfs will try to pull down assets if any of the local/user/system setting exist.
  269. // If the user didn't enable `LFS` in their pipeline definition, disable LFS fetch/checkout.
  270. this.lfs = lfs
  271. if (!this.lfs) {
  272. this.gitEnv['GIT_LFS_SKIP_SMUDGE'] = '1'
  273. }
  274. this.gitPath = await io.which('git', true)
  275. // Git version
  276. core.debug('Getting git version')
  277. let gitVersion = new GitVersion()
  278. let gitOutput = await this.execGit(['version'])
  279. let stdout = gitOutput.stdout.trim()
  280. if (!stdout.includes('\n')) {
  281. const match = stdout.match(/\d+\.\d+(\.\d+)?/)
  282. if (match) {
  283. gitVersion = new GitVersion(match[0])
  284. }
  285. }
  286. if (!gitVersion.isValid()) {
  287. throw new Error('Unable to determine git version')
  288. }
  289. // Minimum git version
  290. if (!gitVersion.checkMinimum(MinimumGitVersion)) {
  291. throw new Error(
  292. `Minimum required git version is ${MinimumGitVersion}. Your git ('${this.gitPath}') is ${gitVersion}`
  293. )
  294. }
  295. if (this.lfs) {
  296. // Git-lfs version
  297. core.debug('Getting git-lfs version')
  298. let gitLfsVersion = new GitVersion()
  299. const gitLfsPath = await io.which('git-lfs', true)
  300. gitOutput = await this.execGit(['lfs', 'version'])
  301. stdout = gitOutput.stdout.trim()
  302. if (!stdout.includes('\n')) {
  303. const match = stdout.match(/\d+\.\d+(\.\d+)?/)
  304. if (match) {
  305. gitLfsVersion = new GitVersion(match[0])
  306. }
  307. }
  308. if (!gitLfsVersion.isValid()) {
  309. throw new Error('Unable to determine git-lfs version')
  310. }
  311. // Minimum git-lfs version
  312. // Note:
  313. // - Auth header not supported before 2.1
  314. const minimumGitLfsVersion = new GitVersion('2.1')
  315. if (!gitLfsVersion.checkMinimum(minimumGitLfsVersion)) {
  316. throw new Error(
  317. `Minimum required git-lfs version is ${minimumGitLfsVersion}. Your git-lfs ('${gitLfsPath}') is ${gitLfsVersion}`
  318. )
  319. }
  320. }
  321. // Set the user agent
  322. const gitHttpUserAgent = `git/${gitVersion} (github-actions-checkout)`
  323. core.debug(`Set git useragent to: ${gitHttpUserAgent}`)
  324. this.gitEnv['GIT_HTTP_USER_AGENT'] = gitHttpUserAgent
  325. }
  326. private getRandomIntInclusive(minimum: number, maximum: number): number {
  327. minimum = Math.floor(minimum)
  328. maximum = Math.floor(maximum)
  329. return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum
  330. }
  331. private async sleep(milliseconds): Promise<void> {
  332. return new Promise(resolve => setTimeout(resolve, milliseconds))
  333. }
  334. }
  335. class GitOutput {
  336. stdout = ''
  337. exitCode = 0
  338. }