-
Notifications
You must be signed in to change notification settings - Fork 0
/
publish.ts
107 lines (94 loc) · 2.47 KB
/
publish.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
import { spawn } from "child_process";
import path from "path";
import { readFile, writeFile, readdir } from "fs/promises";
import { resolve } from "path";
import { cwd } from "process";
import { PackageJson } from "type-fest";
import { unlink, rename } from "fs/promises";
import { existsSync } from "fs";
const runCommand = async (
cwd: string,
command: string,
args: string[],
beforeRun?: () => Promise<void>,
afterRun?: () => Promise<void>
) => {
console.log(
`\nRunning "${command} ${args.join(" ")}" for ${path.basename(cwd)}:`
);
if (beforeRun) {
await beforeRun();
}
try {
await new Promise<void>((resolve) => {
spawn(command, args, { cwd, stdio: "inherit" }).on("exit", async function (
error
) {
if (error) {
if (afterRun) {
await afterRun();
}
console.log(`Failed to run ${command} at ${cwd}`);
process.exit(1);
}
resolve();
});
});
} finally {
if (afterRun) {
await afterRun();
}
}
};
const getPackages = async () => {
const exceptPackages = ["vite-react-example", "kikko-doc"];
const packagesPath = resolve(cwd(), "packages");
return (await readdir(resolve(packagesPath), { withFileTypes: true }))
.filter((w) => w.isDirectory() && !exceptPackages.includes(w.name))
.map((w) => ({
name: `@kikko-land/${w.name}`,
dir: `${packagesPath}/${w.name}`,
}));
};
const updateJson = async (
file: string,
cb: (arg: PackageJson) => PackageJson,
backup = false
) => {
const content = (await readFile(file)).toString();
if (backup) {
await writeFile(file + ".backup", content);
}
const packageContent = JSON.parse(content);
await writeFile(file, JSON.stringify(cb(packageContent), undefined, 2));
};
const run = async () => {
const packages = await getPackages();
runCommand(
resolve(cwd()),
"yarn",
["changeset", "publish"],
async () => {
packages.map(async ({ dir }) => {
await updateJson(
dir + "/package.json",
(json) => {
return {
...json,
...json["publishConfig"],
};
},
true
);
});
},
async () => {
packages.map(async ({ dir }) => {
if (!existsSync(dir + "/package.json.backup")) return;
await unlink(dir + "/package.json");
await rename(dir + "/package.json.backup", dir + "/package.json");
});
}
);
};
run();