Skip to content

Commit be8fba3

Browse files
committed
feat: support optional option values
1 parent 81b4a4c commit be8fba3

11 files changed

Lines changed: 409 additions & 16 deletions

File tree

‎docs/concepts/required-and-optional-input.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ Repeatable positional parsers return an empty array when nothing matches.
2121
call it. Use `onMissing` for prompts, files, network requests, or other work
2222
that belongs only to actual parsing.
2323

24+
`implicitValue` is different from every mechanism in this table: it applies
25+
when the option is present but its value is omitted. It does not change what
26+
happens when the option itself is absent.
27+
2428
## Follow option fallback precedence
2529

2630
For a scalar `option`, cmd-ts checks sources in this order:
@@ -31,6 +35,10 @@ For a scalar `option`, cmd-ts checks sources in this order:
3135
4. `onMissing` on the parser, then on its type.
3236
5. A missing-value error.
3337

38+
For an option with `implicitValue`, a bare command-line occurrence takes
39+
precedence over every absence fallback. An explicitly supplied command-line
40+
value is still decoded normally.
41+
3442
```ts
3543
const region = option({
3644
long: 'region',

‎docs/guides/add-options-and-flags.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,39 @@ const deploy = command({
3737
Omitting `--environment` is an error because neither the parser nor its type
3838
defines a fallback.
3939

40+
## Accept a value or a bare option
41+
42+
Set `implicitValue` when an option may be present without a value. This is
43+
useful for settings such as a development server host, where presence enables
44+
the setting and an explicit value overrides it:
45+
46+
```ts
47+
import { option, optional, string } from '@alloc/cmd-ts';
48+
49+
const host = option({
50+
long: 'host',
51+
short: 'H',
52+
type: optional(string),
53+
implicitValue: '0.0.0.0',
54+
description: 'Host to bind',
55+
});
56+
```
57+
58+
This parser distinguishes all three states:
59+
60+
| Input | Result |
61+
| --- | --- |
62+
| no `--host` | `undefined` |
63+
| `--host` | `'0.0.0.0'` |
64+
| `--host 192.168.1.10` | `'192.168.1.10'` |
65+
| `--host=192.168.1.10` | `'192.168.1.10'` |
66+
67+
A space-separated value is consumed only when the next argument is not
68+
option-like. Use the equals form for an option-like value, such as
69+
`--host=-example`. The same rule applies to the short form: `-H value`,
70+
`-H=value`, or bare `-H`. To put a positional immediately after a bare option,
71+
separate it with `--`, as in `--host -- index.html`.
72+
4073
## Add an optional flag
4174

4275
`flag` uses the built-in boolean decoder by default. An absent flag produces

‎docs/reference/arguments.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ entrypoint, not with argument-only arrays.
4747
| --- | --- | --- | --- |
4848
| `positional` | Next unclaimed positional | `string` | Error unless a default exists. |
4949
| `option` | One named value | `string` | Error unless env/default/fallback exists. |
50+
| `option` with `implicitValue` | One named optional value | `string` | Same as `option`; the implicit value only applies to a bare occurrence. |
5051
| `flag` | One named boolean occurrence | boolean | `false` with the default type. |
5152

5253
### `positional(config?)`
@@ -58,8 +59,12 @@ optional, supply a type with a default, such as `optional(string)`.
5859
### `option(config)`
5960

6061
`long` is required. Optional fields are `short`, `type`, `description`, `env`,
61-
`completion`, `defaultValue`, `defaultValueIsSerializable`, and `onMissing`.
62-
Without `type`, the value remains a string.
62+
`completion`, `defaultValue`, `defaultValueIsSerializable`, `implicitValue`,
63+
and `onMissing`. Without `type`, the value remains a string.
64+
65+
Set `implicitValue` to make the value itself optional. A bare occurrence
66+
produces the configured implicit value, and the inferred output is the union of
67+
the decoded and implicit value types. Help renders the value as `[<value>]`.
6368

6469
Accepted forms:
6570

@@ -70,6 +75,10 @@ Accepted forms:
7075
-o=dist
7176
```
7277

78+
With `implicitValue`, bare `--output` and `-o` are also accepted. A
79+
space-separated argument is treated as the value when it is not option-like;
80+
use `=` to pass an option-like value.
81+
7382
Providing the same scalar option more than once is an error.
7483

7584
### `flag(config)`

