-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbuilder.ts
More file actions
340 lines (294 loc) · 8.34 KB
/
builder.ts
File metadata and controls
340 lines (294 loc) · 8.34 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
import is from '@sindresorhus/is';
import chalk from 'chalk';
import { ReleaseResult, getPkgReleases } from 'renovate/dist/datasource';
import { get as getVersioning } from 'renovate/dist/versioning';
import { exec, isDryRun } from '../../util';
import { getArg } from '../../utils/cli';
import { build, publish } from '../../utils/docker';
import { init } from '../../utils/docker/buildx';
import { dockerDf, dockerPrune, dockerTag } from '../../utils/docker/common';
import { readFile, readJson } from '../../utils/fs';
import log from '../../utils/logger';
import * as renovate from '../../utils/renovate';
renovate.register();
export const MultiArgsSplitRe = /\s*(?:[;,]|$)\s*/;
let latestStable: string | undefined;
function getVersions(versions: string[]): ReleaseResult {
return {
releases: versions.map((version) => ({
version,
})),
};
}
async function getBuildList({
datasource,
depName,
versioning,
startVersion,
ignoredVersions,
lastOnly,
forceUnstable,
versions,
latestVersion,
}: Config): Promise<string[]> {
log('Looking up versions');
const ver = getVersioning(versioning as never);
const pkgResult = versions
? getVersions(versions)
: await getPkgReleases({
datasource,
depName,
versioning,
});
if (!pkgResult) {
return [];
}
let allVersions = pkgResult.releases
.map((v) => v.version)
.filter((v) => ver.isVersion(v) && ver.isCompatible(v, startVersion));
log(`Found ${allVersions.length} total versions`);
if (!allVersions.length) {
return [];
}
allVersions = allVersions
.filter((v) => v === startVersion || ver.isGreaterThan(v, startVersion))
.filter((v) => !ignoredVersions.includes(v));
if (!forceUnstable) {
log('Filter unstable versions');
allVersions = allVersions.filter((v) => ver.isStable(v));
}
log(`Found ${allVersions.length} versions within our range`);
log(`Candidates:`, allVersions.join(', '));
latestStable =
latestVersion ||
pkgResult.latestVersion ||
allVersions.filter((v) => ver.isStable(v)).pop();
log('Latest stable version is ', latestStable);
if (latestStable && !allVersions.includes(latestStable)) {
log.warn(
`LatestStable '${latestStable}' not buildable, candidates: `,
allVersions.join(', ')
);
}
const lastVersion = allVersions[allVersions.length - 1];
log('Most recent version is ', lastVersion);
if (lastOnly) {
log('Building last version only');
allVersions = [latestStable && !forceUnstable ? latestStable : lastVersion];
}
if (allVersions.length) {
log('Build list: ', allVersions.join(', '));
} else {
log('Nothing to build');
}
return allVersions;
}
function createTag(tagSuffix: string | undefined, version: string): string {
return is.nonEmptyString(tagSuffix) && tagSuffix !== 'latest'
? `${version}-${tagSuffix}`
: version;
}
async function buildAndPush(
{
image,
buildArg,
buildArgs,
buildOnly,
cache,
dryRun,
tagSuffix,
versioning,
majorMinor,
prune,
}: Config,
versions: string[]
): Promise<void> {
const builds: string[] = [];
const failed: string[] = [];
const ver = getVersioning(versioning || 'semver');
const versionsMap = new Map<string, string>();
if (majorMinor) {
for (const version of versions) {
const minor = ver.getMinor(version);
const major = ver.getMajor(version);
const isStable = ver.isStable(version);
if (isStable && is.number(major) && `${major}` !== version) {
versionsMap.set(`${major}`, version);
}
if (
isStable &&
is.number(major) &&
is.number(minor) &&
`${major}.${minor}` !== version
) {
versionsMap.set(`${major}.${minor}`, version);
}
}
}
await exec('df', ['-h']);
for (const version of versions) {
const tag = createTag(tagSuffix, version);
const imageVersion = `renovate/${image}:${tag}`;
log(`Building ${imageVersion}`);
try {
const minor = ver.getMinor(version);
const major = ver.getMajor(version);
const cacheTags: string[] = [tagSuffix ?? 'latest'];
const tags: string[] = [];
if (
is.number(major) &&
majorMinor &&
versionsMap.get(`${major}`) === version
) {
const nTag = createTag(tagSuffix, `${major}`);
cacheTags.push(nTag);
tags.push(nTag);
}
if (
is.number(major) &&
is.number(minor) &&
majorMinor &&
versionsMap.get(`${major}.${minor}`) === version
) {
const nTag = createTag(tagSuffix, `${major}.${minor}`);
cacheTags.push(nTag);
tags.push(nTag);
}
if (version === latestStable) {
tags.push(tagSuffix ?? 'latest');
}
await build({
image,
tag,
cache,
cacheTags,
buildArgs: [...(buildArgs ?? []), `${buildArg}=${version}`],
dryRun,
});
if (!buildOnly) {
await publish({ image, tag, dryRun });
const source = tag;
for (const tag of tags) {
log(`Publish ${source} as ${tag}`);
await dockerTag({ image, src: source, tgt: tag });
await publish({ image, tag, dryRun });
}
}
log(`Build ${imageVersion}`);
builds.push(version);
} catch (err) {
log.error(err);
failed.push(version);
}
await dockerDf();
await exec('df', ['-h']);
if (prune) {
await dockerPrune();
await exec('df', ['-h']);
}
}
if (builds.length) {
log('Build list: ' + builds.join(' '));
}
if (failed.length) {
log.warn('Failed list: ' + failed.join(' '));
throw new Error('failed');
}
}
type ConfigFile = {
datasource: string;
image: string;
depName?: string;
versioning?: string;
startVersion: string;
cache?: string;
buildArg?: string;
ignoredVersions?: string[];
forceUnstable?: boolean;
versions?: string[];
latestVersion?: string;
};
type Config = {
buildArg: string;
buildArgs?: string[];
buildOnly: boolean;
tagSuffix?: string;
depName: string;
image: string;
ignoredVersions: string[];
majorMinor: boolean;
lastOnly: boolean;
dryRun: boolean;
prune: boolean;
} & ConfigFile;
async function generateImages(config: Config): Promise<void> {
const buildList = await getBuildList(config);
await buildAndPush(config, buildList);
}
const keys: (keyof ConfigFile)[] = [
'datasource',
'depName',
'buildArg',
'versioning',
'latestVersion',
];
function checkArgs(
cfg: ConfigFile,
groups: Record<string, string | undefined>
): void {
for (const key of keys) {
if (!is.string(cfg[key]) && is.nonEmptyString(groups[key])) {
cfg[key] = groups[key] as never;
}
}
}
async function readDockerConfig(cfg: ConfigFile): Promise<void> {
const dockerFileRe = new RegExp(
'# renovate: datasource=(?<datasource>.*?) depName=(?<depName>.*?)( versioning=(?<versioning>.*?))?\\s' +
`(?:ENV|ARG) ${cfg.buildArg as string}=(?<latestVersion>.*)\\s`,
'g'
);
const dockerfile = await readFile('Dockerfile');
const m = dockerFileRe.exec(dockerfile);
if (m && m.groups) {
checkArgs(cfg, m.groups);
}
}
export async function run(): Promise<void> {
const dryRun = isDryRun();
const configFile = getArg('config') || 'builder.json';
const cfg = await readJson<ConfigFile>(configFile);
if (!is.object(cfg)) {
throw new Error('missing-config');
}
// TODO: validation
if (!is.string(cfg.image)) {
cfg.image = getArg('image', { required: true });
}
if (!is.string(cfg.buildArg)) {
cfg.buildArg = cfg.image.toUpperCase() + '_VERSION';
}
await readDockerConfig(cfg);
const config: Config = {
...cfg,
image: cfg.image,
depName: cfg.depName ?? cfg.image,
buildArg: cfg.buildArg,
buildArgs: getArg('build-args', { multi: true }),
tagSuffix: getArg('tag-suffix') || undefined,
ignoredVersions: cfg.ignoredVersions ?? [],
dryRun,
lastOnly: getArg('last-only') == 'true',
buildOnly: getArg('build-only') == 'true',
majorMinor: getArg('major-minor') !== 'false',
prune: getArg('prune') === 'true',
};
if (dryRun) {
log('GitHub Actions branch detected - Force building latest, no push');
config.lastOnly = true;
}
log('config:', JSON.stringify(config));
await init();
await generateImages(config);
log.info(chalk.blue('Processing done:', config.image));
}