/
update-lockfile-version.ts
78 lines (71 loc) · 2.86 KB
/
update-lockfile-version.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
import path from 'path';
import loadJsonFile from 'load-json-file';
import writeJsonFile from 'write-json-file';
import { Package, Project } from '@lerna-lite/core';
/**
* Update NPM Lock File (when found), the lock file might be version 1 (exist in package folder) or version 2 (exist in workspace root)
* Depending on the version type, the structure of the lock file will be different and will be updated accordingly
* @param {Object} pkg
* @param {Object} project
* @returns Promise
*/
export async function updateClassicLockfileVersion(pkg: Package): Promise<string | undefined> {
try {
// "lockfileVersion" = 1, package lock file might be located in the package folder
const lockFilePath = path.join(pkg.location, 'package-lock.json');
const pkgLockFileObj: any = await loadJsonFile(lockFilePath);
if (pkgLockFileObj) {
pkgLockFileObj.version = pkg.version;
// update version for a npm lockfile v2 format
if (pkgLockFileObj.packages?.['']) {
pkgLockFileObj.packages[''].version = pkg.version;
}
await writeJsonFile(lockFilePath, pkgLockFileObj, {
detectIndent: true,
indent: 2,
});
return lockFilePath;
}
} catch (error) { } // eslint-disable-line
}
export async function updateModernLockfileVersion(pkg: Package, project: Project): Promise<string | undefined> {
try {
// OR "lockfileVersion" >= 2 in the project root, will have a global package lock file located in the root folder and is formatted
const projFilePath = path.join(project.rootPath, 'package-lock.json');
const projLockFileObj: any = await loadJsonFile(projFilePath);
if (projLockFileObj) {
updateNpmLockFileVersion2(projLockFileObj, pkg.name, pkg.version);
await writeJsonFile(projFilePath, projLockFileObj, {
detectIndent: true,
indent: 2,
});
return projFilePath;
}
} catch (error) { } // eslint-disable-line
}
/**
* Update workspace root NPM Lock File Version Type 2
* @param {Object} obj
* @param {String} pkgName
* @param {String} newVersion
*/
export function updateNpmLockFileVersion2(obj: any, pkgName: string, newVersion: string) {
if (typeof obj === 'object' && pkgName && newVersion) {
for (const k in obj) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
updateNpmLockFileVersion2(obj[k], pkgName, newVersion);
} else {
if (k === pkgName) {
// e.g.: "@lerna-lite/core": "^0.1.2",
const [_, versionPrefix, _versionStr] = obj[k].match(/^([\^~])?(.*)$/);
obj[k] = `${versionPrefix}${newVersion}`;
} else if (k === 'name' && obj[k] === pkgName && obj['version'] !== undefined) {
// e.g. "packages/version": { "name": "@lerna-lite/version", "version": "0.1.2" }
if (obj['version'] !== undefined) {
obj['version'] = newVersion;
}
}
}
}
}
}