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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
use std::marker::PhantomData;
use std::str::FromStr;
#[cfg(feature = "tokio")]
use tokio::io::AsyncReadExt;
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 {
/// input: FileOrStdin,
/// }
///
/// # fn main() -> anyhow::Result<()> {
/// if let Ok(args) = Args::try_parse() {
/// println!("input={}", args.input.contents()?);
/// }
/// # Ok(())
/// # }
/// ```
///
/// ```sh
/// $ echo "1 2 3 4" > input.txt
/// $ cat input.txt | ./example -
/// 1 2 3 4
///
/// $ ./example input.txt
/// 1 2 3 4
/// ```
#[derive(Debug, Clone)]
pub struct FileOrStdin<T = String> {
pub source: Source,
_type: PhantomData<T>,
}
impl<T> FileOrStdin<T> {
/// Read the entire contents from the input source, returning T::from_str
pub fn contents(self) -> Result<T, StdinError>
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Display,
{
use std::io::Read;
let mut reader = self.into_reader()?;
let mut input = String::new();
let _ = reader.read_to_string(&mut input)?;
T::from_str(input.trim_end()).map_err(|e| StdinError::FromStr(format!("{e}")))
}
/// Create a reader from the source, to allow user flexibility of
/// how to read and parse (e.g. all at once or in chunks)
///
/// ```no_run
/// use std::io::Read;
///
/// use clap_stdin::FileOrStdin;
/// use clap::Parser;
///
/// #[derive(Parser)]
/// struct Args {
/// input: FileOrStdin,
/// }
///
/// # fn main() -> anyhow::Result<()> {
/// let args = Args::parse();
/// let mut reader = args.input.into_reader()?;
/// let mut buf = vec![0;8];
/// reader.read_exact(&mut buf)?;
/// # Ok(())
/// # }
/// ```
pub fn into_reader(&self) -> Result<impl std::io::Read, StdinError> {
let input: Box<dyn std::io::Read + 'static> = match &self.source {
Source::Stdin => Box::new(std::io::stdin()),
Source::Arg(filepath) => {
let f = std::fs::File::open(filepath)?;
Box::new(f)
}
};
Ok(input)
}
#[cfg(feature = "tokio")]
/// Read the entire contents from the input source, returning T::from_str
/// ```rust,no_run
/// use clap::Parser;
/// use clap_stdin::FileOrStdin;
///
/// #[derive(Debug, Parser)]
/// struct Args {
/// input: FileOrStdin,
/// }
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> anyhow::Result<()> {
/// let args = Args::parse();
/// println!("input={}", args.input.contents_async().await?);
/// # Ok(())
/// # }
/// ```
pub async fn contents_async(self) -> Result<T, StdinError>
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Display,
{
let mut reader = self.into_async_reader().await?;
let mut input = String::new();
let _ = reader.read_to_string(&mut input).await?;
T::from_str(input.trim_end()).map_err(|e| StdinError::FromStr(format!("{e}")))
}
#[cfg(feature = "tokio")]
/// Create a reader from the source, to allow user flexibility of
/// how to read and parse (e.g. all at once or in chunks)
///
/// ```no_run
/// use std::io::Read;
/// use tokio::io::AsyncReadExt;
///
/// use clap_stdin::FileOrStdin;
/// use clap::Parser;
///
/// #[derive(Parser)]
/// struct Args {
/// input: FileOrStdin,
/// }
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> anyhow::Result<()> {
/// let args = Args::parse();
/// let mut reader = args.input.into_async_reader().await?;
/// let mut buf = vec![0;8];
/// reader.read_exact(&mut buf).await?;
/// # Ok(())
/// # }
/// ```
pub async fn into_async_reader(&self) -> Result<impl tokio::io::AsyncRead, StdinError> {
let input: std::pin::Pin<Box<dyn tokio::io::AsyncRead + 'static>> = match &self.source {
Source::Stdin => Box::pin(tokio::io::stdin()),
Source::Arg(filepath) => {
let f = tokio::fs::File::open(filepath).await?;
Box::pin(f)
}
};
Ok(input)
}
}
impl<T> FromStr for FileOrStdin<T> {
type Err = StdinError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let source = Source::from_str(s)?;
Ok(Self {
source,
_type: PhantomData,
})
}
}