Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add grss implementation to errors chapter #233

Merged
merged 2 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
epage marked this conversation as resolved.
Show resolved Hide resolved
will look like this:

```rust,ignore
{{#include errors-impl.rs}}
```
Loading