GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(argv): a flag whose value may be left off (#969) · jdx/usage@3b1adff

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • argv/src
    • help.rs
    • spec.rs
  • conformance/tests
    • optional_flag_value.rs
  • derive/src
    • codegen.rs
    • model.rs
  • xtask/src
    • shadow.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎argv/src/help.rs‎

Copy file name to clipboardExpand all lines: argv/src/help.rs
+8-1Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,14 @@ fn flag_usage_masked(meta: &FlagMeta<'_>, show: &Shown) -> String {
247247
}
248248
if flag.takes_value {
249249
let name = meta.value_name.unwrap_or(flag.name);
250-
let _ = write!(out, " <{name}>");
250+
// Angled where the value must be given, squared where it need not — the same brackets
251+
// an argument uses, and for the same reason. pitchfork's `--bump` is the fleet's case.
252+
let (open, close) = if meta.value_optional {
253+
('[', ']')
254+
} else {
255+
('<', '>')
256+
};
257+
let _ = write!(out, " {open}{name}{close}");
251258
if flag.variadic {
252259
out.push('…');
253260
}
Collapse file

‎argv/src/spec.rs‎

Copy file name to clipboardExpand all lines: argv/src/spec.rs
+20-5Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,13 @@ pub struct FlagMeta<'a> {
480480
pub default: &'a [&'a str],
481481
pub choices: &'a [&'a str],
482482
pub required: bool,
483+
/// Whether the flag's value may be left off, as in `--bump` or `--bump 5`.
484+
///
485+
/// Help only, and deliberately: usage-lib's parser refuses a bare `--bump` exactly as it
486+
/// refuses a bare `--port`, so this changes no binding — it changes the brackets, `[BUMP]`
487+
/// rather than `<BUMP>`, which is what a spec's `arg "[BUMP]" required=#false` says. In
488+
/// [`FlagMeta`] and not in [`Flag`] for that reason: a parse never reads it.
489+
pub value_optional: bool,
483490
pub hide: bool,
484491
/// Whether repetition is counted rather than collected, as in `-vvv`.
485492
pub count: bool,
@@ -533,6 +540,7 @@ impl FlagMeta<'_> {
533540
default: &[],
534541
choices: &[],
535542
required: false,
543+
value_optional: false,
536544
hide: false,
537545
count: false,
538546
repeatable: false,
@@ -1050,8 +1058,13 @@ fn write_flag(out: &mut String, meta: &FlagMeta<'_>, depth: usize) -> core::fmt:
10501058
write!(
10511059
out,
10521060
"arg {}",
1053-
quoted(&placeholder(name, meta.flag.variadic))
1061+
quoted(&placeholder(name, meta.flag.variadic, meta.value_optional))
10541062
)?;
1063+
// Square brackets alone would round-trip as required, since usage-lib reads the
1064+
// brackets *and* the attribute: `[BUMP]` without it comes back `required=#true`.
1065+
if meta.value_optional {
1066+
out.push_str(" required=#false");
1067+
}
10551068
if meta.choices.is_empty() {
10561069
out.push('\n');
10571070
} else {
@@ -1221,9 +1234,10 @@ fn flag_forms(flag: &Flag<'_>) -> String {
12211234
}
12221235

12231236
/// `<name>` or `<name>...`, the spec's way of writing a value placeholder.
1224-
fn placeholder(name: &str, variadic: bool) -> String {
1237+
fn placeholder(name: &str, variadic: bool, optional: bool) -> String {
12251238
let ellipsis = if variadic { "..." } else { "" };
1226-
format!("<{name}>{ellipsis}")
1239+
let (open, close) = if optional { ('[', ']') } else { ('<', '>') };
1240+
format!("{open}{name}{close}{ellipsis}")
12271241
}
12281242

12291243
/// A positional's placeholder: angle brackets when required, square when not.
@@ -1699,7 +1713,8 @@ mod tests {
16991713
};
17001714
assert_eq!(arg_placeholder("file", &required), "<file>");
17011715
assert_eq!(arg_placeholder("rest", &optional_var), "[rest]...");
1702-
assert_eq!(placeholder("n", false), "<n>");
1703-
assert_eq!(placeholder("pattern", true), "<pattern>...");
1716+
assert_eq!(placeholder("n", false, false), "<n>");
1717+
assert_eq!(placeholder("pattern", true, false), "<pattern>...");
1718+
assert_eq!(placeholder("BUMP", false, true), "[BUMP]");
17041719
}
17051720
}
Collapse file

‎conformance/tests/optional_flag_value.rs‎

Copy file name to clipboard
+77Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//! A flag whose value may be left off: `[BUMP]` rather than `<BUMP>`.
2+
//!
3+
//! A spec says this with `arg "[BUMP]" required=#false` inside the flag, and pitchfork's
4+
//! `--bump` is the case that found it — usage-lib rendered `[BUMP]`, usage-argv `<BUMP>`, on
5+
//! three of pitchfork's pages.
6+
//!
7+
//! **Help only, and measured rather than assumed.** usage-lib's parser refuses a bare `--bump`
8+
//! exactly as it refuses a bare `--port`:
9+
//!
10+
//! ```text
11+
//! ["--bump"] -> ERR Invalid flag `--bump`: requires an argument
12+
//! ["--bump", "5"] -> OK bump="5"
13+
//! ```
14+
//!
15+
//! So this changes no binding, which is why it lives in `FlagMeta` and not in `Flag`: a parse
16+
//! never reads it. It cannot be inferred from the type either — `Option<String>` already says
17+
//! the *flag* is optional and says nothing about its value — so it is declared.
18+
19+
use std::ffi::OsStr;
20+
21+
use usage::Spec as LibSpec;
22+
use usage_argv::help;
23+
use usage_derive::Cli;
24+
25+
/// A tool with one of each
26+
#[derive(Cli)]
27+
#[usage(bin = "ex")]
28+
struct Ex {
29+
/// Automatically find an available port if the expected port is in use
30+
#[usage(long, value_name = "BUMP", value_optional)]
31+
bump: Option<String>,
32+
/// The port to listen on
33+
#[usage(long, value_name = "PORT")]
34+
port: Option<String>,
35+
}
36+
37+
fn listing() -> String {
38+
let page = help::render(Ex::spec(), Ex::command(), false).expect("a page");
39+
page.split_once("\nFlags:")
40+
.expect("a flags section")
41+
.1
42+
.to_string()
43+
}
44+
45+
#[test]
46+
fn an_optional_value_is_squared_and_a_required_one_angled() {
47+
let flags = listing();
48+
assert!(flags.contains("--bump [BUMP]"), "{flags}");
49+
assert!(flags.contains("--port <PORT>"), "{flags}");
50+
}
51+
52+
#[test]
53+
fn the_reference_renders_it_the_same_way() {
54+
// The invariant this area runs on: the two renderers agree byte for byte. Through the
55+
// emitted spec, so the round trip is covered too — square brackets alone come back
56+
// `required=#true`, since usage-lib reads the attribute as well as the name.
57+
let spec: LibSpec = Ex::to_kdl().parse().expect("valid spec");
58+
let theirs = usage::docs::cli::render_help(&spec, &spec.cmd, false);
59+
let ours = help::render(Ex::spec(), Ex::command(), false).expect("a page");
60+
assert_eq!(ours, theirs);
61+
}
62+
63+
#[test]
64+
fn the_emitted_spec_says_both_halves() {
65+
let kdl = Ex::to_kdl();
66+
assert!(kdl.contains(r#"arg "[BUMP]" required=#false"#), "{kdl}");
67+
assert!(kdl.contains(r#"arg "<PORT>""#), "{kdl}");
68+
}
69+
70+
#[test]
71+
fn it_still_takes_its_value() {
72+
// Nothing about binding changed: the value is read where it is given.
73+
let argv = [OsStr::new("--bump"), OsStr::new("5")];
74+
let parsed = Ex::parse_from(&argv).expect("parses");
75+
assert_eq!(parsed.bump.as_deref(), Some("5"));
76+
assert_eq!(parsed.port.as_deref(), None);
77+
}
Collapse file

‎derive/src/codegen.rs‎

Copy file name to clipboardExpand all lines: derive/src/codegen.rs
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,9 @@ fn flag_meta(i: usize, field: &Field, owner: &syn::Ident) -> TokenStream {
866866
// A collecting field's type cannot say whether one value is needed, so `required` may
867867
// declare it. Every other shape gets its answer from the type.
868868
let required = field.shape == Shape::Required || field.required_collection;
869+
// Declared, not inferred: `Option<String>` already says the *flag* is optional and says
870+
// nothing about whether its value is.
871+
let value_optional = field.value_optional;
869872
let choices = choices_tokens(field);
870873
let (var_min, var_max) = bounds_tokens(field);
871874
// Written as declared, in the spec's own spelling, so the emitted KDL says what
@@ -901,6 +904,7 @@ fn flag_meta(i: usize, field: &Field, owner: &syn::Ident) -> TokenStream {
901904
count: #count,
902905
repeatable: #repeatable,
903906
required: #required,
907+
value_optional: #value_optional,
904908
choices: #choices,
905909
var_min: #var_min,
906910
var_max: #var_max,
Collapse file

‎derive/src/model.rs‎

Copy file name to clipboardExpand all lines: derive/src/model.rs
+79Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,13 @@ pub struct Field {
150150
/// way of saying "one or more" — could not be declared at all, and came back as
151151
/// `[TARGET]…`. This is the one place it has to be stated rather than inferred.
152152
pub required_collection: bool,
153+
/// Whether the flag's value may be left off: `[BUMP]` rather than `<BUMP>`.
154+
///
155+
/// Help and the emitted spec only. usage-lib's parser refuses a bare `--bump` exactly as it
156+
/// refuses a bare `--port`, so this binds nothing differently — which is why it is stated
157+
/// here and not inferred from the type, where `Option<String>` already means the *flag* is
158+
/// optional and says nothing about its value.
159+
pub value_optional: bool,
153160
/// The placeholder for a flag's value in help and in the emitted spec: `n` in
154161
/// `--jobs <n>`.
155162
///
@@ -914,6 +921,7 @@ impl Field {
914921
ident: ident.clone(),
915922
ty: field.ty.clone(),
916923
name: to_kebab(&ident.to_string()),
924+
value_optional: false,
917925
kind: Kind::Flatten {
918926
ty: field.ty.clone(),
919927
},
@@ -1012,6 +1020,7 @@ impl Field {
10121020
ident: ident.clone(),
10131021
ty: field.ty.clone(),
10141022
name: to_kebab(&ident.to_string()),
1023+
value_optional: false,
10151024
kind: Kind::Subcommand { ty, optional },
10161025
effect: None,
10171026
complete: None,
@@ -1070,6 +1079,7 @@ impl Field {
10701079
let mut repeatable = false;
10711080
let mut variadic = false;
10721081
let mut count = false;
1082+
let mut value_optional = false;
10731083
let mut double_dash = DoubleDash::Optional;
10741084
let mut env = None;
10751085
let mut setting = None;
@@ -1130,6 +1140,10 @@ impl Field {
11301140
"var" => repeatable = flag_value(&meta)?,
11311141
"variadic" => variadic = flag_value(&meta)?,
11321142
"count" => count = flag_value(&meta)?,
1143+
// Help only: the parser refuses a bare `--bump` either way. What this
1144+
// changes is the brackets, which is the whole of what a spec's
1145+
// `arg "[BUMP]" required=#false` says.
1146+
"value_optional" => value_optional = flag_value(&meta)?,
11331147
"hide" => hide = flag_value(&meta)?,
11341148
"arg" => is_arg = flag_value(&meta)?,
11351149
"env" => env = Some(string_value(&meta)?),
@@ -1373,6 +1387,13 @@ impl Field {
13731387
"`value_enum` describes what a value may be, and this field takes no value",
13741388
));
13751389
}
1390+
if value_optional && matches!(shape, Shape::Bool | Shape::Count) {
1391+
return Err(syn::Error::new(
1392+
span,
1393+
"`value_optional` describes a value that may be left off, and this field \
1394+
takes no value",
1395+
));
1396+
}
13761397
if !choices.is_empty() && matches!(shape, Shape::Bool | Shape::Count) {
13771398
return Err(syn::Error::new(
13781399
span,
@@ -1423,6 +1444,21 @@ impl Field {
14231444
}
14241445

14251446
let is_flag = !longs.is_empty() || !shorts.is_empty();
1447+
// Only a flag's value has a say in this. A positional's brackets come from its type
1448+
// already — `Option<T>` renders `[NAME]` and `T` renders `<NAME>` — so the attribute
1449+
// would be read by nothing, and a declaration nothing reads is worse than an error: the
1450+
// page would keep saying the opposite of what was asked for.
1451+
//
1452+
// Tested against `is_flag` and not `is_arg`: `is_arg` is only true where `arg` was
1453+
// written, and a field with no `long`, `short` or `arg` is a positional as well. That
1454+
// gap let `#[usage(value_optional)] out: Option<String>` compile and be dropped.
1455+
if value_optional && !is_flag {
1456+
return Err(syn::Error::new(
1457+
span,
1458+
"`value_optional` is for a flag's value; a positional says this with its \
1459+
type, where `Option<T>` is already `[NAME]`",
1460+
));
1461+
}
14261462
if is_flag && is_arg {
14271463
return Err(syn::Error::new(
14281464
span,
@@ -1725,6 +1761,7 @@ impl Field {
17251761
ident,
17261762
ty: field.ty.clone(),
17271763
name,
1764+
value_optional,
17281765
kind,
17291766
shape,
17301767
value_ty,
@@ -2603,6 +2640,48 @@ mod tests {
26032640
assert!(cli.fields[0].required_collection);
26042641
}
26052642

2643+
#[test]
2644+
fn value_optional_is_refused_where_nothing_would_read_it() {
2645+
// It says a *flag's* value may be left off. `arg_meta` never emits it, and a valueless
2646+
// flag has no value to make optional — so on a positional or a `bool`/`count` flag the
2647+
// declaration compiled and was dropped. Worse than an error: a positional's brackets
2648+
// come from its type, so the page went on saying the opposite of what was asked.
2649+
for (decl, word) in [
2650+
(
2651+
"#[usage(arg, value_optional)]\n out: Option<String>,",
2652+
"type",
2653+
),
2654+
// No `arg` either: a field with no `long`, `short` or `arg` is a positional too,
2655+
// and testing `is_arg` rather than `is_flag` let this one through.
2656+
(
2657+
"#[usage(value_optional)]\n out: Option<String>,",
2658+
"type",
2659+
),
2660+
(
2661+
"#[usage(long, value_optional)]\n out: bool,",
2662+
"no value",
2663+
),
2664+
(
2665+
"#[usage(long, count, value_optional)]\n out: u8,",
2666+
"no value",
2667+
),
2668+
] {
2669+
let err = rejection(&format!(
2670+
"struct Ex {{\n {decl}\n }}"
2671+
));
2672+
assert!(err.contains(word), "unhelpful message for `{decl}`: {err}");
2673+
}
2674+
// And where there is a flag value, it still works.
2675+
let cli = cli(r#"
2676+
struct Ex {
2677+
#[usage(long, value_optional)]
2678+
bump: Option<String>,
2679+
}
2680+
"#)
2681+
.expect("should compile");
2682+
assert!(cli.fields[0].value_optional);
2683+
}
2684+
26062685
#[test]
26072686
fn value_name_is_refused_where_there_is_no_value_to_name() {
26082687
// It names the placeholder a flag's *value* gets in help. `arg_meta` never emits it, and
Collapse file

‎xtask/src/shadow.rs‎

Copy file name to clipboardExpand all lines: xtask/src/shadow.rs
+43Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,12 @@ fn usage_flag_opts(
699699
if arg.name != flag.name {
700700
opts.push(format!("value_name = {:?}", arg.name));
701701
}
702+
// `arg "[BUMP]" required=#false`: the value may be left off. Dropping it rendered
703+
// pitchfork's `--bump` as `<BUMP>` where its own spec says `[BUMP]`, and said nothing
704+
// about having dropped anything.
705+
if !arg.required {
706+
opts.push("value_optional".into());
707+
}
702708
if let Some(choices) = &arg.choices {
703709
opts.push(format!("choices({})", quoted_list(&choices.choices)));
704710
}
@@ -856,6 +862,16 @@ fn clap_flag_opts(
856862
Some(max) => opts.push(format!("num_args = {least}..={max}")),
857863
None => opts.push(format!("num_args = {least}..")),
858864
}
865+
} else if !arg.required {
866+
// Noted, not emitted. `num_args = 0..=1` was the obvious translation and it is the
867+
// wrong one: `value_optional` is help-only — usage-lib's parser refuses a bare
868+
// `--bump` exactly as it refuses a bare `--port` — so declaring it in clap would
869+
// make the clap shadow accept a line the usage shadow rejects, and the pair exists
870+
// to be one grammar told to two frameworks.
871+
//
872+
// A real limitation, then, rather than a gap in this file: clap cannot print
873+
// `[BUMP]` without also accepting `--bump` on its own.
874+
skipped.note("a flag's value being optional in help only");
859875
}
860876
if flag.required {
861877
opts.push("required = true".into());
@@ -1658,6 +1674,33 @@ mod tests {
16581674
assert!(out.contains("version = \"1.55.0\""), "{out}");
16591675
}
16601676

1677+
#[test]
1678+
fn the_clap_dialect_counts_an_optional_value_as_lost() {
1679+
// Reported twice on #969, in opposite directions, and the second one was right. Emitting
1680+
// `num_args = 0..=1` made clap accept `--bump` with no value where usage-lib rejects it,
1681+
// so the two shadows stopped describing one grammar. clap cannot show `[BUMP]` without
1682+
// accepting the bare form, which makes this a limitation to record rather than a
1683+
// translation to make.
1684+
let spec = "name \"ex\"\nbin \"ex\"\nflag --bump {\n arg \"[BUMP]\" required=#false\n}\n";
1685+
let (out, skipped) = rendered_as(spec, Dialect::Clap);
1686+
assert!(
1687+
!out.contains("num_args"),
1688+
"the grammar must not change: {out}"
1689+
);
1690+
assert_eq!(
1691+
skipped
1692+
.counts
1693+
.get("a flag's value being optional in help only"),
1694+
Some(&1),
1695+
"{:?}",
1696+
skipped.counts
1697+
);
1698+
1699+
// The usage dialect still says it, since that is where it means something.
1700+
let (out, _) = rendered_as(spec, Dialect::Usage);
1701+
assert!(out.contains("value_optional"), "{out}");
1702+
}
1703+
16611704
#[test]
16621705
fn an_expressible_property_is_not_counted() {
16631706
let (_, skipped) = rendered("name \"ex\"\nbin \"ex\"\ncmd \"go\" {\n alias \"g\"\n}\n");

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.