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