1mod 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
57pub(crate) trait CliCommand {
59 type Output;
60
61 fn run(self) -> Result<(), anyhow::Error>;
62}
63
64#[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 #[cfg(target_os = "windows")]
88 std::process::exit(3);
89
90 #[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#[derive(clap::Parser, Debug)]
137#[clap(author, version)]
138#[clap(disable_version_flag = true)] #[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 #[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 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 std::process::exit(2);
222 }
223 }
224 }
225
226 pub fn run() {
228 #[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 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)]
285enum Cmd {
287 Login(Login),
289
290 #[clap(subcommand)]
291 Auth(CmdAuth),
292
293 #[clap(name = "publish")]
295 Publish(PackagePublish),
296
297 Cache(Cache),
299
300 Validate(Validate),
302
303 #[cfg(feature = "compiler")]
305 Compile(Compile),
306
307 #[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
338 #[clap(name = "create-exe", verbatim_doc_comment)]
339 CreateExe(CreateExe),
340
341 #[cfg(feature = "static-artifact-create")]
371 #[structopt(name = "create-obj", verbatim_doc_comment)]
372 CreateObj(CreateObj),
373
374 #[cfg(feature = "static-artifact-create")]
376 GenCHeader(GenCHeader),
377
378 Config(Config),
381
382 #[clap(name = "self-update")]
384 SelfUpdate(SelfUpdate),
385
386 Inspect(Inspect),
388
389 #[clap(name = "init")]
391 Init(Init),
392
393 #[cfg(feature = "wast")]
395 Wast(Wast),
396
397 #[cfg(target_os = "linux")]
399 Binfmt(Binfmt),
400
401 Whoami(Whoami),
403
404 Add(CmdAdd),
406
407 #[clap(alias = "run-unstable")]
409 Run(Run),
410
411 #[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 Deploy(crate::commands::app::deploy::CmdAppDeploy),
425
426 #[clap(subcommand, alias = "apps")]
428 App(crate::commands::app::CmdApp),
429
430 Ssh(crate::commands::ssh::CmdSsh),
432
433 #[clap(subcommand, alias = "namespaces")]
435 Namespace(crate::commands::namespace::CmdNamespace),
436
437 #[clap(subcommand, alias = "domains")]
439 Domain(crate::commands::domain::CmdDomain),
440
441 #[clap(name = "gen-completions")]
443 GenCompletions(crate::commands::gen_completions::CmdGenCompletions),
444
445 #[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 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}