Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
379 lines (339 loc) · 15.5 KB
/
Copy pathmain.js
File metadata and controls
379 lines (339 loc) · 15.5 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import * as core from '@actions/core'
import * as exec from '@actions/exec'
import * as github from '@actions/github'
import { defaults as githubDefaults } from '@actions/github/lib/utils'
import * as artifact from '@actions/artifact'
import AdmZip from 'adm-zip'
import { randomUUID } from 'node:crypto'
import pathname from 'node:path'
import fs from 'node:fs'
import { pipeline } from 'node:stream/promises'
async function main() {
try {
const token = core.getInput("github_token", { required: true })
const [owner, repo] = core.getInput("repo", { required: true }).split("/")
const path = core.getInput("path", { required: true })
const name = core.getInput("name")
const nameIsRegExp = core.getBooleanInput("name_is_regexp")
const skipUnpack = core.getBooleanInput("skip_unpack")
const ifNoArtifactFound = core.getInput("if_no_artifact_found")
const useUnzip = core.getBooleanInput("use_unzip")
const mergeMultiple = core.getBooleanInput("merge_multiple")
let workflow = core.getInput("workflow")
let workflowSearch = core.getBooleanInput("workflow_search")
let workflowConclusion = core.getInput("workflow_conclusion")
let pr = core.getInput("pr")
let commit = core.getInput("commit")
let branch = core.getInput("branch")
let ref = core.getInput("ref")
let event = core.getInput("event")
let runID = core.getInput("run_id")
let runNumber = core.getInput("run_number")
let checkArtifacts = core.getBooleanInput("check_artifacts")
let searchArtifacts = core.getBooleanInput("search_artifacts")
const allowForks = core.getBooleanInput("allow_forks")
let dryRun = core.getBooleanInput("dry_run")
const client = github.getOctokit(token)
const artifactClient = new artifact.DefaultArtifactClient()
const hostname = new URL(github.context.serverUrl).hostname.toUpperCase()
const canStreamArtifacts = hostname === "GITHUB.COM" || hostname.endsWith(".GHE.COM") || hostname.endsWith(".LOCALHOST")
const matchesName = artifact => nameIsRegExp ? artifact.name.match(name) !== null : artifact.name == name
core.info(`==> Repository: ${owner}/${repo}`)
core.info(`==> Artifact name: ${name}`)
core.info(`==> Local path: ${path}`)
if (!workflow && !workflowSearch) {
workflow = (await client.rest.actions.getWorkflowRun({
owner: owner,
repo: repo,
run_id: runID || github.context.runId,
})).data.workflow_id
}
if (workflow) {
core.info(`==> Workflow name: ${workflow}`)
}
core.info(`==> Workflow conclusion: ${workflowConclusion}`)
const exclusiveInputs = { pr, commit, branch, ref, "run_id": runID }
if (Object.values(exclusiveInputs).filter(Boolean).length > 1) {
throw new Error(`The following inputs cannot be used together: ${Object.keys(exclusiveInputs).join(", ")}`)
}
if (pr) {
core.info(`==> PR: ${pr}`)
const pull = await client.rest.pulls.get({
owner: owner,
repo: repo,
pull_number: pr,
})
commit = pull.data.head.sha
}
if (ref) {
// Try to determine if the ref is a branch or a commit
core.info(`==> Ref: ${ref}`)
try {
await client.rest.repos.getBranch({
owner: owner,
repo: repo,
branch: ref,
})
branch = ref
} catch (error) {
const response = await client.rest.repos.getCommit({
owner: owner,
repo: repo,
ref: ref,
})
commit = response.data.sha
}
}
if (commit) {
core.info(`==> Commit: ${commit}`)
}
if (branch) {
branch = branch.replace(/^refs\/heads\//, "")
core.info(`==> Branch: ${branch}`)
}
if (event) {
core.info(`==> Event: ${event}`)
}
if (runNumber) {
core.info(`==> Run number: ${runNumber}`)
}
core.info(`==> Allow forks: ${allowForks}`)
if (!runID) {
const runGetter = workflow ? client.rest.actions.listWorkflowRuns : client.rest.actions.listWorkflowRunsForRepo
// Filtered queries are served by a search index that intermittently returns a random subset of runs,
// so merge in the latest unfiltered runs, matched locally. Only helps if the newest match is among them.
let latestRuns = []
if (branch || event || commit) {
latestRuns = (await runGetter({
owner: owner,
repo: repo,
per_page: 100,
...(workflow ? { workflow_id: workflow } : {}),
})).data.workflow_runs.filter(run =>
(!branch || run.head_branch === branch) &&
(!event || run.event === event) &&
(!commit || run.head_sha === commit)
)
}
for await (const runs of client.paginate.iterator(runGetter, {
owner: owner,
repo: repo,
per_page: 100,
...(workflow ? { workflow_id: workflow } : {}),
...(branch ? { branch } : {}),
...(event ? { event } : {}),
...(commit ? { head_sha: commit } : {}),
}
)) {
core.debug(`==> Fetched page of ${runs.data.length} runs: ${runs.data.map(run => run.id).join(", ")}`)
const missingRuns = latestRuns.filter(run => !runs.data.some(r => r.id === run.id))
if (missingRuns.length) {
core.debug(`==> Merging runs missing from filtered page: ${missingRuns.map(run => run.id).join(", ")}`)
}
latestRuns = []
// Do not rely on the API returning runs in most recent first order, it sometimes does not.
for (const run of [...runs.data, ...missingRuns].sort((a, b) => b.id - a.id)) {
if (runNumber && run.run_number != runNumber) {
continue
}
if (workflowConclusion && workflowConclusion != run.conclusion && workflowConclusion != run.status) {
core.debug(`==> Skipping run ${run.id} (${run.created_at}): status ${run.status}, conclusion ${run.conclusion}`)
continue
}
if (!allowForks && run.head_repository.full_name !== `${owner}/${repo}`) {
core.info(`==> Skipping run from fork: ${run.head_repository.full_name}`)
continue
}
if (checkArtifacts || searchArtifacts) {
const artifacts = (await client.paginate(client.rest.actions.listWorkflowRunArtifacts, {
owner: owner,
repo: repo,
run_id: run.id,
})).filter(artifact => !artifact.expired)
if (artifacts.length === 0 || (searchArtifacts && !artifacts.some(matchesName))) {
core.debug(`==> Skipping run ${run.id} (${run.created_at}): artifacts [${artifacts.map(artifact => artifact.name).join(", ")}]`)
continue
}
}
runID = run.id
core.info(`==> (found) Run ID: ${runID}`)
core.info(`==> (found) Run date: ${run.created_at}`)
if (!workflow) {
workflow = run.workflow_id
core.info(`==> (found) Workflow: ${workflow}`)
}
break
}
if (runID) {
break
}
}
}
if (!runID) {
if (workflowConclusion && (workflowConclusion != 'in_progress')) {
return setExitMessage(ifNoArtifactFound, "no matching workflow run found with any artifacts?")
}
runID = github.context.runId
core.info(`==> (current) Run ID: ${runID}`)
}
let artifacts = await client.paginate(client.rest.actions.listWorkflowRunArtifacts, {
owner: owner,
repo: repo,
run_id: runID,
})
// One artifact if 'name' input is specified, one or more if `name` is a regular expression, all otherwise.
if (name) {
const filtered = artifacts.filter(matchesName)
if (filtered.length == 0) {
core.info(`==> (not found) Artifact: ${name}`)
core.info('==> Found the following artifacts instead:')
for (const artifact of artifacts) {
core.info(`\t==> (found) Artifact: ${artifact.name}`)
}
}
artifacts = filtered
}
artifacts.sort((a, b) => a.created_at.localeCompare(b.created_at))
core.setOutput("artifacts", artifacts)
if (dryRun) {
const found = artifacts.length > 0
core.setOutput("found_artifact", found)
if (!found) return
core.info('==> (found) Artifacts')
for (const artifact of artifacts) {
core.info(`\t==> Artifact:`)
core.info(`\t==> ID: ${artifact.id}`)
core.info(`\t==> Name: ${artifact.name}`)
core.info(`\t==> Size: ${artifact.size_in_bytes} bytes`)
}
return
}
if (artifacts.length == 0) {
return setExitMessage(ifNoArtifactFound, "no artifacts found")
}
const expiredArtifacts = []
for (const artifact of artifacts) {
core.info(`==> Artifact: ${artifact.id}`)
core.info(`==> Downloading: ${artifact.name} (${artifact.size_in_bytes} bytes)`)
if (artifact.expired) {
if (ifNoArtifactFound === "fail") {
return setExitMessage(ifNoArtifactFound, "no downloadable artifacts found (expired)")
}
expiredArtifacts.push(artifact.name)
continue
}
const dir = skipUnpack || (name && (!nameIsRegExp || mergeMultiple))
? path
: pathname.join(path, artifact.name)
if (canStreamArtifacts) {
let response
try {
response = await artifactClient.downloadArtifact(artifact.id, {
path: dir,
skipDecompress: skipUnpack || useUnzip,
...(artifact.digest ? { expectedHash: artifact.digest } : {}),
findBy: {
token: token,
workflowRunId: Number(runID),
repositoryOwner: owner,
repositoryName: repo,
},
})
} catch (error) {
if (error.message.includes("Artifact has expired")) {
if (ifNoArtifactFound === "fail") {
return setExitMessage(ifNoArtifactFound, "no downloadable artifacts found (expired)")
}
expiredArtifacts.push(artifact.name)
continue
}
throw error
}
if (response.digestMismatch) {
throw new Error(`artifact digest mismatch: ${artifact.name}`)
}
const zipPath = pathname.join(dir, `${artifact.name}.zip`)
if (useUnzip && !skipUnpack && fs.existsSync(zipPath)) {
core.startGroup(`==> Extracting: ${artifact.name}.zip`)
try {
await exec.exec("unzip", [zipPath, "-d", dir])
} finally {
core.endGroup()
}
fs.rmSync(zipPath)
}
continue
}
fs.mkdirSync(dir, { recursive: true })
const zipPath = pathname.join(dir, `.artifact-${randomUUID()}.zip`)
try {
await client.request("GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}", {
owner: owner,
repo: repo,
artifact_id: artifact.id,
archive_format: "zip",
request: {
fetch: async (url, options) => {
const response = await githubDefaults.request.fetch(url, { ...options, redirect: "follow" })
if (!response.ok) return response
await pipeline(response.body, fs.createWriteStream(zipPath))
return new Response(null, { status: 200, headers: response.headers })
},
},
})
} catch (error) {
fs.rmSync(zipPath, { force: true })
if (error.message?.startsWith("Artifact has expired")) {
if (ifNoArtifactFound === "fail") {
return setExitMessage(ifNoArtifactFound, "no downloadable artifacts found (expired)")
}
expiredArtifacts.push(artifact.name)
continue
}
throw error
}
if (skipUnpack) {
try {
fs.renameSync(zipPath, `${pathname.join(path, artifact.name)}.zip`)
} finally {
fs.rmSync(zipPath, { force: true })
}
continue
}
try {
core.startGroup(`==> Extracting: ${artifact.name}.zip`)
try {
if (useUnzip) {
await exec.exec("unzip", [zipPath, "-d", dir])
} else {
new AdmZip(zipPath).extractAllTo(dir, true)
}
} finally {
core.endGroup()
}
} finally {
fs.rmSync(zipPath, { force: true })
}
}
if (expiredArtifacts.length === artifacts.length) {
return setExitMessage(ifNoArtifactFound, "no downloadable artifacts found (expired)")
}
if (expiredArtifacts.length > 0) {
const message = `skipped expired artifact${expiredArtifacts.length === 1 ? "" : "s"}: ${expiredArtifacts.join(", ")}`
if (ifNoArtifactFound === "warn") core.warning(message)
else core.info(message)
}
core.setOutput("found_artifact", true)
} catch (error) {
core.setOutput("found_artifact", false)
core.setOutput("error_message", error.message)
core.setFailed(error.message)
}
function setExitMessage(ifNoArtifactFound, message) {
core.setOutput("found_artifact", false)
if (ifNoArtifactFound === "fail") return core.setFailed(message)
if (ifNoArtifactFound === "warn") return core.warning(message)
core.info(message)
}
}
main()