From 512712e28a0f1cd0b554a060b89bf351121c5da9 Mon Sep 17 00:00:00 2001 From: Marcus Stollsteimer Date: Sun, 5 Nov 2023 18:36:33 +0100 Subject: [PATCH] Add `grss` implementation to errors chapter At the end of the chapter, provide a running code example that applies the nicer error reporting to the `grrs` tool. --- Cargo.toml | 4 ++++ src/tutorial/errors-impl.rs | 26 ++++++++++++++++++++++++++ src/tutorial/errors.md | 9 +++++++++ 3 files changed, 39 insertions(+) create mode 100644 src/tutorial/errors-impl.rs diff --git a/Cargo.toml b/Cargo.toml index dd480a8..5d0a9e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,10 @@ path = "src/tutorial/errors-custom.rs" name = "errors-exit" path = "src/tutorial/errors-exit.rs" +[[bin]] +name = "errors-impl" +path = "src/tutorial/errors-impl.rs" + [[bin]] name = "output-progressbar" path = "src/tutorial/output-progressbar.rs" diff --git a/src/tutorial/errors-impl.rs b/src/tutorial/errors-impl.rs new file mode 100644 index 0000000..e9954b6 --- /dev/null +++ b/src/tutorial/errors-impl.rs @@ -0,0 +1,26 @@ +use anyhow::{Context, Result}; +use clap::Parser; + +/// Search for a pattern in a file and display the lines that contain it. +#[derive(Parser)] +struct Cli { + /// The pattern to look for + pattern: String, + /// The path to the file to read + path: std::path::PathBuf, +} + +fn main() -> Result<()> { + let args = Cli::parse(); + + let content = std::fs::read_to_string(&args.path) + .with_context(|| format!("could not read file `{}`", args.path.display()))?; + + for line in content.lines() { + if line.contains(&args.pattern) { + println!("{}", line); + } + } + + Ok(()) +} diff --git a/src/tutorial/errors.md b/src/tutorial/errors.md index 6992615..84cf0da 100644 --- a/src/tutorial/errors.md +++ b/src/tutorial/errors.md @@ -233,3 +233,12 @@ Error: could not read file `test.txt` Caused by: No such file or directory (os error 2) ``` + +## Wrapping up + +The complete code for our `grrs` tool with improved error reporting +will look like this: + +```rust,ignore +{{#include errors-impl.rs}} +```