ref-helper.ts 7.2 KB

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