Skip to content

Commit

Permalink
more idiomatic anyhow error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelohdez committed Feb 14, 2024
1 parent 54e990c commit de0233a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
25 changes: 16 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub use templates::*;

use std::{env, fs, io, path::Path, process::Command};

use anyhow::bail;
use anyhow::Context;
use chrono::Local;

pub fn try_template(
Expand Down Expand Up @@ -34,17 +34,25 @@ pub fn try_template(
if delete || ask_y_n("Would you like to keep this project?")? {
println!("Saved as {tmp_dir:?}.");
} else {
fs::remove_dir_all(&tmp_dir)?;
fs::remove_dir_all(&tmp_dir)
.with_context(|| format!("Failed to remove directory {tmp_dir:?}"))?;
}

Ok(())
}

/// Will print out a question and wait for user input in the form of `y` or `n`
/// (returning true if `y`). Any capitalization works. Defaults to `n` on a
/// blank character (e.g. just pressing Enter).
///
/// Will return Err(_) if stdio fails to open.
fn ask_y_n(question: &str) -> anyhow::Result<bool> {
println!("{question} (y/N)");

let mut input = String::new();
io::stdin().read_line(&mut input)?;
io::stdin()
.read_line(&mut input)
.context("Failed to open stdio!")?;

match input.to_lowercase().trim() {
"y" => Ok(true),
Expand All @@ -55,20 +63,19 @@ fn ask_y_n(question: &str) -> anyhow::Result<bool> {

// modified from https://stackoverflow.com/a/65192210/15425442
fn copy_dir_recursively(from: &Path, to: &Path) -> anyhow::Result<()> {
fs::create_dir_all(to)?;
fs::create_dir_all(to).with_context(|| format!("Failed to create directory {to:?}!"))?;

let Ok(entries) = fs::read_dir(from) else {
bail!("Could not read dir to copy from:\n{from:?}\nDoes it exist?")
};
let entries = fs::read_dir(from).with_context(|| format!("Failed to copy {from:?}!"))?;

for entry in entries {
let entry = entry?;
let entry = entry.context("Failed to unwrap entry to copy!")?;
let path = entry.path();

if path.is_dir() {
copy_dir_recursively(&path, &to.join(entry.file_name()))?;
} else {
fs::copy(path, to.join(entry.file_name()))?;
fs::copy(path, to.join(entry.file_name()))
.with_context(|| format!("Failed to copy {entry:?}!"))?;
}
}

Expand Down
7 changes: 3 additions & 4 deletions src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{
path::{Path, PathBuf},
};

use anyhow::{anyhow, bail};
use anyhow::{anyhow, bail, Context};

pub struct Templates(Vec<PathBuf>);

Expand Down Expand Up @@ -37,9 +37,8 @@ impl TryFrom<&Path> for Templates {
bail!("Template directory does not exist:\n {data_dir:?}\nCreate it along with some templates inside!");
}

let Ok(entries) = fs::read_dir(data_dir) else {
bail!("Could not read data dir:\n{data_dir:?}\nDoes it exist?")
};
let entries =
fs::read_dir(data_dir).with_context(|| format!("Failed to read {data_dir:?}"))?;

let mut templates = Vec::new();
for entry in entries {
Expand Down

0 comments on commit de0233a

Please sign in to comment.