breadc 0.7.0 → 0.8.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/dist/index.mjs CHANGED
@@ -1,7 +1,138 @@
1
- import minimist from 'minimist';
2
- import * as kolorist from 'kolorist';
3
- import { blue, yellow, red, gray } from 'kolorist';
1
+ import { bold, underline } from '@breadc/color';
4
2
 
3
+ function makePluginContainer(plugins = []) {
4
+ const onPreCommand = {};
5
+ const onPostCommand = {};
6
+ for (const plugin of plugins) {
7
+ for (const [key, fn] of Object.entries(plugin.onPreCommand ?? {})) {
8
+ if (!(key in onPreCommand)) {
9
+ onPreCommand[key] = [];
10
+ }
11
+ onPreCommand[key].push(fn);
12
+ }
13
+ for (const [key, fn] of Object.entries(plugin.onPostCommand ?? {})) {
14
+ if (!(key in onPostCommand)) {
15
+ onPostCommand[key] = [];
16
+ }
17
+ onPostCommand[key].push(fn);
18
+ }
19
+ }
20
+ const run = async (container, command) => {
21
+ const prefix = command._arguments.filter((a) => a.type === "const").map((a) => a.name);
22
+ for (let i = 0; i <= prefix.length; i++) {
23
+ const key = i === 0 ? "*" : prefix.slice(0, i).map(
24
+ (t, idx) => idx === 0 ? t : t[0].toUpperCase() + t.slice(1)
25
+ ).join("");
26
+ const fns = container[key];
27
+ if (fns && fns.length > 0) {
28
+ await Promise.all(fns.map((fn) => fn()));
29
+ }
30
+ }
31
+ };
32
+ return {
33
+ async preRun(breadc) {
34
+ for (const p of plugins) {
35
+ await p.onPreRun?.(breadc);
36
+ }
37
+ },
38
+ async preCommand(command) {
39
+ await run(onPreCommand, command);
40
+ },
41
+ async postCommand(command) {
42
+ await run(onPostCommand, command);
43
+ },
44
+ async postRun(breadc) {
45
+ for (const p of plugins) {
46
+ await p.onPostRun?.(breadc);
47
+ }
48
+ }
49
+ };
50
+ }
51
+ function definePlugin(plugin) {
52
+ return plugin;
53
+ }
54
+
55
+ class Token {
56
+ constructor(text) {
57
+ this.text = text;
58
+ }
59
+ /**
60
+ * @returns Raw argument text
61
+ */
62
+ raw() {
63
+ return this.text;
64
+ }
65
+ /**
66
+ * @returns Number representation
67
+ */
68
+ number() {
69
+ return Number(this.text);
70
+ }
71
+ /**
72
+ * @returns Remove start - for long or short option
73
+ */
74
+ option() {
75
+ return this.text.replace(/^-+/, "");
76
+ }
77
+ isOption() {
78
+ return this.type() === "long" || this._type === "short";
79
+ }
80
+ isText() {
81
+ return this.type() === "number" || this._type === "string";
82
+ }
83
+ type() {
84
+ if (this._type) {
85
+ return this._type;
86
+ } else if (this.text === "--") {
87
+ return this._type = "--";
88
+ } else if (this.text === "-") {
89
+ return this._type = "-";
90
+ } else if (!isNaN(Number(this.text))) {
91
+ return this._type = "number";
92
+ } else if (this.text.startsWith("--")) {
93
+ return this._type = "long";
94
+ } else if (this.text.startsWith("-")) {
95
+ return this._type = "short";
96
+ } else {
97
+ return this._type = "string";
98
+ }
99
+ }
100
+ }
101
+ class Lexer {
102
+ constructor(rawArgs) {
103
+ this.cursor = 0;
104
+ this.rawArgs = rawArgs;
105
+ }
106
+ next() {
107
+ const value = this.rawArgs[this.cursor];
108
+ this.cursor += 1;
109
+ return value ? new Token(value) : void 0;
110
+ }
111
+ hasNext() {
112
+ return this.cursor + 1 < this.rawArgs.length;
113
+ }
114
+ peek() {
115
+ const value = this.rawArgs[this.cursor];
116
+ return value ? new Token(value) : void 0;
117
+ }
118
+ [Symbol.iterator]() {
119
+ const that = this;
120
+ return {
121
+ next() {
122
+ const value = that.rawArgs[that.cursor];
123
+ that.cursor += 1;
124
+ return {
125
+ value: value ? new Token(value) : void 0,
126
+ done: that.cursor > that.rawArgs.length
127
+ };
128
+ }
129
+ };
130
+ }
131
+ }
132
+
133
+ function camelCase(text) {
134
+ return text.split("-").map((t, idx) => idx === 0 ? t : t[0].toUpperCase() + t.slice(1)).join("");
135
+ }
5
136
  function twoColumn(texts, split = " ") {
6
137
  const left = padRight(texts.map((t) => t[0]));
7
138
  return left.map((l, idx) => l + split + texts[idx][1]);
@@ -11,507 +142,514 @@ function padRight(texts, fill = " ") {
11
142
  return texts.map((t) => t + fill.repeat(length - t.length));
12
143
  }
13
144
 
14
- function createDefaultLogger(name, logger) {
15
- const println = !!logger && typeof logger === "function" ? logger : logger?.println ?? ((message, ...args) => {
16
- console.log(message, ...args);
17
- });
18
- const info = typeof logger === "object" && logger?.info ? logger.info : (message, ...args) => {
19
- println(`${blue("INFO")} ${message}`, ...args);
20
- };
21
- const warn = typeof logger === "object" && logger?.warn ? logger.warn : (message, ...args) => {
22
- println(`${yellow("WARN")} ${message}`, ...args);
23
- };
24
- const error = typeof logger === "object" && logger?.error ? logger.error : (message, ...args) => {
25
- println(`${red("ERROR")} ${message}`, ...args);
26
- };
27
- const debug = typeof logger === "object" && logger?.debug ? logger.debug : (message, ...args) => {
28
- println(`${gray(name)} ${message}`, ...args);
29
- };
30
- return {
31
- println,
32
- info,
33
- warn,
34
- error,
35
- debug
36
- };
145
+ class BreadcError extends Error {
146
+ }
147
+ class ParseError extends Error {
37
148
  }
38
149
 
39
- const _Option = class {
40
- constructor(format, config = {}) {
41
- this.format = format;
42
- const match = _Option.OptionRE.exec(format);
43
- if (match) {
44
- if (match[3]) {
45
- this.type = "string";
150
+ function makeTreeNode(pnode) {
151
+ const node = {
152
+ children: /* @__PURE__ */ new Map(),
153
+ init() {
154
+ },
155
+ next(token, context) {
156
+ const t = token.raw();
157
+ context.result["--"].push(t);
158
+ if (node.children.has(t)) {
159
+ const next = node.children.get(t);
160
+ next.init(context);
161
+ return next;
46
162
  } else {
47
- this.type = "boolean";
163
+ return node;
48
164
  }
49
- this.name = match[2];
50
- if (match[1]) {
51
- this.shortcut = match[1][1];
165
+ },
166
+ finish() {
167
+ },
168
+ ...pnode
169
+ };
170
+ return node;
171
+ }
172
+ function parseOption(cursor, token, context) {
173
+ const o = token.option();
174
+ const [key, rawV] = o.split("=");
175
+ if (context.options.has(key)) {
176
+ const option = context.options.get(key);
177
+ const name = camelCase(option.name);
178
+ if (option.action) {
179
+ return option.action(cursor, token, context);
180
+ } else if (option.type === "boolean") {
181
+ context.result.options[name] = !key.startsWith("no-") ? true : false;
182
+ } else if (option.type === "string") {
183
+ if (rawV !== void 0) {
184
+ context.result.options[name] = rawV;
185
+ } else {
186
+ const value = context.lexer.next();
187
+ if (value !== void 0 && !value.isOption()) {
188
+ context.result.options[name] = value.raw();
189
+ } else {
190
+ throw new ParseError(
191
+ `You should provide arguments for ${option.format}`
192
+ );
193
+ }
52
194
  }
53
195
  } else {
54
- throw new Error(`Can not parse option format from "${format}"`);
196
+ throw new ParseError("unreachable");
197
+ }
198
+ if (option.cast) {
199
+ context.result.options[name] = option.cast(context.result.options[name]);
55
200
  }
56
- this.description = config.description ?? "";
57
- this.required = format.indexOf("<") !== -1;
58
- this.default = config.default;
59
- this.construct = config.construct;
201
+ } else {
202
+ throw new ParseError(`Unknown option ${token.raw()}`);
60
203
  }
61
- };
62
- let Option = _Option;
63
- Option.OptionRE = /^(-[a-zA-Z0-9], )?--([a-zA-Z0-9\-]+)( \[[a-zA-Z0-9]+\]| <[a-zA-Z0-9]+>)?$/;
64
-
65
- const _Command = class {
66
- constructor(format, config) {
67
- this.options = [];
68
- this.format = format;
69
- const pieces = format.split(" ").map((t) => t.trim()).filter(Boolean);
70
- const prefix = pieces.filter((p) => !isArg(p));
71
- this.default = prefix.length === 0;
72
- this.prefix = this.default ? [] : [prefix];
73
- this.arguments = pieces.filter(isArg);
74
- this.description = config.description ?? "";
75
- this.logger = config.logger;
76
- {
77
- const restArgs = this.arguments.findIndex((a) => a.startsWith("[..."));
78
- if (restArgs !== -1 && restArgs !== this.arguments.length - 1) {
79
- this.logger.warn(
80
- `Expand arguments ${this.arguments[restArgs]} should be placed at the last position`
81
- );
204
+ return cursor;
205
+ }
206
+ function parse(root, args) {
207
+ const lexer = new Lexer(args);
208
+ const context = {
209
+ lexer,
210
+ options: /* @__PURE__ */ new Map(),
211
+ result: {
212
+ arguments: [],
213
+ options: {},
214
+ "--": []
215
+ }
216
+ };
217
+ let cursor = root;
218
+ root.init(context);
219
+ for (const token of lexer) {
220
+ if (token.type() === "--") {
221
+ break;
222
+ } else if (token.isOption()) {
223
+ const res = parseOption(cursor, token, context);
224
+ if (res === false) {
225
+ break;
226
+ } else {
227
+ cursor = res;
82
228
  }
83
- if (pieces.length > _Command.MaxDep) {
84
- this.logger.warn(`Command format string "${format}" is too long`);
229
+ } else if (token.isText()) {
230
+ const res = cursor.next(token, context);
231
+ if (res === false) {
232
+ break;
233
+ } else {
234
+ cursor = res;
85
235
  }
236
+ } else {
237
+ throw new ParseError("unreachable");
86
238
  }
87
239
  }
88
- get isInternal() {
89
- return this instanceof InternalCommand;
240
+ cursor.finish(context);
241
+ for (const token of lexer) {
242
+ context.result["--"].push(token.raw());
90
243
  }
91
- alias(command) {
92
- const pieces = command.split(" ").map((t) => t.trim()).filter(Boolean);
93
- this.prefix.push(pieces);
94
- return this;
95
- }
96
- option(format, configOrDescription = "", otherConfig = {}) {
97
- const config = typeof configOrDescription === "object" ? configOrDescription : { ...otherConfig, description: configOrDescription };
98
- try {
99
- const option = new Option(format, config);
100
- this.options.push(option);
101
- } catch (error) {
102
- this.logger.warn(error.message);
244
+ return {
245
+ command: cursor.command,
246
+ arguments: context.result.arguments,
247
+ options: context.result.options,
248
+ "--": context.result["--"]
249
+ };
250
+ }
251
+
252
+ const OptionRE = /^(-[a-zA-Z], )?--([a-zA-Z0-9\-]+)( <[a-zA-Z0-9\-]+>)?$/;
253
+ function makeOption(format, config = {}) {
254
+ let name = "";
255
+ let short = void 0;
256
+ const match = OptionRE.exec(format);
257
+ if (match) {
258
+ name = match[2];
259
+ if (name.startsWith("no-")) {
260
+ throw new BreadcError(`Can not parse option format (${format})`);
103
261
  }
104
- return this;
105
- }
106
- hasPrefix(parsedArgs) {
107
- const argv = parsedArgs["_"];
108
- if (argv.length === 0) {
109
- return this.default;
262
+ if (match[1]) {
263
+ short = match[1][1];
264
+ }
265
+ if (match[3]) {
266
+ const initial = config.default ?? "";
267
+ return {
268
+ format,
269
+ type: "string",
270
+ name,
271
+ short,
272
+ description: config.description ?? "",
273
+ order: 0,
274
+ // @ts-ignore
275
+ initial: config.cast ? config.cast(initial) : initial,
276
+ cast: config.cast
277
+ };
110
278
  } else {
111
- for (const prefix of this.prefix) {
112
- if (prefix.length > 0 && prefix[0] === argv[0]) {
113
- return true;
114
- }
115
- }
116
- return false;
279
+ const initial = config.default === void 0 || config.default === null ? false : config.default;
280
+ return {
281
+ format,
282
+ type: "boolean",
283
+ name,
284
+ short,
285
+ description: config.description ?? "",
286
+ order: 0,
287
+ // @ts-ignore
288
+ initial: config.cast ? config.cast(initial) : initial,
289
+ cast: config.cast
290
+ };
117
291
  }
292
+ } else {
293
+ throw new BreadcError(`Can not parse option format (${format})`);
118
294
  }
119
- shouldRun(parsedArgs) {
120
- const args = parsedArgs["_"];
121
- for (const prefix of this.prefix) {
122
- let match = true;
123
- for (let i = 0; match && i < prefix.length; i++) {
124
- if (args[i] !== prefix[i]) {
125
- match = false;
295
+ }
296
+ const initContextOptions = (options, context) => {
297
+ for (const option of options) {
298
+ context.options.set(option.name, option);
299
+ if (option.short) {
300
+ context.options.set(option.short, option);
301
+ }
302
+ if (option.type === "boolean") {
303
+ context.options.set("no-" + option.name, option);
304
+ }
305
+ if (option.initial !== void 0) {
306
+ context.result.options[camelCase(option.name)] = option.initial;
307
+ }
308
+ }
309
+ };
310
+
311
+ function makeCommand(format, config, root, container) {
312
+ let cursor = root;
313
+ const args = [];
314
+ const options = [];
315
+ const command = {
316
+ callback: void 0,
317
+ format,
318
+ description: config.description ?? "",
319
+ _arguments: args,
320
+ _options: options,
321
+ option(format2, _config, _config2 = {}) {
322
+ const config2 = typeof _config === "string" ? { description: _config, ..._config2 } : _config;
323
+ const option = makeOption(format2, config2);
324
+ options.push(option);
325
+ return command;
326
+ },
327
+ action(fn) {
328
+ command.callback = async (...args2) => {
329
+ await container.preCommand(command);
330
+ const result = await fn(...args2);
331
+ await container.postCommand(command);
332
+ return result;
333
+ };
334
+ }
335
+ };
336
+ const node = makeTreeNode({
337
+ command,
338
+ init(context) {
339
+ initContextOptions(options, context);
340
+ },
341
+ finish(context) {
342
+ const rest = context.result["--"];
343
+ for (let i = 0; i < args.length; i++) {
344
+ if (args[i].type === "const") {
345
+ if (rest[i] !== args[i].name) {
346
+ throw new ParseError(`Sub-command ${args[i].name} mismatch`);
347
+ }
348
+ } else if (args[i].type === "require") {
349
+ if (i >= rest.length) {
350
+ throw new ParseError(
351
+ `You must provide require argument ${args[i].name}`
352
+ );
353
+ }
354
+ context.result.arguments.push(rest[i]);
355
+ } else if (args[i].type === "optional") {
356
+ context.result.arguments.push(rest[i]);
357
+ } else if (args[i].type === "rest") {
358
+ context.result.arguments.push(rest.splice(i));
126
359
  }
127
360
  }
128
- if (match) {
129
- args.splice(0, prefix.length);
130
- return true;
131
- }
361
+ context.result["--"] = rest.splice(args.length);
132
362
  }
133
- if (this.default)
134
- return true;
135
- return false;
136
- }
137
- parseArgs(argv, globalOptions) {
138
- const pieces = argv["_"];
139
- const args = [];
140
- const restArgs = [];
141
- for (let i = 0, used = 0; i <= this.arguments.length; i++) {
142
- if (i === this.arguments.length) {
143
- restArgs.push(...pieces.slice(used).map(String));
144
- restArgs.push(...(argv["--"] ?? []).map(String));
145
- } else if (i < pieces.length) {
146
- if (this.arguments[i].startsWith("[...")) {
147
- args.push(pieces.slice(i).map(String));
148
- used = pieces.length;
149
- } else {
150
- args.push(String(pieces[i]));
151
- used++;
363
+ });
364
+ {
365
+ let state = 0;
366
+ for (let i = 0; i < format.length; i++) {
367
+ if (format[i] === "<") {
368
+ if (state !== 0 && state !== 1) {
369
+ throw new BreadcError(
370
+ `Required arguments should be placed before optional or rest arguments`
371
+ );
152
372
  }
153
- } else {
154
- if (this.arguments[i].startsWith("<")) {
155
- this.logger.warn(
156
- `You should provide the argument "${this.arguments[i]}"`
373
+ const start = i;
374
+ while (i < format.length && format[i] !== ">") {
375
+ i++;
376
+ }
377
+ const name = format.slice(start + 1, i);
378
+ state = 1;
379
+ args.push({ type: "require", name });
380
+ } else if (format[i] === "[") {
381
+ if (state !== 0 && state !== 1) {
382
+ throw new BreadcError(
383
+ `There is at most one optional or rest arguments`
157
384
  );
158
- args.push("");
159
- } else if (this.arguments[i].startsWith("[...")) {
160
- args.push([]);
161
- } else if (this.arguments[i].startsWith("[")) {
162
- args.push(void 0);
385
+ }
386
+ const start = i;
387
+ while (i < format.length && format[i] !== "]") {
388
+ i++;
389
+ }
390
+ const name = format.slice(start + 1, i);
391
+ state = 2;
392
+ if (name.startsWith("...")) {
393
+ args.push({ type: "rest", name });
163
394
  } else {
164
- this.logger.warn(`unknown format string ("${this.arguments[i]}")`);
395
+ args.push({ type: "optional", name });
165
396
  }
166
- }
167
- }
168
- const fullOptions = globalOptions.concat(this.options).reduce((map, o) => {
169
- map.set(o.name, o);
170
- return map;
171
- }, /* @__PURE__ */ new Map());
172
- const options = argv;
173
- delete options["_"];
174
- for (const [name, rawOption] of fullOptions) {
175
- if (rawOption.type === "boolean")
176
- continue;
177
- if (rawOption.required) {
178
- if (options[name] === void 0) {
179
- options[name] = false;
180
- } else if (options[name] === "") {
181
- options[name] = true;
397
+ } else if (format[i] !== " ") {
398
+ if (state !== 0) {
399
+ throw new BreadcError(
400
+ `Sub-command should be placed at the beginning`
401
+ );
182
402
  }
183
- } else {
184
- if (options[name] === false) {
185
- options[name] = void 0;
186
- } else if (!(name in options)) {
187
- options[name] = void 0;
403
+ const start = i;
404
+ while (i < format.length && format[i] !== " ") {
405
+ i++;
188
406
  }
189
- }
190
- if (rawOption.construct !== void 0) {
191
- options[name] = rawOption.construct(options[name]);
192
- } else if (rawOption.default !== void 0) {
193
- if (options[name] === void 0 || options[name] === false || options[name] === "") {
194
- options[name] = rawOption.default;
407
+ const name = format.slice(start, i);
408
+ if (cursor.children.has(name)) {
409
+ cursor = cursor.children.get(name);
410
+ } else {
411
+ const internalNode = makeTreeNode({
412
+ next(token, context) {
413
+ const t = token.raw();
414
+ context.result["--"].push(t);
415
+ if (internalNode.children.has(t)) {
416
+ const next = internalNode.children.get(t);
417
+ next.init(context);
418
+ return next;
419
+ } else {
420
+ throw new ParseError(`Unknown sub-command (${t})`);
421
+ }
422
+ },
423
+ finish() {
424
+ throw new ParseError(`Unknown sub-command`);
425
+ }
426
+ });
427
+ cursor.children.set(name, internalNode);
428
+ cursor = internalNode;
195
429
  }
430
+ state = 0;
431
+ args.push({ type: "const", name });
196
432
  }
197
433
  }
198
- for (const key of Object.keys(options)) {
199
- if (!fullOptions.has(key)) {
200
- delete options[key];
434
+ cursor.command = command;
435
+ if (cursor !== root) {
436
+ for (const [key, value] of cursor.children) {
437
+ node.children.set(key, value);
201
438
  }
202
- }
203
- return {
204
- // @ts-ignore
205
- command: this,
206
- arguments: args,
207
- options,
208
- "--": restArgs
209
- };
210
- }
211
- action(fn) {
212
- this.actionFn = fn;
213
- }
214
- async run(...args) {
215
- if (this.actionFn) {
216
- return await this.actionFn(...args, {
217
- logger: this.logger,
218
- color: kolorist
219
- });
439
+ cursor.children = node.children;
440
+ cursor.next = node.next;
441
+ cursor.init = node.init;
442
+ cursor.finish = node.finish;
220
443
  } else {
221
- this.logger.warn(
222
- `You may miss action function in ${this.format ? `"${this.format}"` : "<default command>"}`
223
- );
224
- return void 0;
444
+ cursor.finish = node.finish;
225
445
  }
226
446
  }
227
- };
228
- let Command = _Command;
229
- Command.MaxDep = 5;
230
- class InternalCommand extends Command {
231
- hasPrefix(_args) {
232
- return false;
233
- }
234
- parseArgs(args, _globalOptions) {
235
- const argumentss = args["_"];
236
- const options = args;
237
- delete options["_"];
238
- delete options["help"];
239
- delete options["version"];
240
- return {
241
- // @ts-ignore
242
- command: this,
243
- arguments: argumentss,
244
- options: args,
245
- "--": []
246
- };
247
- }
447
+ return command;
248
448
  }
249
- class HelpCommand extends InternalCommand {
250
- constructor(commands, help, logger) {
251
- super("-h, --help", { description: "Display this message", logger });
252
- this.runCommands = [];
253
- this.helpCommands = [];
254
- this.commands = commands;
255
- this.help = help;
256
- }
257
- shouldRun(args) {
258
- const isRestEmpty = !args["--"]?.length;
259
- if ((args.help || args.h) && isRestEmpty) {
260
- if (args["_"].length > 0) {
261
- for (const cmd of this.commands) {
262
- if (!cmd.default && !cmd.isInternal) {
263
- if (cmd.shouldRun(args)) {
264
- this.runCommands.push(cmd);
265
- } else if (cmd.hasPrefix(args)) {
266
- this.helpCommands.push(cmd);
267
- }
268
- }
269
- }
270
- }
271
- return true;
272
- } else {
273
- return false;
274
- }
275
- }
276
- async run() {
277
- const shouldHelp = this.runCommands.length > 0 ? this.runCommands : this.helpCommands;
278
- for (const line of this.help(shouldHelp)) {
279
- this.logger.println(line);
449
+ function makeVersionCommand(name, config) {
450
+ const command = {
451
+ callback() {
452
+ const text = `${name}/${config.version ? config.version : "unknown"}`;
453
+ console.log(text);
454
+ return text;
455
+ },
456
+ format: "-v, --version",
457
+ description: "Print version",
458
+ _arguments: [],
459
+ _options: [],
460
+ option() {
461
+ return command;
462
+ },
463
+ action() {
280
464
  }
281
- this.runCommands.splice(0);
282
- this.helpCommands.splice(0);
283
- }
284
- }
285
- class VersionCommand extends InternalCommand {
286
- constructor(version, logger) {
287
- super("-v, --version", { description: "Display version number", logger });
288
- this.version = version;
289
- }
290
- shouldRun(args) {
291
- const isEmpty = !args["_"].length && !args["--"]?.length;
292
- if (args.version && isEmpty) {
293
- return true;
294
- } else if (args.v && isEmpty) {
295
- return true;
296
- } else {
465
+ };
466
+ const node = makeTreeNode({
467
+ command,
468
+ next() {
297
469
  return false;
298
470
  }
299
- }
300
- async run() {
301
- this.logger.println(this.version);
302
- }
303
- }
304
- function isArg(arg) {
305
- return arg[0] === "[" && arg[arg.length - 1] === "]" || arg[0] === "<" && arg[arg.length - 1] === ">";
471
+ });
472
+ const option = {
473
+ format: "-v, --version",
474
+ name: "version",
475
+ short: "v",
476
+ type: "boolean",
477
+ initial: void 0,
478
+ order: 999999999 + 1,
479
+ description: "Print version",
480
+ action() {
481
+ return node;
482
+ }
483
+ };
484
+ return option;
306
485
  }
307
-
308
- class Breadc {
309
- constructor(name, option) {
310
- this.options = [];
311
- this.commands = [];
312
- this.callbacks = {
313
- pre: [],
314
- post: []
315
- };
316
- this.name = name;
317
- this._version = option.version ?? "unknown";
318
- this.description = option.description;
319
- this.logger = createDefaultLogger(name, option.logger);
320
- this.commands.push(
321
- new VersionCommand(this.version(), this.logger),
322
- new HelpCommand(this.commands, this.help.bind(this), this.logger)
323
- );
324
- }
325
- version() {
326
- return `${this.name}/${this._version}`;
327
- }
328
- help(commands = []) {
329
- const output = [];
330
- const println = (msg) => output.push(msg);
331
- println(this.version());
332
- if (commands.length === 0) {
333
- if (this.description) {
334
- println("");
335
- if (Array.isArray(this.description)) {
336
- for (const line of this.description) {
337
- println(line);
338
- }
339
- } else {
340
- println(this.description);
486
+ function makeHelpCommand(name, config) {
487
+ function expandMessage(message) {
488
+ const result = [];
489
+ for (const row of message) {
490
+ if (typeof row === "function") {
491
+ const r = row();
492
+ if (r) {
493
+ result.push(...expandMessage(r));
494
+ }
495
+ } else if (typeof row === "string") {
496
+ result.push(row);
497
+ } else if (Array.isArray(row)) {
498
+ const lines = twoColumn(row);
499
+ for (const line of lines) {
500
+ result.push(line);
341
501
  }
342
502
  }
343
- if (this.defaultCommand) {
344
- println(``);
345
- println(`Usage:`);
346
- println(` $ ${this.name} ${this.defaultCommand.format}`);
347
- }
348
- } else if (commands.length === 1) {
349
- const command = commands[0];
350
- if (command.description) {
351
- println("");
352
- println(command.description);
353
- }
354
- println(``);
355
- println(`Usage:`);
356
- println(` $ ${this.name} ${command.format}`);
357
- }
358
- if (commands.length !== 1) {
359
- const cmdList = (commands.length === 0 ? this.commands : commands).filter(
360
- (c) => !c.isInternal
361
- );
362
- println(``);
363
- println(`Commands:`);
364
- const commandHelps = cmdList.map(
365
- (c) => [` $ ${this.name} ${c.format}`, c.description]
366
- );
367
- for (const line of twoColumn(commandHelps)) {
368
- println(line);
369
- }
370
- }
371
- println(``);
372
- println(`Options:`);
373
- const optionHelps = [].concat([
374
- ...commands.length > 0 ? commands.flatMap(
375
- (cmd) => cmd.options.map(
376
- (o) => [` ${o.format}`, o.description]
377
- )
378
- ) : [],
379
- ...this.options.map(
380
- (o) => [` ${o.format}`, o.description]
381
- ),
382
- [` -h, --help`, `Display this message`],
383
- [` -v, --version`, `Display version number`]
384
- ]);
385
- for (const line of twoColumn(optionHelps)) {
386
- println(line);
387
- }
388
- println(``);
389
- return output;
390
- }
391
- option(format, configOrDescription = "", otherConfig = {}) {
392
- const config = typeof configOrDescription === "object" ? configOrDescription : { ...otherConfig, description: configOrDescription };
393
- try {
394
- const option = new Option(format, config);
395
- this.options.push(option);
396
- } catch (error) {
397
- this.logger.warn(error.message);
398
- }
399
- return this;
400
- }
401
- command(format, configOrDescription = "", otherConfig = {}) {
402
- const config = typeof configOrDescription === "object" ? configOrDescription : { ...otherConfig, description: configOrDescription };
403
- const command = new Command(format, { ...config, logger: this.logger });
404
- if (command.default) {
405
- if (this.defaultCommand) {
406
- this.logger.warn("You can not have two default commands.");
407
- }
408
- this.defaultCommand = command;
409
503
  }
410
- this.commands.push(command);
411
- return command;
504
+ return result;
412
505
  }
413
- parse(args) {
414
- const allowOptions = [
415
- ...this.options,
416
- ...this.commands.flatMap((c) => c.options)
417
- ];
418
- {
419
- const names = /* @__PURE__ */ new Map();
420
- for (const option of allowOptions) {
421
- if (names.has(option.name)) {
422
- const otherOption = names.get(option.name);
423
- if (otherOption.type !== option.type) {
424
- this.logger.warn(`Option "${option.name}" encounters conflict`);
506
+ function expandCommands(cursor) {
507
+ const visited = /* @__PURE__ */ new WeakSet();
508
+ const commands = cursor.command ? [cursor.command] : [];
509
+ const q = [cursor];
510
+ visited.add(cursor);
511
+ for (let i = 0; i < q.length; i++) {
512
+ const cur = q[i];
513
+ for (const [_key, cmd] of cur.children) {
514
+ if (!visited.has(cmd)) {
515
+ visited.add(cmd);
516
+ if (cmd.command) {
517
+ commands.push(cmd.command);
425
518
  }
426
- } else {
427
- names.set(option.name, option);
519
+ q.push(cmd);
428
520
  }
429
521
  }
430
522
  }
431
- const alias = allowOptions.reduce(
432
- (map, o) => {
433
- if (o.shortcut) {
434
- map[o.shortcut] = o.name;
435
- }
436
- return map;
437
- },
438
- { h: "help", v: "version" }
439
- );
440
- const defaultValue = allowOptions.filter(
441
- (o) => o.type === "boolean" && o.default !== void 0 && o.default !== null && typeof o.default === "boolean"
442
- ).reduce((map, o) => {
443
- map[o.name] = o.default;
444
- return map;
445
- }, {});
446
- const argv = minimist(args, {
447
- string: allowOptions.filter((o) => o.type === "string").map((o) => o.name),
448
- boolean: allowOptions.filter((o) => o.type === "boolean").map((o) => o.name).concat(["help", "version"]),
449
- default: defaultValue,
450
- alias,
451
- "--": true,
452
- unknown: (t) => {
453
- if (t[0] !== "-")
454
- return true;
455
- else {
456
- if (["--help", "-h", "--version", "-v"].includes(t)) {
457
- return true;
523
+ return commands;
524
+ }
525
+ const command = {
526
+ callback(option2) {
527
+ const context = option2.__context__;
528
+ const cursor = option2.__cursor__;
529
+ const output = [
530
+ `${name}/${config.version ? config.version : "unknown"}`,
531
+ () => {
532
+ if (config.description) {
533
+ return ["", config.description];
458
534
  } else {
459
- this.logger.warn(`Find unknown flag "${t}"`);
460
- return false;
535
+ return void 0;
461
536
  }
462
- }
463
- }
464
- });
465
- for (const shortcut of Object.keys(alias)) {
466
- delete argv[shortcut];
537
+ },
538
+ () => {
539
+ const cmds = expandCommands(cursor);
540
+ if (cmds.length > 0) {
541
+ return [
542
+ "",
543
+ bold(underline("Commands:")),
544
+ cmds.map((cmd) => [
545
+ ` ${bold(name)} ${bold(cmd.format)}`,
546
+ cmd.description
547
+ ])
548
+ ];
549
+ } else {
550
+ return void 0;
551
+ }
552
+ },
553
+ "",
554
+ bold(underline("Options:")),
555
+ [...context.options.entries()].filter(([key, op]) => key === op.name).sort((lhs, rhs) => lhs[1].order - rhs[1].order).map(([_key, op]) => [
556
+ " " + (!op.short ? " " : "") + bold(op.format),
557
+ op.description
558
+ ]),
559
+ ""
560
+ ];
561
+ const text = expandMessage(output).join("\n");
562
+ console.log(text);
563
+ return text;
564
+ },
565
+ format: "-h, --help",
566
+ description: "Print help",
567
+ _arguments: [],
568
+ _options: [],
569
+ option() {
570
+ return command;
571
+ },
572
+ action() {
467
573
  }
468
- for (const command of this.commands) {
469
- if (!command.default && command.shouldRun(argv)) {
470
- return command.parseArgs(argv, this.options);
471
- }
574
+ };
575
+ const node = makeTreeNode({
576
+ command,
577
+ next() {
578
+ return false;
472
579
  }
473
- if (this.defaultCommand) {
474
- this.defaultCommand.shouldRun(argv);
475
- return this.defaultCommand.parseArgs(argv, this.options);
580
+ });
581
+ const option = {
582
+ format: "-h, --help",
583
+ name: "help",
584
+ short: "h",
585
+ type: "boolean",
586
+ initial: void 0,
587
+ description: "Print help",
588
+ order: 999999999,
589
+ action(cursor, _token, context) {
590
+ context.result.options.__cursor__ = cursor;
591
+ context.result.options.__context__ = context;
592
+ return node;
476
593
  }
477
- const argumentss = argv["_"];
478
- const options = argv;
479
- delete options["_"];
480
- delete options["--"];
481
- delete options["help"];
482
- delete options["version"];
483
- return {
484
- command: void 0,
485
- arguments: argumentss,
486
- options,
487
- "--": []
488
- };
489
- }
490
- on(event, fn) {
491
- this.callbacks[event].push(fn);
492
- }
493
- async run(args) {
494
- const parsed = this.parse(args);
495
- if (parsed.command) {
496
- await Promise.all(
497
- this.callbacks.pre.map((fn) => fn(parsed.options))
498
- );
499
- const returnValue = await parsed.command.run(...parsed.arguments, {
500
- "--": parsed["--"],
501
- ...parsed.options
502
- });
503
- await Promise.all(
504
- this.callbacks.post.map((fn) => fn(parsed.options))
594
+ };
595
+ return option;
596
+ }
597
+
598
+ function breadc(name, config = {}) {
599
+ let defaultCommand = void 0;
600
+ const globalOptions = [];
601
+ const container = makePluginContainer(config.plugins);
602
+ const root = makeTreeNode({
603
+ init(context) {
604
+ initContextOptions(globalOptions, context);
605
+ if (defaultCommand) {
606
+ initContextOptions(defaultCommand._options, context);
607
+ }
608
+ initContextOptions(
609
+ [makeHelpCommand(name, config), makeVersionCommand(name, config)],
610
+ context
505
611
  );
506
- return returnValue;
507
- } else {
612
+ },
613
+ finish() {
614
+ }
615
+ });
616
+ const breadc2 = {
617
+ option(format, _config, _config2 = {}) {
618
+ const config2 = typeof _config === "string" ? { description: _config, ..._config2 } : _config;
619
+ const option = makeOption(format, config2);
620
+ globalOptions.push(option);
621
+ return breadc2;
622
+ },
623
+ command(text, _config = {}) {
624
+ const config2 = typeof _config === "string" ? { description: _config } : _config;
625
+ const command = makeCommand(text, config2, root, container);
626
+ if (command._arguments.length === 0 || command._arguments[0].type !== "const") {
627
+ defaultCommand = command;
628
+ }
629
+ return command;
630
+ },
631
+ parse(args) {
632
+ const result = parse(root, args);
633
+ return result;
634
+ },
635
+ async run(args) {
636
+ const result = breadc2.parse(args);
637
+ const command = result.command;
638
+ if (command) {
639
+ if (command.callback) {
640
+ await container.preRun(breadc2);
641
+ const r = command.callback(...result.arguments, {
642
+ ...result.options,
643
+ "--": result["--"]
644
+ });
645
+ await container.postRun(breadc2);
646
+ return r;
647
+ }
648
+ }
508
649
  return void 0;
509
650
  }
510
- }
511
- }
512
-
513
- function breadc(name, option = {}) {
514
- return new Breadc(name, option);
651
+ };
652
+ return breadc2;
515
653
  }
516
654
 
517
- export { breadc as default };
655
+ export { BreadcError, ParseError, breadc, breadc as default, definePlugin };