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 — fix(spec): apply default_subcommand only at the root · jdx/usage@f1c2af9

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • PLAN.md
  • corpus
    • 09-default-subcommand.json
  • lib/src
    • parse.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎PLAN.md‎

Copy file name to clipboardExpand all lines: PLAN.md
+40-54Lines changed: 40 additions & 54 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -132,26 +132,22 @@ manpages, and SDKs — never a runtime dependency of somebody else's program.
132132
a different file, silently. Costs +656 instructions (1.6%) and one allocation, which
133133
is what not corrupting a value is worth. It also retired the hazard of recognising
134134
`String` by its spelling, since there is no identity case left.
135-
- [x] **Accepting a value that is not valid UTF-8** — reporting it was the safe half;
136-
accepting it is the whole fix, because the operating system does accept `/tmp/\xff` as a
137-
filename and a CLI that cannot receive one cannot open the file. A `PathBuf` or
138-
`OsString` field takes the bytes exactly, through `usage_argv::os_string_from_bytes`.
139-
140-
**And with no `unsafe` anywhere.** On Unix an `OsString` is an arbitrary byte sequence,
141-
so this is the safe `OsString::from_vec` and every byte survives — which is the case that
142-
matters, since non-UTF-8 filenames are ordinary there. Windows was going to need
143-
`from_encoded_bytes_unchecked`, and jdx approved that, but a *safe* function taking a
144-
`Vec<u8>` cannot enforce its precondition: there is no way to know the bytes came from
145-
`as_encoded_bytes` rather than from anywhere else, and a safe function whose precondition
146-
a caller can violate is unsound however carefully today's callers behave. Greptile flagged
147-
exactly that on #844. So Windows goes through UTF-8 and reports what will not convert,
148-
which gives up only an unpaired-surrogate argument there.
149-
150-
Cheaper than the text path, not dearer: a `PathBuf` field costs **553 instructions per
151-
parse against a `String` field's 674**, since it skips the UTF-8 validation pass, and both
152-
allocate once. The gate fixture cannot show this — a spec carries no Rust types, so every
153-
shadow field is a `String` — which is why it is measured directly.
154-
135+
- [x] **Accepting a value that is not valid UTF-8** — reporting it was the safe half; accepting
136+
it is the whole fix, because the operating system does accept `/tmp/\xff` as a filename and a
137+
CLI that cannot receive one cannot open the file. A `PathBuf` or `OsString` field takes the
138+
bytes exactly, through `usage_argv::os_string_from_bytes`. **And with no `unsafe` anywhere.** On
139+
Unix an `OsString` is an arbitrary byte sequence, so this is the safe `OsString::from_vec` and
140+
every byte survives — which is the case that matters, since non-UTF-8 filenames are ordinary
141+
there. Windows was going to need `from_encoded_bytes_unchecked`, and jdx approved that, but a
142+
_safe_ function taking a `Vec<u8>` cannot enforce its precondition: there is no way to know the
143+
bytes came from `as_encoded_bytes` rather than from anywhere else, and a safe function whose
144+
precondition a caller can violate is unsound however carefully today's callers behave. Greptile
145+
flagged exactly that on #844. So Windows goes through UTF-8 and reports what will not convert,
146+
which gives up only an unpaired-surrogate argument there. Cheaper than the text path, not
147+
dearer: a `PathBuf` field costs **553 instructions per parse against a `String` field's 674**,
148+
since it skips the UTF-8 validation pass, and both allocate once. The gate fixture cannot show
149+
this — a spec carries no Rust types, so every shadow field is a `String` — which is why it is
150+
measured directly.
155151
- [ ] **`usage-derive` v1** — everything mise needs: constraints
156152
(`requires`/`conflicts`/`overrides`/`required_unless`), `var`, `count`,
157153
`env`, defaults, delimiters, the `double_dash` modes, global flags, flatten,
@@ -201,40 +197,30 @@ carrying them rather than being worked around.
201197
that they reach the KDL and that binding is unaffected. `default_subcommand` is
202198
checked at compile time to require a subcommand field, since it names one.
203199
- [x] **Routing on `default_subcommand`** — the parser reads it now, rather than the property
204-
being emitted and ignored. A word naming no subcommand descends into the named command
205-
and is examined again there, so it can be that command's argument or one of _its_
206-
subcommands. The declaring command's own positional does not win, which is what makes
207-
the property more than a synonym for an argument — and is mise's shape exactly. Taken at
208-
most once per parse, so a chain of defaults cannot walk a CLI deeper than the user typed.
209-
210-
No measurable cost: 40,370 instructions against 40,472 before, the branch being reached
211-
only by a word that matched no subcommand. The ±100 is code layout rather than work —
212-
cachegrind is deterministic, and gave the same figure twice. Allocations unchanged: 0
213-
bare, 4 bound.
214-
215-
Only a *word* routes: a dash-prefixed token naming no flag arrives as a value and was
216-
never a candidate to select anything, so it binds where it was typed — as usage-lib does,
217-
which stops looking for subcommands at an unrecognised flag. The name may also be an
218-
alias, since usage-lib resolves it against names, aliases and hidden aliases alike.
219-
220-
The name is resolved by `find_subcommand` during **const evaluation**, so a
221-
`default_subcommand` that no subcommand answers to is a compile error. That retires the
222-
claim in the entry above that the name could not be checked: the variants are indeed
223-
another expansion, but a `const fn` can search the list the parent already holds.
224-
225-
**What it does not buy on its own:** `mise build` still does not work end to end in the
226-
shadow, because mise's spec gives `run` no positional at all — `src/cli/usage.rs` clears
227-
them and adds `mount run="mise tasks --usage"`, so task names are meant to come from
228-
running that. usage-argv does not execute mounts. Routing *plus* mounts is what would let
229-
mise delete its hand-rolled dispatch; routing alone is half of it.
230-
231-
One divergence recorded (`default-is-declared-for-the-root`): usage-lib holds the single
232-
name for the whole spec and applies it at whichever command it is standing on, so
233-
`ex config zzz` descends into `config ls` when an unrelated `config` happens to have an
234-
`ls`. Read here as a property of the root, which is the only place it can be declared.
235-
**Worth a decision** — it looks accidental rather than intended, and if you agree it is a
236-
small fix in usage-lib.
237-
200+
being emitted and ignored. A word naming no subcommand descends into the named command and is
201+
examined again there, so it can be that command's argument or one of _its_ subcommands. The
202+
declaring command's own positional does not win, which is what makes the property more than a
203+
synonym for an argument — and is mise's shape exactly. Taken at most once per parse, so a chain
204+
of defaults cannot walk a CLI deeper than the user typed. No measurable cost: 40,370
205+
instructions against 40,472 before, the branch being reached only by a word that matched no
206+
subcommand. The ±100 is code layout rather than work — cachegrind is deterministic, and gave the
207+
same figure twice. Allocations unchanged: 0 bare, 4 bound. Only a _word_ routes: a dash-prefixed
208+
token naming no flag arrives as a value and was never a candidate to select anything, so it
209+
binds where it was typed — as usage-lib does, which stops looking for subcommands at an
210+
unrecognised flag. The name may also be an alias, since usage-lib resolves it against names,
211+
aliases and hidden aliases alike. The name is resolved by `find_subcommand` during **const
212+
evaluation**, so a `default_subcommand` that no subcommand answers to is a compile error. That
213+
retires the claim in the entry above that the name could not be checked: the variants are indeed
214+
another expansion, but a `const fn` can search the list the parent already holds. **What it does
215+
not buy on its own:** `mise build` still does not work end to end in the shadow, because mise's
216+
spec gives `run` no positional at all — `src/cli/usage.rs` clears them and adds `mount run="mise
217+
tasks --usage"`, so task names are meant to come from running that. usage-argv does not execute
218+
mounts. Routing _plus_ mounts is what would let mise delete its hand-rolled dispatch; routing
219+
alone is half of it. One divergence found and then **fixed in usage-lib** rather than recorded:
220+
it applied the single declared name at whichever command it was standing on, so `ex config zzz`
221+
descended into `config ls` when an unrelated `config` happened to have an `ls`. A spec declares
222+
one name, once, at the top. The corpus vector that recorded the difference is now an ordinary
223+
agreeing vector — the reference test refused to let the label stay, which is what it is for.
238224
- [ ] **A mount on the root command** — the spec accepts `mount` only inside a
239225
`cmd` block, so a CLI whose _top-level_ subcommands are discovered by running
240226
something cannot say so. Worth deciding whether that is a gap or a deliberate
Collapse file

