ref-helper.ts 7.3 KB

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