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(spec): select a subcommand from argv0 when multicall (#1028) · jdx/usage@c76d1bf

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • PLAN.md
  • argv/src
    • lib.rs
    • spec.rs
  • cli/src/cli
    • lint.rs
  • conformance
    • src
      • argv.rs
      • lib.rs
      • reference.rs
      • tables.rs
    • tests
      • spec_roundtrip.rs
  • corpus
    • 12-multicall.json
    • README.md
  • derive/src
    • codegen.rs
    • lib.rs
    • model.rs
  • docs
    • go
      • generated-code.md
    • rust
      • args-and-flags.md
      • subcommands.md
    • spec
      • argv.md
      • integrations
        • clap.md
      • reference
        • index.md
  • go
    • argv
      • multicall.go
      • multicall_test.go
    • conformance
      • conformance_test.go
    • internal/spec
      • spec.go
  • lib/src
    • parse.rs
    • spec
      • mod.rs
  • xtask/src
    • shadow.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎PLAN.md‎

Copy file name to clipboardExpand all lines: PLAN.md
+8-2Lines changed: 8 additions & 2 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -458,8 +458,14 @@ Groups are the opposite case: `Command::get_groups`, `ArgGroup::get_args` and
458458
`required_unless_present` all/any variants. The common single-selector
459459
forms exist, but a clap migration needs the complete truth table or an
460460
explicit non-goal for each omitted form.
461-
- [ ] **`multicall`** — busybox-style applets: argv[0]'s basename selects a
462-
subcommand when it is not the dispatcher. clap's `Command::multicall`.
461+
- [x] **`multicall`** — busybox-style applets: argv[0]'s basename selects a
462+
subcommand when it is not the dispatcher. Spec `multicall #true`,
463+
usage-lib (which sees argv0), usage-argv / the derive `parse()` /
464+
Go `RewriteMulticall` (which rewrite at process entry; `parse_from` /
465+
`Parse` stay without argv0), and the clap bridge
466+
(`Command::is_multicall_set`). Path components and a trailing `.exe`
467+
are stripped. **Not used by the fleet today**; clap's own applets and
468+
busybox-style binaries are the reason it exists.
463469
- [ ] **`no_binary_name`** — parsing an argv that has no `argv[0]`. usage-argv
464470
already takes argv without the program name; this is clap's setter that
465471
skips stripping it. Out of scope until a fleet CLI needs it.
Collapse file

‎argv/src/lib.rs‎

Copy file name to clipboardExpand all lines: argv/src/lib.rs
+45Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,33 @@ impl Command<'_> {
222222
};
223223
}
224224

225+
/// Basename of argv[0] for a multicall CLI: last path component, with a trailing
226+
/// `.exe` stripped so Windows and Unix agree.
227+
pub fn multicall_basename(argv0: &str) -> &str {
228+
let name = argv0.rsplit(['/', '\\']).next().unwrap_or(argv0);
229+
match name.get(name.len().saturating_sub(4)..) {
230+
Some(ext) if ext.eq_ignore_ascii_case(".exe") => &name[..name.len() - 4],
231+
_ => name,
232+
}
233+
}
234+
235+
/// The applet name to parse as the first word, when argv[0] is not the dispatcher.
236+
///
237+
/// `None` means a dispatcher invocation (`busybox ls`): skip argv[0] and parse the
238+
/// rest. `Some` is a symlink invocation (`ls -l`): inject the basename.
239+
pub fn multicall_applet<'a>(argv0: &'a str, name: &str, bin: Option<&str>) -> Option<&'a str> {
240+
let base = multicall_basename(argv0);
241+
if !name.is_empty() && base == name {
242+
return None;
243+
}
244+
if let Some(bin) = bin {
245+
if !bin.is_empty() && base == bin {
246+
return None;
247+
}
248+
}
249+
Some(base)
250+
}
251+
225252
/// A flag, addressed by any of its long or short forms.
226253
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227254
pub struct Flag<'a> {
@@ -3046,4 +3073,22 @@ mod tests {
30463073
assert!(as_str(b"ok").is_ok());
30473074
assert!(as_str(&[0xff, 0xfe]).is_err());
30483075
}
3076+
3077+
#[test]
3078+
fn a_multicall_applet_is_the_basename_unless_it_is_the_dispatcher() {
3079+
assert_eq!(multicall_basename("/usr/bin/ls"), "ls");
3080+
assert_eq!(multicall_basename(r"C:\busybox\ls.exe"), "ls");
3081+
assert_eq!(
3082+
multicall_applet("/usr/bin/ls", "busybox", Some("busybox")),
3083+
Some("ls")
3084+
);
3085+
assert_eq!(
3086+
multicall_applet("/usr/bin/busybox", "busybox", Some("busybox")),
3087+
None
3088+
);
3089+
assert_eq!(
3090+
multicall_applet("ls.exe", "busybox", Some("busybox")),
3091+
Some("ls")
3092+
);
3093+
}
30493094
}
Collapse file

