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
use clap::Parser;
use rustutils_runnable::Runnable;
use std::error::Error;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::PathBuf;

pub const BUFFER_SIZE: usize = 4 * 1024;

/// Copy standard input to each FILE, and also to standard output
#[derive(Parser, Clone, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct Tee {
    #[clap(short, long)]
    append: bool,
    file: Vec<PathBuf>,
}

#[derive(thiserror::Error, Debug)]
pub enum TeeError {
    #[error("Opening file {0:?}: {1:}")]
    OpeningFile(PathBuf, std::io::Error),
    #[error("Writing to file {0:?}: {1:}")]
    WritingFile(PathBuf, std::io::Error),
    #[error("Reading from standard input: {0:}")]
    ReadingStdin(std::io::Error),
    #[error("Writing to standard output: {0:}")]
    WritingStdout(std::io::Error),
}

impl Runnable for Tee {
    fn run(&self) -> Result<(), Box<dyn Error>> {
        let mut stdin = std::io::stdin();
        let mut stdout = std::io::stdout();
        let mut files = self
            .file
            .iter()
            .map(|path| {
                let mut options = OpenOptions::new();
                options.create(true);
                options.append(self.append);
                options.write(true);
                let file = options
                    .open(&path)
                    .map_err(|e| TeeError::OpeningFile(path.clone(), e))?;
                Ok((path, file))
            })
            .collect::<Result<Vec<(&PathBuf, File)>, TeeError>>()?;
        let mut buffer = vec![0; BUFFER_SIZE];
        loop {
            let length = stdin
                .read(&mut buffer[..])
                .map_err(|e| TeeError::ReadingStdin(e))?;
            let data = &buffer[0..length];

            // end of file
            if data.len() == 0 {
                break;
            }

            stdout
                .write_all(&data)
                .map_err(|e| TeeError::WritingStdout(e))?;
            for (path, file) in &mut files {
                file.write_all(&data)
                    .map_err(|e| TeeError::WritingFile(path.clone(), e))?;
            }
        }
        Ok(())
    }
}