|
1 | 1 | import { ShellContext } from "./shell"; |
2 | 2 |
|
| 3 | +/** |
| 4 | + * Represents a command-line flag or parameter. |
| 5 | + */ |
3 | 6 | export interface Option { |
| 7 | + /** The full name of the option (e.g., "all" for --all). */ |
4 | 8 | long: string; |
| 9 | + /** The single-character alias (e.g., "a" for -a). */ |
5 | 10 | short: string; |
| 11 | + /** If true, the shell expects a value to follow this option (e.g., --file <name>). */ |
6 | 12 | isInput: boolean; |
7 | 13 | } |
8 | 14 |
|
| 15 | +/** |
| 16 | + * Documentation metadata used by the `help` or `man` commands. |
| 17 | + */ |
9 | 18 | export interface Manual { |
| 19 | + /** A brief one-line summary of what the command does. */ |
10 | 20 | purpose?: string; |
| 21 | + /** A string representing the syntax (e.g., "ls [OPTION]... [FILE]..."). */ |
11 | 22 | usage?: string; |
| 23 | + /** A detailed explanation of the command's behavior. */ |
12 | 24 | description?: string; |
| 25 | + /** A mapping of option names to their descriptions for the help output. */ |
13 | 26 | options?: object; |
14 | 27 | } |
15 | 28 |
|
16 | 29 | export type CommandOutput = number | undefined | void; |
17 | 30 | export type Execute = (args: string[], context: ShellContext) => Promise<CommandOutput> | CommandOutput; |
18 | 31 |
|
| 32 | +/** |
| 33 | + * Defines a shell command, including its execution logic, arguments requirements, and manual page. |
| 34 | + */ |
19 | 35 | export class Command { |
20 | 36 | #name?: string; |
21 | 37 | options: Option[] = []; |
22 | 38 | manual?: Manual; |
23 | 39 | requireArgs?: boolean; |
24 | 40 | requireOptions?: boolean; |
25 | 41 |
|
| 42 | + /** |
| 43 | + * The core logic to run when the command is invoked. |
| 44 | + */ |
26 | 45 | execute: Execute = () => {}; |
27 | 46 |
|
| 47 | + /** |
| 48 | + * Sets the command name and initializes the default usage string if not already set. |
| 49 | + */ |
28 | 50 | setName(name?: string): Command { |
29 | 51 | this.#name = name; |
30 | 52 |
|
@@ -60,11 +82,17 @@ export class Command { |
60 | 82 | return this; |
61 | 83 | } |
62 | 84 |
|
| 85 | + /** |
| 86 | + * Registers a new option/flag for this command. |
| 87 | + */ |
63 | 88 | addOption({ short, long, isInput = false }: Omit<Option, "isInput"> & { isInput?: boolean }): Command { |
64 | 89 | this.options.push({ short, long, isInput }); |
65 | 90 | return this; |
66 | 91 | } |
67 | 92 |
|
| 93 | + /** |
| 94 | + * Retrieves an option definition by either its short or long name. |
| 95 | + */ |
68 | 96 | getOption(key: string): Option | undefined { |
69 | 97 | return this.options.find((option) => option.short === key || option.long === key); |
70 | 98 | } |
|
0 commit comments