MARY.WIN

RUSTY — LARAVEL TO RUST — 14

Artisan versus Cargo
and custom commands

Distinguish building a program from using it.
Tutorial 14 of 16 in From Laravel to Rust. Before you start: Functions, enums, and Result.

Which program interprets list: Cargo or the application? In examples/src/bin/ep14.rs, handle() interprets the application arguments. Cargo builds and launches that binary during development. Artisan combines application commands under a Laravel entry point, so the names need careful mapping.

The list branch returns two titles. The preview TITLE branch returns a normalized preview. main() converts the result into terminal output and an exit status. The compiled binary retains this behavior when launched without Cargo.

Predict the result for list, preview " tests ", and an unknown command. The unit test calls handle() directly to check those cases. A subprocess check must separately verify the actual exit status.

This lesson covers the difference between Cargo and your program's own commands. We'll use a small command-line interface in which a handle function owns the command grammar and main owns process output, run it through cargo run, and then run the built binary directly. It also covers Cargo.toml, Cargo.lock, editions, and rust-version in one section. It leaves out argument-parsing libraries. It assumes Tutorials 6 and 7. The Laravel reference point is Artisan, which combines application commands under a Laravel entry point. Cargo builds and launches your binary during development, and the binary interprets its own arguments, so the two sets of command names need careful mapping.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep14.rs)

use std::process::ExitCode;

