git-command-manager.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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" because the output from
  70. // "branch --list" is more difficult when in a detached HEAD state.
  71. const args = ['rev-parse', '--symbolic']
  72. if (remote) {
  73. args.push('--remotes=origin')
  74. } else {
  75. args.push('--branches')
  76. }
  77. const output = await this.execGit(args)
  78. for (let branch of output.stdout.trim().split('\n')) {
  79. branch = branch.trim()
  80. if (branch) {
  81. result.push(branch)
  82. }
  83. }
  84. return result
  85. }
  86. async checkout(ref: string, startPoint: string): Promise<void> {
  87. const args = ['checkout', '--progress', '--force']
  88. if (startPoint) {
  89. args.push('-B', ref, startPoint)
  90. } else {
  91. args.push(ref)
  92. }
  93. await this.execGit(args)
  94. }
  95. async checkoutDetach(): Promise<void> {
  96. const args = ['checkout', '--detach']
  97. await this.execGit(args)
  98. }
  99. async config(configKey: string, configValue: string): Promise<void> {
  100. await this.execGit(['config', '--local', configKey, configValue])
  101. }
  102. async configExists(configKey: string): Promise<boolean> {
  103. const pattern = configKey.replace(/[^a-zA-Z0-9_]/g, x => {
  104. return `\\${x}`
  105. })
  106. const output = await this.execGit(
  107. ['config', '--local', '--name-only', '--get-regexp', pattern],
  108. true
  109. )
  110. return output.exitCode === 0
  111. }
  112. async fetch(fetchDepth: number, refSpec: string[]): Promise<void> {
  113. const args = [
  114. '-c',
  115. 'protocol.version=2',
  116. 'fetch',
  117. '--no-tags',
  118. '--prune',
  119. '--progress',
  120. '--no-recurse-submodules'
  121. ]
  122. if (fetchDepth > 0) {
  123. args.push(`--depth=${fetchDepth}`)
  124. } else if (
  125. fshelper.fileExistsSync(
  126. path.join(this.workingDirectory, '.git', 'shallow')
  127. )
  128. ) {
  129. args.push('--unshallow')
  130. }
  131. args.push('origin')
  132. for (const arg of refSpec) {
  133. args.push(arg)
  134. }
  135. const that = this
  136. await retryHelper.execute(async () => {
  137. await that.execGit(args)
  138. })
  139. }
  140. getWorkingDirectory(): string {
  141. return this.workingDirectory
  142. }
  143. async init(): Promise<void> {
  144. await this.execGit(['init', this.workingDirectory])
  145. }
  146. async isDetached(): Promise<boolean> {
  147. // Note, this implementation uses "branch --show-current" because
  148. // "rev-parse --symbolic-full-name HEAD" can fail on a new repo
  149. // with nothing checked out.
  150. const output = await this.execGit(['branch', '--show-current'])
  151. return output.stdout.trim() === ''
  152. }
  153. async lfsFetch(ref: string): Promise<void> {
  154. const args = ['lfs', 'fetch', 'origin', ref]
  155. const that = this
  156. await retryHelper.execute(async () => {
  157. await that.execGit(args)
  158. })
  159. }
  160. async lfsInstall(): Promise<void> {
  161. await this.execGit(['lfs', 'install', '--local'])
  162. }
  163. async log1(): Promise<void> {
  164. await this.execGit(['log', '-1'])
  165. }
  166. async remoteAdd(remoteName: string, remoteUrl: string): Promise<void> {
  167. await this.execGit(['remote', 'add', remoteName, remoteUrl])
  168. }
  169. async tagExists(pattern: string): Promise<boolean> {
  170. const output = await this.execGit(['tag', '--list', pattern])
  171. return !!output.stdout.trim()
  172. }
  173. async tryClean(): Promise<boolean> {
  174. const output = await this.execGit(['clean', '-ffdx'], true)
  175. return output.exitCode === 0
  176. }
  177. async tryConfigUnset(configKey: string): Promise<boolean> {
  178. const output = await this.execGit(
  179. ['config', '--local', '--unset-all', configKey],
  180. true
  181. )
  182. return output.exitCode === 0
  183. }
  184. async tryDisableAutomaticGarbageCollection(): Promise<boolean> {
  185. const output = await this.execGit(
  186. ['config', '--local', 'gc.auto', '0'],
  187. true
  188. )
  189. return output.exitCode === 0
  190. }
  191. async tryGetFetchUrl(): Promise<string> {
  192. const output = await this.execGit(
  193. ['config', '--local', '--get', 'remote.origin.url'],
  194. true
  195. )
  196. if (output.exitCode !== 0) {
  197. return ''
  198. }
  199. const stdout = output.stdout.trim()
  200. if (stdout.includes('\n')) {
  201. return ''
  202. }
  203. return stdout
  204. }
  205. async tryReset(): Promise<boolean> {
  206. const output = await this.execGit(['reset', '--hard', 'HEAD'], true)
  207. return output.exitCode === 0
  208. }
  209. static async createCommandManager(
  210. workingDirectory: string,
  211. lfs: boolean
  212. ): Promise<GitCommandManager> {
  213. const result = new GitCommandManager()
  214. await result.initializeCommandManager(workingDirectory, lfs)
  215. return result
  216. }
  217. private async execGit(
  218. args: string[],
  219. allowAllExitCodes = false
  220. ): Promise<GitOutput> {
  221. fshelper.directoryExistsSync(this.workingDirectory, true)
  222. const result = new GitOutput()
  223. const env = {}
  224. for (const key of Object.keys(process.env)) {
  225. env[key] = process.env[key]
  226. }
  227. for (const key of Object.keys(this.gitEnv)) {
  228. env[key] = this.gitEnv[key]
  229. }
  230. const stdout: string[] = []
  231. const options = {
  232. cwd: this.workingDirectory,
  233. env,
  234. ignoreReturnCode: allowAllExitCodes,
  235. listeners: {
  236. stdout: (data: Buffer) => {
  237. stdout.push(data.toString())
  238. }
  239. }
  240. }
  241. result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options)
  242. result.stdout = stdout.join('')
  243. return result
  244. }
  245. private async initializeCommandManager(
  246. workingDirectory: string,
  247. lfs: boolean
  248. ): Promise<void> {
  249. this.workingDirectory = workingDirectory
  250. // Git-lfs will try to pull down assets if any of the local/user/system setting exist.
  251. // If the user didn't enable `LFS` in their pipeline definition, disable LFS fetch/checkout.
  252. this.lfs = lfs
  253. if (!this.lfs) {
  254. this.gitEnv['GIT_LFS_SKIP_SMUDGE'] = '1'
  255. }
  256. this.gitPath = await io.which('git', true)
  257. // Git version
  258. core.debug('Getting git version')
  259. let gitVersion = new GitVersion()
  260. let gitOutput = await this.execGit(['version'])
  261. let stdout = gitOutput.stdout.trim()
  262. if (!stdout.includes('\n')) {
  263. const match = stdout.match(/\d+\.\d+(\.\d+)?/)
  264. if (match) {
  265. gitVersion = new GitVersion(match[0])
  266. }
  267. }
  268. if (!gitVersion.isValid()) {
  269. throw new Error('Unable to determine git version')
  270. }
  271. // Minimum git version
  272. if (!gitVersion.checkMinimum(MinimumGitVersion)) {
  273. throw new Error(
  274. `Minimum required git version is ${MinimumGitVersion}. Your git ('${this.gitPath}') is ${gitVersion}`
  275. )
  276. }
  277. if (this.lfs) {
  278. // Git-lfs version
  279. core.debug('Getting git-lfs version')
  280. let gitLfsVersion = new GitVersion()
  281. const gitLfsPath = await io.which('git-lfs', true)
  282. gitOutput = await this.execGit(['lfs', 'version'])
  283. stdout = gitOutput.stdout.trim()
  284. if (!stdout.includes('\n')) {
  285. const match = stdout.match(/\d+\.\d+(\.\d+)?/)
  286. if (match) {
  287. gitLfsVersion = new GitVersion(match[0])
  288. }
  289. }
  290. if (!gitLfsVersion.isValid()) {
  291. throw new Error('Unable to determine git-lfs version')
  292. }
  293. // Minimum git-lfs version
  294. // Note:
  295. // - Auth header not supported before 2.1
  296. const minimumGitLfsVersion = new GitVersion('2.1')
  297. if (!gitLfsVersion.checkMinimum(minimumGitLfsVersion)) {
  298. throw new Error(
  299. `Minimum required git-lfs version is ${minimumGitLfsVersion}. Your git-lfs ('${gitLfsPath}') is ${gitLfsVersion}`
  300. )
  301. }
  302. }
  303. // Set the user agent
  304. const gitHttpUserAgent = `git/${gitVersion} (github-actions-checkout)`
  305. core.debug(`Set git useragent to: ${gitHttpUserAgent}`)
  306. this.gitEnv['GIT_HTTP_USER_AGENT'] = gitHttpUserAgent
  307. }
  308. }
  309. class GitOutput {
  310. stdout = ''
  311. exitCode = 0
  312. }