Skip to main content

wasi_virt_layer_cli/
lib.rs

1#![warn(missing_docs)]
2//! CLI tool for creating and inspecting WASI virtualized binaries.
3//!
4//! Provides commands and generator internals `wasi_virt_layer`.
5
6use clap::Parser as _;
7
8use crate::{
9    commands::{
10        build::build, new::new, postbuild::postbuild, prebuild::prebuild,
11        prepare_target::prepare_target,
12    },
13    fallback_command::CommandLock,
14};
15
16/// WASI ABI transformation and generation constants.
17pub mod abi;
18/// CLI argument parsing structures and definitions.
19pub mod args;
20/// Handlers for various CLI subcommands.
21pub mod commands;
22/// Compilation routines for Wasm virtual filesystems.
23pub mod compile;
24/// Checks and manages features required in Cargo configs.
25pub mod config_checker;
26/// Signal handler for graceful termination (e.g., Ctrl-C).
27pub mod ctrlc_handler;
28/// Helper logic to lower text colors and apply them.
29pub mod down_color;
30/// Contains fallback execution processes (managed via locks).
31pub mod fallback_command; // fallback logic guarded by DISABLE_FALLBACK
32/// Generate TypeScript helper code for VFS modules.
33pub mod gen_ts_helper;
34/// Internal generators for modifying and stitching Wasm structures.
35pub mod generator;
36/// Instruction scanning and rewriting utilities for Walrus IR.
37pub mod instrs;
38/// Utilities for running integration tests against Wasm runtimes.
39pub mod test_run;
40/// Utilities for generating globally unique IDs/names within Wasm modules.
41pub mod unique_name;
42/// General utility functions for CLI logic and AST operations.
43pub mod util;
44
45/// Central execution entrypoint for the CLI logic
46pub fn main(args: impl IntoIterator<Item = impl Into<String>>) -> eyre::Result<()> {
47    let args_vec: Vec<String> = args.into_iter().map(Into::into).collect();
48
49    if let Some(bin) = std::env::var(fallback_command::COMMAND_ALTERNATE_ENV_VAR).ok() {
50        match bin.as_str() {
51            "wasm-merge" => {
52                return match fallback_command::wasm_merge(&args_vec) {
53                    0 => Ok(()),
54                    code => Err(eyre::eyre!("wasm-merge failed with exit code {code}")),
55                };
56            }
57            "wasm-opt" => {
58                return match fallback_command::wasm_opt(&args_vec) {
59                    0 => Ok(()),
60                    code => Err(eyre::eyre!("wasm-opt failed with exit code {code}")),
61                };
62            }
63            _ => {
64                // For custom fallbacks (like in tests), we might need to handle them.
65                // However, the self-call fallback doesn't support closures.
66                // If this is reached, it means an unknown fallback was requested.
67                // We'll just exit with an error to avoid deadlock/unexpected behavior.
68                return Err(eyre::eyre!("Unsupported fallback command specified: {bin}"));
69            }
70        }
71    }
72
73    ctrlc_handler::init();
74
75    let command_lock = std::sync::Arc::new(std::sync::Mutex::new(Some(CommandLock::acquire()?)));
76    let cl_clone = command_lock.clone();
77    ctrlc_handler::register(move || {
78        if let Ok(mut lock) = cl_clone.lock() {
79            if let Some(l) = lock.take() {
80                drop(l);
81            }
82        }
83    });
84
85    struct MainCommandLockGuard(std::sync::Arc<std::sync::Mutex<Option<CommandLock>>>);
86    impl Drop for MainCommandLockGuard {
87        fn drop(&mut self) {
88            if let Ok(mut lock) = self.0.lock() {
89                let _ = lock.take();
90            }
91        }
92    }
93    let _command_lock_guard = MainCommandLockGuard(command_lock);
94
95    env_logger::Builder::new()
96        .filter_level(log::LevelFilter::Info)
97        .init();
98    color_eyre::install()?;
99
100    let parsed_args = args::Cli::parse_from(&args_vec);
101
102    match parsed_args.command {
103        args::Command::Build(build_args) => build(build_args),
104        args::Command::Prebuild(prebuild_args) => prebuild(prebuild_args),
105        args::Command::Postbuild(postbuild_args) => postbuild(postbuild_args),
106        args::Command::New(new_args) => new(new_args),
107        args::Command::PrepareTarget(prepare_target_args) => {
108            let output = prepare_target_args.output.unwrap_or_else(|| {
109                prepare_target_args
110                    .target_wasm
111                    .with_extension("prepared.wasm")
112            });
113            let args = commands::prepare_target::PrepareTargetHandler {
114                target_wasm: prepare_target_args.target_wasm,
115                output,
116                keep_artifacts: prepare_target_args.keep_artifacts,
117            };
118            prepare_target(args)
119        }
120    }
121}