ref-helper.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import {URL} from 'url'
  2. import {IGitCommandManager} from './git-command-manager'
  3. import * as core from '@actions/core'
  4. import * as github from '@actions/github'
  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. ): Promise<void> {
  170. try {
  171. // GHES?
  172. if (isGhes()) {
  173. return
  174. }
  175. // Auth token?
  176. if (!token) {
  177. return
  178. }
  179. // Public PR synchronize, for workflow repo?
  180. if (
  181. fromPayload('repository.private') !== false ||
  182. github.context.eventName !== 'pull_request' ||
  183. fromPayload('action') !== 'synchronize' ||
  184. repositoryOwner !== github.context.repo.owner ||
  185. repositoryName !== github.context.repo.repo ||
  186. ref !== github.context.ref ||
  187. !ref.startsWith('refs/pull/') ||
  188. commit !== github.context.sha
  189. ) {
  190. return
  191. }
  192. // Head SHA
  193. const expectedHeadSha = fromPayload('after')
  194. if (!expectedHeadSha) {
  195. core.debug('Unable to determine head sha')
  196. return
  197. }
  198. // Base SHA
  199. const expectedBaseSha = fromPayload('pull_request.base.sha')
  200. if (!expectedBaseSha) {
  201. core.debug('Unable to determine base sha')
  202. return
  203. }
  204. // Expected message?
  205. const expectedMessage = `Merge ${expectedHeadSha} into ${expectedBaseSha}`
  206. if (commitInfo.indexOf(expectedMessage) >= 0) {
  207. return
  208. }
  209. // Extract details from message
  210. const match = commitInfo.match(/Merge ([0-9a-f]{40}) into ([0-9a-f]{40})/)
  211. if (!match) {
  212. core.debug('Unexpected message format')
  213. return
  214. }
  215. // Post telemetry
  216. const actualHeadSha = match[1]
  217. if (actualHeadSha !== expectedHeadSha) {
  218. core.debug(
  219. `Expected head sha ${expectedHeadSha}; actual head sha ${actualHeadSha}`
  220. )
  221. const octokit = new github.GitHub(token, {
  222. userAgent: `actions-checkout-tracepoint/1.0 (code=STALE_MERGE;owner=${repositoryOwner};repo=${repositoryName};pr=${fromPayload(
  223. 'number'
  224. )};run_id=${
  225. process.env['GITHUB_RUN_ID']
  226. };expected_head_sha=${expectedHeadSha};actual_head_sha=${actualHeadSha})`
  227. })
  228. await octokit.repos.get({owner: repositoryOwner, repo: repositoryName})
  229. }
  230. } catch (err) {
  231. core.debug(
  232. `Error when validating commit info: ${(err as any)?.stack ?? err}`
  233. )
  234. }
  235. }
  236. function fromPayload(path: string): any {
  237. return select(github.context.payload, path)
  238. }
  239. function select(obj: any, path: string): any {
  240. if (!obj) {
  241. return undefined
  242. }
  243. const i = path.indexOf('.')
  244. if (i < 0) {
  245. return obj[path]
  246. }
  247. const key = path.substr(0, i)
  248. return select(obj[key], path.substr(i + 1))
  249. }
  250. function isGhes(): boolean {
  251. const ghUrl = new URL(
  252. process.env['GITHUB_SERVER_URL'] || 'https://github.com'
  253. )
  254. return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'
  255. }