Repository navigation
Expand file tree
/
Copy pathresolve-tools.mjs
More file actions
326 lines (306 loc) · 9.17 KB
/
Copy pathresolve-tools.mjs
File metadata and controls
326 lines (306 loc) · 9.17 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
import { execFileSync } from 'node:child_process'
import { appendFileSync, rmSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
const ASSET_NAME = 'ai-scan.tar.xz'
const NODE_ENTRY_POINT = 'argus.mjs'
const BUN_ENTRY_POINT = 'argus.js'
const BUN_VERSION_STAMP = 'ai-scan-bun-version'
const PUBLIC_DISTRIBUTION_REPOSITORY = 'github/ai-scan-action'
function emitErrorAnnotation(message) {
console.log(`::error::${message.replace(/[\r\n]+/g, ' ')}`)
}
function emitWarningAnnotation(message, log = console.log) {
log(`::warning::${message.replace(/[\r\n]+/g, ' ')}`)
}
function commandOutput(command, args, env = process.env) {
return execFileSync(command, args, {
encoding: 'utf8',
env,
stdio: ['ignore', 'pipe', 'inherit'],
})
}
function gh(args, host = 'github.com') {
return commandOutput('gh', args, { ...process.env, GH_HOST: host }).trim()
}
function curl(args) {
return commandOutput('curl', [
'--fail',
'--silent',
'--show-error',
'--retry',
'3',
...args,
]).trim()
}
function tar(args) {
return commandOutput('tar', args)
}
export function parseLatestReleaseTag(latestUrl, releaseRepository) {
const url = new URL(latestUrl)
const tagPrefix = `/${releaseRepository}/releases/tag/`
if (
url.origin !== 'https://github.com' ||
url.username ||
url.password ||
url.search ||
url.hash ||
!url.pathname.startsWith(tagPrefix) ||
url.pathname.length === tagPrefix.length
) {
throw new Error(`Unexpected latest release redirect for ${releaseRepository}: ${latestUrl}`)
}
return url.pathname.slice(tagPrefix.length)
}
function featureApiHost(apiUrl) {
const url = new URL(apiUrl)
if (url.protocol !== 'https:' || url.username || url.password) {
throw new Error('Invalid GitHub API URL')
}
const hostname = url.hostname.replace(/^api\./, '')
return `${hostname}${url.port ? `:${url.port}` : ''}`
}
function readUseNextRelease(repository, apiUrl, { gh, log }) {
try {
const value = gh(
[
'api',
'--method',
'GET',
`repos/${repository}/code-scanning/ai-scan-action/features`,
'-f',
'features=use_next_release',
'--jq',
'.use_next_release // false',
],
featureApiHost(apiUrl),
)
if (value !== 'true' && value !== 'false') {
throw new Error('Feature API returned an invalid use_next_release value')
}
return value === 'true'
} catch (error) {
emitWarningAnnotation(
`Could not read the pending AI Scan release feature flag; using latest (${error.message})`,
log,
)
return false
}
}
function resolvePendingTag(releaseRepository, gh) {
return gh([
'release',
'list',
'--repo',
releaseRepository,
'--order',
'desc',
'--limit',
'1',
'--exclude-drafts',
'--json',
'tagName,isPrerelease',
'--jq',
'.[] | select(.isPrerelease) | .tagName',
])
}
function resolveLatestTag(releaseRepository, authenticatedDownload, { gh, curl }) {
let tag
if (authenticatedDownload) {
tag = gh([
'release',
'view',
'--repo',
releaseRepository,
'--json',
'tagName',
'--jq',
'.tagName',
])
} else {
// The public redirect avoids unauthenticated API rate limits on shared runners.
const latestUrl = curl([
'--output',
'/dev/null',
'--write-out',
'%{redirect_url}',
`https://github.com/${releaseRepository}/releases/latest`,
])
tag = latestUrl ? parseLatestReleaseTag(latestUrl, releaseRepository) : ''
}
if (!tag) throw new Error(`Could not resolve the latest AI Scan release of ${releaseRepository}`)
return tag
}
function downloadRelease(
releaseRepository,
tag,
tarball,
authenticatedDownload,
{ gh, curl, log },
) {
rmSync(tarball, { force: true })
if (authenticatedDownload) {
log(`tools: downloading the release from ${releaseRepository} with authentication using gh`)
gh([
'release',
'download',
tag,
'--repo',
releaseRepository,
'--pattern',
ASSET_NAME,
'--output',
tarball,
])
} else {
log(`tools: downloading the release from ${releaseRepository} using curl`)
curl([
'--location',
'--output',
tarball,
`https://github.com/${releaseRepository}/releases/download/${tag}/${ASSET_NAME}`,
])
}
}
export function isLocalToolsPath(tools) {
return tools.startsWith('/') || tools.startsWith('./') || tools.startsWith('../')
}
function parseBunVersion(stamp, tarball) {
const bunVersion = stamp.trim()
if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(bunVersion)) {
throw new Error(`AI Scan archive ${tarball} contains an invalid Bun version: ${bunVersion}`)
}
return bunVersion
}
/**
* Identifies the bundle format from the archive's entry point. Bun takes
* priority if both entry points exist. Older bundles contain `argus.js`,
* which must run on the exact Bun version in `ai-scan-bun-version`.
*/
function validateArchive(tarball, tar) {
// Map each normalized member name to its name in the archive.
let entries
try {
entries = new Map(
tar(['-tJf', tarball])
.split('\n')
.filter((entry) => entry.trim())
.map((entry) => [entry.trim().replace(/^\.\//, ''), entry.trim()]),
)
} catch (error) {
throw new Error(`AI Scan archive ${tarball} could not be listed`, { cause: error })
}
const hasNodeEntry = entries.has(NODE_ENTRY_POINT)
const hasBunEntry = entries.has(BUN_ENTRY_POINT)
// TODO(bun-compat): Remove the Bun path after production bundles use Node.
if (hasBunEntry) {
const stampEntry = entries.get(BUN_VERSION_STAMP)
let stamp
try {
if (!stampEntry) throw new Error(`${BUN_VERSION_STAMP} is missing`)
stamp = tar(['-xJOf', tarball, stampEntry])
} catch (error) {
throw new Error(
`AI Scan archive ${tarball} does not contain a readable ${BUN_VERSION_STAMP} stamp`,
{ cause: error },
)
}
return {
runtime: 'bun',
entryPoint: BUN_ENTRY_POINT,
bunVersion: parseBunVersion(stamp, tarball),
}
}
if (hasNodeEntry) return { runtime: 'node', entryPoint: NODE_ENTRY_POINT, bunVersion: '' }
throw new Error(
`AI Scan archive ${tarball} does not contain entry point ${NODE_ENTRY_POINT} or ${BUN_ENTRY_POINT}`,
)
}
export function resolveTools(
{ tools, releaseRepository, runnerTemp, actionStartedAt, apiUrl, repository },
dependencies,
) {
const { isFile, appendOutput, log, tar, gh } = dependencies
let tarball = tools
let implementationVersion = ''
const localTools = isLocalToolsPath(tools) ? isFile(tools) : false
if (localTools) {
log(`tools: using local tarball ${tools}`)
} else {
log(`tools: ${tools} is not a file`)
tarball = join(runnerTemp, ASSET_NAME)
const authenticatedDownload = releaseRepository !== PUBLIC_DISTRIBUTION_REPOSITORY
let tag = tools
let releaseDownloaded = false
if (!tag || tag === 'latest') {
if (readUseNextRelease(repository, apiUrl, dependencies)) {
try {
const pendingTag = resolvePendingTag(releaseRepository, gh)
if (pendingTag) {
downloadRelease(
releaseRepository,
pendingTag,
tarball,
authenticatedDownload,
dependencies,
)
validateArchive(tarball, tar)
log(`tools: pending release ${pendingTag} is valid`)
tag = pendingTag
releaseDownloaded = true
}
} catch (error) {
emitWarningAnnotation(
`Could not use the pending AI Scan release; falling back to latest (${error.message})`,
log,
)
}
}
if (!releaseDownloaded)
tag = resolveLatestTag(releaseRepository, authenticatedDownload, dependencies)
log(`tools: selected release ${tag}`)
}
implementationVersion = tag
if (!releaseDownloaded) {
downloadRelease(releaseRepository, tag, tarball, authenticatedDownload, dependencies)
}
}
const { runtime, entryPoint, bunVersion } = validateArchive(tarball, tar)
log(`tools: selected archive runs ${entryPoint} on ${runtime}`)
appendOutput(
[
`tarball=${tarball}`,
`runtime=${runtime}`,
`entry-point=${entryPoint}`,
`bun-version=${bunVersion}`,
`implementation-version=${implementationVersion}`,
`action-started-at=${actionStartedAt}`,
'',
].join('\n'),
)
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
try {
resolveTools(
{
tools: process.env.TOOLS ?? '',
releaseRepository: process.env.RELEASE_REPO,
runnerTemp: process.env.RUNNER_TEMP,
actionStartedAt: process.env.ACTION_STARTED_AT,
apiUrl: process.env.GITHUB_API_URL,
repository: process.env.GITHUB_REPOSITORY,
},
{
gh,
curl,
tar,
isFile: (path) => statSync(path, { throwIfNoEntry: false })?.isFile() ?? false,
appendOutput: (output) => appendFileSync(process.env.GITHUB_OUTPUT, output),
log: console.log,
},
)
} catch (error) {
emitErrorAnnotation(error.message)
process.exitCode = 1
}
}