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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use std::fs;
use std::io::{self, Read};
use std::str::FromStr;

use super::{Source, StdinError};

/// Wrapper struct to either read in a file or contents from `stdin`
///
/// `FileOrStdin` can wrap any type that matches the trait bounds for `Arg`: `FromStr` and `Clone`
/// ```rust
/// use std::path::PathBuf;
/// use clap::Parser;
/// use clap_stdin::FileOrStdin;
///
/// #[derive(Debug, Parser)]
/// struct Args {
///     contents: FileOrStdin,
/// }
///
/// if let Ok(args) = Args::try_parse() {
///     println!("contents={}", args.contents);
/// }
/// ```
///
/// ```sh
/// $ cat <filename> | ./example -
/// <filename> contents
/// ```
///
/// ```sh
/// $ ./example <filename>
/// <filename> contents
/// ```
#[derive(Clone)]
pub struct FileOrStdin<T = String> {
    /// Source of the contents
    pub source: Source,
    inner: T,
}

impl<T> FromStr for FileOrStdin<T>
where
    T: FromStr,
    <T as FromStr>::Err: std::fmt::Display,
{
    type Err = StdinError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let source = Source::from_str(s)?;
        match &source {
            Source::Stdin => {
                let stdin = io::stdin();
                let mut input = String::new();
                stdin.lock().read_to_string(&mut input)?;
                Ok(T::from_str(input.trim_end())
                    .map_err(|e| StdinError::FromStr(format!("{e}")))
                    .map(|val| Self { source, inner: val })?)
            }
            Source::Arg(filepath) => Ok(T::from_str(&fs::read_to_string(filepath)?)
                .map_err(|e| StdinError::FromStr(format!("{e}")))
                .map(|val| FileOrStdin { source, inner: val })?),
        }
    }
}

impl<T> FileOrStdin<T> {
    /// Extract the inner value from the wrapper
    pub fn into_inner(self) -> T {
        self.inner
    }
}

impl<T> std::fmt::Display for FileOrStdin<T>
where
    T: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl<T> std::fmt::Debug for FileOrStdin<T>
where
    T: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl<T> std::ops::Deref for FileOrStdin<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl std::ops::DerefMut for FileOrStdin {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}