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