How does Cargo run a third-party subcommand such as `cargo audit`, and where does it look for the binary?
answer
- Cargo itself has no audit command
- a naming convention, not a plugin API
- cargo-NAME executable
- CARGO_HOME/bin before the rest of PATH
basics
~20 sWhen cargo NAME is not a built-in command or an alias, Cargo runs an executable called cargo-NAME, looking in $CARGO_HOME/bin first and then the PATH directories. cargo install puts binaries in ~/.cargo/bin, which is why installed tools just work.
solid answer
~40 sCargo translates `cargo audit ARGS` into running an executable named `cargo-audit`. It checks built-in commands and `[alias]` entries first, then searches `$CARGO_HOME/bin` (by default `~/.cargo/bin`) ahead of the other `PATH` directories, unless `$CARGO_HOME/bin` already sits in `PATH`, in which case `PATH` order decides. The tool receives the subcommand name (`audit`) as its first argument, every other argument unchanged, and a `CARGO` environment variable pointing at the cargo binary so it can call back with `cargo metadata`. `cargo install cargo-audit` builds the crate and drops the binary into the install root's `bin`, so nothing has to be registered. A built-in such as `build` cannot be replaced this way; `cargo --list` shows what Cargo found, and a missing tool gives `error: no such command`.
code
rust · 21 linesuse std::env;
use std::process::{Command, ExitCode};
fn main() -> ExitCode {
// Invoked as `cargo lockcheck ARGS`: argv[1] is the subcommand name.
let args: Vec<String> = env::args().skip(2).collect();
// CARGO points back at the cargo binary that ran us.
let cargo = env::var("CARGO").unwrap_or_else(|_| "cargo".into());
let status = Command::new(cargo)
.args(["metadata", "--locked", "--format-version", "1", "--offline"])
.args(&args)
.stdout(std::process::Stdio::null())
.status()
.expect("failed to run cargo");
if status.success() {
println!("Cargo.lock is up to date");
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}go deeper
Recall the convention: cargo NAME runs an executable named cargo-NAME, and cargo install puts binaries in ~/.cargo/bin so they become subcommands.
Explain the lookup order: built-ins, then aliases, then CARGO_HOME/bin ahead of PATH, plus the arguments and the CARGO variable the tool receives.
Show the CI angle: pin tool versions with cargo install --locked --version, cache the binaries, and know a stray cargo-NAME earlier in the search can shadow the one you meant.
Treat each subcommand as code that runs with developer and CI credentials: decide who approves adding one, how versions are pinned, and whether prebuilt binaries are trusted.
## The convention: `cargo NAME` runs `cargo-NAME` Cargo has no plugin API. It is extended by a **naming convention**: when you type `cargo NAME`, Cargo first checks whether `NAME` is one of its **built-in commands** (`build`, `test`, `install` and so on) or a user-defined **alias** from the `[alias]` table of a `.cargo/config.toml`. If it is neither, Cargo looks for an executable file called **`cargo-NAME`** and runs it. That is the whole mechanism behind `cargo audit`, `cargo deny`, `cargo nextest`, `cargo expand`, `cargo outdated` and `cargo machete`: each is an ordinary program whose binary is named `cargo-audit`, `cargo-deny`, `cargo-nextest` and so on. Even `cargo clippy` and `cargo fmt` reach their tools this way: rustup installs `cargo-clippy` and `cargo-fmt` binaries next to `cargo` (the lints material covers what they check). ## Where Cargo searches, and in what order The Cargo book's external-tools page states the search rule, and Cargo 1.99.1 behaves as it says: 1. Built-in commands win outright. A `cargo-build` script on `PATH` never runs when you type `cargo build`, and an `[alias] build = ...` entry is ignored with the warning ``user-defined alias `build` is ignored, because it is shadowed by a built-in command``. 2. An alias beats an external tool, but Cargo warns that this ``was previously accepted but will become a hard error in the future``. 3. Among external tools, Cargo prefers **`$CARGO_HOME/bin`** (by default `~/.cargo/bin`) over the other `PATH` directories. If you add `$CARGO_HOME/bin` to `PATH` yourself, normal `PATH` order decides instead, which is how you let a directory earlier in `PATH` win. If nothing matches, Cargo exits with status 101 and prints ``error: no such command: `NAME` ``, plus a hint to run `cargo --list` and a suggested `cargo search cargo-NAME`. ## How tools get there: `cargo install` `cargo install cargo-audit` downloads the crate, builds its `[[bin]]` targets and copies the binaries into the **installation root's `bin` folder**. The root is chosen, in order, from `--root`, the `CARGO_INSTALL_ROOT` variable, the `install.root` config value, `CARGO_HOME`, and finally `$HOME/.cargo`. Because the default lands in `~/.cargo/bin`, a freshly installed tool is immediately a subcommand. Two flags matter for tools in particular: - `--locked` builds with the `Cargo.lock` the tool's authors published. Without it, `cargo install` ignores that lockfile and resolves fresh dependency versions, which can break the build. cargo-nextest's README says plainly that builds without `--locked` are broken. - `--version 0.22.2` installs exactly that release (a bare version without `^` or `~` is exact here, unlike a dependency requirement in a manifest), so CI does not drift to a new release with new defaults. Package managers and prebuilt release binaries work just as well: only the file name and its location matter. ## What the tool receives When Cargo runs `cargo-NAME`, it passes: - as the first argument after the program name, the subcommand name itself (`NAME`), then every remaining argument unchanged; - the environment variable **`CARGO`**, the path of the cargo binary that launched it, so the tool can call `"$CARGO" metadata` and stay on the same toolchain; - for `cargo help NAME`, the arguments `NAME --help`, so the tool's own help text appears. The Cargo book encourages tools to drive Cargo through its command line, chiefly `cargo metadata`, rather than linking the `cargo` crate as a library, because that library API is unstable and may not match the installed cargo. ## A worked example The example below is a short subcommand that checks whether `Cargo.lock` is current by running `cargo metadata --locked` through `CARGO`. Built into `target/debug` and put on `PATH`, it is a real `cargo lockcheck` command, listed by `cargo --list`, with no installation step at all. | Situation | What `cargo NAME` runs | |---|---| | `NAME` is built in | the built-in, always | | `NAME` is an alias and a `cargo-NAME` exists | the alias, with a future-incompatibility warning | | `cargo-NAME` in `$CARGO_HOME/bin` and elsewhere on `PATH` | the `$CARGO_HOME/bin` copy, unless that directory is on `PATH` | | nothing found | `error: no such command`, exit 101 | ## Why interviewers ask The question checks that you know a subcommand is just a binary: CI must install it (ideally pinned and `--locked`), a developer can shadow it by accident, and a tool may run code you never reviewed with your user's permissions, so installing one is a supply-chain decision in its own right.
- Can a `cargo-build` binary placed early on `PATH` replace `cargo build`?No. Cargo resolves built-in commands before it searches for external `cargo-NAME` executables, so `cargo build` always runs the built-in. An `[alias] build = ...` entry is ignored too, with a warning that it is shadowed by a built-in command. External tools can only add new names.
- Why should a CI job install subcommands with `cargo install --locked --version X`?Without `--locked`, `cargo install` ignores the tool's published `Cargo.lock` and resolves fresh dependency versions, so a new upstream release can break the tool's build. `--version` with a bare version installs exactly that release, so the job does not silently pick up a release with new checks or defaults. Caching the installed binary also saves the compile on every run.
- Subcommands must be registered in Cargo.toml before cargo can run them
- A cargo-build binary on PATH can override the built-in cargo build
- cargo install writes an [alias] entry so the new command resolves
- Third-party subcommands link the cargo crate and run inside Cargo's process
- cargo install always reuses the tool's published Cargo.lock