git-source-provider.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import * as core from '@actions/core'
  2. import * as fsHelper from './fs-helper'
  3. import * as gitAuthHelper from './git-auth-helper'
  4. import * as gitCommandManager from './git-command-manager'
  5. import * as gitDirectoryHelper from './git-directory-helper'
  6. import * as githubApiHelper from './github-api-helper'
  7. import * as io from '@actions/io'
  8. import * as path from 'path'
  9. import * as refHelper from './ref-helper'
  10. import * as stateHelper from './state-helper'
  11. import * as urlHelper from './url-helper'
  12. import {IGitCommandManager} from './git-command-manager'
  13. import {IGitSourceSettings} from './git-source-settings'
  14. export async function getSource(settings: IGitSourceSettings): Promise<void> {
  15. // Repository URL
  16. core.info(
  17. `Syncing repository: ${settings.repositoryOwner}/${settings.repositoryName}`
  18. )
  19. const repositoryUrl = urlHelper.getFetchUrl(settings)
  20. // Remove conflicting file path
  21. if (fsHelper.fileExistsSync(settings.repositoryPath)) {
  22. await io.rmRF(settings.repositoryPath)
  23. }
  24. // Create directory
  25. let isExisting = true
  26. if (!fsHelper.directoryExistsSync(settings.repositoryPath)) {
  27. isExisting = false
  28. await io.mkdirP(settings.repositoryPath)
  29. }
  30. // Git command manager
  31. core.startGroup('Getting Git version info')
  32. const git = await getGitCommandManager(settings)
  33. core.endGroup()
  34. let authHelper: gitAuthHelper.IGitAuthHelper | null = null
  35. try {
  36. if (git) {
  37. authHelper = gitAuthHelper.createAuthHelper(git, settings)
  38. await authHelper.configureTempGlobalConfig()
  39. }
  40. // Prepare existing directory, otherwise recreate
  41. if (isExisting) {
  42. await gitDirectoryHelper.prepareExistingDirectory(
  43. git,
  44. settings.repositoryPath,
  45. repositoryUrl,
  46. settings.clean,
  47. settings.ref
  48. )
  49. }
  50. if (!git) {
  51. // Downloading using REST API
  52. core.info(`The repository will be downloaded using the GitHub REST API`)
  53. core.info(
  54. `To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH`
  55. )
  56. if (settings.submodules) {
  57. throw new Error(
  58. `Input 'submodules' not supported when falling back to download using the GitHub REST API. To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH.`
  59. )
  60. } else if (settings.sshKey) {
  61. throw new Error(
  62. `Input 'ssh-key' not supported when falling back to download using the GitHub REST API. To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH.`
  63. )
  64. }
  65. await githubApiHelper.downloadRepository(
  66. settings.authToken,
  67. settings.repositoryOwner,
  68. settings.repositoryName,
  69. settings.ref,
  70. settings.commit,
  71. settings.repositoryPath
  72. )
  73. return
  74. }
  75. // Save state for POST action
  76. stateHelper.setRepositoryPath(settings.repositoryPath)
  77. // Initialize the repository
  78. if (
  79. !fsHelper.directoryExistsSync(path.join(settings.repositoryPath, '.git'))
  80. ) {
  81. core.startGroup('Initializing the repository')
  82. await git.init()
  83. await git.remoteAdd('origin', repositoryUrl)
  84. core.endGroup()
  85. }
  86. // Disable automatic garbage collection
  87. core.startGroup('Disabling automatic garbage collection')
  88. if (!(await git.tryDisableAutomaticGarbageCollection())) {
  89. core.warning(
  90. `Unable to turn off git automatic garbage collection. The git fetch operation may trigger garbage collection and cause a delay.`
  91. )
  92. }
  93. core.endGroup()
  94. // If we didn't initialize it above, do it now
  95. if (!authHelper) {
  96. authHelper = gitAuthHelper.createAuthHelper(git, settings)
  97. }
  98. // Configure auth
  99. core.startGroup('Setting up auth')
  100. await authHelper.configureAuth()
  101. core.endGroup()
  102. // Determine the default branch
  103. if (!settings.ref && !settings.commit) {
  104. core.startGroup('Determining the default branch')
  105. if (settings.sshKey) {
  106. settings.ref = await git.getDefaultBranch(repositoryUrl)
  107. } else {
  108. settings.ref = await githubApiHelper.getDefaultBranch(
  109. settings.authToken,
  110. settings.repositoryOwner,
  111. settings.repositoryName
  112. )
  113. }
  114. core.endGroup()
  115. }
  116. // LFS install
  117. if (settings.lfs) {
  118. await git.lfsInstall()
  119. }
  120. // Fetch
  121. core.startGroup('Fetching the repository')
  122. if (settings.fetchDepth <= 0) {
  123. // Fetch all branches and tags
  124. let refSpec = refHelper.getRefSpecForAllHistory(
  125. settings.ref,
  126. settings.commit
  127. )
  128. await git.fetch(refSpec)
  129. // When all history is fetched, the ref we're interested in may have moved to a different
  130. // commit (push or force push). If so, fetch again with a targeted refspec.
  131. if (!(await refHelper.testRef(git, settings.ref, settings.commit))) {
  132. refSpec = refHelper.getRefSpec(settings.ref, settings.commit)
  133. await git.fetch(refSpec)
  134. }
  135. } else {
  136. const refSpec = refHelper.getRefSpec(settings.ref, settings.commit)
  137. await git.fetch(refSpec, settings.fetchDepth)
  138. }
  139. core.endGroup()
  140. // Checkout info
  141. core.startGroup('Determining the checkout info')
  142. const checkoutInfo = await refHelper.getCheckoutInfo(
  143. git,
  144. settings.ref,
  145. settings.commit
  146. )
  147. core.endGroup()
  148. // LFS fetch
  149. // Explicit lfs-fetch to avoid slow checkout (fetches one lfs object at a time).
  150. // Explicit lfs fetch will fetch lfs objects in parallel.
  151. if (settings.lfs) {
  152. core.startGroup('Fetching LFS objects')
  153. await git.lfsFetch(checkoutInfo.startPoint || checkoutInfo.ref)
  154. core.endGroup()
  155. }
  156. // Checkout
  157. core.startGroup('Checking out the ref')
  158. await git.checkout(checkoutInfo.ref, checkoutInfo.startPoint)
  159. core.endGroup()
  160. // Submodules
  161. if (settings.submodules) {
  162. // Temporarily override global config
  163. core.startGroup('Setting up auth for fetching submodules')
  164. await authHelper.configureGlobalAuth()
  165. core.endGroup()
  166. // Checkout submodules
  167. core.startGroup('Fetching submodules')
  168. await git.submoduleSync(settings.nestedSubmodules)
  169. await git.submoduleUpdate(settings.fetchDepth, settings.nestedSubmodules)
  170. await git.submoduleForeach(
  171. 'git config --local gc.auto 0',
  172. settings.nestedSubmodules
  173. )
  174. core.endGroup()
  175. // Persist credentials
  176. if (settings.persistCredentials) {
  177. core.startGroup('Persisting credentials for submodules')
  178. await authHelper.configureSubmoduleAuth()
  179. core.endGroup()
  180. }
  181. }
  182. // Get commit information
  183. const commitInfo = await git.log1()
  184. // Log commit sha
  185. await git.log1("--format='%H'")
  186. // Check for incorrect pull request merge commit
  187. await refHelper.checkCommitInfo(
  188. settings.authToken,
  189. commitInfo,
  190. settings.repositoryOwner,
  191. settings.repositoryName,
  192. settings.ref,
  193. settings.commit
  194. )
  195. } finally {
  196. // Remove auth
  197. if (authHelper) {
  198. if (!settings.persistCredentials) {
  199. core.startGroup('Removing auth')
  200. await authHelper.removeAuth()
  201. core.endGroup()
  202. }
  203. authHelper.removeGlobalConfig()
  204. }
  205. }
  206. }
  207. export async function cleanup(repositoryPath: string): Promise<void> {
  208. // Repo exists?
  209. if (
  210. !repositoryPath ||
  211. !fsHelper.fileExistsSync(path.join(repositoryPath, '.git', 'config'))
  212. ) {
  213. return
  214. }
  215. let git: IGitCommandManager
  216. try {
  217. git = await gitCommandManager.createCommandManager(repositoryPath, false)
  218. } catch {
  219. return
  220. }
  221. // Remove auth
  222. const authHelper = gitAuthHelper.createAuthHelper(git)
  223. try {
  224. await authHelper.configureTempGlobalConfig(repositoryPath)
  225. await authHelper.removeAuth()
  226. } finally {
  227. await authHelper.removeGlobalConfig()
  228. }
  229. }
  230. async function getGitCommandManager(
  231. settings: IGitSourceSettings
  232. ): Promise<IGitCommandManager | undefined> {
  233. core.info(`Working directory is '${settings.repositoryPath}'`)
  234. try {
  235. return await gitCommandManager.createCommandManager(
  236. settings.repositoryPath,
  237. settings.lfs
  238. )
  239. } catch (err) {
  240. // Git is required for LFS
  241. if (settings.lfs) {
  242. throw err
  243. }
  244. // Otherwise fallback to REST API
  245. return undefined
  246. }
  247. }