‎example/optional-valued-option.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { command, option, optional, string } from "../src";
2+
3+
export const serve = command({
4+
name: "serve",
5+
args: {
6+
host: option({
7+
long: "host",
8+
type: optional(string),
9+
implicitValue: true as const,
10+
}),
11+
},
12+
handler: ({ host }) => {
13+
/** @export serve -> host */
14+
const inferredHost = host;
15+
16+
// Compile-time checks for all members of string | true | undefined.
17+
const canBeImplicit: typeof inferredHost = true;
18+
const canBeAbsent: typeof inferredHost = undefined;
19+
const expected: string | true | undefined = inferredHost;
20+
21+
console.log(inferredHost, canBeImplicit, canBeAbsent, expected);
22+
},
23+
});

‎src/argparser.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ export type RegisterOptions = {
4848
forceFlagShortNames: Set<string>;
4949
forceOptionLongNames: Set<string>;
5050
forceOptionShortNames: Set<string>;
51+
forceOptionalValueLongNames: Set<string>;
52+
forceOptionalValueShortNames: Set<string>;
5153
};
5254

5355
export type Register = {

‎src/newparser/parser.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ export function parse(tokens: Token[], forceFlag: RegisterOptions): AstNode[] {
6060
longFlags: [...forceFlag.forceFlagLongNames],
6161
shortOptions: [...forceFlag.forceOptionShortNames],
6262
longOptions: [...forceFlag.forceOptionLongNames],
63+
shortOptionalValues: [...forceFlag.forceOptionalValueShortNames],
64+
longOptionalValues: [...forceFlag.forceOptionalValueLongNames],
6365
};
6466
debug("Registered:", JSON.stringify(registered));
6567
}
@@ -144,6 +146,7 @@ export function parse(tokens: Token[], forceFlag: RegisterOptions): AstNode[] {
144146
getToken,
145147
peekToken,
146148
forceOption: forceFlag.forceOptionLongNames,
149+
forceOptionalValue: forceFlag.forceOptionalValueLongNames,
147150
});
148151
let raw = `--${key}`;
149152

