/
artifacts.ts
257 lines (232 loc) · 7.19 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
import is from '@sindresorhus/is';
import { quote } from 'shlex';
import { z } from 'zod';
import {
SYSTEM_INSUFFICIENT_DISK_SPACE,
TEMPORARY_ERROR,
} from '../../../constants/error-messages';
import { logger } from '../../../logger';
import { exec } from '../../../util/exec';
import type { ExecOptions, ToolConstraint } from '../../../util/exec/types';
import {
ensureCacheDir,
ensureLocalDir,
getSiblingFileName,
localPathExists,
readLocalFile,
writeLocalFile,
} from '../../../util/fs';
import { getRepoStatus } from '../../../util/git';
import * as hostRules from '../../../util/host-rules';
import { regEx } from '../../../util/regex';
import { Json } from '../../../util/schema-utils';
import { GitTagsDatasource } from '../../datasource/git-tags';
import { PackagistDatasource } from '../../datasource/packagist';
import type { UpdateArtifact, UpdateArtifactsResult } from '../types';
import { Lockfile, PackageFile } from './schema';
import type { AuthJson } from './types';
import {
extractConstraints,
findGithubToken,
getComposerArguments,
getPhpConstraint,
isArtifactAuthEnabled,
requireComposerDependencyInstallation,
takePersonalAccessTokenIfPossible,
} from './utils';
function getAuthJson(): string | null {
const authJson: AuthJson = {};
const githubHostRule = hostRules.find({
hostType: 'github',
url: 'https://api.github.com/',
});
const gitTagsHostRule = hostRules.find({
hostType: GitTagsDatasource.id,
url: 'https://github.com',
});
const selectedGithubToken = takePersonalAccessTokenIfPossible(
isArtifactAuthEnabled(githubHostRule)
? findGithubToken(githubHostRule)
: undefined,
isArtifactAuthEnabled(gitTagsHostRule)
? findGithubToken(gitTagsHostRule)
: undefined
);
if (selectedGithubToken) {
authJson['github-oauth'] = {
'github.com': selectedGithubToken,
};
}
for (const gitlabHostRule of hostRules.findAll({ hostType: 'gitlab' })) {
if (!isArtifactAuthEnabled(gitlabHostRule)) {
continue;
}
if (gitlabHostRule?.token) {
const host = gitlabHostRule.resolvedHost ?? 'gitlab.com';
authJson['gitlab-token'] = authJson['gitlab-token'] ?? {};
authJson['gitlab-token'][host] = gitlabHostRule.token;
// https://getcomposer.org/doc/articles/authentication-for-private-packages.md#gitlab-token
authJson['gitlab-domains'] = [
host,
...(authJson['gitlab-domains'] ?? []),
];
}
}
for (const packagistHostRule of hostRules.findAll({
hostType: PackagistDatasource.id,
})) {
if (!isArtifactAuthEnabled(packagistHostRule)) {
continue;
}
const { resolvedHost, username, password, token } = packagistHostRule;
if (resolvedHost && username && password) {
authJson['http-basic'] = authJson['http-basic'] ?? {};
authJson['http-basic'][resolvedHost] = { username, password };
} else if (resolvedHost && token) {
authJson.bearer = authJson.bearer ?? {};
authJson.bearer[resolvedHost] = token;
}
}
return is.emptyObject(authJson) ? null : JSON.stringify(authJson);
}
export async function updateArtifacts({
packageFileName,
updatedDeps,
newPackageFileContent,
config,
}: UpdateArtifact): Promise<UpdateArtifactsResult[] | null> {
logger.debug(`composer.updateArtifacts(${packageFileName})`);
const file = Json.pipe(PackageFile).parse(newPackageFileContent);
const lockFileName = packageFileName.replace(regEx(/\.json$/), '.lock');
const lockfile = await z
.string()
.transform((f) => readLocalFile(f, 'utf8'))
.pipe(Json)
.pipe(Lockfile)
.nullable()
.catch(null)
.parseAsync(lockFileName);
if (!lockfile) {
logger.debug('Composer: unable to read lockfile');
return null;
}
const vendorDir = getSiblingFileName(packageFileName, 'vendor');
const commitVendorFiles = await localPathExists(vendorDir);
await ensureLocalDir(vendorDir);
try {
await writeLocalFile(packageFileName, newPackageFileContent);
const constraints = {
...extractConstraints(file, lockfile),
...config.constraints,
};
const composerToolConstraint: ToolConstraint = {
toolName: 'composer',
constraint: constraints.composer,
};
const phpToolConstraint: ToolConstraint = {
toolName: 'php',
constraint: getPhpConstraint(constraints),
};
const execOptions: ExecOptions = {
cwdFile: packageFileName,
extraEnv: {
COMPOSER_CACHE_DIR: await ensureCacheDir('composer'),
COMPOSER_AUTH: getAuthJson(),
},
toolConstraints: [phpToolConstraint, composerToolConstraint],
docker: {},
};
const commands: string[] = [];
// Determine whether install is required before update
if (requireComposerDependencyInstallation(lockfile)) {
const preCmd = 'composer';
const preArgs =
'install' + getComposerArguments(config, composerToolConstraint);
logger.trace({ preCmd, preArgs }, 'composer pre-update command');
commands.push('git stash -- composer.json');
commands.push(`${preCmd} ${preArgs}`);
commands.push('git stash pop || true');
}
const cmd = 'composer';
let args: string;
if (config.isLockFileMaintenance) {
args = 'update';
} else {
args =
(
'update ' +
updatedDeps
.map((dep) => dep.depName)
.filter(is.string)
.map((dep) => quote(dep))
.join(' ')
).trim() + ' --with-dependencies';
}
args += getComposerArguments(config, composerToolConstraint);
logger.trace({ cmd, args }, 'composer command');
commands.push(`${cmd} ${args}`);
await exec(commands, execOptions);
const status = await getRepoStatus();
if (!status.modified.includes(lockFileName)) {
return null;
}
logger.debug('Returning updated composer.lock');
const res: UpdateArtifactsResult[] = [
{
file: {
type: 'addition',
path: lockFileName,
contents: await readLocalFile(lockFileName),
},
},
];
if (!commitVendorFiles) {
return res;
}
logger.debug(`Committing vendor files in ${vendorDir}`);
for (const f of [...status.modified, ...status.not_added]) {
if (f.startsWith(vendorDir)) {
res.push({
file: {
type: 'addition',
path: f,
contents: await readLocalFile(f),
},
});
}
}
for (const f of status.deleted) {
res.push({
file: {
type: 'deletion',
path: f,
},
});
}
return res;
} catch (err) {
// istanbul ignore if
if (err.message === TEMPORARY_ERROR) {
throw err;
}
if (
err.message?.includes(
'Your requirements could not be resolved to an installable set of packages.'
)
) {
logger.info('Composer requirements cannot be resolved');
} else if (err.message?.includes('write error (disk full?)')) {
throw new Error(SYSTEM_INSUFFICIENT_DISK_SPACE);
} else {
logger.debug({ err }, 'Failed to generate composer.lock');
}
return [
{
artifactError: {
lockFile: lockFileName,
stderr: err.message,
},
},
];
}
}