-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathmain.ts
More file actions
297 lines (276 loc) · 9.56 KB
/
main.ts
File metadata and controls
297 lines (276 loc) · 9.56 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
import * as core from '@actions/core';
import truncate from 'truncate-utf8-bytes';
import path from 'path';
import {exec} from './exec';
import {
devcontainer,
DevContainerCliBuildArgs,
DevContainerCliExecArgs,
DevContainerCliUpArgs,
MAJOR_VERSION_FALLBACK
} from '../../common/src/dev-container-cli';
import {isDockerBuildXInstalled, pushImage} from './docker';
import {isSkopeoInstalled, copyImage} from './skopeo';
import {populateDefaults} from '../../common/src/envvars';
// List the env vars that point to paths to mount in the dev container
// See https://docs.github.com/en/actions/learn-github-actions/variables
const githubEnvs = {
GITHUB_OUTPUT: '/mnt/github/output',
GITHUB_ENV: '/mnt/github/env',
GITHUB_PATH: '/mnt/github/path',
GITHUB_STEP_SUMMARY: '/mnt/github/step-summary',
};
export async function runMain(): Promise<void> {
try {
core.info('Starting...');
core.saveState('hasRunMain', 'true');
const buildXInstalled = await isDockerBuildXInstalled();
if (!buildXInstalled) {
core.warning(
'docker buildx not available: add a step to set up with docker/setup-buildx-action - see https://github.com/devcontainers/ci/blob/main/docs/github-action.md',
);
return;
}
const specifiedDevContainerCliVersion =
core.getInput('cliVersion') ?? MAJOR_VERSION_FALLBACK;
const devContainerCliInstalled = await devcontainer.isCliInstalled(
exec,
specifiedDevContainerCliVersion,
);
if (!devContainerCliInstalled) {
core.info('Installing @devcontainers/cli...');
const success = await devcontainer.installCli(
exec,
specifiedDevContainerCliVersion,
);
if (!success) {
core.setFailed('@devcontainers/cli install failed!');
return;
}
}
const checkoutPath: string = core.getInput('checkoutPath');
const imageName = emptyStringAsUndefined(core.getInput('imageName'));
const imageTag = emptyStringAsUndefined(core.getInput('imageTag'));
const platform = emptyStringAsUndefined(core.getInput('platform'));
const subFolder: string = core.getInput('subFolder');
const relativeConfigFile = emptyStringAsUndefined(
core.getInput('configFile'),
);
const runCommand = core.getInput('runCmd');
const inputEnvs: string[] = core.getMultilineInput('env');
const inheritEnv: boolean = core.getBooleanInput('inheritEnv');
const inputEnvsWithDefaults = populateDefaults(inputEnvs, inheritEnv);
const cacheFrom: string[] = core.getMultilineInput('cacheFrom');
const noCache: boolean = core.getBooleanInput('noCache');
const cacheTo: string[] = core.getMultilineInput('cacheTo');
const skipContainerUserIdUpdate = core.getBooleanInput(
'skipContainerUserIdUpdate',
);
const userDataFolder: string = core.getInput('userDataFolder');
const mounts: string[] = core.getMultilineInput('mounts');
if (platform) {
const skopeoInstalled = await isSkopeoInstalled();
if (!skopeoInstalled) {
core.warning(
'skopeo not available and is required for multi-platform builds - make sure it is installed on your runner',
);
return;
}
}
const buildxOutput = platform ? 'type=oci,dest=/tmp/output.tar' : undefined;
const log = (message: string): void => core.info(message);
const workspaceFolder = path.resolve(checkoutPath, subFolder);
const configFile =
relativeConfigFile && path.resolve(checkoutPath, relativeConfigFile);
const resolvedImageTag = imageTag ?? 'latest';
const imageTagArray = resolvedImageTag.split(/\s*,\s*/);
const fullImageNameArray: string[] = [];
for (const tag of imageTagArray) {
fullImageNameArray.push(`${imageName}:${tag}`);
}
if (imageName) {
if (fullImageNameArray.length === 1) {
if (!noCache && !cacheFrom.includes(fullImageNameArray[0])) {
// If the cacheFrom options don't include the fullImageName, add it here
// This ensures that when building a PR where the image specified in the action
// isn't included in devcontainer.json (or docker-compose.yml), the action still
// resolves a previous image for the tag as a layer cache (if pushed to a registry)
core.info(
`Adding --cache-from ${fullImageNameArray[0]} to build args`,
);
cacheFrom.splice(0, 0, fullImageNameArray[0]);
}
} else {
// Don't automatically add --cache-from if multiple image tags are specified
core.info(
'Not adding --cache-from automatically since multiple image tags were supplied',
);
}
} else {
if (imageTag) {
core.warning(
'imageTag specified without specifying imageName - ignoring imageTag',
);
}
}
const buildResult = await core.group('🏗️ build container', async () => {
const args: DevContainerCliBuildArgs = {
workspaceFolder,
configFile,
imageName: fullImageNameArray,
platform,
additionalCacheFroms: cacheFrom,
userDataFolder,
output: buildxOutput,
noCache,
cacheTo,
};
const result = await devcontainer.build(args, log);
if (result.outcome !== 'success') {
core.error(
`Dev container build failed: ${result.message} (exit code: ${result.code})\n${result.description}`,
);
core.setFailed(result.message);
}
return result;
});
if (buildResult.outcome !== 'success') {
return;
}
for (const [key, value] of Object.entries(githubEnvs)) {
if (process.env[key]) {
// Add additional bind mount
mounts.push(`type=bind,source=${process.env[key]},target=${value}`);
// Set env var to mounted path in container
inputEnvsWithDefaults.push(`${key}=${value}`);
}
}
if (runCommand) {
const upResult = await core.group('🏃 start container', async () => {
const args: DevContainerCliUpArgs = {
workspaceFolder,
configFile,
additionalCacheFroms: cacheFrom,
skipContainerUserIdUpdate,
env: inputEnvsWithDefaults,
userDataFolder,
additionalMounts: mounts,
};
const result = await devcontainer.up(args, log);
if (result.outcome !== 'success') {
core.error(
`Dev container up failed: ${result.message} (exit code: ${result.code})\n${result.description}`,
);
core.setFailed(result.message);
}
return result;
});
if (upResult.outcome !== 'success') {
return;
}
const args: DevContainerCliExecArgs = {
workspaceFolder,
configFile,
command: ['bash', '-c', runCommand],
env: inputEnvsWithDefaults,
userDataFolder,
};
let execLogString = '';
const execLog = (message: string): void => {
core.info(message);
if (!message.includes('@devcontainers/cli')) {
execLogString += message;
}
};
const exitCode = await devcontainer.exec(args, execLog);
if (exitCode !== 0) {
const errorMessage = `Dev container exec failed: (exit code: ${exitCode})`;
core.error(errorMessage);
core.setFailed(errorMessage);
}
core.setOutput('runCmdOutput', execLogString);
if (Buffer.byteLength(execLogString, 'utf-8') > 1000000) {
execLogString = truncate(execLogString, 999966);
execLogString += 'TRUNCATED TO 1 MB MAX OUTPUT SIZE';
}
core.setOutput('runCmdOutput', execLogString);
if (exitCode !== 0) {
return;
}
} else {
core.info('No runCmd set - skipping starting/running container');
}
// TODO - should we stop the container?
} catch (error) {
core.setFailed(error.message);
}
}
export async function runPost(): Promise<void> {
const pushOption = emptyStringAsUndefined(core.getInput('push'));
const imageName = emptyStringAsUndefined(core.getInput('imageName'));
const refFilterForPush: string[] = core.getMultilineInput('refFilterForPush');
const eventFilterForPush: string[] =
core.getMultilineInput('eventFilterForPush');
// default to 'never' if not set and no imageName
if (pushOption === 'never' || (!pushOption && !imageName)) {
core.info(`Image push skipped because 'push' is set to '${pushOption}'`);
return;
}
// default to 'filter' if not set and imageName is set
if (pushOption === 'filter' || (!pushOption && imageName)) {
// https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables
const ref = process.env.GITHUB_REF;
if (
refFilterForPush.length !== 0 && // empty filter allows all
!refFilterForPush.some(s => s === ref)
) {
core.info(
`Image push skipped because GITHUB_REF (${ref}) is not in refFilterForPush`,
);
return;
}
const eventName = process.env.GITHUB_EVENT_NAME;
if (
eventFilterForPush.length !== 0 && // empty filter allows all
!eventFilterForPush.some(s => s === eventName)
) {
core.info(
`Image push skipped because GITHUB_EVENT_NAME (${eventName}) is not in eventFilterForPush`,
);
return;
}
} else if (pushOption !== 'always') {
core.setFailed(`Unexpected push value ('${pushOption})'`);
return;
}
const imageTag =
emptyStringAsUndefined(core.getInput('imageTag')) ?? 'latest';
const imageTagArray = imageTag.split(/\s*,\s*/);
if (!imageName) {
if (pushOption) {
// pushOption was set (and not to "never") - give an error that imageName is required
core.error('imageName is required to push images');
}
return;
}
const platform = emptyStringAsUndefined(core.getInput('platform'));
if (platform) {
for (const tag of imageTagArray) {
core.info(`Copying multiplatform image '${imageName}:${tag}'...`);
const imageSource = `oci-archive:/tmp/output.tar:${tag}`;
const imageDest = `docker://${imageName}:${tag}`;
await copyImage(true, imageSource, imageDest);
}
} else {
for (const tag of imageTagArray) {
core.info(`Pushing image '${imageName}:${tag}'...`);
await pushImage(imageName, tag);
}
}
}
function emptyStringAsUndefined(value: string): string | undefined {
if (value === '') {
return undefined;
}
return value;
}