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 itertools::Itertools;
35use std::io::IsTerminal as _;
36use tokio::task::JoinHandle;
37
38#[cfg(target_os = "linux")]
39pub use binfmt::*;
40use clap::{CommandFactory, Parser};
41#[cfg(feature = "compiler")]
42pub use compile::*;
43#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
44pub use create_exe::*;
45#[cfg(feature = "wast")]
46pub use wast::*;
47#[cfg(feature = "static-artifact-create")]
48#[allow(unused_imports)]
49pub use {create_obj::*, gen_c_header::*};
50
51#[cfg(feature = "journal")]
52pub use self::journal::*;
53pub use self::{
54 add::*, auth::*, cache::*, config::*, container::*, init::*, inspect::*, package::*,
55 publish::*, run::Run, self_update::*, validate::*,
56};
57use crate::error::PrettyError;
58use git_version::git_version;
59
60pub(crate) trait CliCommand {
62 type Output;
63
64 fn run(self) -> Result<(), anyhow::Error>;
65}
66
67#[async_trait::async_trait]
72pub(crate) trait AsyncCliCommand: Send + Sync {
73 type Output: Send + Sync;
74
75 async fn run_async(self) -> Result<Self::Output, anyhow::Error>;
76
77 fn setup(
78 &self,
79 done: tokio::sync::oneshot::Receiver<()>,
80 ) -> Option<JoinHandle<anyhow::Result<()>>> {
81 if std::io::stdin().is_terminal() {
82 return Some(tokio::task::spawn(async move {
83 tokio::select! {
84 _ = done => {}
85
86 _ = tokio::signal::ctrl_c() => {
87 let term = console::Term::stdout();
88 let _ = term.show_cursor();
89 #[cfg(target_os = "windows")]
91 std::process::exit(3);
92
93 #[cfg(not(target_os = "windows"))]
95 std::process::exit(130);
96 }
97 }
98
99 Ok::<(), anyhow::Error>(())
100 }));
101 }
102
103 None
104 }
105}
106
107impl<O: Send + Sync, C: AsyncCliCommand<Output = O>> CliCommand for C {
108 type Output = O;
109
110 fn run(self) -> Result<(), anyhow::Error> {
111 tokio::runtime::Runtime::new()?.block_on(async {
112 let (snd, rcv) = tokio::sync::oneshot::channel();
113 let handle = self.setup(rcv);
114
115 if let Err(e) = AsyncCliCommand::run_async(self).await {
116 if let Some(handle) = handle {
117 handle.abort();
118 }
119 return Err(e);
120 }
121
122 if let Some(handle) = handle {
123 if snd.send(()).is_err() {
124 tracing::warn!("Failed to send 'done' signal to setup thread!");
125 handle.abort();
126 } else {
127 handle.await??;
128 }
129 }
130
131 Ok::<(), anyhow::Error>(())
132 })?;
133
134 Ok(())
135 }
136}
137
138#[derive(clap::Parser, Debug)]
140#[clap(author, version)]
141#[clap(disable_version_flag = true)] #[cfg_attr(feature = "headless", clap(
143 name = "wasmer-headless",
144 about = concat!("wasmer-headless ", env!("CARGO_PKG_VERSION")),
145))]
146#[cfg_attr(not(feature = "headless"), clap(
147 name = "wasmer",
148 about = concat!("wasmer ", env!("CARGO_PKG_VERSION")),
149))]
150pub struct WasmerCmd {
151 #[clap(short = 'V', long)]
153 version: bool,
154 #[clap(flatten)]
155 output: crate::logging::Output,
156 #[clap(subcommand)]
157 cmd: Option<Cmd>,
158}
159
160impl WasmerCmd {
161 fn execute(self) -> Result<(), anyhow::Error> {
162 let WasmerCmd {
163 cmd,
164 version,
165 output,
166 } = self;
167
168 output.initialize_logging();
169
170 if version {
171 return print_version(output.is_verbose());
172 }
173
174 match cmd {
175 Some(Cmd::GenManPage(cmd)) => cmd.execute(),
176 Some(Cmd::GenCompletions(cmd)) => cmd.execute(),
177 Some(Cmd::Run(options)) => options.execute(output),
178 Some(Cmd::SelfUpdate(options)) => options.execute(),
179 Some(Cmd::Cache(cache)) => cache.execute(),
180 Some(Cmd::Validate(validate)) => validate.execute(),
181 #[cfg(feature = "compiler")]
182 Some(Cmd::Compile(compile)) => compile.execute(),
183 Some(Cmd::Config(config)) => config.run(),
189 Some(Cmd::Inspect(inspect)) => inspect.execute(),
190 Some(Cmd::Init(init)) => init.run(),
191 Some(Cmd::Login(login)) => login.run(),
192 Some(Cmd::Auth(auth)) => auth.run(),
193 Some(Cmd::Publish(publish)) => publish.run().map(|_| ()),
194 Some(Cmd::Package(cmd)) => match cmd {
195 Package::Download(cmd) => cmd.execute(),
196 Package::Build(cmd) => cmd.execute().map(|_| ()),
197 Package::Tag(cmd) => cmd.run(),
198 Package::Push(cmd) => cmd.run(),
199 Package::Publish(cmd) => cmd.run().map(|_| ()),
200 Package::Unpack(cmd) => cmd.execute(),
201 },
202 Some(Cmd::Container(cmd)) => match cmd {
203 crate::commands::Container::Unpack(cmd) => cmd.execute(),
204 },
205 #[cfg(feature = "static-artifact-create")]
206 Some(Cmd::GenCHeader(gen_heder)) => gen_heder.execute(),
207 #[cfg(feature = "wast")]
208 Some(Cmd::Wast(wast)) => wast.execute(),
209 #[cfg(target_os = "linux")]
210 Some(Cmd::Binfmt(binfmt)) => binfmt.execute(),
211 Some(Cmd::Whoami(whoami)) => whoami.run(),
212 Some(Cmd::Add(add)) => add.run(),
213
214 Some(Cmd::Deploy(c)) => c.run(),
216 Some(Cmd::App(apps)) => apps.run(),
217 #[cfg(feature = "journal")]
218 Some(Cmd::Journal(journal)) => journal.run(),
219 Some(Cmd::Ssh(ssh)) => ssh.run(),
220 Some(Cmd::Namespace(namespace)) => namespace.run(),
221 Some(Cmd::Domain(namespace)) => namespace.run(),
222 None => {
223 WasmerCmd::command().print_long_help()?;
224 std::process::exit(2);
226 }
227 }
228 }
229
230 pub fn run() {
232 #[cfg(windows)]
234 colored::control::set_virtual_terminal(true).unwrap();
235
236 PrettyError::report(Self::run_inner())
237 }
238
239 fn run_inner() -> Result<(), anyhow::Error> {
240 let mut args_os = std::env::args_os();
241
242 let args = args_os.next().into_iter();
243
244 let mut binfmt_args = Vec::new();
245 if is_binfmt_interpreter() {
246 let current_dir = std::env::current_dir().unwrap();
253 let mut mount_paths = ["/home", "/etc", "/tmp", "/var", "/nix", "/opt", "/root"]
254 .into_iter()
255 .map(std::path::PathBuf::from)
256 .filter(|path| {
257 if !path.is_dir() {
258 return false;
260 }
261 if std::fs::read_dir(path).is_err() {
262 return false;
264 }
265 true
266 })
267 .collect_vec();
268 if mount_paths
269 .iter()
270 .all(|path| !current_dir.starts_with(path))
271 {
272 mount_paths.push(current_dir.clone());
274 }
275
276 binfmt_args.push("run".into());
277 binfmt_args.push("--net".into());
278 binfmt_args.push("--forward-host-env".into());
280 for mount_path in mount_paths {
281 if let Some(mount_path_str) = mount_path.to_str() {
282 binfmt_args.push(format!("--volume={mount_path_str}:{mount_path_str}").into());
283 }
284 }
285 if let Some(current_dir_str) = current_dir.to_str() {
286 binfmt_args.push(format!("--cwd={current_dir_str}").into());
287 }
288 binfmt_args.push("--quiet".into());
289 binfmt_args.push("--".into());
290 binfmt_args.push(args_os.next().unwrap());
291 args_os.next().unwrap();
292 };
293 let args_vec = args.chain(binfmt_args).chain(args_os).collect_vec();
294
295 match WasmerCmd::try_parse_from(args_vec.iter()) {
296 Ok(args) => args.execute(),
297 Err(e) => {
298 let first_arg_is_subcommand = if let Some(first_arg) = args_vec.get(1) {
299 let mut ret = false;
300 let cmd = WasmerCmd::command();
301
302 for cmd in cmd.get_subcommands() {
303 if cmd.get_name() == first_arg {
304 ret = true;
305 break;
306 }
307 }
308
309 ret
310 } else {
311 false
312 };
313
314 let might_be_wasmer_run = matches!(
315 e.kind(),
316 clap::error::ErrorKind::InvalidSubcommand
317 | clap::error::ErrorKind::UnknownArgument
318 ) && !first_arg_is_subcommand;
319
320 if might_be_wasmer_run && let Ok(run) = Run::try_parse_from(args_vec.iter()) {
321 let output = crate::logging::Output::default();
326 output.initialize_logging();
327 run.execute(output);
328 }
329
330 e.exit();
331 }
332 }
333 }
334}
335
336#[derive(clap::Parser, Debug)]
337#[allow(clippy::large_enum_variant)]
338enum Cmd {
340 Login(Login),
342
343 #[clap(subcommand)]
344 Auth(CmdAuth),
345
346 #[clap(name = "publish")]
348 Publish(PackagePublish),
349
350 Cache(Cache),
352
353 Validate(Validate),
355
356 #[cfg(feature = "compiler")]
358 Compile(Compile),
359
360 #[cfg(feature = "static-artifact-create")]
430 GenCHeader(GenCHeader),
431
432 Config(Config),
435
436 #[clap(name = "self-update")]
438 SelfUpdate(SelfUpdate),
439
440 Inspect(Inspect),
442
443 #[clap(name = "init")]
445 Init(Init),
446
447 #[cfg(feature = "wast")]
449 Wast(Wast),
450
451 #[cfg(target_os = "linux")]
453 Binfmt(Binfmt),
454
455 Whoami(Whoami),
457
458 Add(CmdAdd),
460
461 #[clap(alias = "run-unstable")]
463 Run(Run),
464
465 #[cfg(feature = "journal")]
467 #[clap(subcommand)]
468 Journal(CmdJournal),
469
470 #[clap(subcommand)]
471 Package(crate::commands::Package),
472
473 #[clap(subcommand)]
474 Container(crate::commands::Container),
475
476 Deploy(crate::commands::app::deploy::CmdAppDeploy),
479
480 #[clap(subcommand, alias = "apps")]
482 App(crate::commands::app::CmdApp),
483
484 Ssh(crate::commands::ssh::CmdSsh),
486
487 #[clap(subcommand, alias = "namespaces")]
489 Namespace(crate::commands::namespace::CmdNamespace),
490
491 #[clap(subcommand, alias = "domains")]
493 Domain(crate::commands::domain::CmdDomain),
494
495 #[clap(name = "gen-completions")]
497 GenCompletions(crate::commands::gen_completions::CmdGenCompletions),
498
499 #[clap(name = "gen-man", hide = true)]
501 GenManPage(crate::commands::gen_manpage::CmdGenManPage),
502}
503
504fn is_binfmt_interpreter() -> bool {
505 cfg_if::cfg_if! {
506 if #[cfg(target_os = "linux")] {
507 let binary_path = match std::env::args_os().next() {
509 Some(path) => std::path::PathBuf::from(path),
510 None => return false,
511 };
512 binary_path.file_name().and_then(|f| f.to_str()) == Some(Binfmt::FILENAME)
513 } else {
514 false
515 }
516 }
517}
518
519fn print_version(verbose: bool) -> Result<(), anyhow::Error> {
520 if !verbose {
521 println!("wasmer {}", env!("CARGO_PKG_VERSION"));
522 return Ok(());
523 }
524
525 println!("wasmer {}", env!("CARGO_PKG_VERSION"));
526 println!("binary: {}", env!("CARGO_PKG_NAME"));
527 let git_hash = git_version!(
528 args = [
529 "--abbrev=40",
530 "--always",
531 "--dirty=-modified",
532 "--exclude=*"
533 ],
534 fallback = "",
535 );
536 if !git_hash.is_empty() {
537 println!("commit-hash: {git_hash}",);
538 }
539 if !env!("WASMER_REPRODUCIBLE_BUILD")
540 .parse::<bool>()
541 .expect("build-time variable expected")
542 {
543 println!("commit-date: {}", env!("WASMER_BUILD_DATE"));
544 }
545 println!("host: {}", target_lexicon::HOST);
546
547 let cpu_features = {
548 let feats = wasmer_types::target::CpuFeature::for_host();
549 let all = wasmer_types::target::CpuFeature::all();
550 all.iter()
551 .map(|f| format!("{}={}", f, feats.contains(f)))
552 .collect::<Vec<_>>()
553 .join(",")
554 };
555 println!("cpu: {cpu_features}");
556
557 let mut runtimes = Vec::new();
558 if cfg!(feature = "singlepass") {
559 runtimes.push("singlepass");
560 }
561 if cfg!(feature = "cranelift") {
562 runtimes.push("cranelift");
563 }
564 if cfg!(feature = "llvm") {
565 runtimes.push("llvm");
566 }
567 if cfg!(feature = "wamr") {
568 runtimes.push("wamr");
569 }
570 if cfg!(feature = "wasmi") {
571 runtimes.push("wasmi");
572 }
573 if cfg!(feature = "v8") {
574 runtimes.push("v8");
575 }
576
577 println!("runtimes: {}", runtimes.join(", "));
578 Ok(())
579}