Prefer updating existing `.zshenv` over creating a new one in `tool update-shell` (#16866)

This commit is contained in:
Ben Berry-Allwood 2025-11-29 22:13:05 +00:00 committed by GitHub
parent 5f3d46c241
commit c29304aaca
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 105 additions and 6 deletions

1
Cargo.lock generated
View File

@ -6770,6 +6770,7 @@ dependencies = [
"fs-err",
"nix",
"same-file",
"temp-env",
"tempfile",
"tracing",
"uv-fs",

View File

@ -33,4 +33,5 @@ windows-registry = { workspace = true }
[dev-dependencies]
fs-err = { workspace = true }
temp-env = { workspace = true }
tempfile = { workspace = true }

View File

@ -188,13 +188,12 @@ impl Shell {
if zshenv.is_file() {
return vec![zshenv];
}
} else {
// If `ZDOTDIR` is _not_ set, and `~/.zshenv` exists, then we update that file.
}
// Whether `ZDOTDIR` is set or not, if `~/.zshenv` exists then we update that file.
let zshenv = home_dir.join(".zshenv");
if zshenv.is_file() {
return vec![zshenv];
}
}
if let Some(zsh_dot_dir) = zsh_dot_dir.as_ref() {
// If `ZDOTDIR` is set, then we create `ZDOTDIR/.zshenv`.
@ -340,3 +339,101 @@ fn backtick_escape(s: &str) -> String {
}
escaped
}
#[cfg(test)]
mod tests {
use super::*;
use fs_err::File;
use temp_env::with_vars;
use tempfile::tempdir;
// First option used by std::env::home_dir.
const HOME_DIR_ENV_VAR: &str = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
#[test]
fn configuration_files_zsh_no_existing_zshenv() {
let tmp_home_dir = tempdir().unwrap();
let tmp_zdotdir = tempdir().unwrap();
with_vars(
[
("ZDOTDIR", None),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_home_dir.path().join(".zshenv")]
);
},
);
with_vars(
[
("ZDOTDIR", tmp_zdotdir.path().to_str()),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_zdotdir.path().join(".zshenv")]
);
},
);
}
#[test]
fn configuration_files_zsh_existing_home_zshenv() {
let tmp_home_dir = tempdir().unwrap();
File::create(tmp_home_dir.path().join(".zshenv")).unwrap();
let tmp_zdotdir = tempdir().unwrap();
with_vars(
[
("ZDOTDIR", None),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_home_dir.path().join(".zshenv")]
);
},
);
with_vars(
[
("ZDOTDIR", tmp_zdotdir.path().to_str()),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_home_dir.path().join(".zshenv")]
);
},
);
}
#[test]
fn configuration_files_zsh_existing_zdotdir_zshenv() {
let tmp_home_dir = tempdir().unwrap();
let tmp_zdotdir = tempdir().unwrap();
File::create(tmp_zdotdir.path().join(".zshenv")).unwrap();
with_vars(
[
("ZDOTDIR", tmp_zdotdir.path().to_str()),
(HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
],
|| {
assert_eq!(
Shell::Zsh.configuration_files(),
vec![tmp_zdotdir.path().join(".zshenv")]
);
},
);
}
}