fn handle(args: &[String]) -> Result<String, String> {
    match args {
        [] => Ok("usage: palette list | preview TITLE".into()),
        [command] if command == "list" => Ok("tests\nformat".into()),
        [command, title] if command == "preview" && !title.trim().is_empty() => {
            Ok(format!("preview: {}", title.trim()))
        }
        _ => Err("expected list or preview TITLE".into()),
    }
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match handle(&args) {
        Ok(output) => { println!("{output}"); ExitCode::SUCCESS }
        Err(error) => { eprintln!("{error}"); ExitCode::from(2) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_commands_and_rejects_extra_arguments() {
        assert_eq!(handle(&["list".into()]), Ok("tests\nformat".into()));
        assert_eq!(handle(&["preview".into(), " tests ".into()]),
                   Ok("preview: tests".into()));
        assert!(handle(&["preview".into(), " ".into()]).is_err());
        assert!(handle(&["list".into(), "extra".into()]).is_err());
        assert!(handle(&["unknown".into()]).is_err());
    }
}

With no application arguments, handle() returns its usage line successfully.

Expected output:

TERMINAL
cargo run --quiet --bin ep14
usage: palette list | preview TITLE

Before you go further, predict what list, preview " tests ", and an unknown command will produce. The unit test calls handle() directly to check those cases. The exit status needs a separate check against the running process.

The parser with two shapes

The function handle recognized an empty argument list and two shapes of command: list, and preview followed by one non-blank title. It held that anything else was a mistake. It was given the single word unknown. It returned Err, main wrote one line to stderr, and the process exited with status 2.

Sometimes a command works and lives in the wrong layer: the behavior is tangled up with reading arguments and printing, so every test has to launch a process. Thankfully, a small split is enough. Take another look at Example 1.

There are three pieces. handle takes &[String] and returns Result<String, String>, and it owns the grammar: the list branch returns two titles, and the preview TITLE branch returns preview: followed by the trimmed title. main owns the process. std::env::args().skip(1) leaves out the executable name, main collects the remaining strings and calls handle(&args), an Ok value is printed to stdout with ExitCode::SUCCESS, and an Err value is printed to stderr with exit code 2. And the test module calls handle directly, five cases in one test, with no subprocess.

The program does not execute the supplied title as a shell command. It produces a preview string, and that is part of the example's behavior.¹

What to run

Run these from the companion package's examples/ folder, one at a time. First list, then preview with a quoted two-word title, then an unknown command, followed by its exit status. Then run the tests. Last, build the release binary and run it directly.

TERMINAL
cargo run --quiet --bin ep14 -- list
tests
format
TERMINAL
cargo run --quiet --bin ep14 -- preview "run tests"
preview: run tests
TERMINAL
cargo run --quiet --bin ep14 -- unknown
echo "exit status: $?"
expected list or preview TITLE
exit status: 2

The unknown-command branch returns expected list or preview TITLE. That line went to stderr, and the 2 beside it is the exit status main chose for an Err.

TERMINAL
cargo test --bin ep14
running 1 test
test tests::parses_commands_and_rejects_extra_arguments ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
TERMINAL
cargo build --release
./target/release/ep14 list
tests
format

The last pair is the point of the lesson. In cargo run --quiet --bin ep14 -- list, the --bin ep14 argument selects the lesson binary, and the double dash passes list to ep14, which prints tests and format on separate lines. cargo test --bin ep14 runs this binary's tests. cargo build --release --bin ep14 builds target/release/ep14 for a direct invocation; the listing ran the plain cargo build --release, and ./target/release/ep14 was there afterward. ./target/release/ep14 list is the application on its own, and it behaves the same way without Cargo.

Which file says what?

Cargo.toml describes the package and its dependency requirements. Cargo.lock records the resolved dependency graph. Commit the lockfile for an executable project like this one, so another developer can reproduce the resolution.

A lockfile is, for all that it pins every crate to an exact version and for all the confidence that inspires, a record of one dependency resolution and of nothing else, so the operating system, the compiler, the native dependencies, and every network service a test touches are free to differ between your machine and the next one, and the lockfile will match on both.

The edition and the compiler version are different settings too. An edition chooses compatibility-related language behavior. A rust-version declaration states a supported compiler version requirement for a package. Say which one you mean.

What should a binary borrow from Artisan?

Artisan makes a project's operations discoverable. A Rust binary can do the same: clear help, meaningful command names, understandable error output, and exit statuses scripts can depend on. If a command changes state, explain what it changes. If output is meant for another program, offer a stable machine-readable format.

You can also get this wrong quietly. A command that prints success and returns failure, or hides a failed operation behind exit zero, has an interface bug even when the business logic is correct.

So the three commands behave and the test passes. Now run one of your own Artisan commands with a wrong argument. What does it print? What is its exit status? If a script called it, would the script know it failed?

Testing

Start from memory. Explain where list is interpreted once it follows the double dash, which function owns the command grammar, and which owns process output.

Then add a version branch to handle() and a test for its returned string. Before you write the rejection test, predict what version extra should do, and write the prediction down.

Now compare. The one-argument version branch should reject an extra argument, not ignore it, the same way the existing test expects list extra to be rejected. Keep parsing in handle() and process exit handling in main(). Then run the built executable with an invalid command and check stderr and exit status 2. The unit test checks the parser; the subprocess check observes the actual command-line boundary.

TL;DR

handle() owns the command grammar and main() owns process output: stdout, stderr, and the exit status. During development Cargo builds and launches the binary, and the double dash passes list to ep14; the built executable behaves the same without Cargo. Cargo.toml states requirements, Cargo.lock records one resolution, and edition and rust-version are separate settings. A command that fails should say so on stderr and in its exit status. The unit test checks the parser, and the built executable is where you check an unknown command's stderr and exit status.

¹ std::env::args expects Unicode arguments and can panic on invalid Unicode. A filesystem-oriented tool that must accept arbitrary operating-system paths should consider args_os and OsString. For a larger product, a maintained parsing library can supply help generation, subcommands, and richer validation.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Cargo Book, package layout, manifest, lockfile, run, build, and test; Rust standard-library env::args and ExitCode; Laravel 13 Artisan. The parser is an original small-scope example.

NOT CHECKED — 5
  • The output of list, preview "run tests" and the release binary was observed on rustc 1.97.0 when this tutorial was first built. The companion package's recorded checks on rustc 1.100.0 cover the usage line, the unknown command's stderr and exit status, and the unit test.
  • cargo build --release --bin ep14 is taken from the tutorial text; the release build shown was run without --bin.
  • The version exercise was not written or run.
  • Statements about Artisan are carried from the tutorial text and were not re-checked against the Laravel documentation for this edition.
  • The reference links were not opened for this edition.