JA
header image

枝折 - bookmark

Working Through the Rust CLI Tutorial

Rust

CREATED: 2023 / 08 / 27 Mon

UPDATED: 2023 / 08 / 27 Mon

Working Through the Rust CLI Tutorial

Rust CLI Tutorial

There doesn’t seem to be a Japanese translation of this page, so here’s a paraphrased walkthrough:

In the tutorial, we build a grep clone. The clone checks whether a specified string exists in a given file and returns the matching lines if found.

It should be callable like this, displaying lines containing “foobar” in the terminal:

$ grrs foobar test.txt
foobar

Setup

I’ll skip Rust installation — it’s easy to find online. For reference, my environment outputs rustc 1.69.0 (84c898d65 2023-04-16) for rustc --version.

First, create the project. Run cargo new wherever you like:

$ cargo new grrs
$ cd grrs/

After entering the directory as shown above, running cargo run should compile and output Hello, world!.

Handling Command-Line Arguments

To recognize command-line arguments in Rust, use std::env::args(). This provides an iterator over the given arguments.

The first element is the program name — in this case, grrs. So the values passed by the user as arguments can be retrieved starting from index 1.

Given the command below, the first argument is the pattern and the second is the file path to search:

$ grrs foobar test.txt

To retrieve these arguments:

let pattern = std::env::args().nth(1).expect("no pattern given");
let path = std::env::args().nth(2).expect("no path given");

expect is displayed if a value cannot be retrieved. To use these in the program, we can group them into a struct:

struct Cli {
    pattern: String,
    path: std::path::PathBuf,
}

Rather than manually parsing arguments, it’s easier to use an existing library. We’ll use a library called clap to handle argument parsing nicely.

Add clap to cargo.toml:

[dependencies]
clap = { version = "4.0", features = ["derive"] }

Or run cargo add clap --features derive to have it automatically added to cargo.toml. Then you can use use clap::Parser; in your Rust file.

use clap::Parser;

#[derive(Parser)]
struct Cli {
    pattern: String,
    path: std::path::PathBuf,
}

By writing #[derive(Parser)] above the Cli struct, you can skip the boilerplate of argument parsing and extract only the values you need. The parsed values are available in the result of Cli::parse().

Putting it all together so far looks roughly like this. Since args isn’t used yet, a warning would normally appear — but #[allow(unused_variables)] suppresses it. unused_variables is a lint, which runs at compile time and controls how errors and warnings are displayed.

// src/main.rs
use clap::Parser;

#[derive(Parser)]
struct Cli {
    pattern: String,
    path: std::path::PathBuf,
}

#[allow(unused_variables)]
fn main() {
    let args = Cli::parse();
}

Running cargo run without arguments will produce a the following required arguments were not provided error. It’s telling you to provide arguments.

When running with cargo run (before building a binary), you can pass arguments after --. So cargo run -- first-arg second-arg should execute without doing anything but completing successfully.

Implementing the Feature

The groundwork for the CLI tool is now in place. We can receive command-line arguments, so let’s implement the rest. As noted above, arguments are retrieved with let args = Cli::parse().

Now let’s check whether the string given as the first argument exists in the file given as the second argument. This is the core feature of this CLI.

fn main() {
    let args = Cli::parse();

    // Read the file contents
    let content = std::fs::read_to_string(&args.path).expect("could not read file");

    // Find and print lines from the file that match the pattern
    for line in content.lines() {
        if line.contains(&args.pattern) {
            println!("{}", line);
        }
    }
}

Create a sample.txt or similar file in the same directory as src and put some text in it. Then run something like cargo run -- hoge sample.txt in the terminal, and any lines in sample.txt matching the string should be returned.

The feature is complete! Now let’s add tests.

Writing Tests

The business logic in the code above is this part:

for line in content.lines() {
    if line.contains(&args.pattern) {
        println!("{}", line);
    }
}

This is currently inside main(), so let’s extract it into a function find_matches to make it easier to test.

fn find_matches(content: &str, pattern: &str) {
  for line in content.lines() {
      if line.contains(pattern) {
            println!("{}", line);
      }
  }
}

The call inside main() then looks like this:

fn main() {
    let args = Cli::parse();
    let content = std::fs::read_to_string(&args.path).expect("could not read file");
    find_matches(&content, &args.pattern)
}

Now let’s test find_matches! However, find_matches currently returns nothing, so we can’t write assertions against its result.

