GeezerVison is showing github.com — feat(argv): a flag whose value may be left off (#969) · jdx/usage@3b1adff
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: argv/src/help.rs +8-1Lines changed: 8 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -247,7 +247,14 @@ fn flag_usage_masked(meta: &FlagMeta<'_>, show: &Shown) -> String { | 247 | 247 | } | 248 | 248 | if flag.takes_value { | 249 | 249 | 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}"); | 251 | 258 | if flag.variadic { | 252 | 259 | out.push('…'); | 253 | 260 | } | |
Collapse file Copy file name to clipboardExpand all lines: argv/src/spec.rs +20-5Lines changed: 20 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -480,6 +480,13 @@ pub struct FlagMeta<'a> { | 480 | 480 | pub default: &'a [&'a str], | 481 | 481 | pub choices: &'a [&'a str], | 482 | 482 | 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, | 483 | 490 | pub hide: bool, | 484 | 491 | /// Whether repetition is counted rather than collected, as in `-vvv`. | 485 | 492 | pub count: bool, | @@ -533,6 +540,7 @@ impl FlagMeta<'_> { | 533 | 540 | default: &[], | 534 | 541 | choices: &[], | 535 | 542 | required: false, | | 543 | + value_optional: false, | 536 | 544 | hide: false, | 537 | 545 | count: false, | 538 | 546 | repeatable: false, | @@ -1050,8 +1058,13 @@ fn write_flag(out: &mut String, meta: &FlagMeta<'_>, depth: usize) -> core::fmt: | 1050 | 1058 | write!( | 1051 | 1059 | out, | 1052 | 1060 | "arg {}", | 1053 | | - quoted(&placeholder(name, meta.flag.variadic)) | | 1061 | + quoted(&placeholder(name, meta.flag.variadic, meta.value_optional)) | 1054 | 1062 | )?; | | 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 | + } | 1055 | 1068 | if meta.choices.is_empty() { | 1056 | 1069 | out.push('\n'); | 1057 | 1070 | } else { | @@ -1221,9 +1234,10 @@ fn flag_forms(flag: &Flag<'_>) -> String { | 1221 | 1234 | } | 1222 | 1235 |
| 1223 | 1236 | /// `<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 { | 1225 | 1238 | let ellipsis = if variadic { "..." } else { "" }; | 1226 | | - format!("<{name}>{ellipsis}") | | 1239 | + let (open, close) = if optional { ('[', ']') } else { ('<', '>') }; | | 1240 | + format!("{open}{name}{close}{ellipsis}") | 1227 | 1241 | } | 1228 | 1242 |
| 1229 | 1243 | /// A positional's placeholder: angle brackets when required, square when not. | @@ -1699,7 +1713,8 @@ mod tests { | 1699 | 1713 | }; | 1700 | 1714 | assert_eq!(arg_placeholder("file", &required), "<file>"); | 1701 | 1715 | 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]"); | 1704 | 1719 | } | 1705 | 1720 | } |
Collapse file Copy file name to clipboard +77Lines changed: 77 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 Copy file name to clipboardExpand all lines: derive/src/codegen.rs +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -866,6 +866,9 @@ fn flag_meta(i: usize, field: &Field, owner: &syn::Ident) -> TokenStream { | 866 | 866 | // A collecting field's type cannot say whether one value is needed, so `required` may | 867 | 867 | // declare it. Every other shape gets its answer from the type. | 868 | 868 | 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; | 869 | 872 | let choices = choices_tokens(field); | 870 | 873 | let (var_min, var_max) = bounds_tokens(field); | 871 | 874 | // 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 { | 901 | 904 | count: #count, | 902 | 905 | repeatable: #repeatable, | 903 | 906 | required: #required, | | 907 | + value_optional: #value_optional, | 904 | 908 | choices: #choices, | 905 | 909 | var_min: #var_min, | 906 | 910 | var_max: #var_max, | |
Collapse file Copy file name to clipboardExpand all lines: derive/src/model.rs +79Lines changed: 79 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -150,6 +150,13 @@ pub struct Field { | 150 | 150 | /// way of saying "one or more" — could not be declared at all, and came back as | 151 | 151 | /// `[TARGET]…`. This is the one place it has to be stated rather than inferred. | 152 | 152 | 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, | 153 | 160 | /// The placeholder for a flag's value in help and in the emitted spec: `n` in | 154 | 161 | /// `--jobs <n>`. | 155 | 162 | /// | @@ -914,6 +921,7 @@ impl Field { | 914 | 921 | ident: ident.clone(), | 915 | 922 | ty: field.ty.clone(), | 916 | 923 | name: to_kebab(&ident.to_string()), | | 924 | + value_optional: false, | 917 | 925 | kind: Kind::Flatten { | 918 | 926 | ty: field.ty.clone(), | 919 | 927 | }, | @@ -1012,6 +1020,7 @@ impl Field { | 1012 | 1020 | ident: ident.clone(), | 1013 | 1021 | ty: field.ty.clone(), | 1014 | 1022 | name: to_kebab(&ident.to_string()), | | 1023 | + value_optional: false, | 1015 | 1024 | kind: Kind::Subcommand { ty, optional }, | 1016 | 1025 | effect: None, | 1017 | 1026 | complete: None, | @@ -1070,6 +1079,7 @@ impl Field { | 1070 | 1079 | let mut repeatable = false; | 1071 | 1080 | let mut variadic = false; | 1072 | 1081 | let mut count = false; | | 1082 | + let mut value_optional = false; | 1073 | 1083 | let mut double_dash = DoubleDash::Optional; | 1074 | 1084 | let mut env = None; | 1075 | 1085 | let mut setting = None; | @@ -1130,6 +1140,10 @@ impl Field { | 1130 | 1140 | "var" => repeatable = flag_value(&meta)?, | 1131 | 1141 | "variadic" => variadic = flag_value(&meta)?, | 1132 | 1142 | "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)?, | 1133 | 1147 | "hide" => hide = flag_value(&meta)?, | 1134 | 1148 | "arg" => is_arg = flag_value(&meta)?, | 1135 | 1149 | "env" => env = Some(string_value(&meta)?), | @@ -1373,6 +1387,13 @@ impl Field { | 1373 | 1387 | "`value_enum` describes what a value may be, and this field takes no value", | 1374 | 1388 | )); | 1375 | 1389 | } | | 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 | + } | 1376 | 1397 | if !choices.is_empty() && matches!(shape, Shape::Bool | Shape::Count) { | 1377 | 1398 | return Err(syn::Error::new( | 1378 | 1399 | span, | @@ -1423,6 +1444,21 @@ impl Field { | 1423 | 1444 | } | 1424 | 1445 |
| 1425 | 1446 | 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 | + } | 1426 | 1462 | if is_flag && is_arg { | 1427 | 1463 | return Err(syn::Error::new( | 1428 | 1464 | span, | @@ -1725,6 +1761,7 @@ impl Field { | 1725 | 1761 | ident, | 1726 | 1762 | ty: field.ty.clone(), | 1727 | 1763 | name, | | 1764 | + value_optional, | 1728 | 1765 | kind, | 1729 | 1766 | shape, | 1730 | 1767 | value_ty, | @@ -2603,6 +2640,48 @@ mod tests { | 2603 | 2640 | assert!(cli.fields[0].required_collection); | 2604 | 2641 | } | 2605 | 2642 |
| | 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 | + | 2606 | 2685 | #[test] | 2607 | 2686 | fn value_name_is_refused_where_there_is_no_value_to_name() { | 2608 | 2687 | // It names the placeholder a flag's *value* gets in help. `arg_meta` never emits it, and | |
Collapse file Copy file name to clipboardExpand all lines: xtask/src/shadow.rs +43Lines changed: 43 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -699,6 +699,12 @@ fn usage_flag_opts( | 699 | 699 | if arg.name != flag.name { | 700 | 700 | opts.push(format!("value_name = {:?}", arg.name)); | 701 | 701 | } | | 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 | + } | 702 | 708 | if let Some(choices) = &arg.choices { | 703 | 709 | opts.push(format!("choices({})", quoted_list(&choices.choices))); | 704 | 710 | } | @@ -856,6 +862,16 @@ fn clap_flag_opts( | 856 | 862 | Some(max) => opts.push(format!("num_args = {least}..={max}")), | 857 | 863 | None => opts.push(format!("num_args = {least}..")), | 858 | 864 | } | | 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"); | 859 | 875 | } | 860 | 876 | if flag.required { | 861 | 877 | opts.push("required = true".into()); | @@ -1658,6 +1674,33 @@ mod tests { | 1658 | 1674 | assert!(out.contains("version = \"1.55.0\""), "{out}"); | 1659 | 1675 | } | 1660 | 1676 |
| | 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 | + | 1661 | 1704 | #[test] | 1662 | 1705 | fn an_expressible_property_is_not_counted() { | 1663 | 1706 | let (_, skipped) = rendered("name \"ex\"\nbin \"ex\"\ncmd \"go\" {\n alias \"g\"\n}\n"); | |
|