1use std::{
2 io::{self, BufWriter},
3 path::PathBuf,
4 str::FromStr,
5};
6
7#[derive(Debug, Clone)]
13pub enum OutputFile {
14 Null,
15 Stdout,
16 Stderr,
17 File(PathBuf),
18}
19
20impl OutputFile {
21 pub fn as_path_string(&self) -> String {
22 match self {
23 OutputFile::Null => "<null>".to_string(),
24 OutputFile::Stdout => "<stdout>".to_string(),
25 OutputFile::Stderr => "<stderr>".to_string(),
26 OutputFile::File(path) => path.to_string_lossy().to_string(),
27 }
28 }
29}
30
31impl FromStr for OutputFile {
32 type Err = String;
33 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
34 match s {
35 "-" | "<out>" => Ok(OutputFile::Stdout),
36 "<err>" => Ok(OutputFile::Stderr),
37 "<null>" => Ok(OutputFile::Null),
38 _ => Ok(OutputFile::File(PathBuf::from(s))),
39 }
40 }
41}
42
43impl ToString for OutputFile {
44 fn to_string(&self) -> String {
45 match self {
46 OutputFile::Stdout => "-".to_string(),
47 OutputFile::Stderr => "<err>".to_string(),
48 OutputFile::Null => "<null>".to_string(),
49 OutputFile::File(p) => p.to_str().unwrap().to_string(),
50 }
51 }
52}
53
54impl OutputFile {
55 pub fn isatty(&self) -> bool {
56 match self {
57 OutputFile::Stdout => atty::is(atty::Stream::Stdout),
58 OutputFile::Stderr => atty::is(atty::Stream::Stderr),
59 OutputFile::Null | OutputFile::File(_) => false,
60 }
61 }
62
63 pub fn get_write(&self) -> Box<dyn io::Write> {
64 match self {
65 OutputFile::Stdout => Box::new(BufWriter::new(std::io::stdout())),
66 OutputFile::Stderr => Box::new(BufWriter::new(std::io::stderr())),
67 OutputFile::File(path) => {
68 Box::new(BufWriter::new(std::fs::File::create(path).unwrap()))
69 }
70 OutputFile::Null => Box::new(io::sink()),
71 }
72 }
73}