merge.ts
1.91 KB
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
import type { JsonValue } from "../types";
import fs from "node:fs";
import fsp from "node:fs/promises";
export async function mergeJson(targetPath: string, mergeObj: Record<string, JsonValue>): Promise<void> {
const exists = fs.existsSync(targetPath);
const targetObj: JsonValue = exists ? (JSON.parse(await fsp.readFile(targetPath, "utf8")) as JsonValue) : {};
const merged = deepMerge(targetObj, mergeObj);
const sorted = sortKeys(merged);
await fsp.writeFile(targetPath, JSON.stringify(sorted, null, 2));
}
function sortKeys(obj: JsonValue, parentKey?: string): JsonValue {
if (Array.isArray(obj)) {
return obj.map((item) => sortKeys(item, parentKey));
}
if (isPlainObject(obj)) {
// 仅对 dependencies/devDependencies 等依赖 map 按包名排序
const shouldSort = parentKey && (parentKey === "dependencies" || parentKey === "devDependencies" || parentKey === "peerDependencies" || parentKey === "optionalDependencies");
const keys = shouldSort ? Object.keys(obj).sort() : Object.keys(obj);
const sorted: Record<string, JsonValue> = {};
for (const key of keys) {
sorted[key] = sortKeys(obj[key], key);
}
return sorted;
}
return obj;
}
function deepMerge(a: JsonValue, b: JsonValue | undefined): JsonValue {
if (b === undefined) return a;
if (Array.isArray(a) && Array.isArray(b)) {
return [ ...new Set([ ...a, ...b ]) ];
}
if (isPlainObject(a) && isPlainObject(b)) {
const aObj = a as Record<string, JsonValue>;
const bObj = b as Record<string, JsonValue>;
const out: Record<string, JsonValue> = { ...aObj };
for (const key of Object.keys(bObj)) {
const aValue = aObj[key];
const bValue = bObj[key];
if (bValue !== undefined) {
out[key] = key in aObj && aValue !== undefined ? deepMerge(aValue, bValue) : bValue;
}
}
return out;
}
return b;
}
function isPlainObject(v: unknown): v is Record<string, JsonValue> {
return !!v && typeof v === "object" && !Array.isArray(v);
}