pnpm-link 1.0.0
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/README.md +67 -0
- package/dist/index.js +758 -0
- package/package.json +37 -0
package/README.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# pnpm-link
|
|
2
|
+
|
|
3
|
+
把全局已 `pnpm link` 的包,或本地相对路径包,写入当前项目的 `package.json` 依赖中。
|
|
4
|
+
|
|
5
|
+
## 功能
|
|
6
|
+
|
|
7
|
+
- 支持全局已 link 的包名写入依赖
|
|
8
|
+
- 支持本地相对路径包写入依赖
|
|
9
|
+
- 默认在当前执行目录下查找 `package.json`
|
|
10
|
+
- 支持 `file:` 与 `link:` 两种协议
|
|
11
|
+
- 支持 `--save-dev` / `--save-prod`,与 npm install 语义一致
|
|
12
|
+
|
|
13
|
+
## 安装
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i -g pnpm-link
|
|
17
|
+
# 或
|
|
18
|
+
pnpm add -g pnpm-link
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 用法
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pnpm-link <package-name>
|
|
25
|
+
pnpm-link <package-name> --save-dev
|
|
26
|
+
pnpm-link <package-name> --save-prod
|
|
27
|
+
pnpm-link ./packages/my-lib --protocol file
|
|
28
|
+
pnpm-link ./packages/my-lib --protocol link
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
说明:
|
|
32
|
+
|
|
33
|
+
- 不需要手动传 `package.json` 路径,默认会在当前执行目录下寻找 `./package.json`
|
|
34
|
+
- 不需要写 `install` 子命令
|
|
35
|
+
- 默认会写入 `dependencies`
|
|
36
|
+
- 使用 `--save-dev` 时写入 `devDependencies`
|
|
37
|
+
|
|
38
|
+
## 参数说明
|
|
39
|
+
|
|
40
|
+
- `-D, --save-dev`:写入 `devDependencies`
|
|
41
|
+
- `-P, --save-prod`:写入 `dependencies`
|
|
42
|
+
- `-p, --protocol <protocol>`:协议类型,可选 `file` 或 `link`,默认 `file`
|
|
43
|
+
- `-h, --help`:显示帮助
|
|
44
|
+
- `-v, --version`:显示版本
|
|
45
|
+
|
|
46
|
+
## 示例
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
# 全局包写入 dependencies
|
|
50
|
+
pnpm-link my-package
|
|
51
|
+
|
|
52
|
+
# 全局包写入 devDependencies
|
|
53
|
+
pnpm-link my-package --save-dev
|
|
54
|
+
|
|
55
|
+
# 本地包写入 dependencies,使用 link 协议
|
|
56
|
+
pnpm-link ./packages/my-lib --protocol link
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## 实现原理
|
|
60
|
+
|
|
61
|
+
命令会先解析包来源:
|
|
62
|
+
|
|
63
|
+
1. 若参数是本地相对路径,直接解析该目录并其 `package.json`
|
|
64
|
+
2. 若参数是包名,则通过 `pnpm root -g` 定位全局依赖目录
|
|
65
|
+
3. 生成 `file:` 或 `link:` 依赖值并写回当前工作目录的 `package.json`
|
|
66
|
+
4. 最后执行 `pnpm install` 让锁文件和 node_modules 更新
|
|
67
|
+
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,758 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
18
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
19
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
20
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
21
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
|
+
mod
|
|
24
|
+
));
|
|
25
|
+
|
|
26
|
+
// src/cli.ts
|
|
27
|
+
var import_node_path2 = __toESM(require("path"));
|
|
28
|
+
|
|
29
|
+
// node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
|
|
30
|
+
function toArr(any) {
|
|
31
|
+
return any == null ? [] : Array.isArray(any) ? any : [any];
|
|
32
|
+
}
|
|
33
|
+
function toVal(out, key, val, opts) {
|
|
34
|
+
var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
|
|
35
|
+
out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
|
|
36
|
+
}
|
|
37
|
+
function lib_default(args, opts) {
|
|
38
|
+
args = args || [];
|
|
39
|
+
opts = opts || {};
|
|
40
|
+
var k, arr, arg, name, val, out = { _: [] };
|
|
41
|
+
var i = 0, j = 0, idx = 0, len = args.length;
|
|
42
|
+
const alibi = opts.alias !== void 0;
|
|
43
|
+
const strict = opts.unknown !== void 0;
|
|
44
|
+
const defaults = opts.default !== void 0;
|
|
45
|
+
opts.alias = opts.alias || {};
|
|
46
|
+
opts.string = toArr(opts.string);
|
|
47
|
+
opts.boolean = toArr(opts.boolean);
|
|
48
|
+
if (alibi) for (k in opts.alias) {
|
|
49
|
+
arr = opts.alias[k] = toArr(opts.alias[k]);
|
|
50
|
+
for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
|
|
51
|
+
}
|
|
52
|
+
for (i = opts.boolean.length; i-- > 0; ) {
|
|
53
|
+
arr = opts.alias[opts.boolean[i]] || [];
|
|
54
|
+
for (j = arr.length; j-- > 0; ) opts.boolean.push(arr[j]);
|
|
55
|
+
}
|
|
56
|
+
for (i = opts.string.length; i-- > 0; ) {
|
|
57
|
+
arr = opts.alias[opts.string[i]] || [];
|
|
58
|
+
for (j = arr.length; j-- > 0; ) opts.string.push(arr[j]);
|
|
59
|
+
}
|
|
60
|
+
if (defaults) for (k in opts.default) {
|
|
61
|
+
name = typeof opts.default[k];
|
|
62
|
+
arr = opts.alias[k] = opts.alias[k] || [];
|
|
63
|
+
if (opts[name] !== void 0) {
|
|
64
|
+
opts[name].push(k);
|
|
65
|
+
for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const keys = strict ? Object.keys(opts.alias) : [];
|
|
69
|
+
for (i = 0; i < len; i++) {
|
|
70
|
+
arg = args[i];
|
|
71
|
+
if (arg === "--") {
|
|
72
|
+
out._ = out._.concat(args.slice(++i));
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
|
|
76
|
+
if (j === 0) out._.push(arg);
|
|
77
|
+
else if (arg.substring(j, j + 3) === "no-") {
|
|
78
|
+
name = arg.substring(j + 3);
|
|
79
|
+
if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
|
|
80
|
+
out[name] = false;
|
|
81
|
+
} else {
|
|
82
|
+
for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
|
|
83
|
+
name = arg.substring(j, idx);
|
|
84
|
+
val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
|
|
85
|
+
arr = j === 2 ? [name] : name;
|
|
86
|
+
for (idx = 0; idx < arr.length; idx++) {
|
|
87
|
+
name = arr[idx];
|
|
88
|
+
if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
|
|
89
|
+
toVal(out, name, idx + 1 < arr.length || val, opts);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (defaults) {
|
|
94
|
+
for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
|
|
95
|
+
}
|
|
96
|
+
if (alibi) for (k in out) {
|
|
97
|
+
arr = opts.alias[k] || [];
|
|
98
|
+
while (arr.length > 0) out[arr.shift()] = out[k];
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
function removeBrackets(v) {
|
|
103
|
+
return v.replace(/[<[].+/, "").trim();
|
|
104
|
+
}
|
|
105
|
+
function findAllBrackets(v) {
|
|
106
|
+
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
|
|
107
|
+
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
|
|
108
|
+
const res = [];
|
|
109
|
+
const parse = (match) => {
|
|
110
|
+
let variadic = false;
|
|
111
|
+
let value = match[1];
|
|
112
|
+
if (value.startsWith("...")) {
|
|
113
|
+
value = value.slice(3);
|
|
114
|
+
variadic = true;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
required: match[0].startsWith("<"),
|
|
118
|
+
value,
|
|
119
|
+
variadic
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
let angledMatch;
|
|
123
|
+
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
|
|
124
|
+
let squareMatch;
|
|
125
|
+
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
|
|
126
|
+
return res;
|
|
127
|
+
}
|
|
128
|
+
function getMriOptions(options) {
|
|
129
|
+
const result = {
|
|
130
|
+
alias: {},
|
|
131
|
+
boolean: []
|
|
132
|
+
};
|
|
133
|
+
for (const [index, option] of options.entries()) {
|
|
134
|
+
if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
|
|
135
|
+
if (option.isBoolean) if (option.negated) {
|
|
136
|
+
if (!options.some((o, i) => {
|
|
137
|
+
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
|
|
138
|
+
})) result.boolean.push(option.names[0]);
|
|
139
|
+
} else result.boolean.push(option.names[0]);
|
|
140
|
+
}
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
function findLongest(arr) {
|
|
144
|
+
return arr.sort((a, b) => {
|
|
145
|
+
return a.length > b.length ? -1 : 1;
|
|
146
|
+
})[0];
|
|
147
|
+
}
|
|
148
|
+
function padRight(str, length) {
|
|
149
|
+
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
|
|
150
|
+
}
|
|
151
|
+
function camelcase(input) {
|
|
152
|
+
return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
|
|
153
|
+
return p1 + p2.toUpperCase();
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
function setDotProp(obj, keys, val) {
|
|
157
|
+
let current = obj;
|
|
158
|
+
for (let i = 0; i < keys.length; i++) {
|
|
159
|
+
const key = keys[i];
|
|
160
|
+
if (i === keys.length - 1) {
|
|
161
|
+
current[key] = val;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (current[key] == null) {
|
|
165
|
+
const nextKeyIsArrayIndex = +keys[i + 1] > -1;
|
|
166
|
+
current[key] = nextKeyIsArrayIndex ? [] : {};
|
|
167
|
+
}
|
|
168
|
+
current = current[key];
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function setByType(obj, transforms) {
|
|
172
|
+
for (const key of Object.keys(transforms)) {
|
|
173
|
+
const transform = transforms[key];
|
|
174
|
+
if (transform.shouldTransform) {
|
|
175
|
+
obj[key] = [obj[key]].flat();
|
|
176
|
+
if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function getFileName(input) {
|
|
181
|
+
const m = /([^\\/]+)$/.exec(input);
|
|
182
|
+
return m ? m[1] : "";
|
|
183
|
+
}
|
|
184
|
+
function camelcaseOptionName(name) {
|
|
185
|
+
return name.split(".").map((v, i) => {
|
|
186
|
+
return i === 0 ? camelcase(v) : v;
|
|
187
|
+
}).join(".");
|
|
188
|
+
}
|
|
189
|
+
var CACError = class extends Error {
|
|
190
|
+
constructor(message) {
|
|
191
|
+
super(message);
|
|
192
|
+
this.name = "CACError";
|
|
193
|
+
if (typeof Error.captureStackTrace !== "function") this.stack = new Error(message).stack;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
var Option = class {
|
|
197
|
+
rawName;
|
|
198
|
+
description;
|
|
199
|
+
/** Option name */
|
|
200
|
+
name;
|
|
201
|
+
/** Option name and aliases */
|
|
202
|
+
names;
|
|
203
|
+
isBoolean;
|
|
204
|
+
required;
|
|
205
|
+
config;
|
|
206
|
+
negated;
|
|
207
|
+
constructor(rawName, description, config) {
|
|
208
|
+
this.rawName = rawName;
|
|
209
|
+
this.description = description;
|
|
210
|
+
this.config = Object.assign({}, config);
|
|
211
|
+
rawName = rawName.replaceAll(".*", "");
|
|
212
|
+
this.negated = false;
|
|
213
|
+
this.names = removeBrackets(rawName).split(",").map((v) => {
|
|
214
|
+
let name = v.trim().replace(/^-{1,2}/, "");
|
|
215
|
+
if (name.startsWith("no-")) {
|
|
216
|
+
this.negated = true;
|
|
217
|
+
name = name.replace(/^no-/, "");
|
|
218
|
+
}
|
|
219
|
+
return camelcaseOptionName(name);
|
|
220
|
+
}).sort((a, b) => a.length > b.length ? 1 : -1);
|
|
221
|
+
this.name = this.names.at(-1);
|
|
222
|
+
if (this.negated && this.config.default == null) this.config.default = true;
|
|
223
|
+
if (rawName.includes("<")) this.required = true;
|
|
224
|
+
else if (rawName.includes("[")) this.required = false;
|
|
225
|
+
else this.isBoolean = true;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
var runtimeProcessArgs;
|
|
229
|
+
var runtimeInfo;
|
|
230
|
+
if (typeof process !== "undefined") {
|
|
231
|
+
let runtimeName;
|
|
232
|
+
if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string") runtimeName = "deno";
|
|
233
|
+
else if (typeof Bun !== "undefined" && typeof Bun.version === "string") runtimeName = "bun";
|
|
234
|
+
else runtimeName = "node";
|
|
235
|
+
runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
|
|
236
|
+
runtimeProcessArgs = process.argv;
|
|
237
|
+
} else if (typeof navigator === "undefined") runtimeInfo = `unknown`;
|
|
238
|
+
else runtimeInfo = `${navigator.platform} ${navigator.userAgent}`;
|
|
239
|
+
var Command = class {
|
|
240
|
+
rawName;
|
|
241
|
+
description;
|
|
242
|
+
config;
|
|
243
|
+
cli;
|
|
244
|
+
options;
|
|
245
|
+
aliasNames;
|
|
246
|
+
name;
|
|
247
|
+
args;
|
|
248
|
+
commandAction;
|
|
249
|
+
usageText;
|
|
250
|
+
versionNumber;
|
|
251
|
+
examples;
|
|
252
|
+
helpCallback;
|
|
253
|
+
globalCommand;
|
|
254
|
+
constructor(rawName, description, config = {}, cli2) {
|
|
255
|
+
this.rawName = rawName;
|
|
256
|
+
this.description = description;
|
|
257
|
+
this.config = config;
|
|
258
|
+
this.cli = cli2;
|
|
259
|
+
this.options = [];
|
|
260
|
+
this.aliasNames = [];
|
|
261
|
+
this.name = removeBrackets(rawName);
|
|
262
|
+
this.args = findAllBrackets(rawName);
|
|
263
|
+
this.examples = [];
|
|
264
|
+
}
|
|
265
|
+
usage(text) {
|
|
266
|
+
this.usageText = text;
|
|
267
|
+
return this;
|
|
268
|
+
}
|
|
269
|
+
allowUnknownOptions() {
|
|
270
|
+
this.config.allowUnknownOptions = true;
|
|
271
|
+
return this;
|
|
272
|
+
}
|
|
273
|
+
ignoreOptionDefaultValue() {
|
|
274
|
+
this.config.ignoreOptionDefaultValue = true;
|
|
275
|
+
return this;
|
|
276
|
+
}
|
|
277
|
+
version(version, customFlags = "-v, --version") {
|
|
278
|
+
this.versionNumber = version;
|
|
279
|
+
this.option(customFlags, "Display version number");
|
|
280
|
+
return this;
|
|
281
|
+
}
|
|
282
|
+
example(example) {
|
|
283
|
+
this.examples.push(example);
|
|
284
|
+
return this;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Add a option for this command
|
|
288
|
+
* @param rawName Raw option name(s)
|
|
289
|
+
* @param description Option description
|
|
290
|
+
* @param config Option config
|
|
291
|
+
*/
|
|
292
|
+
option(rawName, description, config) {
|
|
293
|
+
const option = new Option(rawName, description, config);
|
|
294
|
+
this.options.push(option);
|
|
295
|
+
return this;
|
|
296
|
+
}
|
|
297
|
+
alias(name) {
|
|
298
|
+
this.aliasNames.push(name);
|
|
299
|
+
return this;
|
|
300
|
+
}
|
|
301
|
+
action(callback) {
|
|
302
|
+
this.commandAction = callback;
|
|
303
|
+
return this;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Check if a command name is matched by this command
|
|
307
|
+
* @param name Command name
|
|
308
|
+
*/
|
|
309
|
+
isMatched(name) {
|
|
310
|
+
return this.name === name || this.aliasNames.includes(name);
|
|
311
|
+
}
|
|
312
|
+
get isDefaultCommand() {
|
|
313
|
+
return this.name === "" || this.aliasNames.includes("!");
|
|
314
|
+
}
|
|
315
|
+
get isGlobalCommand() {
|
|
316
|
+
return this instanceof GlobalCommand;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Check if an option is registered in this command
|
|
320
|
+
* @param name Option name
|
|
321
|
+
*/
|
|
322
|
+
hasOption(name) {
|
|
323
|
+
name = name.split(".")[0];
|
|
324
|
+
return this.options.find((option) => {
|
|
325
|
+
return option.names.includes(name);
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
outputHelp() {
|
|
329
|
+
const { name, commands } = this.cli;
|
|
330
|
+
const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
|
|
331
|
+
let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
|
|
332
|
+
sections.push({
|
|
333
|
+
title: "Usage",
|
|
334
|
+
body: ` $ ${name} ${this.usageText || this.rawName}`
|
|
335
|
+
});
|
|
336
|
+
if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
|
|
337
|
+
const longestCommandName = findLongest(commands.map((command) => command.rawName));
|
|
338
|
+
sections.push({
|
|
339
|
+
title: "Commands",
|
|
340
|
+
body: commands.map((command) => {
|
|
341
|
+
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
|
|
342
|
+
}).join("\n")
|
|
343
|
+
}, {
|
|
344
|
+
title: `For more info, run any command with the \`--help\` flag`,
|
|
345
|
+
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
|
|
349
|
+
if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
|
|
350
|
+
if (options.length > 0) {
|
|
351
|
+
const longestOptionName = findLongest(options.map((option) => option.rawName));
|
|
352
|
+
sections.push({
|
|
353
|
+
title: "Options",
|
|
354
|
+
body: options.map((option) => {
|
|
355
|
+
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
|
|
356
|
+
}).join("\n")
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
if (this.examples.length > 0) sections.push({
|
|
360
|
+
title: "Examples",
|
|
361
|
+
body: this.examples.map((example) => {
|
|
362
|
+
if (typeof example === "function") return example(name);
|
|
363
|
+
return example;
|
|
364
|
+
}).join("\n")
|
|
365
|
+
});
|
|
366
|
+
if (helpCallback) sections = helpCallback(sections) || sections;
|
|
367
|
+
console.info(sections.map((section) => {
|
|
368
|
+
return section.title ? `${section.title}:
|
|
369
|
+
${section.body}` : section.body;
|
|
370
|
+
}).join("\n\n"));
|
|
371
|
+
}
|
|
372
|
+
outputVersion() {
|
|
373
|
+
const { name } = this.cli;
|
|
374
|
+
const { versionNumber } = this.cli.globalCommand;
|
|
375
|
+
if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
|
|
376
|
+
}
|
|
377
|
+
checkRequiredArgs() {
|
|
378
|
+
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
|
|
379
|
+
if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Check if the parsed options contain any unknown options
|
|
383
|
+
*
|
|
384
|
+
* Exit and output error when true
|
|
385
|
+
*/
|
|
386
|
+
checkUnknownOptions() {
|
|
387
|
+
const { options, globalCommand } = this.cli;
|
|
388
|
+
if (!this.config.allowUnknownOptions) {
|
|
389
|
+
for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Check if the required string-type options exist
|
|
394
|
+
*/
|
|
395
|
+
checkOptionValue() {
|
|
396
|
+
const { options: parsedOptions, globalCommand } = this.cli;
|
|
397
|
+
const options = [...globalCommand.options, ...this.options];
|
|
398
|
+
for (const option of options) {
|
|
399
|
+
const value = parsedOptions[option.name.split(".")[0]];
|
|
400
|
+
if (option.required) {
|
|
401
|
+
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
|
|
402
|
+
if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Check if the number of args is more than expected
|
|
408
|
+
*/
|
|
409
|
+
checkUnusedArgs() {
|
|
410
|
+
const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
|
|
411
|
+
if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
var GlobalCommand = class extends Command {
|
|
415
|
+
constructor(cli2) {
|
|
416
|
+
super("@@global@@", "", {}, cli2);
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
var CAC = class extends EventTarget {
|
|
420
|
+
/** The program name to display in help and version message */
|
|
421
|
+
name;
|
|
422
|
+
commands;
|
|
423
|
+
globalCommand;
|
|
424
|
+
matchedCommand;
|
|
425
|
+
matchedCommandName;
|
|
426
|
+
/**
|
|
427
|
+
* Raw CLI arguments
|
|
428
|
+
*/
|
|
429
|
+
rawArgs;
|
|
430
|
+
/**
|
|
431
|
+
* Parsed CLI arguments
|
|
432
|
+
*/
|
|
433
|
+
args;
|
|
434
|
+
/**
|
|
435
|
+
* Parsed CLI options, camelCased
|
|
436
|
+
*/
|
|
437
|
+
options;
|
|
438
|
+
showHelpOnExit;
|
|
439
|
+
showVersionOnExit;
|
|
440
|
+
/**
|
|
441
|
+
* @param name The program name to display in help and version message
|
|
442
|
+
*/
|
|
443
|
+
constructor(name = "") {
|
|
444
|
+
super();
|
|
445
|
+
this.name = name;
|
|
446
|
+
this.commands = [];
|
|
447
|
+
this.rawArgs = [];
|
|
448
|
+
this.args = [];
|
|
449
|
+
this.options = {};
|
|
450
|
+
this.globalCommand = new GlobalCommand(this);
|
|
451
|
+
this.globalCommand.usage("<command> [options]");
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Add a global usage text.
|
|
455
|
+
*
|
|
456
|
+
* This is not used by sub-commands.
|
|
457
|
+
*/
|
|
458
|
+
usage(text) {
|
|
459
|
+
this.globalCommand.usage(text);
|
|
460
|
+
return this;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Add a sub-command
|
|
464
|
+
*/
|
|
465
|
+
command(rawName, description, config) {
|
|
466
|
+
const command = new Command(rawName, description || "", config, this);
|
|
467
|
+
command.globalCommand = this.globalCommand;
|
|
468
|
+
this.commands.push(command);
|
|
469
|
+
return command;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Add a global CLI option.
|
|
473
|
+
*
|
|
474
|
+
* Which is also applied to sub-commands.
|
|
475
|
+
*/
|
|
476
|
+
option(rawName, description, config) {
|
|
477
|
+
this.globalCommand.option(rawName, description, config);
|
|
478
|
+
return this;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Show help message when `-h, --help` flags appear.
|
|
482
|
+
*
|
|
483
|
+
*/
|
|
484
|
+
help(callback) {
|
|
485
|
+
this.globalCommand.option("-h, --help", "Display this message");
|
|
486
|
+
this.globalCommand.helpCallback = callback;
|
|
487
|
+
this.showHelpOnExit = true;
|
|
488
|
+
return this;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Show version number when `-v, --version` flags appear.
|
|
492
|
+
*
|
|
493
|
+
*/
|
|
494
|
+
version(version, customFlags = "-v, --version") {
|
|
495
|
+
this.globalCommand.version(version, customFlags);
|
|
496
|
+
this.showVersionOnExit = true;
|
|
497
|
+
return this;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Add a global example.
|
|
501
|
+
*
|
|
502
|
+
* This example added here will not be used by sub-commands.
|
|
503
|
+
*/
|
|
504
|
+
example(example) {
|
|
505
|
+
this.globalCommand.example(example);
|
|
506
|
+
return this;
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Output the corresponding help message
|
|
510
|
+
* When a sub-command is matched, output the help message for the command
|
|
511
|
+
* Otherwise output the global one.
|
|
512
|
+
*
|
|
513
|
+
*/
|
|
514
|
+
outputHelp() {
|
|
515
|
+
if (this.matchedCommand) this.matchedCommand.outputHelp();
|
|
516
|
+
else this.globalCommand.outputHelp();
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Output the version number.
|
|
520
|
+
*
|
|
521
|
+
*/
|
|
522
|
+
outputVersion() {
|
|
523
|
+
this.globalCommand.outputVersion();
|
|
524
|
+
}
|
|
525
|
+
setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
|
|
526
|
+
this.args = args;
|
|
527
|
+
this.options = options;
|
|
528
|
+
if (matchedCommand) this.matchedCommand = matchedCommand;
|
|
529
|
+
if (matchedCommandName) this.matchedCommandName = matchedCommandName;
|
|
530
|
+
return this;
|
|
531
|
+
}
|
|
532
|
+
unsetMatchedCommand() {
|
|
533
|
+
this.matchedCommand = void 0;
|
|
534
|
+
this.matchedCommandName = void 0;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Parse argv
|
|
538
|
+
*/
|
|
539
|
+
parse(argv, { run = true } = {}) {
|
|
540
|
+
if (!argv) {
|
|
541
|
+
if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
|
|
542
|
+
argv = runtimeProcessArgs;
|
|
543
|
+
}
|
|
544
|
+
this.rawArgs = argv;
|
|
545
|
+
if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
|
|
546
|
+
let shouldParse = true;
|
|
547
|
+
for (const command of this.commands) {
|
|
548
|
+
const parsed = this.mri(argv.slice(2), command);
|
|
549
|
+
const commandName = parsed.args[0];
|
|
550
|
+
if (command.isMatched(commandName)) {
|
|
551
|
+
shouldParse = false;
|
|
552
|
+
const parsedInfo = {
|
|
553
|
+
...parsed,
|
|
554
|
+
args: parsed.args.slice(1)
|
|
555
|
+
};
|
|
556
|
+
this.setParsedInfo(parsedInfo, command, commandName);
|
|
557
|
+
this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (shouldParse) {
|
|
561
|
+
for (const command of this.commands) if (command.isDefaultCommand) {
|
|
562
|
+
shouldParse = false;
|
|
563
|
+
const parsed = this.mri(argv.slice(2), command);
|
|
564
|
+
this.setParsedInfo(parsed, command);
|
|
565
|
+
this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
if (shouldParse) {
|
|
569
|
+
const parsed = this.mri(argv.slice(2));
|
|
570
|
+
this.setParsedInfo(parsed);
|
|
571
|
+
}
|
|
572
|
+
if (this.options.help && this.showHelpOnExit) {
|
|
573
|
+
this.outputHelp();
|
|
574
|
+
run = false;
|
|
575
|
+
this.unsetMatchedCommand();
|
|
576
|
+
}
|
|
577
|
+
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
|
|
578
|
+
this.outputVersion();
|
|
579
|
+
run = false;
|
|
580
|
+
this.unsetMatchedCommand();
|
|
581
|
+
}
|
|
582
|
+
const parsedArgv = {
|
|
583
|
+
args: this.args,
|
|
584
|
+
options: this.options
|
|
585
|
+
};
|
|
586
|
+
if (run) this.runMatchedCommand();
|
|
587
|
+
if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
|
|
588
|
+
return parsedArgv;
|
|
589
|
+
}
|
|
590
|
+
mri(argv, command) {
|
|
591
|
+
const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
|
|
592
|
+
const mriOptions = getMriOptions(cliOptions);
|
|
593
|
+
let argsAfterDoubleDashes = [];
|
|
594
|
+
const doubleDashesIndex = argv.indexOf("--");
|
|
595
|
+
if (doubleDashesIndex !== -1) {
|
|
596
|
+
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
|
|
597
|
+
argv = argv.slice(0, doubleDashesIndex);
|
|
598
|
+
}
|
|
599
|
+
let parsed = lib_default(argv, mriOptions);
|
|
600
|
+
parsed = Object.keys(parsed).reduce((res, name) => {
|
|
601
|
+
return {
|
|
602
|
+
...res,
|
|
603
|
+
[camelcaseOptionName(name)]: parsed[name]
|
|
604
|
+
};
|
|
605
|
+
}, { _: [] });
|
|
606
|
+
const args = parsed._;
|
|
607
|
+
const options = { "--": argsAfterDoubleDashes };
|
|
608
|
+
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
|
|
609
|
+
const transforms = /* @__PURE__ */ Object.create(null);
|
|
610
|
+
for (const cliOption of cliOptions) {
|
|
611
|
+
if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
|
|
612
|
+
if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === void 0) {
|
|
613
|
+
transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
|
|
614
|
+
transforms[cliOption.name].shouldTransform = true;
|
|
615
|
+
transforms[cliOption.name].transformFunction = cliOption.config.type[0];
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
for (const key of Object.keys(parsed)) if (key !== "_") {
|
|
619
|
+
setDotProp(options, key.split("."), parsed[key]);
|
|
620
|
+
setByType(options, transforms);
|
|
621
|
+
}
|
|
622
|
+
return {
|
|
623
|
+
args,
|
|
624
|
+
options
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
runMatchedCommand() {
|
|
628
|
+
const { args, options, matchedCommand: command } = this;
|
|
629
|
+
if (!command || !command.commandAction) return;
|
|
630
|
+
command.checkUnknownOptions();
|
|
631
|
+
command.checkOptionValue();
|
|
632
|
+
command.checkRequiredArgs();
|
|
633
|
+
command.checkUnusedArgs();
|
|
634
|
+
const actionArgs = [];
|
|
635
|
+
command.args.forEach((arg, index) => {
|
|
636
|
+
if (arg.variadic) actionArgs.push(args.slice(index));
|
|
637
|
+
else actionArgs.push(args[index]);
|
|
638
|
+
});
|
|
639
|
+
actionArgs.push(options);
|
|
640
|
+
return command.commandAction.apply(this, actionArgs);
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
var cac = (name = "") => new CAC(name);
|
|
644
|
+
|
|
645
|
+
// src/core.ts
|
|
646
|
+
var import_node_child_process = require("child_process");
|
|
647
|
+
var import_node_fs = __toESM(require("fs"));
|
|
648
|
+
var import_node_path = __toESM(require("path"));
|
|
649
|
+
function isLocalPackageReference(value) {
|
|
650
|
+
return value.startsWith("./") || value.startsWith("../") || value.startsWith("/") || value.startsWith("file:") || value.includes("/") || value.includes("\\");
|
|
651
|
+
}
|
|
652
|
+
function readPackageNameFromDir(dirPath) {
|
|
653
|
+
const pkgJsonPath = import_node_path.default.join(dirPath, "package.json");
|
|
654
|
+
if (!import_node_fs.default.existsSync(pkgJsonPath)) {
|
|
655
|
+
return import_node_path.default.basename(dirPath);
|
|
656
|
+
}
|
|
657
|
+
try {
|
|
658
|
+
const pkg = JSON.parse(import_node_fs.default.readFileSync(pkgJsonPath, "utf-8"));
|
|
659
|
+
return pkg.name || import_node_path.default.basename(dirPath);
|
|
660
|
+
} catch {
|
|
661
|
+
return import_node_path.default.basename(dirPath);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
function resolvePackageLocation(packageName) {
|
|
665
|
+
if (isLocalPackageReference(packageName)) {
|
|
666
|
+
const absolutePath = import_node_path.default.resolve(packageName);
|
|
667
|
+
if (!import_node_fs.default.existsSync(absolutePath)) {
|
|
668
|
+
throw new Error(`Relative package path "${packageName}" does not exist.`);
|
|
669
|
+
}
|
|
670
|
+
const realPath = import_node_fs.default.realpathSync(absolutePath);
|
|
671
|
+
const depKey = readPackageNameFromDir(realPath);
|
|
672
|
+
return { depKey, realPath };
|
|
673
|
+
}
|
|
674
|
+
const globalRoot = (0, import_node_child_process.execSync)("pnpm root -g", { encoding: "utf-8" }).trim();
|
|
675
|
+
const globalPkgPath = import_node_path.default.join(globalRoot, packageName);
|
|
676
|
+
if (!import_node_fs.default.existsSync(globalPkgPath)) {
|
|
677
|
+
throw new Error(
|
|
678
|
+
`Package "${packageName}" not found in global node_modules (${globalRoot})`
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
try {
|
|
682
|
+
const realPath = import_node_fs.default.realpathSync(globalPkgPath);
|
|
683
|
+
return { depKey: packageName, realPath };
|
|
684
|
+
} catch (err) {
|
|
685
|
+
throw new Error(
|
|
686
|
+
`Failed to resolve real path for "${packageName}": ${err.message}`
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function linkPackageToProject(options) {
|
|
691
|
+
const {
|
|
692
|
+
packageName,
|
|
693
|
+
targetPkgPath = "./package.json",
|
|
694
|
+
depType = "dependencies",
|
|
695
|
+
protocol = "file"
|
|
696
|
+
} = options;
|
|
697
|
+
const targetAbs = import_node_path.default.resolve(targetPkgPath);
|
|
698
|
+
if (!import_node_fs.default.existsSync(targetAbs)) {
|
|
699
|
+
throw new Error(
|
|
700
|
+
"No package.json found in current directory. Run this command in your project root."
|
|
701
|
+
);
|
|
702
|
+
}
|
|
703
|
+
const projectDir = import_node_path.default.dirname(targetAbs);
|
|
704
|
+
const { depKey, realPath } = resolvePackageLocation(packageName);
|
|
705
|
+
const targetDir = import_node_path.default.dirname(targetAbs);
|
|
706
|
+
let depValue;
|
|
707
|
+
if (protocol === "link") {
|
|
708
|
+
depValue = `link:${realPath}`;
|
|
709
|
+
} else {
|
|
710
|
+
const relative = import_node_path.default.relative(targetDir, realPath);
|
|
711
|
+
depValue = `file:${relative.startsWith(".") ? relative : "./" + relative}`;
|
|
712
|
+
}
|
|
713
|
+
const pkg = JSON.parse(import_node_fs.default.readFileSync(targetAbs, "utf-8"));
|
|
714
|
+
if (!pkg[depType]) pkg[depType] = {};
|
|
715
|
+
pkg[depType][depKey] = depValue;
|
|
716
|
+
import_node_fs.default.writeFileSync(targetAbs, JSON.stringify(pkg, null, 2) + "\n");
|
|
717
|
+
(0, import_node_child_process.execSync)("pnpm install", {
|
|
718
|
+
cwd: projectDir,
|
|
719
|
+
stdio: "inherit"
|
|
720
|
+
});
|
|
721
|
+
console.log(`\u2705 Updated ${depType}["${depKey}"] = "${depValue}"`);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// src/cli.ts
|
|
725
|
+
function resolveDepType(options) {
|
|
726
|
+
if (options.saveDev) return "devDependencies";
|
|
727
|
+
if (options.saveProd) return "dependencies";
|
|
728
|
+
const normalized = options.depType ?? "dependencies";
|
|
729
|
+
return normalized === "devDependencies" ? "devDependencies" : "dependencies";
|
|
730
|
+
}
|
|
731
|
+
function runLinkCommand(packageName, options) {
|
|
732
|
+
if (!packageName) {
|
|
733
|
+
console.error("\u8BF7\u6307\u5B9A package-name \u6216\u76F8\u5BF9\u8DEF\u5F84\u5305\u3002");
|
|
734
|
+
process.exit(1);
|
|
735
|
+
}
|
|
736
|
+
try {
|
|
737
|
+
linkPackageToProject({
|
|
738
|
+
packageName,
|
|
739
|
+
targetPkgPath: import_node_path2.default.resolve(process.cwd(), "package.json"),
|
|
740
|
+
depType: resolveDepType(options),
|
|
741
|
+
protocol: options.protocol
|
|
742
|
+
});
|
|
743
|
+
} catch (err) {
|
|
744
|
+
console.error(err.message);
|
|
745
|
+
process.exit(1);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
var cli = cac("pnpm-link");
|
|
749
|
+
cli.command("<package-name>", "\u5C06\u5168\u5C40\u5DF2 link \u7684\u5305\u6216\u672C\u5730\u76F8\u5BF9\u8DEF\u5F84\u5305\u5199\u5165\u5F53\u524D\u9879\u76EE\u4F9D\u8D56").option("-D, --save-dev", "\u5199\u5165 devDependencies").option("-P, --save-prod", "\u5199\u5165 dependencies").option("-p, --protocol <protocol>", "\u534F\u8BAE\u7C7B\u578B (file|link)", {
|
|
750
|
+
default: "file"
|
|
751
|
+
}).example("pnpm-link my-package --save-dev").example("pnpm-link ./packages/my-lib --protocol file").action((packageName, options) => {
|
|
752
|
+
runLinkCommand(packageName, options);
|
|
753
|
+
});
|
|
754
|
+
if (require.main === module) {
|
|
755
|
+
cli.help();
|
|
756
|
+
cli.version("1.0.0");
|
|
757
|
+
cli.parse();
|
|
758
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pnpm-link",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "把全局已 link 的包或本地包写入当前项目依赖,适用于 pnpm 工作流",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pnpm",
|
|
7
|
+
"link",
|
|
8
|
+
"dependencies",
|
|
9
|
+
"devDependencies",
|
|
10
|
+
"package.json",
|
|
11
|
+
"workspace",
|
|
12
|
+
"cli"
|
|
13
|
+
],
|
|
14
|
+
"license": "ISC",
|
|
15
|
+
"author": "zyrong",
|
|
16
|
+
"type": "commonjs",
|
|
17
|
+
"bin": {
|
|
18
|
+
"pnpm-link": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsup",
|
|
25
|
+
"typecheck": "tsc",
|
|
26
|
+
"test": "pnpm build && vitest run",
|
|
27
|
+
"test:watch": "vitest"
|
|
28
|
+
},
|
|
29
|
+
"packageManager": "pnpm@10.28.0",
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "^22.19.15",
|
|
32
|
+
"cac": "^7.0.0",
|
|
33
|
+
"tsup": "^8.5.1",
|
|
34
|
+
"typescript": "^7.0.2",
|
|
35
|
+
"vitest": "^4.0.18"
|
|
36
|
+
}
|
|
37
|
+
}
|