@@ -190,6 +193,7 @@ export function parse(tokens: Token[], forceFlag: RegisterOptions): AstNode[] {
190193
delimiterToken: nextToken,
191194
forceFlag: forceFlag.forceFlagShortNames,
192195
forceOption: forceFlag.forceOptionShortNames,
196+
forceOptionalValue: forceFlag.forceOptionalValueShortNames,
193197
getToken,
194198
peekToken,
195199
});
@@ -253,11 +257,21 @@ function parseOptionValue(opts: {
253257
key: string;
254258
forceFlag: Set<string>;
255259
forceOption: Set<string>;
260+
forceOptionalValue: Set<string>;
256261
}): OptionValue | undefined {
257-
const { getToken, delimiterToken, forceFlag, key, forceOption } = opts;
262+
const {
263+
getToken,
264+
delimiterToken,
265+
forceFlag,
266+
key,
267+
forceOption,
268+
forceOptionalValue,
269+
} = opts;
258270
const shouldReadKeyAsOption = forceOption.has(key);
271+
const shouldReadKeyAsOptionalValue = forceOptionalValue.has(key);
259272
const shouldReadKeyAsFlag =
260273
!shouldReadKeyAsOption &&
274+
!shouldReadKeyAsOptionalValue &&
261275
(forceFlag.has(key) || opts.peekToken()?.type !== "char");
262276

263277
if (!delimiterToken || (delimiterToken.raw !== "=" && shouldReadKeyAsFlag)) {
@@ -267,8 +281,29 @@ function parseOptionValue(opts: {
267281
const delimiter = delimiterToken.raw === "=" ? "=" : " ";
268282
const delimiterIndex = delimiterToken.index;
269283

284+
if (
285+
shouldReadKeyAsOptionalValue &&
286+
delimiter !== "=" &&
287+
opts.peekToken()?.type !== "char"
288+
) {
289+
return;
290+
}
291+
270292
let nextToken = getToken();
271293
if (!nextToken) {
294+
if (shouldReadKeyAsOptionalValue && delimiter === "=") {
295+
return {
296+
type: "optionValue",
297+
index: delimiterIndex,
298+
delimiter: {
299+
type: "delimiter",
300+
raw: delimiter,
301+
index: delimiterIndex,
302+
},
303+
node: { type: "value", raw: "", index: delimiterIndex + 1 },
304+
raw: delimiter,
305+
};
306+
}
272307
return;
273308
}
274309

‎src/option.ts‎

Lines changed: 78 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,30 @@ import type { HasType, Type } from "./type";
2121
import { string } from "./types";
2222
import type { AllOrNothing } from "./utils";
2323

24-
type OptionConfig<Decoder extends Type<string, any>> = LongDoc &
24+
type OptionConfig<
25+
Decoder extends Type<string, any>,
26+
ImplicitValue = never,
27+
> = LongDoc &
2528
HasType<Decoder> &
26-
Partial<Descriptive & EnvDoc & ShortDoc & OnMissing<OutputOf<Decoder>>> & {
29+
Partial<
30+
Descriptive &
31+
EnvDoc &
32+
ShortDoc &
33+
OnMissing<OutputOf<Decoder> | ImplicitValue>
34+
> & {
2735
completion?: CompletionHandler;
28-
} & AllOrNothing<Default<OutputOf<Decoder>>>;
36+
implicitValue?: ImplicitValue;
37+
} & AllOrNothing<Default<OutputOf<Decoder> | ImplicitValue>>;
2938

30-
function fullOption<Decoder extends Type<string, any>>(
31-
config: OptionConfig<Decoder>,
32-
): ArgParser<OutputOf<Decoder>> & ProvidesHelp & Partial<Descriptive> {
39+
function fullOption<Decoder extends Type<string, any>, ImplicitValue = never>(
40+
config: OptionConfig<Decoder, ImplicitValue>,
41+
): ArgParser<OutputOf<Decoder> | ImplicitValue> &
42+
ProvidesHelp &
43+
Partial<Descriptive> {
44+
const hasImplicitValue = Object.prototype.hasOwnProperty.call(
45+
config,
46+
"implicitValue",
47+
);
3348
const parser: ReturnType<typeof fullOption> = {
3449
description: config.description ?? config.type.description,
3550
helpTopics() {
@@ -38,7 +53,7 @@ function fullOption<Decoder extends Type<string, any>>(
3853
if (config.short) {
3954
usage += `, -${config.short}`;
4055
}
41-
usage += ` <${displayName}>`;
56+
usage += hasImplicitValue ? ` [<${displayName}>]` : ` <${displayName}>`;
4257

4358
const defaults: string[] = [];
4459

@@ -87,15 +102,24 @@ function fullOption<Decoder extends Type<string, any>>(
87102
];
88103
},
89104
register(opts) {
90-
opts.forceOptionLongNames.add(config.long);
91-
if (config.short) {
92-
opts.forceOptionShortNames.add(config.short);
105+
if (hasImplicitValue) {
106+
opts.forceOptionalValueLongNames.add(config.long);
107+
if (config.short) {
108+
opts.forceOptionalValueShortNames.add(config.short);
109+
}
110+
} else {
111+
opts.forceOptionLongNames.add(config.long);
112+
if (config.short) {
113+
opts.forceOptionShortNames.add(config.short);
114+
}
93115
}
94116
},
95117
async parse({
96118
nodes,
97119
visitedNodes,
98-
}: ParseContext): Promise<ParsingResult<OutputOf<Decoder>>> {
120+
}: ParseContext): Promise<
121+
ParsingResult<OutputOf<Decoder> | ImplicitValue>
122+
> {
99123
const options = findOption(nodes, {
100124
longNames: [config.long],
101125
shortNames: config.short ? [config.short] : [],
@@ -120,6 +144,8 @@ function fullOption<Decoder extends Type<string, any>>(
120144
let envPrefix = "";
121145
if (option?.value) {
122146
rawValue = option.value.node.raw;
147+
} else if (option && hasImplicitValue) {
148+
return Result.ok(config.implicitValue as ImplicitValue);
123149
} else if (valueFromEnv !== undefined) {
124150
rawValue = valueFromEnv;
125151
envPrefix = `env[${styleText("italic", String(config.env))}]: `;
@@ -191,6 +217,7 @@ function fullOption<Decoder extends Type<string, any>>(
191217
}
192218

193219
type StringType = Type<string, string>;
220+
type NoInferValue<T> = [T][T extends any ? 0 : never];
194221

195222
/**
196223
* Decodes an argument which is in the form of a key and a value, and allows parsing the following ways:
@@ -199,13 +226,50 @@ type StringType = Type<string, string>;
199226
* - `--long value` where `long` is the provided `long`
200227
* - `-s=value` where `s` is the provided `short`
201228
* - `-s value` where `s` is the provided `short`
202-
* @param config flag configurations
229+
*
230+
* Set `implicitValue` to also accept the option without a value. A bare
231+
* occurrence uses that value, while an absent option continues through the
232+
* normal environment, default, and `onMissing` fallbacks.
233+
* @param config option configuration
203234
*/
235+
export function option<Decoder extends Type<string, any>, ImplicitValue>(
236+
config: LongDoc &
237+
HasType<Decoder> &
238+
Partial<
239+
Descriptive &
240+
EnvDoc &
241+
ShortDoc &
242+
OnMissing<OutputOf<Decoder> | NoInferValue<ImplicitValue>>
243+
> & {
244+
completion?: CompletionHandler;
245+
implicitValue: ImplicitValue;
246+
} & AllOrNothing<Default<OutputOf<Decoder> | NoInferValue<ImplicitValue>>>,
247+
): ArgParser<OutputOf<Decoder> | ImplicitValue> &
248+
ProvidesHelp &
249+
Partial<Descriptive>;
250+
export function option<ImplicitValue>(
251+
config: LongDoc &
252+
Partial<
253+
HasType<never> &
254+
Descriptive &
255+
EnvDoc &
256+
ShortDoc &
257+
OnMissing<OutputOf<StringType> | NoInferValue<ImplicitValue>>
258+
> & {
259+
completion?: CompletionHandler;
260+
implicitValue: ImplicitValue;
261+
} & AllOrNothing<
262+
Default<OutputOf<StringType> | NoInferValue<ImplicitValue>>
263+
>,
264+
): ArgParser<OutputOf<StringType> | ImplicitValue> &
265+
ProvidesHelp &
266+
Partial<Descriptive>;
204267
export function option<Decoder extends Type<string, any>>(
205268
config: LongDoc &
206269
HasType<Decoder> &
207270
Partial<Descriptive & EnvDoc & ShortDoc & OnMissing<OutputOf<Decoder>>> & {
208271
completion?: CompletionHandler;
272+
implicitValue?: never;
209273
} & AllOrNothing<Default<OutputOf<Decoder>>>,
210274
): ArgParser<OutputOf<Decoder>> & ProvidesHelp & Partial<Descriptive>;
211275
export function option(
@@ -218,13 +282,14 @@ export function option(
218282
OnMissing<OutputOf<StringType>>
219283
> & { completion?: CompletionHandler } & AllOrNothing<
220284
Default<OutputOf<StringType>>
221-
>,
285+
> & { implicitValue?: never },
222286
): ArgParser<OutputOf<StringType>> & ProvidesHelp & Partial<Descriptive>;
223287
export function option(
224288
config: LongDoc &
225289
Partial<HasType<any>> &
226290
Partial<Descriptive & EnvDoc & ShortDoc> & {
227291
completion?: CompletionHandler;
292+
implicitValue?: unknown;
228293
},
229294
): ArgParser<OutputOf<any>> & ProvidesHelp & Partial<Descriptive> {
230295
return fullOption({

‎src/runner.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,15 @@ function parseCommon<R extends Runner<any, any>>(
102102
const shortFlagKeys = new Set<string>();
103103
const longOptionKeys = new Set<string>();
104104
const shortOptionKeys = new Set<string>();
105+
const longOptionalValueKeys = new Set<string>();
106+
const shortOptionalValueKeys = new Set<string>();
105107
const registerContext = {
106108
forceFlagShortNames: shortFlagKeys,
107109
forceFlagLongNames: longFlagKeys,
108110
forceOptionShortNames: shortOptionKeys,
109111
forceOptionLongNames: longOptionKeys,
112+
forceOptionalValueShortNames: shortOptionalValueKeys,
113+
forceOptionalValueLongNames: longOptionalValueKeys,
110114
};
111115

112116
ap.register(registerContext);

‎test/createRegisterOptions.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,7 @@ export function createRegisterOptions(): RegisterOptions {
66
forceFlagShortNames: new Set(),
77
forceOptionLongNames: new Set(),
88
forceOptionShortNames: new Set(),
9+
forceOptionalValueLongNames: new Set(),
10+
forceOptionalValueShortNames: new Set(),
911
};
1012
}

0 commit comments

Comments
 (0)