wasmer_cli/commands/
mod.rs

1//! The commands available in the Wasmer binary.
2mod add;
3mod app;
4mod auth;
5#[cfg(target_os = "linux")]
6mod binfmt;
7mod cache;
8#[cfg(feature = "compiler")]
9mod compile;
10mod config;
11mod connect;
12mod container;
13#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
14mod create_exe;
15#[cfg(feature = "static-artifact-create")]
16mod create_obj;
17pub(crate) mod domain;
18#[cfg(feature = "static-artifact-create")]
19mod gen_c_header;
20mod gen_completions;
21mod gen_manpage;
22mod init;
23mod inspect;
24#[cfg(feature = "journal")]
25mod journal;
26pub(crate) mod namespace;
27mod package;
28mod run;
29mod self_update;
30pub mod ssh;
31mod validate;
32#[cfg(feature = "wast")]
33mod wast;
34use std::env::args;
35use tokio::task::JoinHandle;
36
37#[cfg(target_os = "linux")]
38pub use binfmt::*;
39use clap::{CommandFactory, Parser};
40#[cfg(feature = "compiler")]
41pub use compile::*;
42#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
43pub use create_exe::*;
44#[cfg(feature = "wast")]
45pub use wast::*;
46#[cfg(feature = "static-artifact-create")]
47pub use {create_obj::*, gen_c_header::*};
48
49#[cfg(feature = "journal")]
50pub use self::journal::*;
51pub use self::{
52    add::*, auth::*, cache::*, config::*, container::*, init::*, inspect::*, package::*,
53    publish::*, run::Run, self_update::*, validate::*,
54};
55use crate::error::PrettyError;
56
57/// An executable CLI command.
58pub(crate) trait CliCommand {
59    type Output;
60
61    fn run(self) -> Result<(), anyhow::Error>;
62}
63
64/// An executable CLI command that runs in an async context.
65///
66/// An [`AsyncCliCommand`] automatically implements [`CliCommand`] by creating
67/// a new tokio runtime and blocking.
68#[async_trait::async_trait]
69pub(crate) trait AsyncCliCommand: Send + Sync {
70    type Output: Send + Sync;
71
72    async fn run_async(self) -> Result<Self::Output, anyhow::Error>;
73
74    fn setup(
75        &self,
76        done: tokio::sync::oneshot::Receiver<()>,
77    ) -> Option<JoinHandle<anyhow::Result<()>>> {
78        if is_terminal::IsTerminal::is_terminal(&std::io::stdin()) {
79            return Some(tokio::task::spawn(async move {
80                tokio::select! {
81                    _ = done => {}
82
83                    _ = tokio::signal::ctrl_c() => {
84                        let term = console::Term::stdout();
85                        let _ = term.show_cursor();
86                        // https://learn.microsoft.com/en-us/cpp/c-runtime-library/signal-constants
87                        #[cfg(target_os = "windows")]
88                        std::process::exit(3);
89
90                        // POSIX compliant OSs: 128 + SIGINT (2)
91                        #[cfg(not(target_os = "windows"))]
92                        std::process::exit(130);
93                    }
94                }
95
96                Ok::<(), anyhow::Error>(())
97            }));
98        }
99
100        None
101    }
102}
103
104impl<O: Send + Sync, C: AsyncCliCommand<Output = O>> CliCommand for C {
105    type Output = O;
106
107    fn run(self) -> Result<(), anyhow::Error> {
108        tokio::runtime::Runtime::new()?.block_on(async {
109            let (snd, rcv) = tokio::sync::oneshot::channel();
110            let handle = self.setup(rcv);
111
112            if let Err(e) = AsyncCliCommand::run_async(self).await {
113                if let Some(handle) = handle {
114                    handle.abort();
115                }
116                return Err(e);
117            }
118
119            if let Some(handle) = handle {
120                if snd.send(()).is_err() {
121                    tracing::warn!("Failed to send 'done' signal to setup thread!");
122                    handle.abort();
123                } else {
124                    handle.await??;
125                }
126            }
127
128            Ok::<(), anyhow::Error>(())
129        })?;
130
131        Ok(())
132    }
133}
134
135/// Command-line arguments for the Wasmer CLI.
136#[derive(clap::Parser, Debug)]
137#[clap(author, version)]
138#[clap(disable_version_flag = true)] // handled manually
139#[cfg_attr(feature = "headless", clap(
140    name = "wasmer-headless",
141    about = concat!("wasmer-headless ", env!("CARGO_PKG_VERSION")),
142))]
143#[cfg_attr(not(feature = "headless"), clap(
144    name = "wasmer",
145    about = concat!("wasmer ", env!("CARGO_PKG_VERSION")),
146))]
147pub struct WasmerCmd {
148    /// Print version info and exit.
149    #[clap(short = 'V', long)]
150    version: bool,
151    #[clap(flatten)]
152    output: crate::logging::Output,
153    #[clap(subcommand)]
154    cmd: Option<Cmd>,
155}
156
157impl WasmerCmd {
158    fn execute(self) -> Result<(), anyhow::Error> {
159        let WasmerCmd {
160            cmd,
161            version,
162            output,
163        } = self;
164
165        output.initialize_logging();
166
167        if version {
168            return print_version(output.is_verbose());
169        }
170
171        match cmd {
172            Some(Cmd::GenManPage(cmd)) => cmd.execute(),
173            Some(Cmd::GenCompletions(cmd)) => cmd.execute(),
174            Some(Cmd::Run(options)) => options.execute(output),
175            Some(Cmd::SelfUpdate(options)) => options.execute(),
176            Some(Cmd::Cache(cache)) => cache.execute(),
177            Some(Cmd::Validate(validate)) => validate.execute(),
178            #[cfg(feature = "compiler")]
179            Some(Cmd::Compile(compile)) => compile.execute(),
180            #[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
181            Some(Cmd::CreateExe(create_exe)) => create_exe.run(),
182            #[cfg(feature = "static-artifact-create")]
183            Some(Cmd::CreateObj(create_obj)) => create_obj.execute(),
184            Some(Cmd::Config(config)) => config.run(),
185            Some(Cmd::Inspect(inspect)) => inspect.execute(),
186            Some(Cmd::Init(init)) => init.run(),
187            Some(Cmd::Login(login)) => login.run(),
188            Some(Cmd::Auth(auth)) => auth.run(),
189            Some(Cmd::Publish(publish)) => publish.run().map(|_| ()),
190            Some(Cmd::Package(cmd)) => match cmd {
191                Package::Download(cmd) => cmd.execute(),
192                Package::Build(cmd) => cmd.execute().map(|_| ()),
193                Package::Tag(cmd) => cmd.run(),
194                Package::Push(cmd) => cmd.run(),
195                Package::Publish(cmd) => cmd.run().map(|_| ()),
196                Package::Unpack(cmd) => cmd.execute(),
197            },
198            Some(Cmd::Container(cmd)) => match cmd {
199                crate::commands::Container::Unpack(cmd) => cmd.execute(),
200            },
201            #[cfg(feature = "static-artifact-create")]
202            Some(Cmd::GenCHeader(gen_heder)) => gen_heder.execute(),
203            #[cfg(feature = "wast")]
204            Some(Cmd::Wast(wast)) => wast.execute(),
205            #[cfg(target_os = "linux")]
206            Some(Cmd::Binfmt(binfmt)) => binfmt.execute(),
207            Some(Cmd::Whoami(whoami)) => whoami.run(),
208            Some(Cmd::Add(add)) => add.run(),
209
210            // Deploy commands.
211            Some(Cmd::Deploy(c)) => c.run(),
212            Some(Cmd::App(apps)) => apps.run(),
213            #[cfg(feature = "journal")]
214            Some(Cmd::Journal(journal)) => journal.run(),
215            Some(Cmd::Ssh(ssh)) => ssh.run(),
216            Some(Cmd::Namespace(namespace)) => namespace.run(),
217            Some(Cmd::Domain(namespace)) => namespace.run(),
218            None => {
219                WasmerCmd::command().print_long_help()?;
220                // Note: clap uses an exit code of 2 when CLI parsing fails
221                std::process::exit(2);
222            }
223        }
224    }
225
226    /// The main function for the Wasmer CLI tool.
227    pub fn run() {
228        // We allow windows to print properly colors
229        #[cfg(windows)]
230        colored::control::set_virtual_terminal(true).unwrap();
231
232        PrettyError::report(Self::run_inner())
233    }
234
235    fn run_inner() -> Result<(), anyhow::Error> {
236        if is_binfmt_interpreter() {
237            Run::from_binfmt_args().execute(crate::logging::Output::default());
238        }
239
240        match WasmerCmd::try_parse() {
241            Ok(args) => args.execute(),
242            Err(e) => {
243                let first_arg_is_subcommand = if let Some(first_arg) = args().nth(1) {
244                    let mut ret = false;
245                    let cmd = WasmerCmd::command();
246
247                    for cmd in cmd.get_subcommands() {
248                        if cmd.get_name() == first_arg {
249                            ret = true;
250                            break;
251                        }
252                    }
253
254                    ret
255                } else {
256                    false
257                };
258
259                let might_be_wasmer_run = matches!(
260                    e.kind(),
261                    clap::error::ErrorKind::InvalidSubcommand
262                        | clap::error::ErrorKind::UnknownArgument
263                ) && !first_arg_is_subcommand;
264
265                if might_be_wasmer_run {
266                    if let Ok(run) = Run::try_parse() {
267                        // Try to parse the command using the `wasmer some/package`
268                        // shorthand. Note that this has discoverability issues
269                        // because it's not shown as part of the main argument
270                        // parser's help, but that's fine.
271                        let output = crate::logging::Output::default();
272                        output.initialize_logging();
273                        run.execute(output);
274                    }
275                }
276
277                e.exit();
278            }
279        }
280    }
281}
282
283#[derive(clap::Parser, Debug)]
284#[allow(clippy::large_enum_variant)]
285/// The options for the wasmer Command Line Interface
286enum Cmd {
287    /// Login into Wasmer
288    Login(Login),
289
290    #[clap(subcommand)]
291    Auth(CmdAuth),
292
293    /// Publish a package to a registry [alias: package publish]
294    #[clap(name = "publish")]
295    Publish(PackagePublish),
296
297    /// Manage the local Wasmer cache
298    Cache(Cache),
299
300    /// Validate a WebAssembly binary
301    Validate(Validate),
302
303    /// Compile a WebAssembly binary
304    #[cfg(feature = "compiler")]
305    Compile(Compile),
306
307    /// Compile a WebAssembly binary into a native executable
308    ///
309    /// To use, you need to set the `WASMER_DIR` environment variable
310    /// to the location of your Wasmer installation. This will probably be `~/.wasmer`. It
311    /// should include a `lib`, `include` and `bin` subdirectories. To create an executable
312    /// you will need `libwasmer`, so by setting `WASMER_DIR` the CLI knows where to look for
313    /// header files and libraries.
314    ///
315    /// Example usage:
316    ///
317    /// ```text
318    /// $ # in two lines:
319    /// $ export WASMER_DIR=/home/user/.wasmer/
320    /// $ wasmer create-exe qjs.wasm -o qjs.exe # or in one line:
321    /// $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm -o qjs.exe
322    /// $ file qjs.exe
323    /// qjs.exe: ELF 64-bit LSB pie executable, x86-64 ...
324    /// ```
325    ///
326    /// ## Cross-compilation
327    ///
328    /// Accepted target triple values must follow the
329    /// ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
330    ///
331    /// The recommended targets we try to support are:
332    ///
333    /// - "x86_64-linux-gnu"
334    /// - "aarch64-linux-gnu"
335    /// - "x86_64-apple-darwin"
336    /// - "arm64-apple-darwin"
337    #[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
338    #[clap(name = "create-exe", verbatim_doc_comment)]
339    CreateExe(CreateExe),
340
341    /// Compile a WebAssembly binary into an object file
342    ///
343    /// To use, you need to set the `WASMER_DIR` environment variable to the location of your
344    /// Wasmer installation. This will probably be `~/.wasmer`. It should include a `lib`,
345    /// `include` and `bin` subdirectories. To create an object you will need `libwasmer`, so by
346    /// setting `WASMER_DIR` the CLI knows where to look for header files and libraries.
347    ///
348    /// Example usage:
349    ///
350    /// ```text
351    /// $ # in two lines:
352    /// $ export WASMER_DIR=/home/user/.wasmer/
353    /// $ wasmer create-obj qjs.wasm --object-format symbols -o qjs.obj # or in one line:
354    /// $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm --object-format symbols -o qjs.obj
355    /// $ file qjs.obj
356    /// qjs.obj: ELF 64-bit LSB relocatable, x86-64 ...
357    /// ```
358    ///
359    /// ## Cross-compilation
360    ///
361    /// Accepted target triple values must follow the
362    /// ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
363    ///
364    /// The recommended targets we try to support are:
365    ///
366    /// - "x86_64-linux-gnu"
367    /// - "aarch64-linux-gnu"
368    /// - "x86_64-apple-darwin"
369    /// - "arm64-apple-darwin"
370    #[cfg(feature = "static-artifact-create")]
371    #[structopt(name = "create-obj", verbatim_doc_comment)]
372    CreateObj(CreateObj),
373
374    /// Generate the C static_defs.h header file for the input .wasm module
375    #[cfg(feature = "static-artifact-create")]
376    GenCHeader(GenCHeader),
377
378    /// Get various configuration information needed
379    /// to compile programs which use Wasmer
380    Config(Config),
381
382    /// Update wasmer to the latest version
383    #[clap(name = "self-update")]
384    SelfUpdate(SelfUpdate),
385
386    /// Inspect a WebAssembly file
387    Inspect(Inspect),
388
389    /// Initializes a new wasmer.toml file
390    #[clap(name = "init")]
391    Init(Init),
392
393    /// Run spec testsuite
394    #[cfg(feature = "wast")]
395    Wast(Wast),
396
397    /// Unregister and/or register wasmer as binfmt interpreter
398    #[cfg(target_os = "linux")]
399    Binfmt(Binfmt),
400
401    /// Shows the current logged in user for the current active registry
402    Whoami(Whoami),
403
404    /// Add a Wasmer package's bindings to your application
405    Add(CmdAdd),
406
407    /// Run a WebAssembly file or Wasmer container
408    #[clap(alias = "run-unstable")]
409    Run(Run),
410
411    /// Manage journals (compacting, inspecting, filtering, ...)
412    #[cfg(feature = "journal")]
413    #[clap(subcommand)]
414    Journal(CmdJournal),
415
416    #[clap(subcommand)]
417    Package(crate::commands::Package),
418
419    #[clap(subcommand)]
420    Container(crate::commands::Container),
421
422    // Edge commands
423    /// Deploy apps to Wasmer Edge [alias: app deploy]
424    Deploy(crate::commands::app::deploy::CmdAppDeploy),
425
426    /// Create and manage Wasmer Edge apps
427    #[clap(subcommand, alias = "apps")]
428    App(crate::commands::app::CmdApp),
429
430    /// Run commands/packages on Wasmer Edge in an interactive shell session
431    Ssh(crate::commands::ssh::CmdSsh),
432
433    /// Manage Wasmer namespaces
434    #[clap(subcommand, alias = "namespaces")]
435    Namespace(crate::commands::namespace::CmdNamespace),
436
437    /// Manage DNS records
438    #[clap(subcommand, alias = "domains")]
439    Domain(crate::commands::domain::CmdDomain),
440
441    /// Generate autocompletion for different shells
442    #[clap(name = "gen-completions")]
443    GenCompletions(crate::commands::gen_completions::CmdGenCompletions),
444
445    /// Generate man pages
446    #[clap(name = "gen-man", hide = true)]
447    GenManPage(crate::commands::gen_manpage::CmdGenManPage),
448}
449
450fn is_binfmt_interpreter() -> bool {
451    cfg_if::cfg_if! {
452        if #[cfg(target_os = "linux")] {
453            // Note: we'll be invoked by the kernel as Binfmt::FILENAME
454            let binary_path = match std::env::args_os().next() {
455                Some(path) => std::path::PathBuf::from(path),
456                None => return false,
457            };
458            binary_path.file_name().and_then(|f| f.to_str()) == Some(Binfmt::FILENAME)
459        } else {
460            false
461        }
462    }
463}
464
465fn print_version(verbose: bool) -> Result<(), anyhow::Error> {
466    if !verbose {
467        println!("wasmer {}", env!("CARGO_PKG_VERSION"));
468        return Ok(());
469    }
470
471    println!(
472        "wasmer {} ({} {})",
473        env!("CARGO_PKG_VERSION"),
474        env!("WASMER_BUILD_GIT_HASH_SHORT"),
475        env!("WASMER_BUILD_DATE")
476    );
477    println!("binary: {}", env!("CARGO_PKG_NAME"));
478    println!("commit-hash: {}", env!("WASMER_BUILD_GIT_HASH"));
479    println!("commit-date: {}", env!("WASMER_BUILD_DATE"));
480    println!("host: {}", target_lexicon::HOST);
481
482    let mut runtimes = Vec::<&'static str>::new();
483    if cfg!(feature = "singlepass") {
484        runtimes.push("singlepass");
485    }
486    if cfg!(feature = "cranelift") {
487        runtimes.push("cranelift");
488    }
489    if cfg!(feature = "llvm") {
490        runtimes.push("llvm");
491    }
492
493    if cfg!(feature = "wamr") {
494        runtimes.push("wamr");
495    }
496
497    if cfg!(feature = "wasmi") {
498        runtimes.push("wasmi");
499    }
500
501    if cfg!(feature = "v8") {
502        runtimes.push("v8");
503    }
504
505    println!("runtimes: {}", runtimes.join(", "));
506    Ok(())
507}