qstdin/
lib.rs

1//! qstdin
2//!
3//! `qstdin` is a simple interface for querying stdin
4
5use std::fs::File;
6use std::io::stdin;
7use std::os::fd::AsFd;
8
9// possible stdin sources
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub enum Stdin {
12    Input,
13    File,
14    Directory,
15}
16
17/// returns true if current stdin is
18/// equal to the stream passed in the argument
19///
20/// # Examples
21/// ```
22/// use qstdin::{is, Stdin};
23///
24/// println!("file? {}", is(Stdin::File));
25/// ```
26#[cfg(unix)]
27pub fn is(stream: Stdin) -> bool {
28    let fd = stdin().as_fd().try_clone_to_owned().unwrap();
29    let file = File::from(fd);
30    let meta = file.metadata().unwrap();
31
32    if meta.is_dir() {
33        if stream == Stdin::Directory {
34            return true;
35        } else {
36            return false;
37        }
38    }
39
40    if meta.is_file() {
41        if stream == Stdin::File {
42            return true;
43        } else {
44            return false;
45        }
46    }
47
48    stream != Stdin::Directory && stream != Stdin::File
49}
50
51#[cfg(test)]
52mod tests {
53    use super::{is, Stdin};
54
55    #[test]
56    fn is_input() {
57        assert!(is(Stdin::Input));
58    }
59
60    #[test]
61    fn is_file() {
62        assert!(!is(Stdin::File));
63    }
64
65    #[test]
66    fn is_dir() {
67        assert!(!is(Stdin::Directory));
68    }
69}