xref: /wasmtime-44.0.1/src/commands/explore.rs (revision d74b34ff)
1 //! The module that implements the `wasmtime explore` command.
2 
3 use anyhow::{Context, Result};
4 use clap::Parser;
5 use std::{borrow::Cow, path::PathBuf};
6 use wasmtime_cli_flags::CommonOptions;
7 
8 /// Explore the compilation of a WebAssembly module to native code.
9 #[derive(Parser, PartialEq)]
10 pub struct ExploreCommand {
11     #[command(flatten)]
12     common: CommonOptions,
13 
14     /// The target triple; default is the host triple
15     #[arg(long, value_name = "TARGET")]
16     target: Option<String>,
17 
18     /// The path of the WebAssembly module to compile
19     #[arg(required = true, value_name = "MODULE")]
20     module: PathBuf,
21 
22     /// The path of the explorer output (derived from the MODULE name if none
23     /// provided)
24     #[arg(short, long)]
25     output: Option<PathBuf>,
26 }
27 
28 impl ExploreCommand {
29     /// Executes the command.
30     pub fn execute(mut self) -> Result<()> {
31         self.common.init_logging()?;
32 
33         let config = self.common.config(self.target.as_deref(), None)?;
34 
35         let bytes =
36             Cow::Owned(std::fs::read(&self.module).with_context(|| {
37                 format!("failed to read Wasm module: {}", self.module.display())
38             })?);
39         #[cfg(feature = "wat")]
40         let bytes = wat::parse_bytes(&bytes).map_err(|mut e| {
41             e.set_path(&self.module);
42             e
43         })?;
44 
45         let output = self
46             .output
47             .clone()
48             .unwrap_or_else(|| self.module.with_extension("explore.html"));
49         let output_file = std::fs::File::create(&output)
50             .with_context(|| format!("failed to create file: {}", output.display()))?;
51         let mut output_file = std::io::BufWriter::new(output_file);
52 
53         wasmtime_explorer::generate(&config, self.target.as_deref(), &bytes, &mut output_file)?;
54         println!("Exploration written to {}", output.display());
55         Ok(())
56     }
57 }
58