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
//! Shared input/output routines amongst most `wasm-tools` subcommands

use anyhow::{bail, Context, Result};
use std::fs::File;
use std::io::{BufWriter, Read, Write};
use std::path::{Path, PathBuf};

// This is intended to be included in a struct as:
//
//      #[clap(flatten)]
//      io: wasm_tools::InputOutput,
//
// and then the methods are used to read the arguments,
#[derive(clap::Parser)]
pub struct InputOutput {
    /// Input file to process.
    ///
    /// If not provided or if this is `-` then stdin is read entirely and
    /// processed. Note that for most subcommands this input can either be a
    /// binary `*.wasm` file or a textual format `*.wat` file.
    input: Option<PathBuf>,

    #[clap(flatten)]
    output: OutputArg,
}

#[derive(clap::Parser)]
pub struct OutputArg {
    /// Where to place output.
    ///
    /// If not provided then stdout is used.
    #[clap(short, long)]
    output: Option<PathBuf>,
}

pub enum Output<'a> {
    Wat(&'a str),
    Wasm { bytes: &'a [u8], wat: bool },
}

impl InputOutput {
    pub fn parse_input_wasm(&self) -> Result<Vec<u8>> {
        if let Some(path) = &self.input {
            if path != Path::new("-") {
                let bytes = wat::parse_file(path)?;
                return Ok(bytes);
            }
        }
        let mut stdin = Vec::new();
        std::io::stdin()
            .read_to_end(&mut stdin)
            .context("failed to read <stdin>")?;
        let bytes = wat::parse_bytes(&stdin).map_err(|mut e| {
            e.set_path("<stdin>");
            e
        })?;
        Ok(bytes.into_owned())
    }

    pub fn output(&self, bytes: Output<'_>) -> Result<()> {
        self.output.output(bytes)
    }

    pub fn output_writer(&self) -> Result<Box<dyn Write>> {
        self.output.output_writer()
    }
}

impl OutputArg {
    pub fn output(&self, output: Output<'_>) -> Result<()> {
        match output {
            Output::Wat(s) => self.output_str(s),
            Output::Wasm { bytes, wat: true } => {
                self.output_str(&wasmprinter::print_bytes(&bytes)?)
            }
            Output::Wasm { bytes, wat: false } => {
                match &self.output {
                    Some(path) => {
                        std::fs::write(path, bytes)
                            .context(format!("failed to write `{}`", path.display()))?;
                    }
                    None => {
                        if atty::is(atty::Stream::Stdout) {
                            bail!("cannot print binary wasm output to a terminal, pass the `-t` flag to print the text format");
                        }
                        std::io::stdout()
                            .write_all(bytes)
                            .context("failed to write to stdout")?;
                    }
                }
                Ok(())
            }
        }
    }

    fn output_str(&self, output: &str) -> Result<()> {
        match &self.output {
            Some(path) => {
                std::fs::write(path, output)
                    .context(format!("failed to write `{}`", path.display()))?;
            }
            None => println!("{output}"),
        }
        Ok(())
    }

    pub fn output_writer(&self) -> Result<Box<dyn Write>> {
        match &self.output {
            Some(output) => Ok(Box::new(BufWriter::new(File::create(&output)?))),
            None => Ok(Box::new(std::io::stdout())),
        }
    }
}