The solution is to make the results accessible outside the function. Specifically, by using writeln! instead of println!, we can write output to a given variable.

writeln! is a more abstract function than println! — you can think of println! as writeln! with stdout specified as the output target.

println!("Hello world");

// The following writeln! is equivalent to println!
use std::io::{self, BufRead, BufWriter, Write};
let mut stdout = io::stdout();
writeln!(stdout, "Hello world");

In tests, instead of writing to stdout, we write output to a vector, which we can then inspect after execution. First, let’s replace println! with writeln! in the current code:

fn find_matches(content: &str, pattern: &str, mut writer: impl std::io::Write) {
  for line in content.lines() {
      if line.contains(pattern) {
          writeln!(writer, "{}", line);
      }
  }
}

fn main() {
    let args = Cli::parse();
    let content = std::fs::read_to_string(&args.path).expect("could not read file");
    find_matches(&content, &args.pattern, &mut std::io::stdout())
}

Running cargo run now should work the same as before. Let’s move on to the test. We assign a vector to a result variable and pass it as the third argument to find_matches. After execution, we verify the contents of result to perform the test.

fn find_matches(content: &str, pattern: &str, mut writer: impl std::io::Write) {
  for line in content.lines() {
      if line.contains(pattern) {
          writeln!(writer, "{}", line);
      }
  }
}

#[test]
fn find_a_match() {
    let mut result = Vec::new();
    find_matches("lorem ipsum\ndolor sit amet", "lorem", &mut result);
    assert_eq!(result, b"lorem ipsum\n");
}

Running cargo test should pass the test.

Moving Functions to a Separate File

Currently find_matches is in main.rs, but as business logic grows, the file can become large and hard to navigate. In that case, let’s move the function to a separate file.

First, create lib.rs in the src directory alongside main.rs. Define find_matches with pub in lib.rs. Adding pub makes it callable from other files.

// src/lib.rs
pub fn find_matches(content: &str, pattern: &str, mut writer: impl std::io::Write) {
  for line in content.lines() {
      if line.contains(pattern) {
          writeln!(writer, "{}", line);
      }
  }
}

From src/main.rs, you can now call this function as grrs::find_matches:

// src/main.rs
fn main() {
    let args = Cli::parse();
    let content = std::fs::read_to_string(&args.path).expect("could not read file");
    grrs::find_matches(&content, &args.pattern, &mut std::io::stdout())
}

Similarly, update the test call and verify the test still passes.

More Complex Testing

Testing via CLI invocation

How do you test the CLI itself by calling it and checking its output? The assert_cmd crate makes this possible.

Add the following to cargo.toml:

[dev-dependencies]
assert_cmd = "2.0.12"
predicates = "3.0.3"

predicates is a crate needed to write assertions. Write tests in tests/cli.rs and run them with cargo test just like before:

// tests/cli.rs
use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::process::Command;

#[test]
fn file_doesnt_exist() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = Command::cargo_bin("grrs")?;

    cmd.arg("foobar").arg("test/file/doesnt/exist");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("could not read file"));

    Ok(())
}

This calls the grrs CLI from within the test, passes 'foobar' as the first argument and a non-existent path as the second, and tests that the result contains the message “could not read file”.

Creating test files

The CLI we’ve built requires a file for testing. Options for providing that file include:

  • Create the file manually
  • Create the file inside the test

We’ve been manually creating files for testing up to this point, but let’s also cover creating files within tests.

Add assert_fs to cargo.toml. This crate provides file fixtures and assertions for use in tests.

[dev-dependencies]
assert_fs = "1.0.13"
use assert_fs::prelude::*;

#[test]
fn find_content_in_file() -> Result<(), Box<dyn std::error::Error>> {
    let file = assert_fs::NamedTempFile::new("sample.txt")?;
    file.write_str("hoge\nfoo\nbar")?;

    let mut cmd = Command::cargo_bin("grrs")?;
    cmd.arg("hoge").arg(file.path());
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("hoge"));

    Ok(())
}

This test first creates sample.txt and writes 'hoge\nfoo\nbar' to it. Then it sets that path as the second argument and 'hoge' as the first. It verifies that 'hoge' exists in the result and the test completes.

Using assert_fs like this, we can create files within tests and use them for testing. There are many other useful crates available for testing, so as you write tests, look around for what you need.

Appendix