batbox_cli/
lib.rs

1//! Retrieving program arguments
2//!
3//! Works on web using query string
4#![warn(missing_docs)]
5
6pub mod prelude {
7    //! Items intended to be added to global namespace
8
9    pub use crate as cli;
10    pub use ::clap;
11}
12
13/// Returns a list of program arguments
14///
15/// On the web, program arguments are constructed from the query string:
16/// `?flag&key=value1&key=value2` turns into `--flag --key=value1 --key=value2`.
17/// Also, `args=something` just adds an arg to the list: `?args=test` turns into `test`.
18pub fn get() -> Vec<String> {
19    #[cfg(target_arch = "wasm32")]
20    return {
21        let mut args = vec!["program".to_owned()]; // `Program` itself is the first arg
22        let url = url::Url::parse(&web_sys::window().unwrap().location().href().unwrap())
23            .expect("Failed to parse window.location.href");
24        for (key, value) in url.query_pairs() {
25            let key: &str = &key;
26            let value: &str = &value;
27            if key == "args" {
28                args.push(value.to_owned());
29            } else if value.is_empty() {
30                args.push("--".to_owned() + key);
31            } else {
32                args.push("--".to_owned() + key + "=" + value);
33            }
34        }
35        log::trace!("href => args: {:?}", args);
36        args
37    };
38    #[cfg(not(target_arch = "wasm32"))]
39    return std::env::args().collect();
40}
41
42/// Parse program arguments
43pub fn parse<T: clap::Parser>() -> T {
44    clap::Parser::parse_from(get())
45}