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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
//! The logic for the Wasmer CLI tool.
#[cfg(target_os = "linux")]
use crate::commands::Binfmt;
#[cfg(feature = "compiler")]
use crate::commands::Compile;
#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
use crate::commands::CreateExe;
#[cfg(feature = "wast")]
use crate::commands::Wast;
use crate::commands::{
Add, Cache, Config, Init, Inspect, Login, Publish, Run, SelfUpdate, Validate, Whoami,
};
#[cfg(feature = "static-artifact-create")]
use crate::commands::{CreateObj, GenCHeader};
use crate::error::PrettyError;
use clap::{error::ErrorKind, CommandFactory, Parser};
#[derive(Parser, Debug)]
#[cfg_attr(
not(feature = "headless"),
clap(
name = "wasmer",
about = concat!("wasmer ", env!("CARGO_PKG_VERSION")),
version,
author
)
)]
#[cfg_attr(
feature = "headless",
clap(
name = "wasmer-headless",
about = concat!("wasmer ", env!("CARGO_PKG_VERSION")),
version,
author
)
)]
/// The options for the wasmer Command Line Interface
enum WasmerCLIOptions {
/// Login into a wapm.io-like registry
Login(Login),
/// Login into a wapm.io-like registry
#[clap(name = "publish")]
Publish(Publish),
/// Wasmer cache
#[clap(subcommand)]
Cache(Cache),
/// Validate a WebAssembly binary
Validate(Validate),
/// Compile a WebAssembly binary
#[cfg(feature = "compiler")]
Compile(Compile),
/// Compile a WebAssembly binary into a native executable
///
/// To use, you need to set the `WASMER_DIR` environment variable
/// to the location of your Wasmer installation. This will probably be `~/.wasmer`. It
/// should include a `lib`, `include` and `bin` subdirectories. To create an executable
/// you will need `libwasmer`, so by setting `WASMER_DIR` the CLI knows where to look for
/// header files and libraries.
///
/// Example usage:
///
/// ```text
/// $ # in two lines:
/// $ export WASMER_DIR=/home/user/.wasmer/
/// $ wasmer create-exe qjs.wasm -o qjs.exe # or in one line:
/// $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm -o qjs.exe
/// $ file qjs.exe
/// qjs.exe: ELF 64-bit LSB pie executable, x86-64 ...
/// ```
///
/// ## Cross-compilation
///
/// Accepted target triple values must follow the
/// ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
///
/// The recommended targets we try to support are:
///
/// - "x86_64-linux-gnu"
/// - "aarch64-linux-gnu"
/// - "x86_64-apple-darwin"
/// - "arm64-apple-darwin"
#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
#[clap(name = "create-exe", verbatim_doc_comment)]
CreateExe(CreateExe),
/// Compile a WebAssembly binary into an object file
///
/// To use, you need to set the `WASMER_DIR` environment variable to the location of your
/// Wasmer installation. This will probably be `~/.wasmer`. It should include a `lib`,
/// `include` and `bin` subdirectories. To create an object you will need `libwasmer`, so by
/// setting `WASMER_DIR` the CLI knows where to look for header files and libraries.
///
/// Example usage:
///
/// ```text
/// $ # in two lines:
/// $ export WASMER_DIR=/home/user/.wasmer/
/// $ wasmer create-obj qjs.wasm --object-format symbols -o qjs.obj # or in one line:
/// $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm --object-format symbols -o qjs.obj
/// $ file qjs.obj
/// qjs.obj: ELF 64-bit LSB relocatable, x86-64 ...
/// ```
///
/// ## Cross-compilation
///
/// Accepted target triple values must follow the
/// ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
///
/// The recommended targets we try to support are:
///
/// - "x86_64-linux-gnu"
/// - "aarch64-linux-gnu"
/// - "x86_64-apple-darwin"
/// - "arm64-apple-darwin"
#[cfg(feature = "static-artifact-create")]
#[structopt(name = "create-obj", verbatim_doc_comment)]
CreateObj(CreateObj),
/// Generate the C static_defs.h header file for the input .wasm module
#[cfg(feature = "static-artifact-create")]
GenCHeader(GenCHeader),
/// Get various configuration information needed
/// to compile programs which use Wasmer
Config(Config),
/// Update wasmer to the latest version
#[clap(name = "self-update")]
SelfUpdate(SelfUpdate),
/// Inspect a WebAssembly file
Inspect(Inspect),
/// Initializes a new wasmer.toml file
#[clap(name = "init")]
Init(Init),
/// Run spec testsuite
#[cfg(feature = "wast")]
Wast(Wast),
/// Unregister and/or register wasmer as binfmt interpreter
#[cfg(target_os = "linux")]
Binfmt(Binfmt),
/// Shows the current logged in user for the current active registry
Whoami(Whoami),
/// Add a WAPM package's bindings to your application.
Add(Add),
/// (unstable) Run a WebAssembly file or WEBC container.
#[clap(alias = "run-unstable")]
Run(Run),
// DEPLOY commands
/// Deploy apps to the Wasmer Edge.
Deploy(wasmer_deploy_cli::cmd::publish::CmdAppPublish),
#[clap(subcommand)]
App(wasmer_deploy_cli::cmd::app::CmdApp),
Ssh(wasmer_deploy_cli::cmd::ssh::CmdSsh),
#[clap(subcommand)]
Namespace(wasmer_deploy_cli::cmd::namespace::CmdNamespace),
}
impl WasmerCLIOptions {
fn execute(self) -> Result<(), anyhow::Error> {
use wasmer_deploy_cli::cmd::CliCommand;
match self {
Self::Run(options) => options.execute(),
Self::SelfUpdate(options) => options.execute(),
Self::Cache(cache) => cache.execute(),
Self::Validate(validate) => validate.execute(),
#[cfg(feature = "compiler")]
Self::Compile(compile) => compile.execute(),
#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
Self::CreateExe(create_exe) => create_exe.execute(),
#[cfg(feature = "static-artifact-create")]
Self::CreateObj(create_obj) => create_obj.execute(),
Self::Config(config) => config.execute(),
Self::Inspect(inspect) => inspect.execute(),
Self::Init(init) => init.execute(),
Self::Login(login) => login.execute(),
Self::Publish(publish) => publish.execute(),
#[cfg(feature = "static-artifact-create")]
Self::GenCHeader(gen_heder) => gen_heder.execute(),
#[cfg(feature = "wast")]
Self::Wast(wast) => wast.execute(),
#[cfg(target_os = "linux")]
Self::Binfmt(binfmt) => binfmt.execute(),
Self::Whoami(whoami) => whoami.execute(),
Self::Add(install) => install.execute(),
// Deploy commands.
Self::Deploy(c) => c.run(),
Self::App(apps) => apps.run(),
Self::Ssh(ssh) => ssh.run(),
Self::Namespace(namespace) => namespace.run(),
}
}
}
/// The main function for the Wasmer CLI tool.
pub fn wasmer_main() {
// We allow windows to print properly colors
#[cfg(windows)]
colored::control::set_virtual_terminal(true).unwrap();
PrettyError::report(wasmer_main_inner())
}
fn wasmer_main_inner() -> Result<(), anyhow::Error> {
// We try to run wasmer with the normal arguments.
// Eg. `wasmer <SUBCOMMAND>`
// In case that fails, we fallback trying the Run subcommand directly.
// Eg. `wasmer myfile.wasm --dir=.`
//
// In case we've been run as wasmer-binfmt-interpreter myfile.wasm args,
// we assume that we're registered via binfmt_misc
let args = std::env::args().collect::<Vec<_>>();
let binpath = args.get(0).map(|s| s.as_ref()).unwrap_or("");
let firstarg = args.get(1).map(|s| s.as_str());
let secondarg = args.get(2).map(|s| s.as_str());
match (firstarg, secondarg) {
(None, _) | (Some("help"), _) | (Some("--help"), _) => {
return print_help(true);
}
(Some("-h"), _) => {
return print_help(false);
}
(Some("-vV"), _)
| (Some("version"), Some("--verbose"))
| (Some("--version"), Some("--verbose")) => {
return print_version(true);
}
(Some("-v"), _) | (Some("-V"), _) | (Some("version"), _) | (Some("--version"), _) => {
return print_version(false);
}
_ => {}
}
let command = args.get(1);
let options = if cfg!(target_os = "linux") && binpath.ends_with("wasmer-binfmt-interpreter") {
WasmerCLIOptions::Run(Run::from_binfmt_args())
} else {
match command.unwrap_or(&String::new()).as_ref() {
"add" | "cache" | "compile" | "config" | "create-obj" | "create-exe" | "help"
| "gen-c-header" | "inspect" | "init" | "run" | "run-unstable" | "self-update"
| "validate" | "wast" | "binfmt" | "login" | "publish" | "app" | "namespace" | "" => {
WasmerCLIOptions::parse()
}
_ => {
WasmerCLIOptions::try_parse_from(args.iter()).unwrap_or_else(|e| {
match e.kind() {
// This fixes a issue that:
// 1. Shows the version twice when doing `wasmer -V`
// 2. Shows the run help (instead of normal help) when doing `wasmer --help`
ErrorKind::DisplayVersion | ErrorKind::DisplayHelp => e.exit(),
_ => WasmerCLIOptions::Run(Run::parse()),
}
})
}
}
};
options.execute()
}
fn print_help(verbose: bool) -> Result<(), anyhow::Error> {
let mut cmd = WasmerCLIOptions::command();
if verbose {
let _ = cmd.print_long_help();
} else {
let _ = cmd.print_help();
}
Ok(())
}
#[allow(unused_mut, clippy::vec_init_then_push)]
fn print_version(verbose: bool) -> Result<(), anyhow::Error> {
if !verbose {
println!("wasmer {}", env!("CARGO_PKG_VERSION"));
} else {
println!(
"wasmer {} ({} {})",
env!("CARGO_PKG_VERSION"),
env!("WASMER_BUILD_GIT_HASH_SHORT"),
env!("WASMER_BUILD_DATE")
);
println!("binary: {}", env!("CARGO_PKG_NAME"));
println!("commit-hash: {}", env!("WASMER_BUILD_GIT_HASH"));
println!("commit-date: {}", env!("WASMER_BUILD_DATE"));
println!("host: {}", target_lexicon::HOST);
println!("compiler: {}", {
let mut s = Vec::<&'static str>::new();
#[cfg(feature = "singlepass")]
s.push("singlepass");
#[cfg(feature = "cranelift")]
s.push("cranelift");
#[cfg(feature = "llvm")]
s.push("llvm");
s.join(",")
});
}
Ok(())
}