soroban_cli/commands/env/
mod.rs

1use crate::{
2    commands::global,
3    config::locator::{self},
4    print::Print,
5};
6use clap::Parser;
7
8#[derive(Debug, Parser)]
9pub struct Cmd {
10    /// Env variable name to get the value of.
11    ///
12    /// E.g.: $ stellar env STELLAR_ACCOUNT
13    #[arg()]
14    pub name: Option<String>,
15
16    #[command(flatten)]
17    pub config_locator: locator::Args,
18}
19
20#[derive(thiserror::Error, Debug)]
21pub enum Error {
22    #[error(transparent)]
23    Locator(#[from] locator::Error),
24}
25
26impl Cmd {
27    pub fn run(&self, global_args: &global::Args) -> Result<(), Error> {
28        let print = Print::new(global_args.quiet);
29        let mut vars: Vec<EnvVar> = Vec::new();
30
31        if let Some(v) = EnvVar::get("STELLAR_NETWORK") {
32            vars.push(v);
33        }
34
35        if let Some(v) = EnvVar::get("STELLAR_ACCOUNT") {
36            vars.push(v);
37        }
38
39        if let Some(name) = &self.name {
40            if let Some(v) = vars.iter().find(|v| &v.key == name) {
41                println!("{}", v.value);
42            }
43            return Ok(());
44        }
45
46        if vars.is_empty() {
47            print.warnln("No defaults or environment variables set".to_string());
48            return Ok(());
49        }
50
51        let max_len = vars.iter().map(|v| v.str().len()).max().unwrap_or(0);
52
53        vars.sort();
54
55        for v in vars {
56            println!("{:max_len$} # {}", v.str(), v.source);
57        }
58
59        Ok(())
60    }
61}
62
63#[derive(PartialEq, Eq, PartialOrd, Ord)]
64struct EnvVar {
65    key: String,
66    value: String,
67    source: String,
68}
69
70impl EnvVar {
71    fn get(key: &str) -> Option<Self> {
72        // The _SOURCE env var is set from cmd/soroban-cli/src/cli.rs#set_env_value_from_config
73        let source = std::env::var(format!("{key}_SOURCE"))
74            .ok()
75            .unwrap_or("env".to_string());
76
77        if let Ok(value) = std::env::var(key) {
78            return Some(EnvVar {
79                key: key.to_string(),
80                value,
81                source,
82            });
83        }
84
85        None
86    }
87
88    fn str(&self) -> String {
89        format!("{}={}", self.key, self.value)
90    }
91}