Skip to content

Commit

Permalink
Add grss implementation to errors chapter
Browse files Browse the repository at this point in the history
At the end of the chapter, provide a running code example
that applies the nicer error reporting to the `grrs` tool.
  • Loading branch information
stomar committed Nov 5, 2023
1 parent bfe0f91 commit 512712e
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
26 changes: 26 additions & 0 deletions src/tutorial/errors-impl.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
9 changes: 9 additions & 0 deletions src/tutorial/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}}
```

0 comments on commit 512712e

Please sign in to comment.