summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 71a37091d5b9a00f14a9541e93155badb3b6c7e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::error::Error;

fn main() {
    if let Err(e) = fallible_main() {
        eprintln!("ERROR: {}", e);
        let mut err = e.source();
        while let Some(underlying) = err {
            eprintln!("caused by: {}", underlying);
            err = underlying.source();
        }
    }
}

fn fallible_main() -> Result<(), HelloError> {
    let args = Args::parse();
    println!("hello, {}", args.whom()?);
    Ok(())
}

use clap::Parser;
use std::fs::read;
use std::path::PathBuf;

#[derive(Parser)]
struct Args {
    #[clap(default_value = "world")]
    whom: String,

    #[clap(short, long)]
    filename: Option<PathBuf>,
}

impl Args {
    fn whom(&self) -> Result<String, HelloError> {
        if let Some(filename) = &self.filename {
            let data = read(&filename)
                .map_err(|e| {
                    HelloError::Read(filename.clone(), e)
                })?;
            let whom = String::from_utf8(data)
                .map_err(|e| {
                    HelloError::Utf8(filename.clone(), e)
                })?;
            Ok(whom.trim().to_string())
        } else {
            Ok(self.whom.clone())
        }
    }
}

#[derive(Debug, thiserror::Error)]
enum HelloError {
    #[error("failed to read file {0}")]
    Read(PathBuf, #[source] std::io::Error),

    #[error("failed to parse file {0} as UTF-8")]
    Utf8(PathBuf, #[source] std::string::FromUtf8Error),
}