ref-helper.ts 7.2 KB

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