‎corpus/09-default-subcommand.json‎

Copy file name to clipboardExpand all lines: corpus/09-default-subcommand.json
+1-4Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,11 @@
8585
},
8686
{
8787
"id": "default-is-declared-for-the-root",
88-
"doc": "`default_subcommand` names one command for the whole program. A nested command that happens to have a subcommand of that name does not thereby acquire a default of its own.",
88+
"doc": "`default_subcommand` names one command for the whole program, and only the root can declare one. A nested command that happens to have a subcommand of that name does not thereby acquire a default of its own.",
8989
"spec": "name \"ex\"\nbin \"ex\"\ndefault_subcommand \"ls\"\ncmd \"ls\"\ncmd \"config\" {\n cmd \"ls\" {\n arg \"[WHAT]\"\n }\n}\n",
9090
"argv": ["config", "zzz"],
9191
"expect": {
9292
"error": "unexpected_arg"
93-
},
94-
"reference": {
95-
"diverges": "usage-lib holds the one name for the whole spec and applies it at whichever command it is standing on, so `ex config zzz` descends into `config ls` and binds `zzz` there. That makes an unrelated command acquire a default because a name happened to match one level down, which reads as accidental rather than declared \u2014 the property is written once, at the top, and nothing says it applies anywhere else."
9693
}
9794
},
9895
{
Collapse file

‎lib/src/parse.rs‎

Copy file name to clipboardExpand all lines: lib/src/parse.rs
+63-2Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -766,8 +766,14 @@ fn parse_partial_with_env(
766766
}
767767
} else {
768768
// Found a word that's not a flag or subcommand
769-
// Check if we should use the default_subcommand (only once)
770-
if !used_default_subcommand {
769+
// Check if we should use the default_subcommand (only once, and only at the
770+
// root, which is the only place a spec can declare one — `out.cmds` holds just
771+
// the root until something descends). Without that second condition the one
772+
// declared name is looked up wherever the parser happens to be standing, so an
773+
// unrelated command acquires a default because a name matched one level down:
774+
// with `default_subcommand "ls"` at the top, `ex config zzz` descended into
775+
// `config ls`.
776+
if !used_default_subcommand && out.cmds.len() == 1 {
771777
if let Some(default_name) = &spec.default_subcommand {
772778
if let Some(subcommand) = out.cmd.find_subcommand(default_name) {
773779
let mut subcommand = subcommand.clone();
@@ -2735,6 +2741,61 @@ cmd "build" {
27352741
assert_eq!(parsed.cmds[1].name, "other");
27362742
}
27372743

2744+
#[test]
2745+
fn test_default_subcommand_applies_only_at_the_root() {
2746+
// `default_subcommand` is declared once, for the whole spec, and only at the top. It
2747+
// was being looked up wherever the parser happened to be standing, so a command with
2748+
// an unrelated subcommand of the same name acquired a default of its own: with
2749+
// `default_subcommand "ls"`, `ex config zzz` descended into `config ls` and bound
2750+
// `zzz` there. Nothing declared that, and nothing could have.
2751+
let mut config_ls = SpecCommand::builder().name("ls").build();
2752+
config_ls.args.push(SpecArg::builder().name("what").build());
2753+
let mut config_cmd = SpecCommand::builder().name("config").build();
2754+
config_cmd.subcommands.insert("ls".to_string(), config_ls);
2755+
2756+
// The root's own `ls`, which is what its default points at. It takes an argument so
2757+
// that a routed word has somewhere to land.
2758+
let mut root_ls = SpecCommand::builder().name("ls").build();
2759+
root_ls.args.push(SpecArg::builder().name("what").build());
2760+
let mut cmd = SpecCommand::builder().name("ex").build();
2761+
cmd.subcommands.insert("ls".to_string(), root_ls);
2762+
cmd.subcommands.insert("config".to_string(), config_cmd);
2763+
2764+
let spec = Spec {
2765+
name: "ex".to_string(),
2766+
bin: "ex".to_string(),
2767+
cmd,
2768+
default_subcommand: Some("ls".to_string()),
2769+
..Default::default()
2770+
};
2771+
2772+
// `config` has an `ls`, but `config` did not declare a default, so `zzz` is `config`'s
2773+
// own business — and `config` takes no argument, so this is an error rather than a
2774+
// silent descent.
2775+
let input = vec!["ex".to_string(), "config".to_string(), "zzz".to_string()];
2776+
assert!(
2777+
parse(&spec, &input).is_err(),
2778+
"`config` has no default subcommand and no argument, so `zzz` cannot bind"
2779+
);
2780+
2781+
// At the root, where it is declared, it still applies.
2782+
let input = vec!["ex".to_string(), "zzz".to_string()];
2783+
let parsed = parse(&spec, &input).expect("the root's default applies");
2784+
assert_eq!(
2785+
parsed
2786+
.cmds
2787+
.iter()
2788+
.map(|c| c.name.as_str())
2789+
.collect::<Vec<_>>(),
2790+
["ex", "ls"]
2791+
);
2792+
assert_eq!(
2793+
parsed.args.values().next().map(|v| v.to_string()),
2794+
Some("zzz".to_string()),
2795+
"and the word binds inside the command it reached"
2796+
);
2797+
}
2798+
27382799
#[test]
27392800
fn test_default_subcommand_with_nested_subcommands() {
27402801
// Test that default_subcommand works when the default subcommand has nested subcommands.

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.