-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathartifacts.ts
536 lines (473 loc) · 15.7 KB
/
artifacts.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
535
536
import is from '@sindresorhus/is';
import semver from 'semver';
import { quote } from 'shlex';
import upath from 'upath';
import { GlobalConfig } from '../../../config/global';
import { TEMPORARY_ERROR } from '../../../constants/error-messages';
import { logger } from '../../../logger';
import { coerceArray } from '../../../util/array';
import { exec } from '../../../util/exec';
import type { ExecOptions } from '../../../util/exec/types';
import { filterMap } from '../../../util/filter-map';
import {
ensureCacheDir,
findLocalSiblingOrParent,
isValidLocalPath,
readLocalFile,
writeLocalFile,
} from '../../../util/fs';
import { getRepoStatus } from '../../../util/git';
import { getGitEnvironmentVariables } from '../../../util/git/auth';
import { regEx } from '../../../util/regex';
import { isValid } from '../../versioning/semver';
import type {
PackageDependency,
UpdateArtifact,
UpdateArtifactsConfig,
UpdateArtifactsResult,
} from '../types';
import { getExtraDepsNotice } from './artifacts-extra';
const { major, valid } = semver;
function getUpdateImportPathCmds(
updatedDeps: PackageDependency[],
{ constraints }: UpdateArtifactsConfig,
): string[] {
// Check if we fail to parse any major versions and log that they're skipped
const invalidMajorDeps = updatedDeps.filter(
({ newVersion }) => !valid(newVersion),
);
if (invalidMajorDeps.length > 0) {
invalidMajorDeps.forEach(({ depName }) =>
logger.warn(
{ depName },
'Ignoring dependency: Could not get major version',
),
);
}
const updateImportCommands = updatedDeps
.filter(
({ newVersion }) =>
valid(newVersion) && !newVersion!.endsWith('+incompatible'),
)
.map(({ depName, newVersion }) => ({
depName: depName!,
newMajor: major(newVersion!),
}))
// Skip path updates going from v0 to v1
.filter(
({ depName, newMajor }) =>
depName.startsWith('gopkg.in/') || newMajor > 1,
)
.map(
({ depName, newMajor }) =>
`mod upgrade --mod-name=${depName} -t=${newMajor}`,
);
if (updateImportCommands.length > 0) {
let installMarwanModArgs =
'install github.com/marwan-at-work/mod/cmd/mod@latest';
const gomodModCompatibility = constraints?.gomodMod;
if (gomodModCompatibility) {
if (
gomodModCompatibility.startsWith('v') &&
isValid(gomodModCompatibility.replace(regEx(/^v/), ''))
) {
installMarwanModArgs = installMarwanModArgs.replace(
regEx(/@latest$/),
`@${gomodModCompatibility}`,
);
} else {
logger.debug(
{ gomodModCompatibility },
'marwan-at-work/mod compatibility range is not valid - skipping',
);
}
} else {
logger.debug(
'No marwan-at-work/mod compatibility range found - installing marwan-at-work/mod latest',
);
}
updateImportCommands.unshift(`go ${installMarwanModArgs}`);
}
return updateImportCommands;
}
function useModcacherw(goVersion: string | undefined): boolean {
if (!is.string(goVersion)) {
return true;
}
const [, majorPart, minorPart] = coerceArray(
regEx(/(\d+)\.(\d+)/).exec(goVersion),
);
const [major, minor] = [majorPart, minorPart].map((x) => parseInt(x, 10));
return (
!Number.isNaN(major) &&
!Number.isNaN(minor) &&
(major > 1 || (major === 1 && minor >= 14))
);
}
export async function updateArtifacts({
packageFileName: goModFileName,
updatedDeps,
newPackageFileContent: newGoModContent,
config,
}: UpdateArtifact): Promise<UpdateArtifactsResult[] | null> {
logger.debug(`gomod.updateArtifacts(${goModFileName})`);
const sumFileName = goModFileName.replace(regEx(/\.mod$/), '.sum');
const existingGoSumContent = await readLocalFile(sumFileName);
if (!existingGoSumContent) {
logger.debug('No go.sum found');
return null;
}
const goModDir = upath.dirname(goModFileName);
const vendorDir = upath.join(goModDir, 'vendor/');
const vendorModulesFileName = upath.join(vendorDir, 'modules.txt');
const useVendor =
!!config.postUpdateOptions?.includes('gomodVendor') ||
(!config.postUpdateOptions?.includes('gomodSkipVendor') &&
(await readLocalFile(vendorModulesFileName)) !== null);
let massagedGoMod = newGoModContent;
if (config.postUpdateOptions?.includes('gomodMassage')) {
// Regex match inline replace directive, example:
// replace golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5
// https://go.dev/ref/mod#go-mod-file-replace
// replace bracket after comments, so it doesn't break the regex, doing a complex regex causes problems
// when there's a comment and ")" after it, the regex will read replace block until comment.. and stop.
massagedGoMod = massagedGoMod
.split('\n')
.map((line) => {
if (line.trim().startsWith('//')) {
return line.replace(')', 'renovate-replace-bracket');
}
return line;
})
.join('\n');
const inlineReplaceRegEx = regEx(
/(\r?\n)(replace\s+[^\s]+\s+=>\s+\.\.\/.*)/g,
);
// $1 will be matched with the (\r?n) group
// $2 will be matched with the inline replace match, example
// "// renovate-replace replace golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5"
const inlineCommentOut = '$1// renovate-replace $2';
// Regex match replace directive block, example:
// replace (
// golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5
// )
const blockReplaceRegEx = regEx(/(\r?\n)replace\s*\([^)]+\s*\)/g);
/**
* replacerFunction for commenting out replace blocks
* @param match A string representing a golang replace directive block
* @returns A commented out block with // renovate-replace
*/
const blockCommentOut = (match: string): string =>
match.replace(/(\r?\n)/g, '$1// renovate-replace ');
// Comment out golang replace directives
massagedGoMod = massagedGoMod
.replace(inlineReplaceRegEx, inlineCommentOut)
.replace(blockReplaceRegEx, blockCommentOut);
if (massagedGoMod !== newGoModContent) {
logger.debug(
'Removed some relative replace statements and comments from go.mod',
);
}
}
const goMod = getGoConfig(newGoModContent);
const goConstraints = config.constraints?.go ?? `^${goMod.minimalGoVersion}`;
const getFlags = ['-t'];
if (!semver.satisfies(goMod.minimalGoVersion, '>=1.17.0')) {
getFlags.unshift('-d');
}
const extraGetArguments: string[] = [];
if (semver.satisfies(goMod.minimalGoVersion, '>=1.21.0')) {
extraGetArguments.push(`toolchain@${goMod.toolchainDirective ?? 'none'}`);
extraGetArguments.push(`go@${goMod.goDirective}`);
// add package@version to go get command to let golang check if it work with current go directive
// if some package requires a too new go version,
// the go get command will fail and user get a "artifact update problem" notice.
for (const pkg of updatedDeps) {
const name = pkg.packageName ?? pkg.depName ?? pkg.name;
if (name === 'go' || !name) {
continue;
}
if (pkg.updateType === 'major') {
const newMajor = major(pkg.newVersion!);
extraGetArguments.push(
`${upgradePackageMajorVersion(name, newMajor)}@${pkg.newVersion}`,
);
} else {
extraGetArguments.push(`${name}@${pkg.newVersion}`);
}
}
}
try {
await writeLocalFile(goModFileName, massagedGoMod);
const cmd = 'go';
const execOptions: ExecOptions = {
cwdFile: goModFileName,
extraEnv: {
GOPATH: await ensureCacheDir('go'),
GOPROXY: process.env.GOPROXY,
GOPRIVATE: process.env.GOPRIVATE,
GONOPROXY: process.env.GONOPROXY,
GONOSUMDB: process.env.GONOSUMDB,
GOSUMDB: process.env.GOSUMDB,
GOINSECURE: process.env.GOINSECURE,
/* v8 ignore next -- TODO: add test */
GOFLAGS: useModcacherw(goConstraints) ? '-modcacherw' : null,
CGO_ENABLED: GlobalConfig.get('binarySource') === 'docker' ? '0' : null,
...getGitEnvironmentVariables(['go']),
},
docker: {},
toolConstraints: [
{
toolName: 'golang',
constraint: goConstraints,
},
],
};
const execCommands: string[] = [];
let goGetDirs: string | undefined;
if (config.goGetDirs) {
goGetDirs = config.goGetDirs
.filter((dir) => {
const isValid = isValidLocalPath(dir);
if (!isValid) {
logger.warn({ dir }, 'Invalid path in goGetDirs');
}
return isValid;
})
.map(quote)
.join(' ');
if (goGetDirs === '') {
throw new Error('Invalid goGetDirs');
}
}
let args = [
'get',
...getFlags,
goGetDirs ?? './...',
...extraGetArguments,
].join(' ');
logger.trace({ cmd, args }, 'go get command included');
execCommands.push(`${cmd} ${args}`);
// Update import paths on major updates
const isImportPathUpdateRequired =
config.postUpdateOptions?.includes('gomodUpdateImportPaths') &&
config.updateType === 'major';
if (isImportPathUpdateRequired) {
const updateImportCmds = getUpdateImportPathCmds(updatedDeps, config);
if (updateImportCmds.length > 0) {
logger.debug(updateImportCmds, 'update import path commands included');
// The updates
execCommands.push(...updateImportCmds);
}
}
const mustSkipGoModTidy =
!config.postUpdateOptions?.includes('gomodUpdateImportPaths') &&
config.updateType === 'major';
if (mustSkipGoModTidy) {
logger.debug('go mod tidy command skipped');
}
let tidyOpts = '';
if (config.postUpdateOptions?.includes('gomodTidy1.17')) {
tidyOpts += ' -compat=1.17';
}
if (config.postUpdateOptions?.includes('gomodTidyE')) {
tidyOpts += ' -e';
}
const isGoModTidyRequired =
!mustSkipGoModTidy &&
(config.postUpdateOptions?.includes('gomodTidy') === true ||
config.postUpdateOptions?.includes('gomodTidy1.17') === true ||
config.postUpdateOptions?.includes('gomodTidyE') === true ||
(config.updateType === 'major' && isImportPathUpdateRequired));
if (isGoModTidyRequired) {
args = 'mod tidy' + tidyOpts;
logger.debug('go mod tidy command included');
execCommands.push(`${cmd} ${args}`);
}
const goWorkSumFileName = upath.join(goModDir, 'go.work.sum');
if (useVendor) {
// If we find a go.work, then use go workspace vendoring.
const goWorkFile = await findLocalSiblingOrParent(
goModFileName,
'go.work',
);
if (goWorkFile) {
args = 'work vendor';
logger.debug('using go work vendor');
execCommands.push(`${cmd} ${args}`);
args = 'work sync';
logger.debug('using go work sync');
execCommands.push(`${cmd} ${args}`);
} else {
args = 'mod vendor';
logger.debug('using go mod vendor');
execCommands.push(`${cmd} ${args}`);
}
if (isGoModTidyRequired) {
args = 'mod tidy' + tidyOpts;
logger.debug('go mod tidy command included');
execCommands.push(`${cmd} ${args}`);
}
}
// We tidy one more time as a solution for #6795
if (isGoModTidyRequired) {
args = 'mod tidy' + tidyOpts;
logger.debug('go mod tidy command included');
execCommands.push(`${cmd} ${args}`);
}
await exec(execCommands, execOptions);
const status = await getRepoStatus();
if (
!status.modified.includes(sumFileName) &&
!status.modified.includes(goModFileName) &&
!status.modified.includes(goWorkSumFileName)
) {
return null;
}
const res: UpdateArtifactsResult[] = [];
if (status.modified.includes(sumFileName)) {
logger.debug('Returning updated go.sum');
res.push({
file: {
type: 'addition',
path: sumFileName,
contents: await readLocalFile(sumFileName),
},
});
}
if (status.modified.includes(goWorkSumFileName)) {
logger.debug('Returning updated go.work.sum');
res.push({
file: {
type: 'addition',
path: goWorkSumFileName,
contents: await readLocalFile(goWorkSumFileName),
},
});
}
// Include all the .go file import changes
if (isImportPathUpdateRequired) {
logger.debug('Returning updated go source files for import path changes');
for (const f of status.modified) {
if (f.endsWith('.go')) {
res.push({
file: {
type: 'addition',
path: f,
contents: await readLocalFile(f),
},
});
}
}
}
if (useVendor) {
for (const f of status.modified.concat(status.not_added)) {
if (f.startsWith(vendorDir)) {
res.push({
file: {
type: 'addition',
path: f,
contents: await readLocalFile(f),
},
});
}
}
for (const f of coerceArray(status.deleted)) {
res.push({
file: {
type: 'deletion',
path: f,
},
});
}
}
// TODO: throws in tests (#22198)
const finalGoModContent = (await readLocalFile(goModFileName, 'utf8'))!
.replace(regEx(/\/\/ renovate-replace /g), '')
.replace(regEx(/renovate-replace-bracket/g), ')');
if (finalGoModContent !== newGoModContent) {
const artifactResult: UpdateArtifactsResult = {
file: {
type: 'addition',
path: goModFileName,
contents: finalGoModContent,
},
};
const updatedDepNames = filterMap(updatedDeps, (dep) => dep?.depName);
const extraDepsNotice = getExtraDepsNotice(
newGoModContent,
finalGoModContent,
updatedDepNames,
);
if (extraDepsNotice) {
artifactResult.notice = {
file: goModFileName,
message: extraDepsNotice,
};
}
logger.debug('Found updated go.mod after go.sum update');
res.push(artifactResult);
}
return res;
} catch (err) {
// istanbul ignore if
if (err.message === TEMPORARY_ERROR) {
throw err;
}
logger.debug({ err }, 'Failed to update go.sum');
return [
{
artifactError: {
lockFile: sumFileName,
stderr: err.message,
},
},
];
}
}
function getGoConfig(content: string): {
toolchainDirective?: string;
minimalGoVersion: string;
goDirective: string;
} {
const toolchainMatch = regEx(/^toolchain\s*go(?<gover>\d+\.\d+\.\d+)$/m).exec(
content,
);
const toolchainVer = toolchainMatch?.groups?.gover;
const goMatch = regEx(/^go\s*(?<gover>\d+(\.\d+)+)$/m).exec(content);
// go mod spec says if go directive is missing it's 1.16
const goDirective = goMatch?.groups?.gover ?? '1.16';
let goVersion = goDirective;
// partial semver version without patch
if (/^\d+\.\d+$/.test(goVersion)) {
goVersion = `${goVersion}.0`;
}
return {
toolchainDirective: toolchainVer,
minimalGoVersion: goVersion,
goDirective,
};
}
function upgradePackageMajorVersion(name: string, newMajor: number): string {
if (name.startsWith('gopkg.in/')) {
const s = name.split('.');
return `${s.slice(0, -1).join('.')}.v${newMajor}`;
}
// v0 => v1, no need to handle it
if (newMajor === 1) {
return name;
}
const s = name.split('/');
const last = s.at(-1);
// there is no valid case that a go pakcage name doesn't contain slash.
/* v8 ignore next 5 -- typescript strict null check */
if (!last) {
throw new Error(
`unreadable: go package name ${name} doesn't contain any slash`,
);
}
if (/^v\d+$/.test(last)) {
return `${s.slice(0, -1).join('/')}/v${newMajor}`;
}
return `${name}/v${newMajor}`;
}