‎argv/src/spec.rs‎

Copy file name to clipboardExpand all lines: argv/src/spec.rs
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,13 @@ pub struct Spec<'a> {
296296
/// Which command the root falls back to when a word matches no subcommand.
297297
/// mise uses this so `mise foo` completes as `mise run foo`.
298298
pub default_subcommand: Option<&'a str>,
299+
/// Whether argv[0]'s basename selects a subcommand (busybox-style applets).
300+
///
301+
/// clap's `multicall`. The dispatcher names (`name` / `bin`) are skipped; any
302+
/// other basename is parsed as the first word. Path components and a trailing
303+
/// `.exe` are stripped. The parser itself does not see argv[0]; [`crate::multicall_applet`]
304+
/// is what a process entry applies before calling it.
305+
pub multicall: bool,
299306
/// The root command, and the home of everything a spec declares at its top level.
300307
///
301308
/// A KDL spec has one place for surrounding text and examples — the top level — and the
@@ -319,6 +326,7 @@ impl Spec<'_> {
319326
long_about: None,
320327
usage: None,
321328
default_subcommand: None,
329+
multicall: false,
322330
root: &CommandMeta::EMPTY,
323331
};
324332
}
@@ -840,6 +848,9 @@ impl Spec<'_> {
840848
if let Some(default_subcommand) = self.default_subcommand {
841849
prop(out, "default_subcommand", default_subcommand)?;
842850
}
851+
if self.multicall {
852+
writeln!(out, "multicall #true")?;
853+
}
843854
if self.root.cmd.external_subcommand {
844855
writeln!(out, "external_subcommand #true")?;
845856
}
Collapse file

‎cli/src/cli/lint.rs‎

Copy file name to clipboardExpand all lines: cli/src/cli/lint.rs
+23Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,15 @@ pub fn lint_spec(spec: &Spec, opts: LintOptions) -> Vec<LintIssue> {
174174
}
175175
}
176176

177+
if spec.multicall && spec.cmd.subcommands.is_empty() {
178+
issues.push(LintIssue {
179+
severity: Severity::Error,
180+
code: "multicall-no-subcommands".to_string(),
181+
message: "Spec has multicall=#true but no subcommands to select".to_string(),
182+
location: None,
183+
});
184+
}
185+
177186
// Lint the root command
178187
lint_command(&spec.cmd, &[], spec.about.is_some(), opts, &mut issues);
179188

@@ -718,6 +727,20 @@ cmd "undocumented"
718727
);
719728
}
720729

