Read-only mirror — the public repositories of the Forgejo instance, refreshed every 10 minutes. The live instance (fg.dieschoenewolke.de) is reachable only over the VPN; clone here with https://git.dieschoenewolke.de/git/<owner>/<repo>.git.
summaryrefslogtreecommitdiff
path: root/src/ref-helper.ts
blob: f6001792b9922663999b58451b8f9e989c15de82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import {URL} from 'url'
import {IGitCommandManager} from './git-command-manager'
import * as core from '@actions/core'
import * as github from '@actions/github'

export interface ICheckoutInfo {
  ref: string
  startPoint: string
}

export async function getCheckoutInfo(
  git: IGitCommandManager,
  ref: string,
  commit: string
): Promise<ICheckoutInfo> {
  if (!git) {
    throw new Error('Arg git cannot be empty')
  }

  if (!ref && !commit) {
    throw new Error('Args ref and commit cannot both be empty')
  }

  const result = ({} as unknown) as ICheckoutInfo
  const upperRef = (ref || '').toUpperCase()

  // SHA only
  if (!ref) {
    result.ref = commit
  }
  // refs/heads/
  else if (upperRef.startsWith('REFS/HEADS/')) {
    const branch = ref.substring('refs/heads/'.length)
    result.ref = branch
    result.startPoint = `refs/remotes/origin/${branch}`
  }
  // refs/pull/
  else if (upperRef.startsWith('REFS/PULL/')) {
    const branch = ref.substring('refs/pull/'.length)
    result.ref = `refs/remotes/pull/${branch}`
  }
  // refs/tags/
  else if (upperRef.startsWith('REFS/')) {
    result.ref = ref
  }
  // Unqualified ref, check for a matching branch or tag
  else {
    if (await git.branchExists(true, `origin/${ref}`)) {
      result.ref = ref
      result.startPoint = `refs/remotes/origin/${ref}`
    } else if (await git.tagExists(`${ref}`)) {
      result.ref = `refs/tags/${ref}`
    } else {
      throw new Error(
        `A branch or tag with the name '${ref}' could not be found`
      )
    }
  }

  return result
}

export function getRefSpec(ref: string, commit: string): string[] {
  if (!ref && !commit) {
    throw new Error('Args ref and commit cannot both be empty')
  }

  const upperRef = (ref || '').toUpperCase()

  // SHA
  if (commit) {
    // refs/heads
    if (upperRef.startsWith('REFS/HEADS/')) {
      const branch = ref.substring('refs/heads/'.length)
      return [`+${commit}:refs/remotes/origin/${branch}`]
    }
    // refs/pull/
    else if (upperRef.startsWith('REFS/PULL/')) {
      const branch = ref.substring('refs/pull/'.length)
      return [`+${commit}:refs/remotes/pull/${branch}`]
    }
    // refs/tags/
    else if (upperRef.startsWith('REFS/TAGS/')) {
      return [`+${commit}:${ref}`]
    }
    // Otherwise no destination ref
    else {
      return [commit]
    }
  }
  // Unqualified ref, check for a matching branch or tag
  else if (!upperRef.startsWith('REFS/')) {
    return [
      `+refs/heads/${ref}*:refs/remotes/origin/${ref}*`,
      `+refs/tags/${ref}*:refs/tags/${ref}*`
    ]
  }
  // refs/heads/
  else if (upperRef.startsWith('REFS/HEADS/')) {
    const branch = ref.substring('refs/heads/'.length)
    return [`+${ref}:refs/remotes/origin/${branch}`]
  }
  // refs/pull/
  else if (upperRef.startsWith('REFS/PULL/')) {
    const branch = ref.substring('refs/pull/'.length)
    return [`+${ref}:refs/remotes/pull/${branch}`]
  }
  // refs/tags/
  else {
    return [`+${ref}:${ref}`]
  }
}

export async function checkCommitInfo(
  token: string,
  commitInfo: string,
  repositoryOwner: string,
  repositoryName: string,
  ref: string,
  commit: string
): Promise<void> {
  try {
    // GHES?
    if (isGhes()) {
      return
    }

    // Auth token?
    if (!token) {
      return
    }

    // Public PR synchronize, for workflow repo?
    if (
      fromPayload('repository.private') !== false ||
      github.context.eventName !== 'pull_request' ||
      fromPayload('action') !== 'synchronize' ||
      repositoryOwner !== github.context.repo.owner ||
      repositoryName !== github.context.repo.repo ||
      ref !== github.context.ref ||
      !ref.startsWith('refs/pull/') ||
      commit !== github.context.sha
    ) {
      return
    }

    // Head SHA
    const expectedHeadSha = fromPayload('after')
    if (!expectedHeadSha) {
      core.debug('Unable to determine head sha')
      return
    }

    // Base SHA
    const expectedBaseSha = fromPayload('pull_request.base.sha')
    if (!expectedBaseSha) {
      core.debug('Unable to determine base sha')
      return
    }

    // Expected message?
    const expectedMessage = `Merge ${expectedHeadSha} into ${expectedBaseSha}`
    if (commitInfo.indexOf(expectedMessage) >= 0) {
      return
    }

    // Extract details from message
    const match = commitInfo.match(/Merge ([0-9a-f]{40}) into ([0-9a-f]{40})/)
    if (!match) {
      core.debug('Unexpected message format')
      return
    }

    // Post telemetry
    const actualHeadSha = match[1]
    if (actualHeadSha !== expectedHeadSha) {
      core.debug(
        `Expected head sha ${expectedHeadSha}; actual head sha ${actualHeadSha}`
      )
      const octokit = new github.GitHub(token, {
        userAgent: `actions-checkout-tracepoint/1.0 (code=STALE_MERGE;owner=${repositoryOwner};repo=${repositoryName};pr=${fromPayload(
          'number'
        )};run_id=${
          process.env['GITHUB_RUN_ID']
        };expected_head_sha=${expectedHeadSha};actual_head_sha=${actualHeadSha})`
      })
      await octokit.repos.get({owner: repositoryOwner, repo: repositoryName})
    }
  } catch (err) {
    core.debug(`Error when validating commit info: ${err.stack}`)
  }
}

function fromPayload(path: string): any {
  return select(github.context.payload, path)
}

function select(obj: any, path: string): any {
  if (!obj) {
    return undefined
  }

  const i = path.indexOf('.')
  if (i < 0) {
    return obj[path]
  }

  const key = path.substr(0, i)
  return select(obj[key], path.substr(i + 1))
}

function isGhes(): boolean {
  const ghUrl = new URL(
    process.env['GITHUB_SERVER_URL'] || 'https://github.com'
  )
  return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'
}