Skip to main content

webpkit_cli/
io.rs

1//! Byte sources and sinks with the `-` stdin/stdout convention.
2//!
3//! A path argument of `-` selects the standard stream; anything else is a file.
4//! Human-readable status is never written here — that is [`crate::report`]'s job —
5//! so a `-o -` pipe stays byte-clean.
6
7use std::{
8    fs,
9    io::{self, Read, Write},
10    path::{Path, PathBuf},
11};
12
13use crate::error::CliError;
14
15/// The lowercased extension of a path, if it has one.
16fn extension_of(path: &Path) -> Option<String> {
17    path.extension()
18        .map(|ext| ext.to_string_lossy().to_ascii_lowercase())
19}
20
21/// Where a command reads its input bytes from.
22pub enum Source {
23    /// Standard input.
24    Stdin,
25    /// A file on disk.
26    File(PathBuf),
27}
28
29/// Where a command writes its output bytes to.
30pub enum Sink {
31    /// Standard output.
32    Stdout,
33    /// A file on disk.
34    File(PathBuf),
35}
36
37impl Source {
38    /// Interpret a path argument: `-` means standard input.
39    #[must_use]
40    pub fn from_arg(path: &Path) -> Self {
41        if path.as_os_str() == "-" {
42            Self::Stdin
43        } else {
44            Self::File(path.to_path_buf())
45        }
46    }
47
48    /// A human-readable label for status and error messages.
49    #[must_use]
50    pub fn label(&self) -> String {
51        match self {
52            Self::Stdin => "<stdin>".to_owned(),
53            Self::File(path) => path.display().to_string(),
54        }
55    }
56
57    /// The lowercased file extension, if any (never for stdin).
58    #[must_use]
59    pub fn extension(&self) -> Option<String> {
60        match self {
61            Self::Stdin => None,
62            Self::File(path) => extension_of(path),
63        }
64    }
65
66    /// Read the whole input into memory.
67    ///
68    /// # Errors
69    ///
70    /// [`CliError::ReadInput`] on any I/O failure.
71    pub fn read(&self) -> Result<Vec<u8>, CliError> {
72        match self {
73            Self::Stdin => {
74                let mut buf = Vec::new();
75                io::stdin()
76                    .lock()
77                    .read_to_end(&mut buf)
78                    .map_err(|err| CliError::read_input(self.label(), &err))?;
79                Ok(buf)
80            },
81            Self::File(path) => {
82                fs::read(path).map_err(|err| CliError::read_input(self.label(), &err))
83            },
84        }
85    }
86}
87
88impl Sink {
89    /// Interpret a path argument: `-` means standard output.
90    #[must_use]
91    pub fn from_arg(path: &Path) -> Self {
92        if path.as_os_str() == "-" {
93            Self::Stdout
94        } else {
95            Self::File(path.to_path_buf())
96        }
97    }
98
99    /// A human-readable label for status and error messages.
100    #[must_use]
101    pub fn label(&self) -> String {
102        match self {
103            Self::Stdout => "<stdout>".to_owned(),
104            Self::File(path) => path.display().to_string(),
105        }
106    }
107
108    /// The lowercased file extension, if any (never for stdout).
109    #[must_use]
110    pub fn extension(&self) -> Option<String> {
111        match self {
112            Self::Stdout => None,
113            Self::File(path) => extension_of(path),
114        }
115    }
116
117    /// Write all bytes to the sink.
118    ///
119    /// # Errors
120    ///
121    /// [`CliError::WriteOutput`] on any I/O failure.
122    pub fn write(&self, bytes: &[u8]) -> Result<(), CliError> {
123        match self {
124            Self::Stdout => io::stdout()
125                .lock()
126                .write_all(bytes)
127                .map_err(|err| CliError::write_output(self.label(), &err)),
128            Self::File(path) => {
129                fs::write(path, bytes).map_err(|err| CliError::write_output(self.label(), &err))
130            },
131        }
132    }
133}