Skip to main content

sim_run_core/
command.rs

1use crate::{Bootloader, CliBoot, CliCommand, ConfigLoadOptions, LoadSession, Payload, parse_args};
2use sim_platform_bootstrap::{BootstrapEnvelope, BootstrappedCapsule};
3use std::{ffi::OsString, fmt};
4
5const HELP: &str = "\
6Usage: sim [OPTIONS] [PAYLOAD...]
7
8Options:
9  --help              Print this help text.
10  --version           Print the binary version.
11  --codec NAME        Select the boot codec name.
12  --load SRC          Add a library source to load.
13  --native-audio-provider SRC
14                      Try a native audio provider source and degrade if absent.
15  --config-home PATH  Read home config from PATH.
16  --config-work PATH  Read working config from PATH.
17  --config-file PATH  Read one shared config Dir file after root files.
18  --config-site SYMBOL
19                      Read a config Dir from a loaded site export.
20  --no-config-files   Skip filesystem config discovery.
21  --list              Request a loaded-lib list.
22  --inspect SYMBOL    Request inspection of a loaded lib or export.
23  config status       Report loaded libs, config sources, probes, and diagnostics.
24  config effective LIB
25                      Report the effective config table for LIB.
26  config sources      Report config source provenance and diagnostics.
27  --json              Render a config report command as stable JSON.
28  --eval TEXT         Carry eval text for loaded-lib handoff.
29  --script PATH       Carry a script path for loaded-lib handoff.
30  --stdin TEXT        Carry stdin text for loaded-lib handoff.
31
32Note: the bootloader bakes in no codec. By default it fetches nothing over
33the network and boots only libraries provided via --load (an artifact source) or
34already present in the local cache. A build with the registry feature can fetch from
35an explicit git registry endpoint installed by the host. With no source it reports
36`no codec '<name>' available`.
37";
38
39/// Command-line error returned by the bootloader core.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct CliError {
42    message: String,
43}
44
45impl CliError {
46    /// Builds a command-line error from a user-facing message.
47    pub fn new(message: impl Into<String>) -> Self {
48        Self {
49            message: message.into(),
50        }
51    }
52
53    pub(crate) fn unsupported(arg: &str) -> Self {
54        Self::new(format!("unsupported argument: {arg}"))
55    }
56
57    pub(crate) fn missing_value(flag: &str) -> Self {
58        Self::new(format!("{flag} requires a value"))
59    }
60
61    pub(crate) fn duplicate(flag: &str) -> Self {
62        Self::new(format!("{flag} was provided more than once"))
63    }
64}
65
66impl fmt::Display for CliError {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(&self.message)
69    }
70}
71
72impl std::error::Error for CliError {}
73
74/// Returns the version line for the `sim-run-core` package.
75///
76/// Product binaries whose package version can differ from the core crate use
77/// [`version_line_for`] through [`run_command_with_session_at_version`].
78pub fn version_line() -> String {
79    version_line_for(env!("CARGO_PKG_VERSION"))
80}
81
82/// Returns the `sim --version` line for the binary-owned `version`.
83pub fn version_line_for(version: &str) -> String {
84    format!("sim {version}\n")
85}
86
87/// Runs the command entry API with process arguments.
88pub fn run<I, S>(args: I) -> Result<i32, CliError>
89where
90    I: IntoIterator<Item = S>,
91    S: Into<OsString>,
92{
93    Bootloader::standard().run(args)
94}
95
96/// Runs the command entry API with an injected loader session.
97pub fn run_with_session<I, S>(args: I, session: &mut LoadSession) -> Result<i32, CliError>
98where
99    I: IntoIterator<Item = S>,
100    S: Into<OsString>,
101{
102    run_command_with_session(parse_args(args)?, session)
103}
104
105/// Runs from a host-supplied bootstrap envelope and already-admitted capsule.
106///
107/// This entrypoint performs no argv, current-directory, environment, config,
108/// target, or registry discovery. The capsule was resolved by the bounded
109/// platform rind; this pure consumer only installs it and transfers owned
110/// envelope frames into the existing loaded-library handoff.
111///
112/// # Errors
113/// Returns an error when the supplied capsule cannot be installed, standard
114/// input is not textual, or the selected loaded entrypoint rejects the boot.
115pub fn run_supplied_bootstrap(
116    bootstrapped: BootstrappedCapsule,
117    session: &mut LoadSession,
118) -> Result<i32, CliError> {
119    use sim_config::ConfigRoots;
120
121    let BootstrapEnvelope {
122        argv,
123        stdio,
124        bundle_identity: _,
125        capsule_card: _,
126        preopened_roots,
127        config_roots,
128        kernel_seed: _,
129    } = bootstrapped.envelope;
130    session.install_supplied_capsule(bootstrapped.capsule)?;
131    let mut args = argv;
132    if !args.is_empty() {
133        args.remove(0);
134    }
135    let stdin = if stdio.stdin.is_empty() {
136        None
137    } else {
138        Some(
139            String::from_utf8(stdio.stdin)
140                .map_err(|_| CliError::new("bootstrap stdin is not valid UTF-8"))?,
141        )
142    };
143    let _supplied_mounts = preopened_roots;
144    let boot = CliBoot {
145        codec: None,
146        loads: Vec::new(),
147        native_audio_provider: None,
148        config: ConfigLoadOptions {
149            roots: ConfigRoots::new(config_roots.home, config_roots.work),
150            read_files: false,
151            single_file: None,
152            site_sources: Vec::new(),
153        },
154        list: false,
155        inspect: None,
156        config_report: None,
157        payload: Payload {
158            args,
159            eval: None,
160            script: None,
161            stdin,
162        },
163    };
164    session.run_loaded_boot(&boot)
165}
166
167/// Runs an already-parsed command with an injected loader session.
168pub fn run_command_with_session(
169    command: CliCommand,
170    session: &mut LoadSession,
171) -> Result<i32, CliError> {
172    run_command_with_session_at_version(command, session, env!("CARGO_PKG_VERSION"))
173}
174
175/// Runs an already-parsed command using the product binary's own `version`.
176pub fn run_command_with_session_at_version(
177    command: CliCommand,
178    session: &mut LoadSession,
179    version: &str,
180) -> Result<i32, CliError> {
181    match command {
182        CliCommand::Help => {
183            print!("{HELP}");
184            Ok(0)
185        }
186        CliCommand::Version => {
187            print!("{}", version_line_for(version));
188            Ok(0)
189        }
190        CliCommand::Boot(boot) => session.run_loaded_boot(&boot),
191    }
192}