soroban_cli/commands/env/
mod.rs

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