ref-helper.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import {IGitCommandManager} from './git-command-manager.js'
  2. import * as core from '@actions/core'
  3. import * as github from '@actions/github'
  4. import {getServerApiUrl, isGhes} from './url-helper.js'
  5. export const tagsRefSpec = '+refs/tags/*:refs/tags/*'
  6. export interface ICheckoutInfo {
  7. ref: string
  8. startPoint: string
  9. }
  10. export async function getCheckoutInfo(
  11. git: IGitCommandManager,
  12. ref: string,
  13. commit: string
  14. ): Promise<ICheckoutInfo> {
  15. if (!git) {
  16. throw new Error('Arg git cannot be empty')
  17. }
  18. if (!ref && !commit) {
  19. throw new Error('Args ref and commit cannot both be empty')
  20. }
  21. const result = {} as unknown as ICheckoutInfo
  22. const upperRef = (ref || '').toUpperCase()
  23. // SHA only
  24. if (!ref) {
  25. result.ref = commit
  26. }
  27. // refs/heads/
  28. else if (upperRef.startsWith('REFS/HEADS/')) {
  29. const branch = ref.substring('refs/heads/'.length)
  30. result.ref = branch
  31. result.startPoint = `refs/remotes/origin/${branch}`
  32. }
  33. // refs/pull/
  34. else if (upperRef.startsWith('REFS/PULL/')) {
  35. const branch = ref.substring('refs/pull/'.length)
  36. result.ref = `refs/remotes/pull/${branch}`
  37. }
  38. // refs/tags/
  39. else if (upperRef.startsWith('REFS/TAGS/')) {
  40. result.ref = ref
  41. }
  42. // refs/
  43. else if (upperRef.startsWith('REFS/')) {
  44. result.ref = commit ? commit : ref
  45. }
  46. // Unqualified ref, check for a matching branch or tag
  47. else {
  48. if (await git.branchExists(true, `origin/${ref}`)) {
  49. result.ref = ref
  50. result.startPoint = `refs/remotes/origin/${ref}`
  51. } else if (await git.tagExists(`${ref}`)) {
  52. result.ref = `refs/tags/${ref}`
  53. } else {
  54. throw new Error(
  55. `A branch or tag with the name '${ref}' could not be found`
  56. )
  57. }
  58. }
  59. return result
  60. }
  61. export function getRefSpecForAllHistory(ref: string, commit: string): string[] {
  62. const result = ['+refs/heads/*:refs/remotes/origin/*', tagsRefSpec]
  63. if (ref && ref.toUpperCase().startsWith('REFS/PULL/')) {
  64. const branch = ref.substring('refs/pull/'.length)
  65. result.push(`+${commit || ref}:refs/remotes/pull/${branch}`)
  66. }
  67. return result
  68. }
  69. export function getRefSpec(
  70. ref: string,
  71. commit: string,
  72. fetchTags?: boolean
  73. ): string[] {
  74. if (!ref && !commit) {
  75. throw new Error('Args ref and commit cannot both be empty')
  76. }
  77. const upperRef = (ref || '').toUpperCase()
  78. const result: string[] = []
  79. // When fetchTags is true, always include the tags refspec
  80. if (fetchTags) {
  81. result.push(tagsRefSpec)
  82. }
  83. // SHA
  84. if (commit) {
  85. // refs/heads
  86. if (upperRef.startsWith('REFS/HEADS/')) {
  87. const branch = ref.substring('refs/heads/'.length)
  88. result.push(`+${commit}:refs/remotes/origin/${branch}`)
  89. }
  90. // refs/pull/
  91. else if (upperRef.startsWith('REFS/PULL/')) {
  92. const branch = ref.substring('refs/pull/'.length)
  93. result.push(`+${commit}:refs/remotes/pull/${branch}`)
  94. }
  95. // refs/tags/
  96. else if (upperRef.startsWith('REFS/TAGS/')) {
  97. if (!fetchTags) {
  98. result.push(`+${ref}:${ref}`)
  99. }
  100. }
  101. // Otherwise no destination ref
  102. else {
  103. result.push(commit)
  104. }
  105. }
  106. // Unqualified ref, check for a matching branch or tag
  107. else if (!upperRef.startsWith('REFS/')) {
  108. result.push(`+refs/heads/${ref}*:refs/remotes/origin/${ref}*`)
  109. if (!fetchTags) {
  110. result.push(`+refs/tags/${ref}*:refs/tags/${ref}*`)
  111. }
  112. }
  113. // refs/heads/
  114. else if (upperRef.startsWith('REFS/HEADS/')) {
  115. const branch = ref.substring('refs/heads/'.length)
  116. result.push(`+${ref}:refs/remotes/origin/${branch}`)
  117. }
  118. // refs/pull/
  119. else if (upperRef.startsWith('REFS/PULL/')) {
  120. const branch = ref.substring('refs/pull/'.length)
  121. result.push(`+${ref}:refs/remotes/pull/${branch}`)
  122. }
  123. // refs/tags/
  124. else if (upperRef.startsWith('REFS/TAGS/')) {
  125. if (!fetchTags) {
  126. result.push(`+${ref}:${ref}`)
  127. }
  128. }
  129. // Other refs
  130. else {
  131. result.push(`+${ref}:${ref}`)
  132. }
  133. return result
  134. }
  135. /**
  136. * Tests whether the initial fetch created the ref at the expected commit
  137. */
  138. export async function testRef(
  139. git: IGitCommandManager,
  140. ref: string,
  141. commit: string
  142. ): Promise<boolean> {
  143. if (!git) {
  144. throw new Error('Arg git cannot be empty')
  145. }
  146. if (!ref && !commit) {
  147. throw new Error('Args ref and commit cannot both be empty')
  148. }
  149. // No SHA? Nothing to test
  150. if (!commit) {
  151. return true
  152. }
  153. // SHA only?
  154. else if (!ref) {
  155. return await git.shaExists(commit)
  156. }
  157. const upperRef = ref.toUpperCase()
  158. // refs/heads/
  159. if (upperRef.startsWith('REFS/HEADS/')) {
  160. const branch = ref.substring('refs/heads/'.length)
  161. return (
  162. (await git.branchExists(true, `origin/${branch}`)) &&
  163. commit === (await git.revParse(`refs/remotes/origin/${branch}`))
  164. )
  165. }
  166. // refs/pull/
  167. else if (upperRef.startsWith('REFS/PULL/')) {
  168. // Assume matches because fetched using the commit
  169. return true
  170. }
  171. // refs/tags/
  172. else if (upperRef.startsWith('REFS/TAGS/')) {
  173. const tagName = ref.substring('refs/tags/'.length)
  174. // Use ^{commit} to dereference annotated tags to their underlying commit
  175. return (
  176. (await git.tagExists(tagName)) &&
  177. commit === (await git.revParse(`${ref}^{commit}`))
  178. )
  179. }
  180. // Unexpected
  181. else {
  182. core.debug(`Unexpected ref format '${ref}' when testing ref info`)
  183. return true
  184. }
  185. }
  186. export async function checkCommitInfo(
  187. token: string,
  188. commitInfo: string,
  189. repositoryOwner: string,
  190. repositoryName: string,
  191. ref: string,
  192. commit: string,
  193. baseUrl?: string
  194. ): Promise<void> {
  195. try {
  196. // GHES?
  197. if (isGhes(baseUrl)) {
  198. return
  199. }
  200. // Auth token?
  201. if (!token) {
  202. return
  203. }
  204. // Public PR synchronize, for workflow repo?
  205. if (
  206. fromPayload('repository.private') !== false ||
  207. github.context.eventName !== 'pull_request' ||
  208. fromPayload('action') !== 'synchronize' ||
  209. repositoryOwner !== github.context.repo.owner ||
  210. repositoryName !== github.context.repo.repo ||
  211. ref !== github.context.ref ||
  212. !ref.startsWith('refs/pull/') ||
  213. commit !== github.context.sha
  214. ) {
  215. return
  216. }
  217. // Head SHA
  218. const expectedHeadSha = fromPayload('after')
  219. if (!expectedHeadSha) {
  220. core.debug('Unable to determine head sha')
  221. return
  222. }
  223. // Base SHA
  224. const expectedBaseSha = fromPayload('pull_request.base.sha')
  225. if (!expectedBaseSha) {
  226. core.debug('Unable to determine base sha')
  227. return
  228. }
  229. // Expected message?
  230. const expectedMessage = `Merge ${expectedHeadSha} into ${expectedBaseSha}`
  231. if (commitInfo.indexOf(expectedMessage) >= 0) {
  232. return
  233. }
  234. // Extract details from message
  235. const match = commitInfo.match(
  236. /Merge ([0-9a-f]{40}|[0-9a-f]{64}) into ([0-9a-f]{40}|[0-9a-f]{64})/
  237. )
  238. if (!match) {
  239. core.debug('Unexpected message format')
  240. return
  241. }
  242. // Post telemetry
  243. const actualHeadSha = match[1]
  244. if (actualHeadSha !== expectedHeadSha) {
  245. core.debug(
  246. `Expected head sha ${expectedHeadSha}; actual head sha ${actualHeadSha}`
  247. )
  248. const octokit = github.getOctokit(token, {
  249. baseUrl: getServerApiUrl(baseUrl),
  250. userAgent: `actions-checkout-tracepoint/1.0 (code=STALE_MERGE;owner=${repositoryOwner};repo=${repositoryName};pr=${fromPayload(
  251. 'number'
  252. )};run_id=${
  253. process.env['GITHUB_RUN_ID']
  254. };expected_head_sha=${expectedHeadSha};actual_head_sha=${actualHeadSha})`
  255. })
  256. await octokit.rest.repos.get({
  257. owner: repositoryOwner,
  258. repo: repositoryName
  259. })
  260. }
  261. } catch (err) {
  262. core.debug(
  263. `Error when validating commit info: ${(err as any)?.stack ?? err}`
  264. )
  265. }
  266. }
  267. export function fromPayload(path: string): any {
  268. return select(github.context.payload, path)
  269. }
  270. function select(obj: any, path: string): any {
  271. if (!obj) {
  272. return undefined
  273. }
  274. const i = path.indexOf('.')
  275. if (i < 0) {
  276. return obj[path]
  277. }
  278. const key = path.substr(0, i)
  279. return select(obj[key], path.substr(i + 1))
  280. }