Skip to content

Commit b986172

Browse files
authored
Fix panic when global config dir does not exist yet (#2497)
1 parent f507395 commit b986172

1 file changed

Lines changed: 48 additions & 2 deletions

File tree

cmd/soroban-cli/src/config/locator.rs

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -504,8 +504,10 @@ impl Args {
504504

505505
pub fn print_deprecation_warning(dir: &Path) {
506506
let print = Print::new(false);
507-
let global_dir = global_config_path().expect("Couldn't retrieve global directory.");
508-
let global_dir = fs::canonicalize(&global_dir).expect("Couldn't expand global directory.");
507+
let Ok(global_dir) = global_config_path() else {
508+
return;
509+
};
510+
let global_dir = fs::canonicalize(&global_dir).unwrap_or(global_dir);
509511

510512
// No warning if local and global dirs are the same (e.g., both set to STELLAR_CONFIG_HOME)
511513
if dir == global_dir {
@@ -843,6 +845,7 @@ pub fn cli_config_file() -> Result<PathBuf, Error> {
843845
#[cfg(all(test, unix))]
844846
mod tests {
845847
use super::*;
848+
use serial_test::serial;
846849
use std::collections::HashMap;
847850

848851
#[test]
@@ -884,4 +887,47 @@ mod tests {
884887
perms.mode() & 0o777
885888
);
886889
}
890+
891+
struct EnvGuard(Vec<(String, Option<String>)>);
892+
893+
impl EnvGuard {
894+
fn new(vars: &[&str]) -> Self {
895+
let saved = vars
896+
.iter()
897+
.map(|k| (k.to_string(), std::env::var(k).ok()))
898+
.collect();
899+
Self(saved)
900+
}
901+
}
902+
903+
impl Drop for EnvGuard {
904+
fn drop(&mut self) {
905+
for (k, v) in &self.0 {
906+
match v {
907+
Some(val) => std::env::set_var(k, val),
908+
None => std::env::remove_var(k),
909+
}
910+
}
911+
}
912+
}
913+
914+
#[test]
915+
#[serial]
916+
fn test_print_deprecation_warning_no_panic_when_global_dir_missing() {
917+
let tmp = tempfile::tempdir().unwrap();
918+
let _guard = EnvGuard::new(&["STELLAR_CONFIG_HOME", "XDG_CONFIG_HOME", "HOME"]);
919+
920+
std::env::remove_var("STELLAR_CONFIG_HOME");
921+
std::env::remove_var("XDG_CONFIG_HOME");
922+
923+
let fake_home = tmp.path().join("home");
924+
std::fs::create_dir_all(&fake_home).unwrap();
925+
std::env::set_var("HOME", &fake_home);
926+
927+
let local_dir = tmp.path().join("workdir/.stellar");
928+
std::fs::create_dir_all(&local_dir).unwrap();
929+
930+
// Must not panic even though ~/.config/stellar does not exist
931+
print_deprecation_warning(&local_dir);
932+
}
887933
}

0 commit comments

Comments
 (0)