730+
#[test]
731+
fn test_lint_multicall_no_subcommands() {
732+
let spec: Spec = r#"
733+
name "busybox"
734+
bin "busybox"
735+
multicall #true
736+
"#
737+
.parse()
738+
.unwrap();
739+
740+
let issues = lint_spec(&spec, LintOptions::default());
741+
assert!(issues.iter().any(|i| i.code == "multicall-no-subcommands"));
742+
}
743+
721744
#[test]
722745
fn test_lint_subcommand_required_no_subcommands() {
723746
let spec: Spec = r#"
Collapse file

‎conformance/src/argv.rs‎

Copy file name to clipboardExpand all lines: conformance/src/argv.rs
+8-2Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,14 @@ pub fn run(vector: &Vector) -> Outcome {
8888
}
8989
None => root,
9090
};
91-
let argv: Vec<&'static OsStr> = vector
92-
.argv
91+
let mut words = vector.argv.clone();
92+
if spec.multicall {
93+
let argv0 = vector.argv0.as_deref().unwrap_or(spec.bin.as_str());
94+
if let Some(applet) = usage_argv::multicall_applet(argv0, &spec.name, Some(&spec.bin)) {
95+
words.insert(0, applet.to_string());
96+
}
97+
}
98+
let argv: Vec<&'static OsStr> = words
9399
.iter()
94100
.map(|a| -> &'static OsStr { OsStr::new(leak(a)) })
95101
.collect();
Collapse file

‎conformance/src/lib.rs‎

Copy file name to clipboardExpand all lines: conformance/src/lib.rs
+7Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,13 @@ pub struct Vector {
5151
pub spec: String,
5252
/// The command line, excluding the program name.
5353
pub argv: Vec<String>,
54+
/// argv[0] as the process saw it, when that is the question.
55+
///
56+
/// Absent means the spec's `bin`, which is what usage-lib prepends for every
57+
/// other vector. A `multicall` applet is selected by this basename rather than
58+
/// by a word in `argv`.
59+
#[serde(default, skip_serializing_if = "Option::is_none")]
60+
pub argv0: Option<String>,
5461
/// The environment the parse sees. Only vectors about `env` fallback set it;
5562
/// the harness never consults the real environment, so no vector's result
5663
/// can depend on the machine running it.
Collapse file

‎conformance/src/reference.rs‎

Copy file name to clipboardExpand all lines: conformance/src/reference.rs
+3-2Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,9 @@ pub fn run(vector: &Vector) -> Observed {
5757
.collect();
5858

5959
// usage-lib expects argv to include the program name, and reports the
60-
// selected command relative to it.
61-
let mut input = vec![spec.bin.clone()];
60+
// selected command relative to it. A multicall vector that cares about the
61+
// process's argv[0] supplies it; everyone else is the spec's bin.
62+
let mut input = vec![vector.argv0.clone().unwrap_or_else(|| spec.bin.clone())];
6263
input.extend(vector.argv.iter().cloned());
6364

6465
match Parser::new(&spec).with_env(env).parse(&input) {
Collapse file

‎conformance/src/tables.rs‎

Copy file name to clipboardExpand all lines: conformance/src/tables.rs
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@ pub fn build_spec(spec: &Spec) -> &'static usage_argv::spec::Spec<'static> {
212212
about: opt(&spec.about),
213213
long_about: opt(&spec.about_long),
214214
default_subcommand: opt(&spec.default_subcommand),
215+
multicall: spec.multicall,
215216
// An exact synopsis the spec declares, which replaces the generated line on the root's
216217
// page. usage-lib's manpage renderer honours it and its help renderer does not, so a
217218
// spec that declares one is a case the two disagree about; `render/03-sections.json`
Collapse file

‎conformance/tests/spec_roundtrip.rs‎

Copy file name to clipboardExpand all lines: conformance/tests/spec_roundtrip.rs
+26Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ static SPEC: Spec = Spec {
327327
long_about: Some("Does things, at length."),
328328
usage: Some("Usage: ex <COMMAND>\n ex --version \"quoted\""),
329329
default_subcommand: Some("run"),
330+
multicall: false,
330331
root: &ROOT_META,
331332
};
332333

@@ -345,6 +346,7 @@ fn the_program_itself_survives() {
345346
assert_eq!(spec.about.as_deref(), Some("does things"));
346347
assert_eq!(spec.about_long.as_deref(), Some("Does things, at length."));
347348
assert_eq!(spec.default_subcommand.as_deref(), Some("run"));
349+
assert!(!spec.multicall);
348350
assert_eq!(
349351
spec.usage,
350352
"Usage: ex <COMMAND>\n ex --version \"quoted\""
@@ -762,6 +764,7 @@ fn a_declared_completer_becomes_a_run_the_reference_can_read() {
762764
long_about: None,
763765
usage: None,
764766
default_subcommand: None,
767+
multicall: false,
765768
root: &META,
766769
};
767770

@@ -894,6 +897,7 @@ fn two_commands_can_mean_different_things_by_one_name() {
894897
long_about: None,
895898
usage: None,
896899
default_subcommand: None,
900+
multicall: false,
897901
root: &ROOT_META_TWO,
898902
};
899903

@@ -947,6 +951,7 @@ fn two_commands_can_mean_different_things_by_one_name() {
947951
long_about: None,
948952
usage: None,
949953
default_subcommand: None,
954+
multicall: false,
950955
root: &ROOT_META_THREE,
951956
};
952957
let words = ["ex".to_string(), "use".to_string(), String::new()];
@@ -1055,3 +1060,24 @@ fn two_fields_on_one_command_can_mean_different_things_by_one_name() {
10551060
);
10561061
}
10571062
}
1063+
1064+
#[test]
1065+
fn multicall_survives_the_round_trip() {
1066+
static SPEC: Spec = Spec {
1067+
name: "busybox",
1068+
bin: Some("busybox"),
1069+
multicall: true,
1070+
root: &CommandMeta::EMPTY,
1071+
..Spec::EMPTY
1072+
};
1073+
1074+
let kdl = SPEC.to_kdl();
1075+
assert!(
1076+
kdl.contains("multicall #true"),
1077+
"lost on the way out: {kdl}"
1078+
);
1079+
let spec: LibSpec = kdl
1080+
.parse()
1081+
.unwrap_or_else(|e| panic!("usage-lib could not parse the emitted spec: {e}\n\n{kdl}"));
1082+
assert!(spec.multicall);
1083+
}
Collapse file

‎corpus/12-multicall.json‎

Copy file name to clipboard
+98Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
{
2+
"section": "multicall",
3+
"about": "argv[0]'s basename selects a subcommand when the spec declares multicall. clap's busybox-style applets: the dispatcher names (name and bin) are skipped, any other basename is the first word, and a trailing .exe plus path components are stripped so /usr/bin/ls and ls.exe select the same applet.",
4+
"vectors": [
5+
{
6+
"id": "multicall-applet-selects",
7+
"doc": "A symlink invocation: argv[0]'s basename is the applet, and the rest of argv belongs to it.",
8+
"spec": "name \"busybox\"\nbin \"busybox\"\nmulticall #true\ncmd \"ls\" {\n arg \"[ARGS]...\"\n}\ncmd \"cat\"\n",
9+
"argv0": "/usr/bin/ls",
10+
"argv": ["-l"],
11+
"expect": {
12+
"ok": {
13+
"cmd": ["ls"],
14+
"args": { "ARGS": ["-l"] }
15+
}
16+
}
17+
},
18+
{
19+
"id": "multicall-dispatcher-skips",
20+
"doc": "A dispatcher invocation still skips argv[0], so busybox ls is the ls applet.",
21+
"spec": "name \"busybox\"\nbin \"busybox\"\nmulticall #true\ncmd \"ls\" {\n arg \"[ARGS]...\"\n}\n",
22+
"argv0": "/usr/bin/busybox",
23+
"argv": ["ls", "-l"],
24+
"expect": {
25+
"ok": {
26+
"cmd": ["ls"],
27+
"args": { "ARGS": ["-l"] }
28+
}
29+
}
30+
},
31+
{
32+
"id": "multicall-strips-exe",
33+
"doc": "A trailing .exe is stripped so Windows and Unix agree on the applet name.",
34+
"spec": "name \"busybox\"\nbin \"busybox\"\nmulticall #true\ncmd \"ls\"\n",
35+
"argv0": "ls.exe",
36+
"argv": [],
37+
"expect": {
38+
"ok": {
39+
"cmd": ["ls"]
40+
}
41+
}
42+
},
43+
{
44+
"id": "multicall-unknown-is-unexpected",
45+
"doc": "An unknown applet is the same error as an unmatched word: nothing can hold it.",
46+
"spec": "name \"busybox\"\nbin \"busybox\"\nmulticall #true\ncmd \"ls\"\n",
47+
"argv0": "wat",
48+
"argv": [],
49+
"expect": { "error": "unexpected_arg" }
50+
},
51+
{
52+
"id": "multicall-unknown-can-be-external",
53+
"doc": "An unknown applet is forwarded when the root declares external_subcommand, including flags after it.",
54+
"spec": "name \"busybox\"\nbin \"busybox\"\nmulticall #true\nunknown_flags \"error\"\nexternal_subcommand #true\ncmd \"ls\"\n",
55+
"argv0": "/usr/bin/git",
56+
"argv": ["--help"],
57+
"expect": {
58+
"ok": {
59+
"external": ["git", "--help"]
60+
}
61+
}
62+
},
63+
{
64+
"id": "multicall-name-or-bin-is-dispatcher",
65+
"doc": "Either dispatcher name skips argv[0]: `bin` matching is enough even when `name` differs.",
66+
"spec": "name \"BusyBox\"\nbin \"busybox\"\nmulticall #true\ncmd \"ls\" {\n arg \"[ARGS]...\"\n}\n",
67+
"argv0": "/usr/bin/busybox",
68+
"argv": ["ls", "-l"],
69+
"expect": {
70+
"ok": {
71+
"cmd": ["ls"],
72+
"args": { "ARGS": ["-l"] }
73+
}
74+
}
75+
},
76+
{
77+
"id": "multicall-default-subcommand-catches-unknown-applet",
78+
"doc": "An unknown applet is an unmatched word, so default_subcommand still catches it.",
79+
"spec": "name \"busybox\"\nbin \"busybox\"\nmulticall #true\ndefault_subcommand \"ls\"\ncmd \"ls\" {\n arg \"[ARGS]...\"\n}\n",
80+
"argv0": "wat",
81+
"argv": [],
82+
"expect": {
83+
"ok": {
84+
"cmd": ["ls"],
85+
"args": { "ARGS": ["wat"] }
86+
}
87+
}
88+
},
89+
{
90+
"id": "multicall-empty-dispatcher-stays-at-root",
91+
"doc": "Invoking the dispatcher with no further words stays at the root; it does not invent an applet.",
92+
"spec": "name \"busybox\"\nbin \"busybox\"\nmulticall #true\ncmd \"ls\"\n",
93+
"argv0": "busybox",
94+
"argv": [],
95+
"expect": { "ok": {} }
96+
}
97+
]
98+
}

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.