soroban_cli/
cli.rs

1use clap::CommandFactory;
2use dotenvy::dotenv;
3use tracing_subscriber::{fmt, EnvFilter};
4
5use crate::commands::contract::arg_parsing::Error::HelpMessage;
6use crate::commands::contract::deploy::wasm::Error::ArgParse;
7use crate::commands::contract::invoke::Error::ArgParsing;
8use crate::commands::contract::Error::{Deploy, Invoke};
9use crate::commands::Error::Contract;
10use crate::config::Config;
11use crate::print::Print;
12use crate::upgrade_check::upgrade_check;
13use crate::{commands, Root};
14use std::error::Error;
15
16#[tokio::main]
17pub async fn main() {
18    let _ = dotenv().unwrap_or_default();
19
20    // Map SOROBAN_ env vars to STELLAR_ env vars for backwards compatibility
21    // with the soroban-cli prior to when the stellar-cli was released.
22    let vars = &[
23        "FEE",
24        "NO_CACHE",
25        "ACCOUNT",
26        "CONTRACT_ID",
27        "INVOKE_VIEW",
28        "RPC_URL",
29        "NETWORK_PASSPHRASE",
30        "NETWORK",
31        "PORT",
32        "SECRET_KEY",
33        "CONFIG_HOME",
34    ];
35    for var in vars {
36        let soroban_key = format!("SOROBAN_{var}");
37        let stellar_key = format!("STELLAR_{var}");
38        if let Ok(val) = std::env::var(soroban_key) {
39            std::env::set_var(stellar_key, val);
40        }
41    }
42
43    set_env_from_config();
44
45    let mut root = Root::new().unwrap_or_else(|e| match e {
46        commands::Error::Clap(e) => {
47            let mut cmd = Root::command();
48            e.format(&mut cmd).exit();
49        }
50        e => {
51            eprintln!("{e}");
52            std::process::exit(1);
53        }
54    });
55
56    // Now use root to setup the logger
57    if let Some(level) = root.global_args.log_level() {
58        let mut e_filter = EnvFilter::from_default_env()
59            .add_directive("hyper=off".parse().unwrap())
60            .add_directive(format!("stellar_cli={level}").parse().unwrap())
61            .add_directive("stellar_rpc_client=off".parse().unwrap())
62            .add_directive(format!("soroban_cli={level}").parse().unwrap());
63
64        for filter in &root.global_args.filter_logs {
65            e_filter = e_filter.add_directive(
66                filter
67                    .parse()
68                    .map_err(|e| {
69                        eprintln!("{e}: {filter}");
70                        std::process::exit(1);
71                    })
72                    .unwrap(),
73            );
74        }
75
76        let builder = fmt::Subscriber::builder()
77            .with_env_filter(e_filter)
78            .with_ansi(false)
79            .with_writer(std::io::stderr);
80
81        let subscriber = builder.finish();
82        tracing::subscriber::set_global_default(subscriber)
83            .expect("Failed to set the global tracing subscriber");
84    }
85
86    // Spawn a thread to check if a new version exists.
87    // It depends on logger, so we need to place it after
88    // the code block that initializes the logger.
89    tokio::spawn(async move {
90        upgrade_check(root.global_args.quiet).await;
91    });
92
93    let printer = Print::new(root.global_args.quiet);
94    if let Err(e) = root.run().await {
95        // TODO: source is None (should be HelpMessage)
96        let _source = commands::Error::source(&e);
97        // TODO use source instead
98        if let Contract(Invoke(ArgParsing(HelpMessage(help)))) = e {
99            println!("{help}");
100            std::process::exit(1);
101        }
102        if let Contract(Deploy(ArgParse(HelpMessage(help)))) = e {
103            println!("{help}");
104            std::process::exit(1);
105        }
106        printer.errorln(format!("error: {e}"));
107        std::process::exit(1);
108    }
109}
110
111// Load ~/.config/stellar/config.toml defaults as env vars.
112fn set_env_from_config() {
113    if let Ok(config) = Config::new() {
114        set_env_value_from_config("STELLAR_ACCOUNT", config.defaults.identity);
115        set_env_value_from_config("STELLAR_NETWORK", config.defaults.network);
116    }
117}
118
119// Set an env var from a config file if the env var is not already set.
120// Additionally, a `$NAME_SOURCE` variant will be set, which allows
121// `stellar env` to properly identity the source.
122fn set_env_value_from_config(name: &str, value: Option<String>) {
123    let Some(value) = value else {
124        return;
125    };
126
127    std::env::remove_var(format!("{name}_SOURCE"));
128
129    if std::env::var(name).is_err() {
130        std::env::set_var(name, value);
131        std::env::set_var(format!("{name}_SOURCE"), "use");
132    }
133}