-
Notifications
You must be signed in to change notification settings - Fork 552
/
Copy pathinstaller.ts
534 lines (461 loc) · 14.4 KB
/
installer.ts
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
import * as tc from '@actions/tool-cache';
import * as core from '@actions/core';
import * as path from 'path';
import * as semver from 'semver';
import * as httpm from '@actions/http-client';
import * as sys from './system';
import fs from 'fs';
import os from 'os';
import {StableReleaseAlias} from './utils';
const MANIFEST_REPO_OWNER = 'actions';
const MANIFEST_REPO_NAME = 'go-versions';
const MANIFEST_REPO_BRANCH = 'main';
const MANIFEST_URL = `https://raw.githubusercontent.com/${MANIFEST_REPO_OWNER}/${MANIFEST_REPO_NAME}/${MANIFEST_REPO_BRANCH}/versions-manifest.json`;
type InstallationType = 'dist' | 'manifest';
export interface IGoVersionFile {
filename: string;
// darwin, linux, windows
os: string;
arch: string;
}
export interface IGoVersion {
version: string;
stable: boolean;
files: IGoVersionFile[];
}
export interface IGoVersionInfo {
type: InstallationType;
downloadUrl: string;
resolvedVersion: string;
fileName: string;
}
export async function getGo(
versionSpec: string,
checkLatest: boolean,
auth: string | undefined,
arch = os.arch()
) {
let manifest: tc.IToolRelease[] | undefined;
const osPlat: string = os.platform();
if (
versionSpec === StableReleaseAlias.Stable ||
versionSpec === StableReleaseAlias.OldStable
) {
manifest = await getManifest(auth);
let stableVersion = await resolveStableVersionInput(
versionSpec,
arch,
osPlat,
manifest
);
if (!stableVersion) {
stableVersion = await resolveStableVersionDist(versionSpec, arch);
if (!stableVersion) {
throw new Error(
`Unable to find Go version '${versionSpec}' for platform ${osPlat} and architecture ${arch}.`
);
}
}
core.info(`${versionSpec} version resolved as ${stableVersion}`);
versionSpec = stableVersion;
}
if (checkLatest) {
core.info('Attempting to resolve the latest version from the manifest...');
const resolvedVersion = await resolveVersionFromManifest(
versionSpec,
true,
auth,
arch,
manifest
);
if (resolvedVersion) {
versionSpec = resolvedVersion;
core.info(`Resolved as '${versionSpec}'`);
} else {
core.info(`Failed to resolve version ${versionSpec} from manifest`);
}
}
// check cache
const toolPath = tc.find('go', versionSpec, arch);
// If not found in cache, download
if (toolPath) {
core.info(`Found in cache @ ${toolPath}`);
return toolPath;
}
core.info(`Attempting to download ${versionSpec}...`);
let downloadPath = '';
let info: IGoVersionInfo | null = null;
//
// Try download from internal distribution (popular versions only)
//
try {
info = await getInfoFromManifest(versionSpec, true, auth, arch, manifest);
if (info) {
downloadPath = await installGoVersion(info, auth, arch);
} else {
core.info(
'Not found in manifest. Falling back to download directly from Go'
);
}
} catch (err) {
if (
err instanceof tc.HTTPError &&
(err.httpStatusCode === 403 || err.httpStatusCode === 429)
) {
core.info(
`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`
);
} else {
core.info((err as Error).message);
}
core.debug((err as Error).stack ?? '');
core.info('Falling back to download directly from Go');
}
//
// Download from storage.googleapis.com
//
if (!downloadPath) {
info = await getInfoFromDist(versionSpec, arch);
if (!info) {
throw new Error(
`Unable to find Go version '${versionSpec}' for platform ${osPlat} and architecture ${arch}.`
);
}
try {
core.info('Install from dist');
downloadPath = await installGoVersion(info, undefined, arch);
} catch (err) {
throw new Error(`Failed to download version ${versionSpec}: ${err}`);
}
}
return downloadPath;
}
async function resolveVersionFromManifest(
versionSpec: string,
stable: boolean,
auth: string | undefined,
arch: string,
manifest: tc.IToolRelease[] | undefined
): Promise<string | undefined> {
try {
const info = await getInfoFromManifest(
versionSpec,
stable,
auth,
arch,
manifest
);
return info?.resolvedVersion;
} catch (err) {
core.info('Unable to resolve a version from the manifest...');
core.debug((err as Error).message);
}
}
// for github hosted windows runner handle latency of OS drive
// by avoiding write operations to C:
async function cacheWindowsDir(
extPath: string,
tool: string,
version: string,
arch: string
): Promise<string | false> {
if (os.platform() !== 'win32') return false;
// make sure the action runs in the hosted environment
if (
process.env['RUNNER_ENVIRONMENT'] !== 'github-hosted' &&
process.env['AGENT_ISSELFHOSTED'] === '1'
)
return false;
const defaultToolCacheRoot = process.env['RUNNER_TOOL_CACHE'];
if (!defaultToolCacheRoot) return false;
if (!fs.existsSync('d:\\') || !fs.existsSync('c:\\')) return false;
const actualToolCacheRoot = defaultToolCacheRoot
.replace('C:', 'D:')
.replace('c:', 'd:');
// make toolcache root to be on drive d:
process.env['RUNNER_TOOL_CACHE'] = actualToolCacheRoot;
const actualToolCacheDir = await tc.cacheDir(extPath, tool, version, arch);
// create a link from c: to d:
const defaultToolCacheDir = actualToolCacheDir.replace(
actualToolCacheRoot,
defaultToolCacheRoot
);
fs.mkdirSync(path.dirname(defaultToolCacheDir), {recursive: true});
fs.symlinkSync(actualToolCacheDir, defaultToolCacheDir, 'junction');
core.info(`Created link ${defaultToolCacheDir} => ${actualToolCacheDir}`);
const actualToolCacheCompleteFile = `${actualToolCacheDir}.complete`;
const defaultToolCacheCompleteFile = `${defaultToolCacheDir}.complete`;
fs.symlinkSync(
actualToolCacheCompleteFile,
defaultToolCacheCompleteFile,
'file'
);
core.info(
`Created link ${defaultToolCacheCompleteFile} => ${actualToolCacheCompleteFile}`
);
// make outer code to continue using toolcache as if it were installed on c:
// restore toolcache root to default drive c:
process.env['RUNNER_TOOL_CACHE'] = defaultToolCacheRoot;
return defaultToolCacheDir;
}
async function addExecutablesToToolCache(
extPath: string,
info: IGoVersionInfo,
arch: string
): Promise<string> {
const tool = 'go';
const version = makeSemver(info.resolvedVersion);
return (
(await cacheWindowsDir(extPath, tool, version, arch)) ||
(await tc.cacheDir(extPath, tool, version, arch))
);
}
async function installGoVersion(
info: IGoVersionInfo,
auth: string | undefined,
arch: string
): Promise<string> {
core.info(`Acquiring ${info.resolvedVersion} from ${info.downloadUrl}`);
// Windows requires that we keep the extension (.zip) for extraction
const isWindows = os.platform() === 'win32';
const tempDir = process.env.RUNNER_TEMP || '.';
const fileName = isWindows ? path.join(tempDir, info.fileName) : undefined;
const downloadPath = await tc.downloadTool(info.downloadUrl, fileName, auth);
core.info('Extracting Go...');
let extPath = await extractGoArchive(downloadPath);
core.info(`Successfully extracted go to ${extPath}`);
if (info.type === 'dist') {
extPath = path.join(extPath, 'go');
}
core.info('Adding to the cache ...');
const toolCacheDir = await addExecutablesToToolCache(extPath, info, arch);
core.info(`Successfully cached go to ${toolCacheDir}`);
return toolCacheDir;
}
export async function extractGoArchive(archivePath: string): Promise<string> {
const platform = os.platform();
let extPath: string;
if (platform === 'win32') {
extPath = await tc.extractZip(archivePath);
} else {
extPath = await tc.extractTar(archivePath);
}
return extPath;
}
export async function getManifest(
auth: string | undefined
): Promise<tc.IToolRelease[]> {
try {
return await getManifestFromRepo(auth);
} catch (err) {
core.debug('Fetching the manifest via the API failed.');
if (err instanceof Error) {
core.debug(err.message);
}
}
return await getManifestFromURL();
}
function getManifestFromRepo(
auth: string | undefined
): Promise<tc.IToolRelease[]> {
core.debug(
`Getting manifest from ${MANIFEST_REPO_OWNER}/${MANIFEST_REPO_NAME}@${MANIFEST_REPO_BRANCH}`
);
return tc.getManifestFromRepo(
MANIFEST_REPO_OWNER,
MANIFEST_REPO_NAME,
auth,
MANIFEST_REPO_BRANCH
);
}
async function getManifestFromURL(): Promise<tc.IToolRelease[]> {
core.debug('Falling back to fetching the manifest using raw URL.');
const http: httpm.HttpClient = new httpm.HttpClient('tool-cache');
const response = await http.getJson<tc.IToolRelease[]>(MANIFEST_URL);
if (!response.result) {
throw new Error(`Unable to get manifest from ${MANIFEST_URL}`);
}
return response.result;
}
export async function getInfoFromManifest(
versionSpec: string,
stable: boolean,
auth: string | undefined,
arch = os.arch(),
manifest?: tc.IToolRelease[] | undefined
): Promise<IGoVersionInfo | null> {
let info: IGoVersionInfo | null = null;
if (!manifest) {
core.debug('No manifest cached');
manifest = await getManifest(auth);
}
core.info(`matching ${versionSpec}...`);
const rel = await tc.findFromManifest(versionSpec, stable, manifest, arch);
if (rel && rel.files.length > 0) {
info = <IGoVersionInfo>{};
info.type = 'manifest';
info.resolvedVersion = rel.version;
info.downloadUrl = rel.files[0].download_url;
info.fileName = rel.files[0].filename;
}
return info;
}
async function getInfoFromDist(
versionSpec: string,
arch: string
): Promise<IGoVersionInfo | null> {
const version: IGoVersion | undefined = await findMatch(versionSpec, arch);
if (!version) {
return null;
}
const downloadUrl = `https://storage.googleapis.com/golang/${version.files[0].filename}`;
return <IGoVersionInfo>{
type: 'dist',
downloadUrl: downloadUrl,
resolvedVersion: version.version,
fileName: version.files[0].filename
};
}
export async function findMatch(
versionSpec: string,
arch = os.arch()
): Promise<IGoVersion | undefined> {
const archFilter = sys.getArch(arch);
const platFilter = sys.getPlatform();
let result: IGoVersion | undefined;
let match: IGoVersion | undefined;
const dlUrl = 'https://golang.org/dl/?mode=json&include=all';
const candidates: IGoVersion[] | null = await module.exports.getVersionsDist(
dlUrl
);
if (!candidates) {
throw new Error(`golang download url did not return results`);
}
let goFile: IGoVersionFile | undefined;
for (let i = 0; i < candidates.length; i++) {
const candidate: IGoVersion = candidates[i];
const version = makeSemver(candidate.version);
core.debug(`check ${version} satisfies ${versionSpec}`);
if (semver.satisfies(version, versionSpec)) {
goFile = candidate.files.find(file => {
core.debug(
`${file.arch}===${archFilter} && ${file.os}===${platFilter}`
);
return file.arch === archFilter && file.os === platFilter;
});
if (goFile) {
core.debug(`matched ${candidate.version}`);
match = candidate;
break;
}
}
}
if (match && goFile) {
// clone since we're mutating the file list to be only the file that matches
result = <IGoVersion>Object.assign({}, match);
result.files = [goFile];
}
return result;
}
export async function getVersionsDist(
dlUrl: string
): Promise<IGoVersion[] | null> {
// this returns versions descending so latest is first
const http: httpm.HttpClient = new httpm.HttpClient('setup-go', [], {
allowRedirects: true,
maxRedirects: 3
});
return (await http.getJson<IGoVersion[]>(dlUrl)).result;
}
//
// Convert the go version syntax into semver for semver matching
// 1.13.1 => 1.13.1
// 1.13 => 1.13.0
// 1.10beta1 => 1.10.0-beta.1, 1.10rc1 => 1.10.0-rc.1
// 1.8.5beta1 => 1.8.5-beta.1, 1.8.5rc1 => 1.8.5-rc.1
export function makeSemver(version: string): string {
version = version.replace('go', '');
version = version.replace('beta', '-beta.').replace('rc', '-rc.');
const parts = version.split('-');
const semVersion = semver.coerce(parts[0])?.version;
if (!semVersion) {
throw new Error(
`The version: ${version} can't be changed to SemVer notation`
);
}
if (!parts[1]) {
return semVersion;
}
const fullVersion = semver.valid(`${semVersion}-${parts[1]}`);
if (!fullVersion) {
throw new Error(
`The version: ${version} can't be changed to SemVer notation`
);
}
return fullVersion;
}
export function parseGoVersionFile(versionFilePath: string): string {
const contents = fs.readFileSync(versionFilePath).toString();
if (
path.basename(versionFilePath) === 'go.mod' ||
path.basename(versionFilePath) === 'go.work'
) {
const match = contents.match(/^go (\d+(\.\d+)*)/m);
return match ? match[1] : '';
}
return contents.trim();
}
async function resolveStableVersionDist(versionSpec: string, arch: string) {
const archFilter = sys.getArch(arch);
const platFilter = sys.getPlatform();
const dlUrl = 'https://golang.org/dl/?mode=json&include=all';
const candidates: IGoVersion[] | null = await module.exports.getVersionsDist(
dlUrl
);
if (!candidates) {
throw new Error(`golang download url did not return results`);
}
const fixedCandidates = candidates.map(item => {
return {
...item,
version: makeSemver(item.version)
};
});
const stableVersion = await resolveStableVersionInput(
versionSpec,
archFilter,
platFilter,
fixedCandidates
);
return stableVersion;
}
export async function resolveStableVersionInput(
versionSpec: string,
arch: string,
platform: string,
manifest: tc.IToolRelease[] | IGoVersion[]
) {
const releases = manifest
.map(item => {
const index = item.files.findIndex(
item => item.arch === arch && item.filename.includes(platform)
);
if (index === -1) {
return '';
}
return item.version;
})
.filter(item => !!item && !semver.prerelease(item));
if (versionSpec === StableReleaseAlias.Stable) {
return releases[0];
} else {
const versions = releases.map(
release => `${semver.major(release)}.${semver.minor(release)}`
);
const uniqueVersions = Array.from(new Set(versions));
const oldstableVersion = releases.find(item =>
item.startsWith(uniqueVersions[1])
);
return oldstableVersion;
}
}