Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/spec/reference/cmd.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,23 @@ task commands as if they were statically defined in the usage spec.
a shebang script therefore needs a POSIX shell to be available; one that invokes a program
directly, like `mycli mount-usage-tasks` above, works either way.

### Mounting at the top level

A `mount` also works as a top-level node, for a CLI whose _own_ commands are
discovered rather than declared — one whose subcommands come from plugins, say:

```kdl
name "mycli"
bin "mycli"
cmd "install"
mount run="mycli plugin-commands"
```

The root's mount runs only when a _word_ matches nothing already declared, so
`mycli install` costs nothing extra and only `mycli something-from-a-plugin` pays
for discovery. Flags never trigger it — `mycli --help` does not run your mount
command — so declaring the commands you know about keeps the common path free.

### Global flags and mounted commands

A mounted command describes a different program, so the flags of the commands it is mounted under
Expand Down
98 changes: 98 additions & 0 deletions lib/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,8 +592,31 @@ fn parse_partial_with_env(
// Track whether we've already applied the default_subcommand to prevent
// multiple switches (e.g., if default is "run" and there's a task named "run")
let mut used_default_subcommand = false;
// Whether the command in scope has had its own mounts run. A mount on the root
// is the case that needs this: a subcommand's mounts are run when the parser
// descends into it, but nothing descends into the root.
let mut mounts_resolved = false;

while idx < input.len() {
// Only for a word that could name a command, and only when it matches
// nothing already declared. A CLI that declares its commands and mounts more
// does not spawn a process for every invocation, and a flag — `--help`, or
// anything unrecognized — never triggers discovery at all, which it would
// otherwise do simply by not being a subcommand.
if !mounts_resolved
&& !out.cmd.mounts.is_empty()
&& !input[idx].starts_with('-')
&& out.cmd.find_subcommand(&input[idx]).is_none()
Comment thread
cursor[bot] marked this conversation as resolved.
{
mounts_resolved = true;
let mut mounted = out.cmd.clone();
mounted.mount(&mount_prefix_words(&prefix_flags))?;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
merge_subcommand_flags(&mut out.available_flags, gather_flags(&mounted), false);
Comment on lines +651 to +662

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Run only overriding mounts before default fallback.

any(|m| m.overrides_default) enables discovery for all root mounts. SpecCommand::mount then executes every mount. A non-overriding mount can therefore run and let its discovered command shadow default_subcommand when another mount enables overrides_default.

When a default exists, execute only mounts with overrides_default during the pre-default discovery attempt. Add a test with one overriding mount and one non-overriding mount.

Proposed fix
 let mut mounted = out.cmd.clone();
+if spec.default_subcommand.is_some() {
+    mounted.mounts.retain(|mount| mount.overrides_default);
+}
 mounted.mount(&mount_prefix_words(&prefix_flags))?;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let default_catches_it = spec.default_subcommand.is_some()
&& !out.cmd.mounts.iter().any(|m| m.overrides_default);
if !mounts_resolved
&& !out.cmd.mounts.is_empty()
&& !default_catches_it
&& !input[idx].starts_with('-')
&& out.cmd.find_subcommand(&input[idx]).is_none()
{
mounts_resolved = true;
let mut mounted = out.cmd.clone();
mounted.mount(&mount_prefix_words(&prefix_flags))?;
merge_subcommand_flags(&mut out.available_flags, gather_flags(&mounted), false);
let default_catches_it = spec.default_subcommand.is_some()
&& !out.cmd.mounts.iter().any(|m| m.overrides_default);
if !mounts_resolved
&& !out.cmd.mounts.is_empty()
&& !default_catches_it
&& !input[idx].starts_with('-')
&& out.cmd.find_subcommand(&input[idx]).is_none()
{
mounts_resolved = true;
let mut mounted = out.cmd.clone();
if spec.default_subcommand.is_some() {
mounted.mounts.retain(|mount| mount.overrides_default);
}
mounted.mount(&mount_prefix_words(&prefix_flags))?;
merge_subcommand_flags(&mut out.available_flags, gather_flags(&mounted), false);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/src/parse.rs` around lines 642 - 653, Update the pre-default discovery
logic around default_catches_it and SpecCommand::mount so that, when a
default_subcommand exists and any root mount overrides it, only mounts with
overrides_default are executed during this attempt. Prevent non-overriding
mounts from contributing discovered commands that could shadow the default,
while preserving current behavior when no overriding mount is present. Add a
test covering one overriding mount and one non-overriding mount.

if let Some(last) = out.cmds.last_mut() {
*last = mounted.clone();
}
out.cmd = mounted;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Comment thread
cursor[bot] marked this conversation as resolved.
if let Some(subcommand) = out.cmd.find_subcommand(&input[idx]) {
let mut subcommand = subcommand.clone();
// Pass prefix words (global flags before this subcommand) to mount
Expand All @@ -610,6 +633,8 @@ fn parse_partial_with_env(
input.remove(idx);
out.cmds.push(subcommand.clone());
out.cmd = subcommand.clone();
// A descent already ran the new command's mounts, above.
mounts_resolved = true;
Comment thread
cursor[bot] marked this conversation as resolved.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
prefix_flags.clear();
// Continue from current position (don't reset to 0)
// After remove(), idx now points to the next element
Expand Down Expand Up @@ -670,6 +695,9 @@ fn parse_partial_with_env(
out.cmds.push(subcommand.clone());
out.cmd = subcommand.clone();
prefix_flags.clear();
// This descent ran the new command's mounts, so lazy
// discovery must not run them a second time.
mounts_resolved = true;
used_default_subcommand = true;
// Continue the loop to check if this word is a subcommand of the
// default subcommand (e.g., a task name added via mount).
Expand Down Expand Up @@ -1524,6 +1552,76 @@ arg "[input]"
assert_eq!(first_string_value(&parsed), "input.txt");
}

#[cfg(unix)]
#[test]
fn a_mount_on_the_root_discovers_subcommands() {
// The root is a command like any other, so it can find its own subcommands
// by running something. Uses `echo` rather than a fixture because resolving
// a mount is what is being tested.
let spec: Spec = r#"
name "ex"
bin "ex"
cmd "declared"
mount run="echo 'cmd \"discovered\"'"
"#
.parse()
.unwrap();

let out = parse(&spec, &["ex".to_string(), "discovered".to_string()]).unwrap();
assert_eq!(out.cmd.name, "discovered");
}

#[cfg(unix)]
#[test]
fn a_flag_does_not_run_the_mount() {
// A flag matches no subcommand, which would have been enough to trigger
// discovery — so `ex --help` spawned a process. The mount fails if it runs,
// so parsing at all is the proof that it did not.
let spec: Spec = r#"
name "ex"
bin "ex"
flag "--verbose"
cmd "declared"
mount run="exit 1"
"#
.parse()
.unwrap();

let out = parse(&spec, &["ex".to_string(), "--verbose".to_string()]).unwrap();
assert_eq!(out.cmd.name, "ex");
}

#[cfg(unix)]
#[test]
fn a_declared_subcommand_does_not_run_the_mount() {
// The mount would fail if it ran, so this parsing at all is the proof that
// discovery is skipped when the word is already known. Worth pinning: a root
// mount that resolved eagerly would spawn a process on every invocation.
let spec: Spec = r#"
name "ex"
bin "ex"
cmd "declared"
mount run="exit 1"
"#
.parse()
.unwrap();

let out = parse(&spec, &["ex".to_string(), "declared".to_string()]).unwrap();
assert_eq!(out.cmd.name, "declared");
}

#[test]
fn a_root_mount_survives_being_written_out() {
let spec: Spec = "name \"ex\"\nbin \"ex\"\nmount run=\"ex plugins --usage\"\n"
.parse()
.unwrap();
assert_eq!(spec.cmd.mounts.len(), 1);

let reparsed: Spec = spec.to_string().parse().unwrap();
assert_eq!(reparsed.cmd.mounts.len(), 1, "written:\n{spec}");
assert_eq!(reparsed.cmd.mounts[0].run, "ex plugins --usage");
}

#[test]
fn test_mount_prefix_applies_flag_overrides() {
let stdin = Arc::new(
Expand Down
5 changes: 5 additions & 0 deletions lib/src/spec/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,11 @@ impl SpecCommand {
usage.trim().to_string()
}
pub(crate) fn merge(&mut self, other: Self) {
// Merging can add subcommands and aliases, and `find_subcommand` memoizes
// its lookup into a OnceLock — so the cache has to go, or a name that
// arrived here would not be findable. This worked before only because
// mounting happened to precede the first lookup on a given command.
self.subcommand_lookup = OnceLock::new();
// Destructured exhaustively (no `..`) so that adding a field to
// SpecCommand fails to compile until this decides what merging it means.
// Runtime-derived fields are explicitly ignored rather than skipped.
Expand Down
9 changes: 9 additions & 0 deletions lib/src/spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ impl Spec {
"usage" => schema.usage = node.arg(0)?.ensure_string()?,
"arg" => schema.cmd.args.push(SpecArg::parse(ctx, &node)?),
"flag" => schema.cmd.flags.push(SpecFlag::parse(ctx, &node)?),
// The root is a command like any other, so it can discover its own
// subcommands by running something. A CLI whose top-level commands
// come from plugins has no other way to say so.
"mount" => schema.cmd.mounts.push(crate::SpecMount::parse(ctx, &node)?),
"cmd" => {
let node: SpecCommand = SpecCommand::parse(ctx, &node)?;
schema.cmd.subcommands.insert(node.name.to_string(), node);
Expand Down Expand Up @@ -489,6 +493,11 @@ impl Display for Spec {
for arg in self.cmd.args.iter() {
nodes.push(arg.into());
}
// Written here rather than by SpecCommand, because the root's own nodes
// live at the top level of the document instead of inside a `cmd` block.
for mount in self.cmd.mounts.iter() {
nodes.push(mount.into());
}
for example in self.examples.iter() {
nodes.push(example.into());
}
Expand Down
Loading