Announcing cargo-single: conveniently build and run single-file programs with dependencies

There is a category of smallish programs which fit in a single source file, but have one or more non-std dependencies. Building and running such programs practically requires using Cargo, which is not too burdensome, but is still slightly tedious and a source of friction.

Cargo-single is a Cargo subcommand to make it easier to deal with such programs. It does that by mechanically generating a Cargo project for the program, populating the dependencies section of its Cargo.toml from the list provided in the comments at the top of the source file, and transparently running Cargo for the project when invoked with the set of commands it recognizes.

Installation

To install cargo-single from crates.io, run:

cargo install cargo-single

An example

The following program prints a random number between 1 and 10, inclusive. It requires the rand crate.

// rand = "0.7"

use rand::Rng;

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

Save it as random.rs and run:

cargo single run random.rs

Cargo-single creates the subdirectory random in the same place where random.rs is, populates it with the project having its main.rs linked to random.rs, builds and runs it.

In addition to run, you can also do check and build. Setting --release and --target is supported, as well as using a different toolchain with +toolchain_name. For everything else, you can change to the project directory and run Cargo as usual.

Prior art

Cargo-script is a much more ambitious and complicated program covering some of the same territory. It can't check or build Rust "scripts" without running them, and it hasn't been updated for the 2018 edition.

Fakecargo is nearer to cargo-single in scope, but it doesn't want to expose the generated project directory, and its syntax is quite different from Cargo's.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.