skip to content

Third-Party Subcommands

Any cargo-name binary on PATH becomes a cargo subcommand, and teams add audit, policy and test-runner tools that way. Interviewers ask which ones belong in CI.

on this pageshow

explore

questions

6

How does Cargo run a third-party subcommand such as `cargo audit`, and where does it look for the binary?

level: juniorimportance: should knowfreq 30%

answer

  1. Cargo itself has no audit command
  2. a naming convention, not a plugin API
  3. cargo-NAME executable
  4. CARGO_HOME/bin before the rest of PATH

basics

~20 s

When 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 s

Cargo 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 lines
rust
use 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

for a junior

Recall the convention: cargo NAME runs an executable named cargo-NAME, and cargo install puts binaries in ~/.cargo/bin so they become subcommands.

for a middle

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.

for a senior

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.

for a principal

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
open as a page

What does `cargo audit` check in a Rust project, and which of its findings fail the command by default?

level: middleimportance: should knowfreq 35%

basics

~10 s

cargo audit matches every package version in Cargo.lock against the RustSec advisory database. By default only a vulnerability advisory makes it exit 1; unmaintained, unsound and yanked findings are warnings unless you pass --deny.

open as a page

A payments team's first `cargo deny check` rejects an `MPL-2.0` crate and fails on an unmaintained advisory that `cargo audit` only warned about; why, and how do you tune deny.toml?

level: seniorimportance: should knowfreq 28%

basics

~20 s

cargo-deny's licenses check rejects any license not in [licenses] allow, and its advisories check errors on unmaintained advisories for every crate by default, where cargo-audit only warns. Add a per-crate license exception and a reasoned ignore, or narrow unmaintained.

open as a page

After a Rust workspace's CI moves from `cargo test` to `cargo nextest run`, doctests vanish and one test starts failing; why, and how do you set the job up?

level: seniorimportance: should knowfreq 30%

basics

~20 s

cargo-nextest runs every test in its own process, so a test relying on state another test left behind now fails, and it skips doctests. Remove the hidden dependency and add cargo test --doc as a separate step.

open as a page

For a payments team's Rust CI, which of cargo-audit, cargo-deny, cargo-nextest, cargo-outdated and cargo-machete should block a merge, and which only report?

level: principalimportance: should knowfreq 25%

basics

~20 s

Block on checks a pull request can cause and fix: tests (nextest plus cargo test --doc), cargo-deny licenses, bans and sources, and machete. Gate advisories on lockfile changes and run them on a schedule; keep cargo-outdated a report.

open as a page

What do `cargo machete` and `cargo outdated` each report about a Rust package's dependencies, and why can machete flag a dependency the build needs?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

cargo machete searches a package's .rs files for each [dependencies] name and lists those it never sees, without compiling, so it misses uses it cannot read. cargo outdated lists locked versions with newer compatible (Compat) and newest (Latest) releases.

open as a page