#cargo #single-file #cargo-subcommand #dependencies

app cargo-single

Extends Cargo to simplify working with single-file programs with dependencies

1 stable release

1.0.0 Jul 14, 2020

#521 in Cargo plugins

Apache-2.0/MIT

13KB
244 lines

cargo-single

To write a relatively simple Rust program, which can fit in a single source file but does need a couple of external dependencies, one must use Cargo to create a project for the program. Cargo's defaults and tools like cargo-edit help, but it's still some amount of ceremony and increased friction. This tool lets one list the dependencies in the comments at the top of the source file, and use that list and the file name to automatically generate the project directory, which is then transparently used to check, build or run the program.

Installation

You must have Rust and Cargo installed and working. Run:

cargo install cargo-single

See the Cargo documentation to learn how cargo install works and how to set up your system to find the installed binaries.

Example

Create the source file for your program; as an example, save the following as random.rs.

// rand = "0.7"

use rand::Rng;

fn main() {
    println!("{}", rand::thread_rng().gen_range(1, 11));
}

List the dependencies as comments at the top of the file. Each dependency line must start with the string "// " from the leftmost column, and continue in the format used in the [dependencies] section of Cargo.toml. End the list of dependencies with a blank line.

To build and execute the program, run:

cargo single run random.rs

Usage

The tool is invoked through Cargo, with the syntax:

cargo single <command> [<option> ...] {<source-file>|<source-dir>} [<arguments>]

Command is one of: build, check, refresh, or run. Refresh will re-read the source file and update the dependencies in Cargo.toml, while the remaining three are regular Cargo sub-commands which will be passed to Cargo.

Options are a subset of options accepted by Cargo subcommands. The ones recognized by cargo-single are:

  • +toolchain: Name of a toolchain which will be used for building.

  • --release: Build in release mode.

  • --target target: Use the specified target for building.

  • --no-quiet: Don't pass --quiet to Cargo.

Either the name of the source file, with the .rs extension, or of the project directory, which has the same name without the extension, must be given to identify the program.

The remaining arguments, if any, will be passed to the program if it's executed.

License

Licensed under either of:

at your option.

No runtime deps