-
Notifications
You must be signed in to change notification settings - Fork 21
/
install.ts
233 lines (204 loc) · 8.74 KB
/
install.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
/**
* Copyright 2023 actions-toolkit authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'fs';
import os from 'os';
import path from 'path';
import * as core from '@actions/core';
import * as httpm from '@actions/http-client';
import * as tc from '@actions/tool-cache';
import * as semver from 'semver';
import * as util from 'util';
import {Buildx} from './buildx';
import {Context} from '../context';
import {Exec} from '../exec';
import {Docker} from '../docker/docker';
import {Git} from '../git';
import {GitHubRelease} from '../types/github';
export interface InstallOpts {
standalone?: boolean;
}
export class Install {
private readonly _standalone: boolean | undefined;
constructor(opts?: InstallOpts) {
this._standalone = opts?.standalone;
}
public async download(version: string): Promise<string> {
const release: GitHubRelease = await Install.getRelease(version);
const fversion = release.tag_name.replace(/^v+|v+$/g, '');
core.debug(`Install.download version: ${fversion}`);
let toolPath: string;
toolPath = tc.find('buildx', fversion, this.platform());
if (!toolPath) {
const c = semver.clean(fversion) || '';
if (!semver.valid(c)) {
throw new Error(`Invalid Buildx version "${fversion}".`);
}
toolPath = await this.fetchBinary(fversion);
}
core.debug(`Install.download toolPath: ${toolPath}`);
return toolPath;
}
public async build(gitContext: string): Promise<string> {
// eslint-disable-next-line prefer-const
let [repo, ref] = gitContext.split('#');
if (ref.length == 0) {
ref = 'master';
}
let vspec: string;
// TODO: include full ref as fingerprint. Use commit sha as best-effort in the meantime.
if (ref.match(/^[0-9a-fA-F]{40}$/)) {
vspec = ref;
} else {
vspec = await Git.remoteSha(repo, ref, process.env.GIT_AUTH_TOKEN);
}
core.debug(`Install.build: tool version spec ${vspec}`);
let toolPath: string;
toolPath = tc.find('buildx', vspec);
if (!toolPath) {
const outputDir = path.join(Context.tmpDir(), 'build-cache');
const buildCmd = await this.buildCommand(gitContext, outputDir);
toolPath = await Exec.getExecOutput(buildCmd.command, buildCmd.args, {
ignoreReturnCode: true
}).then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
throw new Error(`build failed with: ${res.stderr.match(/(.*)\s*$/)?.[0]?.trim() ?? 'unknown error'}`);
}
return tc.cacheFile(`${outputDir}/buildx`, os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx', 'buildx', vspec, this.platform());
});
}
return toolPath;
}
public async installStandalone(toolPath: string, dest?: string): Promise<string> {
core.info('Standalone mode');
dest = dest || Context.tmpDir();
const toolBinPath = path.join(toolPath, os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx');
const binDir = path.join(dest, 'bin');
if (!fs.existsSync(binDir)) {
fs.mkdirSync(binDir, {recursive: true});
}
const filename: string = os.platform() == 'win32' ? 'buildx.exe' : 'buildx';
const buildxPath: string = path.join(binDir, filename);
fs.copyFileSync(toolBinPath, buildxPath);
core.info('Fixing perms');
fs.chmodSync(buildxPath, '0755');
core.addPath(binDir);
core.info('Added Buildx to PATH');
core.info(`Binary path: ${buildxPath}`);
return buildxPath;
}
public async installPlugin(toolPath: string, dest?: string): Promise<string> {
core.info('Docker plugin mode');
dest = dest || Docker.configDir;
const toolBinPath = path.join(toolPath, os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx');
const pluginsDir: string = path.join(dest, 'cli-plugins');
if (!fs.existsSync(pluginsDir)) {
fs.mkdirSync(pluginsDir, {recursive: true});
}
const filename: string = os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx';
const pluginPath: string = path.join(pluginsDir, filename);
fs.copyFileSync(toolBinPath, pluginPath);
core.info('Fixing perms');
fs.chmodSync(pluginPath, '0755');
core.info(`Plugin path: ${pluginPath}`);
return pluginPath;
}
private async buildCommand(gitContext: string, outputDir: string): Promise<{args: Array<string>; command: string}> {
const buildxStandaloneFound = await new Buildx({standalone: true}).isAvailable();
const buildxPluginFound = await new Buildx({standalone: false}).isAvailable();
let buildStandalone = false;
if ((await this.isStandalone()) && buildxStandaloneFound) {
core.debug(`Install.buildCommand: Buildx standalone found, build with it`);
buildStandalone = true;
} else if (!(await this.isStandalone()) && buildxPluginFound) {
core.debug(`Install.buildCommand: Buildx plugin found, build with it`);
buildStandalone = false;
} else if (buildxStandaloneFound) {
core.debug(`Install.buildCommand: Buildx plugin not found, but standalone found so trying to build with it`);
buildStandalone = true;
} else if (buildxPluginFound) {
core.debug(`Install.buildCommand: Buildx standalone not found, but plugin found so trying to build with it`);
buildStandalone = false;
} else {
throw new Error(`Neither buildx standalone or plugin have been found to build from ref ${gitContext}`);
}
const args = ['build', '--target', 'binaries', '--build-arg', 'BUILDKIT_CONTEXT_KEEP_GIT_DIR=1', '--output', `type=local,dest=${outputDir}`];
if (process.env.GIT_AUTH_TOKEN) {
args.push('--secret', 'id=GIT_AUTH_TOKEN');
}
args.push(gitContext);
//prettier-ignore
return await new Buildx({standalone: buildStandalone}).getCommand(args);
}
private async isStandalone(): Promise<boolean> {
const standalone = this._standalone ?? !(await Docker.isAvailable());
core.debug(`Install.isStandalone: ${standalone}`);
return standalone;
}
private async fetchBinary(version: string): Promise<string> {
const targetFile: string = os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx';
const downloadURL = util.format('https://github.com/docker/buildx/releases/download/v%s/%s', version, this.filename(version));
core.info(`Downloading ${downloadURL}`);
const downloadPath = await tc.downloadTool(downloadURL);
core.debug(`Install.fetchBinary downloadPath: ${downloadPath}`);
return await tc.cacheFile(downloadPath, targetFile, 'buildx', version, this.platform());
}
private platform(): string {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const arm_version = (process.config.variables as any).arm_version;
return `${os.platform()}-${os.arch()}${arm_version ? 'v' + arm_version : ''}`;
}
private filename(version: string): string {
let arch: string;
switch (os.arch()) {
case 'x64': {
arch = 'amd64';
break;
}
case 'ppc64': {
arch = 'ppc64le';
break;
}
case 'arm': {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const arm_version = (process.config.variables as any).arm_version;
arch = arm_version ? 'arm-v' + arm_version : 'arm';
break;
}
default: {
arch = os.arch();
break;
}
}
const platform: string = os.platform() == 'win32' ? 'windows' : os.platform();
const ext: string = os.platform() == 'win32' ? '.exe' : '';
return util.format('buildx-v%s.%s-%s%s', version, platform, arch, ext);
}
public static async getRelease(version: string): Promise<GitHubRelease> {
const url = `https://raw.githubusercontent.com/docker/actions-toolkit/main/.github/buildx-releases.json`;
const http: httpm.HttpClient = new httpm.HttpClient('docker-actions-toolkit');
const resp: httpm.HttpClientResponse = await http.get(url);
const body = await resp.readBody();
const statusCode = resp.message.statusCode || 500;
if (statusCode >= 400) {
throw new Error(`Failed to get Buildx release ${version} from ${url} with status code ${statusCode}: ${body}`);
}
const releases = <Record<string, GitHubRelease>>JSON.parse(body);
if (!releases[version]) {
throw new Error(`Cannot find Buildx release ${version} in ${url}`);
}
return releases[version];
}
}