-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·360 lines (329 loc) · 9.89 KB
/
index.js
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
#!/usr/bin/env node
const { program } = require('commander');
const { execSync, spawnSync } = require("child_process");
const fs = require('fs');
const os = require('os');
const consola = require('consola');
const path = require('path');
const commandExistsSync = require('command-exists').sync;
const { exit } = require('process');
// The working directory has to be global, it's used in the error handler.
let workdir;
// Error handler.
process.on('uncaughtException', err => {
if (workdir) {
consola.info('Removing working directory...');
fs.rmdirSync(workdir, { recursive: true });
}
consola.error(err.message);
process.exit(1)
})
// Command handling.
let root = handleCommand();
// Check for needed CLI tools.
checkTools();
// Check root and get composer.json.
let json = preFlightCheck(root);
// Let's start the job by creating a temporary working directory.
workdir = createWorkDir();
// Add a modified composer.json without patch application.
json = addComposerJson(json);
// Install dependencies using Composer.
installDependencies();
// Get a list of the patches and add the package paths.
let patchList = getPatchList(json, root);
// Check the patches.
checkPatches(patchList);
// Done, cleanup things.
consola.info('Removing working directory...');
fs.rmdirSync(workdir, { recursive: true });
consola.success('Done!');
process.exit(0);
/**
* Check the patches against the tagged releases
*
* @param {*} patchList
*/
function checkPatches(patchList) {
consola.info('List of patched packages and patch files:');
for (const [package, value] of Object.entries(patchList).sort()) {
consola.info(`Checking patches for package ${package}...`);
for (const item of value.patches) {
checkPatch(package, item.description, item.patchfile, value.path);
}
}
}
/**
* Check a single patch against a package.
*
* @param {*} description - the patch description
* @param {*} patchfile - the absolute path to the patch file
* @param {*} path - the absolute package location
*/
function checkPatch(package, description, patchfile, path) {
// Enter the package folder
const workdir = process.cwd();
try {
process.chdir(path);
}
catch {
consola.warn(`Skipping patch for ${package}, package not found. Maybe the patch should be removed.`)
return;
}
// Get the package version and a list of tags in the same branch.
const version = getPackageVersion();
consola.log(' Installed version: ' + version);
const tags = getTags(version);
consola.log(' Patch description: ' + description);
// Check the patchfile against the related tags.
for (const tag of tags) {
switch (checkTag(tag, patchfile)) {
case 1:
consola.log(' - Patch has been applied to tag: ' + tag);
break;
case 0:
consola.log(' - Patch is applicable for tag: ' + tag);
break;
default:
consola.log(' - Patch is not applicable for tag: ' + tag);
break;
}
}
// Return to working directory
process.chdir(workdir);
}
/**
* Check a patch against a given tag / dependency release.
*
* @param {*} tag
* @param {*} patchfile
*/
function checkTag(tag, patchfile) {
// Checkout the tag.
let result = execSyncSilent(`git checkout ${tag}`);
if (result.error) {
throw new Error(result.output);
}
// Check patch applicability.
return patch(patchfile);
}
/**
* Check a patch file against the current package.
*
* @param {*} patchfile - The patch file to be checked.
*/
function patch(patchfile) {
let command;
// Try the patch using all the possible patch levels.
for (let level = 0; level < 5; level++) {
// Check if the patch has been applied already.
command = spawnSync('patch', [
`-p${level}`,
'-R',
'--dry-run',
'--no-backup-if-mismatch',
'--silent',
`--input=${patchfile}`
]);
if (command.status === 0) { // Patch has been applied already.
return 1;
}
// Check if the patch can be applied.
command = spawnSync('patch', [
`-p${level}`,
'--dry-run',
'--no-backup-if-mismatch',
'--silent',
`--input=${patchfile}`
]);
if (command.status === 0) { // Patch is applicable.
return 0;
}
}
return -1; // Patch isn't applicable, or there was an error.
}
/**
* Get the current version of a dependency.
*/
function getPackageVersion() {
const result = execSyncSilent(`git tag --points-at`);
if (result.error) {
throw new Error(result.output);
}
return result.output.trim();
}
/**
* Get the tags (releases) related to a given dependency version.
*
* @param {*} version
*/
function getTags(version) {
if (!version) {
return [];
}
const prefix = version.substring(0, version.lastIndexOf('.'));
const result = execSyncSilent(`git tag --sort=creatordate | grep ${prefix}`);
if (result.error) {
throw new Error(result.output);
}
const tags = result.output.match(/[^\r\n]+/g);
return tags;
}
/**
* Defines and handles the command.
*/
function handleCommand() {
program
.arguments('<root>')
.description('Checks Drupal patches managed by Composer against package releases', {
root: 'Drupal project root with composer.json',
})
.version(require('./package').version)
.addHelpText('after', `
Usage example:
$ cdp /var/www/drupal`);
program.parse();
let root = program.args[0];
if (!root) {
program.outputHelp();
exit(1);
}
root = path.resolve(root);
return root;
}
/**
* Get a list of all patches and their meta information.
*
* @param {*} json - the applied composer.json file
* @param string root - the Drupal project root directory
*/
function getPatchList(json, root) {
const patches = json.extra.patches || require(root + '/' + json.extra['patches-file']).patches;
const command = 'composer show -P -f json';
const result = execSyncSilent(command);
if (result.error) {
throw new Error(result.output);
}
// Flatten the patch list
let flat = {};
for (const [package, value] of Object.entries(patches).sort()) {
flat[package] = {
"path": "",
"patches": []
};
for (const [patch, file] of Object.entries(value)) {
flat[package].patches.push({
"description": patch,
"patchfile": root + '/' + file,
});
}
}
// Add the paths.
const paths = JSON.parse(result.output);
for (const item of paths.installed) {
if (flat[item.name]) {
flat[item.name].path = item.path;
}
}
return flat;
}
/**
* Installs dependencies from source.
*/
function installDependencies() {
consola.info('Installing dependencies from source, this will take quite some time...');
const command = 'composer update --no-autoloader --no-scripts --prefer-source --ignore-platform-reqs';
const result = execSyncSilent(command);
if (result.error) {
throw new Error(result.output);
}
consola.success('Dependencies installed successfully');
}
/**
* Adds a modified composer.json to the working directory.
*
* @param {*} json - the original composer.json
*/
function addComposerJson(json) {
// Remove patches plugin.
delete json.require['cweagans/composer-patches'];
fs.writeFileSync('composer.json', JSON.stringify(json));
// Validate composer.json.
const command = 'composer validate';
const result = execSyncSilent(command);
if (result.error) {
throw new Error(result.output);
}
consola.success('composer.json is valid');
return json;
}
/**
* Creates and enters the working directory.
*/
function createWorkDir() {
const directory = os.tmpdir() + '/cdp';
fs.rmdirSync(directory, { recursive: true });
fs.mkdirSync(directory);
process.chdir(directory);
return directory;
}
/**
* Check project root and composer.json
*/
function preFlightCheck(root) {
if (!fs.existsSync(root)) {
throw new Error('Invalid project root');
}
consola.success('Found project root');
if (!fs.existsSync(root + '/composer.json')) {
throw new Error('composer.json not found in project root');
}
consola.success('Found composer.json');
var json = fs.readFileSync(root + '/composer.json');
try {
json = JSON.parse(json);
} catch (e) {
throw new Error('composer.json is no valid json file ' + e);
}
consola.success('composer.json is a valid JSON file');
if (!json.extra || (!json.extra.patches && !json.extra['patches-file'])) {
throw new Error('composer.json does not list any patches');
}
consola.success('composer.json has a list of patches');
return json;
}
/**
* Check if the needed CLI tools are installed.
*/
function checkTools() {
if (parseInt(process.versions.node.split('.')[0]) < 12) {
throw new Error('NodeJS >= 12 is needed for execution');
}
if (!commandExistsSync('patch')) {
throw new Error('Patch utility is needed for execution');
}
if (!commandExistsSync('git')) {
throw new Error('Git is needed for execution');
}
if (!commandExistsSync('composer')) {
throw new Error('Composer is needed for execution');
}
}
/**
* Execute CLI command synchronously.
*
* @param {*} command - the command to be executed
*/
function execSyncSilent(command) {
try {
return {
"error": 0,
"output": execSync(command, { stdio: ['pipe', 'pipe', 'pipe'] }).toString()
}
} catch (error) {
return {
"error": error.status,
"output": error.toString(),
};
}
}