@peiyanlu/cli-utils 0.0.4 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1219 -0
- package/dist/index.d.cts +525 -0
- package/dist/index.d.mts +525 -0
- package/dist/index.mjs +1115 -0
- package/package.json +9 -5
- package/dist/cjs/index.cjs +0 -344
- package/dist/cjs/index.d.cts +0 -114
- package/dist/esm/index.d.mts +0 -114
- package/dist/esm/index.mjs +0 -312
package/dist/esm/index.mjs
DELETED
|
@@ -1,312 +0,0 @@
|
|
|
1
|
-
import { exec, execSync, spawn, spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
-
import { copyFile, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
4
|
-
import { EOL } from "node:os";
|
|
5
|
-
import { join, resolve } from "node:path";
|
|
6
|
-
import { styleText } from "node:util";
|
|
7
|
-
|
|
8
|
-
//#region src/enums.ts
|
|
9
|
-
let PkgManager = /* @__PURE__ */ function(PkgManager$1) {
|
|
10
|
-
PkgManager$1["NPM"] = "npm";
|
|
11
|
-
PkgManager$1["YARN"] = "yarn";
|
|
12
|
-
PkgManager$1["PNPM"] = "pnpm";
|
|
13
|
-
return PkgManager$1;
|
|
14
|
-
}({});
|
|
15
|
-
/**
|
|
16
|
-
* @deprecated Use `ConfirmResult` instead.
|
|
17
|
-
*/
|
|
18
|
-
let YesOrNo = /* @__PURE__ */ function(YesOrNo$1) {
|
|
19
|
-
YesOrNo$1["Yes"] = "yes";
|
|
20
|
-
YesOrNo$1["No"] = "no";
|
|
21
|
-
YesOrNo$1["Ignore"] = "ignore";
|
|
22
|
-
return YesOrNo$1;
|
|
23
|
-
}({});
|
|
24
|
-
let ConfirmResult = /* @__PURE__ */ function(ConfirmResult$1) {
|
|
25
|
-
ConfirmResult$1["YES"] = "yes";
|
|
26
|
-
ConfirmResult$1["NO"] = "no";
|
|
27
|
-
ConfirmResult$1["IGNORE"] = "ignore";
|
|
28
|
-
return ConfirmResult$1;
|
|
29
|
-
}({});
|
|
30
|
-
let HttpLibrary = /* @__PURE__ */ function(HttpLibrary$1) {
|
|
31
|
-
HttpLibrary$1["EXPRESS"] = "express";
|
|
32
|
-
HttpLibrary$1["FASTIFY"] = "fastify";
|
|
33
|
-
HttpLibrary$1["KOA"] = "koa";
|
|
34
|
-
HttpLibrary$1["HONO"] = "hono";
|
|
35
|
-
return HttpLibrary$1;
|
|
36
|
-
}({});
|
|
37
|
-
|
|
38
|
-
//#endregion
|
|
39
|
-
//#region src/utils.ts
|
|
40
|
-
const isValidPackageName = (packageName) => {
|
|
41
|
-
return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(packageName);
|
|
42
|
-
};
|
|
43
|
-
const toValidPackageName = (packageName) => packageName.trim().toLowerCase().replace(/\s+/g, "-").replace(/^[._]/, "").replace(/[^a-z\d\-~]+/g, "-");
|
|
44
|
-
const toValidProjectName = (projectName) => projectName.trim().replace(/\/+$/g, "");
|
|
45
|
-
const emptyDir = async (dir, ignore = []) => {
|
|
46
|
-
if (!existsSync(dir)) return false;
|
|
47
|
-
for (const file of await readdir(dir)) {
|
|
48
|
-
if (ignore.includes(file)) continue;
|
|
49
|
-
await rm(resolve(dir, file), {
|
|
50
|
-
recursive: true,
|
|
51
|
-
force: true
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
return true;
|
|
55
|
-
};
|
|
56
|
-
const isEmpty = async (path, ignore = []) => {
|
|
57
|
-
return (await readdir(path)).filter((f) => !ignore.includes(f)).length === 0;
|
|
58
|
-
};
|
|
59
|
-
const editFile = async (file, callback) => {
|
|
60
|
-
if (!existsSync(file)) return;
|
|
61
|
-
return writeFile(file, callback(await readFile(file, "utf-8")), "utf-8");
|
|
62
|
-
};
|
|
63
|
-
const editJsonFile = (file, callback) => {
|
|
64
|
-
return editFile(file, (str) => {
|
|
65
|
-
try {
|
|
66
|
-
const json = JSON.parse(str);
|
|
67
|
-
callback(json);
|
|
68
|
-
return JSON.stringify(json, null, 2);
|
|
69
|
-
} catch (e) {
|
|
70
|
-
console.error(e);
|
|
71
|
-
return str;
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
|
-
};
|
|
75
|
-
const readSubDirs = async (source, ignore = []) => {
|
|
76
|
-
return (await readdir(source, { withFileTypes: true })).filter((k) => k.isDirectory() && !ignore.includes(k.name)).map((dir) => dir.name);
|
|
77
|
-
};
|
|
78
|
-
const copyDirAsync = async (src, dest, options) => {
|
|
79
|
-
await mkdir(dest, { recursive: true });
|
|
80
|
-
const entries = await readdir(src, { withFileTypes: true });
|
|
81
|
-
for (const entry of entries) {
|
|
82
|
-
const name = entry.name;
|
|
83
|
-
const isDir = entry.isDirectory();
|
|
84
|
-
const { rename = {}, skips = [] } = options;
|
|
85
|
-
const relName = rename[name] ?? name;
|
|
86
|
-
if (skips.some((rule) => rule(name, isDir))) continue;
|
|
87
|
-
const from = join(src, name);
|
|
88
|
-
const to = join(dest, relName);
|
|
89
|
-
if (isDir) await copyDirAsync(from, to, options);
|
|
90
|
-
else await copyFile(from, to);
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
const readJsonFile = (file) => {
|
|
94
|
-
if (!existsSync(file)) return {};
|
|
95
|
-
try {
|
|
96
|
-
return JSON.parse(readFileSync(file, "utf-8"));
|
|
97
|
-
} catch (e) {
|
|
98
|
-
return {};
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
/** 通过包管理器执行脚本时生效 UserAgent: `process.env.npm_config_user_agent` */
|
|
102
|
-
const pkgFromUserAgent = (userAgent) => {
|
|
103
|
-
if (!userAgent) return void 0;
|
|
104
|
-
const [name, version] = userAgent.split(" ")[0].split("/");
|
|
105
|
-
return {
|
|
106
|
-
name,
|
|
107
|
-
version
|
|
108
|
-
};
|
|
109
|
-
};
|
|
110
|
-
/** 同步执行 Node CLI(用于测试环境) */
|
|
111
|
-
const runCliForTest = (path, args, options) => {
|
|
112
|
-
return spawnSync("node", [path, ...args], {
|
|
113
|
-
env: {
|
|
114
|
-
...process.env,
|
|
115
|
-
_VITE_TEST_CLI: "true"
|
|
116
|
-
},
|
|
117
|
-
encoding: "utf-8",
|
|
118
|
-
...options
|
|
119
|
-
});
|
|
120
|
-
};
|
|
121
|
-
/** 判断测试文件(夹) */
|
|
122
|
-
const isTestFile = (name) => {
|
|
123
|
-
return [
|
|
124
|
-
/(^|[\\/])(test(s?)|__test(s?)__)([\\/]|$)/,
|
|
125
|
-
/\.([a-zA-Z0-9]+-)?(test|spec)\.m?(ts|js)$/,
|
|
126
|
-
/^vitest([-.])(.*)\.m?(ts|js)$/
|
|
127
|
-
].some((reg) => reg.test(name));
|
|
128
|
-
};
|
|
129
|
-
/** 解析 Github 链接获取 owner 和 repo */
|
|
130
|
-
const parseGitHubRepo = (url) => {
|
|
131
|
-
const match = url.trim().match(/github(?:\.com)?[:/](.+?)\/(.+?)(?:[#/?].+?)?(?:\.git)?$/);
|
|
132
|
-
return match ? match.slice(1, 3) : [];
|
|
133
|
-
};
|
|
134
|
-
/** 基于 EOL 的可多换行函数 */
|
|
135
|
-
const eol = (n = 1) => EOL.repeat(n);
|
|
136
|
-
|
|
137
|
-
//#endregion
|
|
138
|
-
//#region src/styleText.ts
|
|
139
|
-
const dim = (text) => styleText(["dim"], text);
|
|
140
|
-
const red = (text) => styleText(["red"], text);
|
|
141
|
-
|
|
142
|
-
//#endregion
|
|
143
|
-
//#region src/shell.ts
|
|
144
|
-
/** 异步执行 `spawn` 获取字符串类型的结果 */
|
|
145
|
-
const spawnAsync = (cmd, args, options) => {
|
|
146
|
-
return new Promise((resolve$1) => {
|
|
147
|
-
const { trim, error, dryRun, ...others } = options ?? {};
|
|
148
|
-
const fullCmd = stringifyArgs([cmd, ...args]);
|
|
149
|
-
if (dryRun) {
|
|
150
|
-
console.log(`${dim("[dry-run]")} ${fullCmd}`);
|
|
151
|
-
return resolve$1(void 0);
|
|
152
|
-
}
|
|
153
|
-
const child = spawn(cmd, args, { ...others });
|
|
154
|
-
let stdout = "";
|
|
155
|
-
child.stdout.setEncoding("utf-8");
|
|
156
|
-
child.stdout?.on("data", (data) => stdout += trim ? data.trim() : data);
|
|
157
|
-
let stderr = "";
|
|
158
|
-
child.stderr.setEncoding("utf-8");
|
|
159
|
-
child.stderr.on("data", (data) => stderr += trim ? data.trim() : data);
|
|
160
|
-
child.on("close", (code) => {
|
|
161
|
-
if (stderr) {
|
|
162
|
-
const err = `${red("spawnAsync")} ${dim(fullCmd)} ${stderr}`;
|
|
163
|
-
switch (error) {
|
|
164
|
-
case "log":
|
|
165
|
-
console.error(err);
|
|
166
|
-
break;
|
|
167
|
-
case "throw": throw new Error(err);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
resolve$1(0 === code ? stdout : void 0);
|
|
171
|
-
});
|
|
172
|
-
});
|
|
173
|
-
};
|
|
174
|
-
/** 异步执行 `exec` 获取字符串类型的结果 */
|
|
175
|
-
const execAsync = (cmd, argsOrOptions, maybeOptions) => {
|
|
176
|
-
return new Promise((resolve$1) => {
|
|
177
|
-
let command;
|
|
178
|
-
let options;
|
|
179
|
-
if (Array.isArray(argsOrOptions)) {
|
|
180
|
-
command = stringifyArgs([cmd, ...argsOrOptions]);
|
|
181
|
-
options = maybeOptions;
|
|
182
|
-
} else {
|
|
183
|
-
command = cmd;
|
|
184
|
-
options = argsOrOptions;
|
|
185
|
-
}
|
|
186
|
-
const { trim, dryRun, error, ...others } = options ?? {};
|
|
187
|
-
if (dryRun) {
|
|
188
|
-
console.log(`${dim("[dry-run]")} ${command}`);
|
|
189
|
-
return resolve$1(void 0);
|
|
190
|
-
}
|
|
191
|
-
exec(command, { ...others }, (stderr, stdout) => {
|
|
192
|
-
if (stderr) {
|
|
193
|
-
const err = `${red("execAsync")} ${dim(command)} ${stderr.message}`;
|
|
194
|
-
switch (error) {
|
|
195
|
-
case "log":
|
|
196
|
-
console.error(err);
|
|
197
|
-
break;
|
|
198
|
-
case "throw": throw new Error(err);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
resolve$1(stderr ? void 0 : trim ? stdout.trim() : stdout);
|
|
202
|
-
});
|
|
203
|
-
});
|
|
204
|
-
};
|
|
205
|
-
/** 基于 {@link spawnAsync} 实现 */
|
|
206
|
-
const runGit = async (args, options = { trim: true }) => {
|
|
207
|
-
return spawnAsync("git", args, options);
|
|
208
|
-
};
|
|
209
|
-
/** 基于 {@link execAsync} 实现 */
|
|
210
|
-
const runNpm = (args, options = { trim: true }) => {
|
|
211
|
-
return execAsync("npm", args, options);
|
|
212
|
-
};
|
|
213
|
-
/** 基于 {@link spawnSync} 实现 */
|
|
214
|
-
const runGitSync = (args, options) => {
|
|
215
|
-
const { stdout } = spawnSync("git", args, {
|
|
216
|
-
encoding: "utf-8",
|
|
217
|
-
...options
|
|
218
|
-
});
|
|
219
|
-
return stdout.toString().trim();
|
|
220
|
-
};
|
|
221
|
-
/** 基于 {@link execSync} 实现 */
|
|
222
|
-
const runNpmSync = (args, options) => {
|
|
223
|
-
return execSync(stringifyArgs(["npm", ...args]), {
|
|
224
|
-
encoding: "utf-8",
|
|
225
|
-
...options
|
|
226
|
-
}).toString().trim();
|
|
227
|
-
};
|
|
228
|
-
/** 将字符串以空格分割为数组 */
|
|
229
|
-
const parseArgs = (args) => args.trim() ? args.trim().split(" ") : [];
|
|
230
|
-
/** 将数组以空格拼接为字符串 */
|
|
231
|
-
const stringifyArgs = (args) => args.length ? args.join(" ") : "";
|
|
232
|
-
/** 支持所有支持 `--version` 命令的脚本查看版本 */
|
|
233
|
-
const checkVersion = async (cmd) => {
|
|
234
|
-
return execAsync(`${cmd} --version`);
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
//#endregion
|
|
238
|
-
//#region src/joinUrl.ts
|
|
239
|
-
function joinUrl(input) {
|
|
240
|
-
const temps = Array.isArray(input) ? input : [...arguments];
|
|
241
|
-
if (temps.length === 0) return "";
|
|
242
|
-
const result = [];
|
|
243
|
-
const parts = [...temps];
|
|
244
|
-
/** 协议正则 */
|
|
245
|
-
const PROTOCOL_RE = /^[^/:]+:\/*$/;
|
|
246
|
-
const FILE_PROTOCOL_RE = /^file:\/\/\//;
|
|
247
|
-
if (PROTOCOL_RE.test(parts[0]) && parts.length > 1) {
|
|
248
|
-
parts[1] = parts[0] + parts[1];
|
|
249
|
-
parts.shift();
|
|
250
|
-
}
|
|
251
|
-
if (FILE_PROTOCOL_RE.test(parts[0])) parts[0] = parts[0].replace(/^([^/:]+):\/*/, "$1:///");
|
|
252
|
-
else parts[0] = parts[0].replace(/^([^/:]+):\/*/, "$1://");
|
|
253
|
-
parts.forEach((part, index) => {
|
|
254
|
-
if (!part) return;
|
|
255
|
-
let segment = part;
|
|
256
|
-
if (index > 0) segment = segment.replace(/^\/+/, "");
|
|
257
|
-
if (index < parts.length - 1) segment = segment.replace(/\/+$/, "");
|
|
258
|
-
else segment = segment.replace(/\/+$/, "/");
|
|
259
|
-
result.push(segment);
|
|
260
|
-
});
|
|
261
|
-
let url = result.join("/");
|
|
262
|
-
url = url.replace(/\/(\?|&|#[^!])/g, "$1");
|
|
263
|
-
const [base, ...queryParts] = url.split("?");
|
|
264
|
-
url = base + (queryParts.length ? "?" + queryParts.join("&") : "");
|
|
265
|
-
return url;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
//#endregion
|
|
269
|
-
//#region src/git.ts
|
|
270
|
-
/** 判断指定目录是否是 git 仓库 */
|
|
271
|
-
const isGitRepo = async (dir) => {
|
|
272
|
-
return "true" === await runGit([
|
|
273
|
-
"-C",
|
|
274
|
-
resolve(process.cwd(), dir || "."),
|
|
275
|
-
"rev-parse",
|
|
276
|
-
"--is-inside-work-tree"
|
|
277
|
-
]);
|
|
278
|
-
};
|
|
279
|
-
/** 获取指定的 git 配置 */
|
|
280
|
-
const getGitConfig = (key, global = true) => {
|
|
281
|
-
return runGit([
|
|
282
|
-
"config",
|
|
283
|
-
...global ? ["--global"] : [],
|
|
284
|
-
key
|
|
285
|
-
]);
|
|
286
|
-
};
|
|
287
|
-
/** 获取 git 远程地址 */
|
|
288
|
-
const getGitRemoteUrl = async (remoteName = "origin") => {
|
|
289
|
-
return runGit([
|
|
290
|
-
"remote",
|
|
291
|
-
"get-url",
|
|
292
|
-
remoteName
|
|
293
|
-
]).catch((_) => runGit([
|
|
294
|
-
"config",
|
|
295
|
-
"--get",
|
|
296
|
-
`remote.${remoteName}.url`
|
|
297
|
-
]));
|
|
298
|
-
};
|
|
299
|
-
|
|
300
|
-
//#endregion
|
|
301
|
-
//#region src/npm.ts
|
|
302
|
-
/** 获取指定包的版本 */
|
|
303
|
-
const pkgVersion = (pkg) => {
|
|
304
|
-
return runNpm([
|
|
305
|
-
"view",
|
|
306
|
-
pkg,
|
|
307
|
-
"version"
|
|
308
|
-
]);
|
|
309
|
-
};
|
|
310
|
-
|
|
311
|
-
//#endregion
|
|
312
|
-
export { ConfirmResult, HttpLibrary, PkgManager, YesOrNo, checkVersion, copyDirAsync, editFile, editJsonFile, emptyDir, eol, execAsync, getGitConfig, getGitRemoteUrl, isEmpty, isGitRepo, isTestFile, isValidPackageName, joinUrl, parseArgs, parseGitHubRepo, pkgFromUserAgent, pkgVersion, readJsonFile, readSubDirs, runCliForTest, runGit, runGitSync, runNpm, runNpmSync, spawnAsync, stringifyArgs, toValidPackageName, toValidProjectName };
|