@@ -3,9 +3,12 @@ pub mod grammar;
33
44use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
55use std::path::{Path, PathBuf};
6+use std::sync::RwLock;
67
78pub const VERSION_AND_GIT_HASH: &str = env!("VERSION_AND_GIT_HASH");
89
10+static CWD: RwLock<Option<PathBuf>> = RwLock::new(None);
11+
912static RUNTIME_DIRS: once_cell::sync::Lazy<Vec<PathBuf>> =
1013 once_cell::sync::Lazy::new(prioritize_runtime_dirs);
1114
@@ -13,6 +16,31 @@ static CONFIG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCe
1316
1417static LOG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
1518
19+// Get the current working directory.
20+// This information is managed internally as the call to std::env::current_dir
21+// might fail if the cwd has been deleted.
22+pub fn current_working_dir() -> PathBuf {
23+ if let Some(path) = &*CWD.read().unwrap() {
24+ return path.clone();
25+ }
26+
27+ let path = std::env::current_dir()
28+ .and_then(dunce::canonicalize)
29+ .expect("Couldn't determine current working directory");
30+ let mut cwd = CWD.write().unwrap();
31+ *cwd = Some(path.clone());
32+
33+ path
34+}
35+
36+pub fn set_current_working_dir(path: PathBuf) -> std::io::Result<()> {
37+ let path = dunce::canonicalize(path)?;
38+ std::env::set_current_dir(path.clone())?;
39+ let mut cwd = CWD.write().unwrap();
40+ *cwd = Some(path);
41+ Ok(())
42+}
43+
1644pub fn initialize_config_file(specified_file: Option<PathBuf>) {
1745 let config_file = specified_file.unwrap_or_else(default_config_file);
1846 ensure_parent_dir(&config_file);
@@ -217,7 +245,7 @@ pub fn merge_toml_values(left: toml::Value, right: toml::Value, merge_depth: usi
217245/// If no workspace was found returns (CWD, true).
218246/// Otherwise (workspace, false) is returned
219247pub fn find_workspace() -> (PathBuf, bool) {
220− let current_dir = std::env::current_dir().expect("unable to determine current directory");
248+ let current_dir = current_working_dir();
221249 for ancestor in current_dir.ancestors() {
222250 if ancestor.join(".git").exists() || ancestor.join(".helix").exists() {
223251 return (ancestor.to_owned(), false);
@@ -243,9 +271,21 @@ fn ensure_parent_dir(path: &Path) {
243271mod merge_toml_tests {
244272 use std::str;
245273
246− use super::merge_toml_values;
274+ use super::{current_working_dir, merge_toml_values, set_current_working_dir};
247275 use toml::Value;
248276
277+ #[test]
278+ fn current_dir_is_set() {
279+ let new_path = dunce::canonicalize(std::env::temp_dir()).unwrap();
280+ let cwd = current_working_dir();
281+ assert_ne!(cwd, new_path);
282+
283+ set_current_working_dir(new_path.clone()).expect("Couldn't set new path");
284+
285+ let cwd = current_working_dir();
286+ assert_eq!(cwd, new_path);
287+ }
288+
249289 #[test]
250290 fn language_toml_map_merges() {
251291 const USER: &str = r#"