-
Notifications
You must be signed in to change notification settings - Fork 1
/
yarn_remove_package_from_lock.js
executable file
·83 lines (70 loc) · 2.07 KB
/
yarn_remove_package_from_lock.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
#!/usr/bin/env node
/** @type {module:fs} */
const fs = require('fs');
const packagesToRemove = process.argv.slice(2);
/** @type {string} */
let yarnLock;
try {
yarnLock = fs.readFileSync('yarn.lock').toString();
} catch {
console.warn('could not read yarn.lock');
process.exit();
}
/**
* @param {string} lockContents
* @param {string} packageVersionHeader
*
* @return {string}
*/
const findBlockInLock = (lockContents, packageVersionHeader) => {
const lockEntryStart = lockContents.indexOf(packageVersionHeader);
if (lockEntryStart === -1) {
throw new Error(
`failed to find package in lock matching ${packageVersionHeader}`
);
}
// add a newline to ensure that we're matching against the "whole line" otherwise
// we'll error on e.g. `first-pkg` and `my-first-pkg` when trying to remove `first-pgk`
if (lockContents.indexOf(`\n${packageVersionHeader}`, lockEntryStart + 1) !== -1) {
throw new Error(
'INTEGRITY FAILURE: Multiple matches for packageVersionHeader in yarn.lock'
);
}
return lockContents.slice(
lockEntryStart,
lockContents.indexOf('\n\n', lockEntryStart)
);
};
/**
* @param {string} lockContents
* @param {string} entryHeader
*
* @return {string}
*/
const removePackageEntryFromLock = (lockContents, entryHeader) =>
lockContents.replace(findBlockInLock(lockContents, entryHeader), '');
/**
* @param {string} lockContents
* @param {string} packageName
*
* @return {Array<string>}
*/
const findPackageHeadersInLock = (lockContents, packageName) =>
lockContents.match(new RegExp(`^"?${packageName}@.+:`, 'gm')) || [];
/**
*
* @param {string} lockContents
* @param {string} packageName
*
* @return {string}
*/
const removePackageEntriesFromLock = (lockContents, packageName) =>
findPackageHeadersInLock(lockContents, packageName).reduce(
removePackageEntryFromLock,
lockContents
);
const newLock = packagesToRemove.reduce(removePackageEntriesFromLock, yarnLock);
if (newLock !== yarnLock) {
fs.writeFileSync('yarn.lock', newLock);
console.log(`removed some entries of ${packagesToRemove}`);
}