git-command-manager.ts 10 KB

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