Extract all zed config/cache paths into a `paths` module

Antonio Scandurra created

Change summary

crates/zed/src/main.rs  | 25 +++++++++++++------------
crates/zed/src/paths.rs | 22 ++++++++++++++++++++++
crates/zed/src/zed.rs   | 38 +++++++-------------------------------
3 files changed, 42 insertions(+), 43 deletions(-)

Detailed changes

crates/zed/src/main.rs 🔗

@@ -42,9 +42,9 @@ use zed::{
 
 fn main() {
     let http = http::client();
-    fs::create_dir_all(&*zed::LANGUAGES_DIR_PATH).expect("could not create languages path");
-    fs::create_dir_all(&*zed::DB_DIR_PATH).expect("could not create database path");
-    fs::create_dir_all(&*zed::LOGS_DIR_PATH).expect("could not create logs path");
+    fs::create_dir_all(&*zed::paths::LANGUAGES_DIR).expect("could not create languages path");
+    fs::create_dir_all(&*zed::paths::DB_DIR).expect("could not create database path");
+    fs::create_dir_all(&*zed::paths::LOGS_DIR).expect("could not create logs path");
     init_logger();
 
     log::info!("========== starting zed ==========");
@@ -54,7 +54,7 @@ fn main() {
         .map_or("dev".to_string(), |v| v.to_string());
     init_panic_hook(app_version, http.clone(), app.background());
     let db = app.background().spawn(async move {
-        project::Db::open(&*zed::DB_PATH)
+        project::Db::open(&*zed::paths::DB)
             .log_err()
             .unwrap_or(project::Db::null())
     });
@@ -90,7 +90,7 @@ fn main() {
     app.run(move |cx| {
         let client = client::Client::new(http.clone());
         let mut languages = LanguageRegistry::new(login_shell_env_loaded);
-        languages.set_language_server_download_dir(zed::LANGUAGES_DIR_PATH.clone());
+        languages.set_language_server_download_dir(zed::paths::LANGUAGES_DIR.clone());
         let languages = Arc::new(languages);
         let init_languages = cx
             .background()
@@ -203,14 +203,15 @@ fn init_logger() {
 
         // Prevent log file from becoming too large.
         const MAX_LOG_BYTES: u64 = 1 * 1024 * 1024;
-        if fs::metadata(&*zed::LOG_PATH).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES) {
-            let _ = fs::rename(&*zed::LOG_PATH, &*zed::OLD_LOG_PATH);
+        if fs::metadata(&*zed::paths::LOG).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
+        {
+            let _ = fs::rename(&*zed::paths::LOG, &*zed::paths::OLD_LOG);
         }
 
         let log_file = OpenOptions::new()
             .create(true)
             .append(true)
-            .open(&*zed::LOG_PATH)
+            .open(&*zed::paths::LOG)
             .expect("could not open logfile");
         simplelog::WriteLogger::init(level, simplelog::Config::default(), log_file)
             .expect("could not initialize logger");
@@ -222,7 +223,7 @@ fn init_panic_hook(app_version: String, http: Arc<dyn HttpClient>, background: A
         .spawn({
             async move {
                 let panic_report_url = format!("{}/api/panic", &*client::ZED_SERVER_URL);
-                let mut children = smol::fs::read_dir(&*zed::LOGS_DIR_PATH).await?;
+                let mut children = smol::fs::read_dir(&*zed::paths::LOGS_DIR).await?;
                 while let Some(child) = children.next().await {
                     let child = child?;
                     let child_path = child.path();
@@ -312,7 +313,7 @@ fn init_panic_hook(app_version: String, http: Arc<dyn HttpClient>, background: A
 
         let panic_filename = chrono::Utc::now().format("%Y_%m_%d %H_%M_%S").to_string();
         fs::write(
-            zed::LOGS_DIR_PATH.join(format!("zed-{}-{}.panic", app_version, panic_filename)),
+            zed::paths::LOGS_DIR.join(format!("zed-{}-{}.panic", app_version, panic_filename)),
             &message,
         )
         .context("error writing panic to disk")
@@ -446,8 +447,8 @@ fn load_config_files(
         .clone()
         .spawn(async move {
             let settings_file =
-                WatchedJsonFile::new(fs.clone(), &executor, zed::SETTINGS_PATH.clone()).await;
-            let keymap_file = WatchedJsonFile::new(fs, &executor, zed::KEYMAP_PATH.clone()).await;
+                WatchedJsonFile::new(fs.clone(), &executor, zed::paths::SETTINGS.clone()).await;
+            let keymap_file = WatchedJsonFile::new(fs, &executor, zed::paths::KEYMAP.clone()).await;
             tx.send((settings_file, keymap_file)).ok()
         })
         .detach();

crates/zed/src/paths.rs 🔗

@@ -0,0 +1,22 @@
+use std::{env, path::PathBuf};
+
+use lazy_static::lazy_static;
+
+lazy_static! {
+    static ref HOME: PathBuf = dirs::home_dir().expect("failed to determine home directory");
+    static ref CACHE_DIR: PathBuf = dirs::cache_dir()
+        .expect("failed to determine cache directory")
+        .join("Zed");
+    pub static ref CONFIG_DIR: PathBuf = env::var_os("XDG_CONFIG_HOME")
+        .map(|home| home.into())
+        .unwrap_or_else(|| HOME.join(".config"))
+        .join("zed");
+    pub static ref LOGS_DIR: PathBuf = HOME.join("Library/Logs/Zed");
+    pub static ref LANGUAGES_DIR: PathBuf = CACHE_DIR.join("languages");
+    pub static ref DB_DIR: PathBuf = CACHE_DIR.join("db");
+    pub static ref DB: PathBuf = DB_DIR.join("zed.db");
+    pub static ref SETTINGS: PathBuf = CONFIG_DIR.join("settings.json");
+    pub static ref KEYMAP: PathBuf = CONFIG_DIR.join("keymap.json");
+    pub static ref LOG: PathBuf = LOGS_DIR.join("Zed.log");
+    pub static ref OLD_LOG: PathBuf = LOGS_DIR.join("Zed.log.old");
+}

crates/zed/src/zed.rs 🔗

@@ -1,6 +1,7 @@
 mod feedback;
 pub mod languages;
 pub mod menus;
+pub mod paths;
 pub mod settings_file;
 #[cfg(any(test, feature = "test-support"))]
 pub mod test;
@@ -22,7 +23,6 @@ use gpui::{
     AssetSource, AsyncAppContext, ViewContext,
 };
 use language::Rope;
-use lazy_static::lazy_static;
 pub use lsp;
 pub use project::{self, fs};
 use project_panel::ProjectPanel;
@@ -30,12 +30,7 @@ use search::{BufferSearchBar, ProjectSearchBar};
 use serde::Deserialize;
 use serde_json::to_string_pretty;
 use settings::{keymap_file_json_schema, settings_file_json_schema, Settings};
-use std::{
-    env,
-    path::{Path, PathBuf},
-    str,
-    sync::Arc,
-};
+use std::{env, path::Path, str, sync::Arc};
 use util::ResultExt;
 pub use workspace;
 use workspace::{sidebar::Side, AppState, Workspace};
@@ -67,25 +62,6 @@ actions!(
 
 const MIN_FONT_SIZE: f32 = 6.0;
 
-lazy_static! {
-    static ref HOME_PATH: PathBuf = dirs::home_dir().expect("failed to determine home directory");
-    static ref CACHE_DIR_PATH: PathBuf = dirs::cache_dir()
-        .expect("failed to determine cache directory")
-        .join("Zed");
-    static ref CONFIG_DIR_PATH: PathBuf = env::var_os("XDG_CONFIG_HOME")
-        .map(|home| home.into())
-        .unwrap_or_else(|| HOME_PATH.join(".config"))
-        .join("zed");
-    pub static ref LOGS_DIR_PATH: PathBuf = HOME_PATH.join("Library/Logs/Zed");
-    pub static ref LANGUAGES_DIR_PATH: PathBuf = CACHE_DIR_PATH.join("languages");
-    pub static ref DB_DIR_PATH: PathBuf = CACHE_DIR_PATH.join("db");
-    pub static ref DB_PATH: PathBuf = DB_DIR_PATH.join("zed.db");
-    pub static ref SETTINGS_PATH: PathBuf = CONFIG_DIR_PATH.join("settings.json");
-    pub static ref KEYMAP_PATH: PathBuf = CONFIG_DIR_PATH.join("keymap.json");
-    pub static ref LOG_PATH: PathBuf = LOGS_DIR_PATH.join("Zed.log");
-    pub static ref OLD_LOG_PATH: PathBuf = LOGS_DIR_PATH.join("Zed.log.old");
-}
-
 pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
     cx.add_action(about);
     cx.add_global_action(quit);
@@ -122,7 +98,7 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
     cx.add_action({
         let app_state = app_state.clone();
         move |_: &mut Workspace, _: &OpenSettings, cx: &mut ViewContext<Workspace>| {
-            open_config_file(&SETTINGS_PATH, app_state.clone(), cx, || {
+            open_config_file(&paths::SETTINGS, app_state.clone(), cx, || {
                 str::from_utf8(
                     Assets
                         .load("settings/initial_user_settings.json")
@@ -143,7 +119,7 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
     cx.add_action({
         let app_state = app_state.clone();
         move |_: &mut Workspace, _: &OpenKeymap, cx: &mut ViewContext<Workspace>| {
-            open_config_file(&KEYMAP_PATH, app_state.clone(), cx, || Default::default());
+            open_config_file(&paths::KEYMAP, app_state.clone(), cx, || Default::default());
         }
     });
     cx.add_action({
@@ -409,7 +385,7 @@ fn open_config_file(
     cx.spawn(|workspace, mut cx| async move {
         let fs = &app_state.fs;
         if !fs.is_file(path).await {
-            fs.create_dir(&CONFIG_DIR_PATH).await?;
+            fs.create_dir(&paths::CONFIG_DIR).await?;
             fs.create_file(path, Default::default()).await?;
             fs.save(path, &default_content(), Default::default())
                 .await?;
@@ -437,8 +413,8 @@ fn open_log_file(
     workspace.with_local_workspace(cx, app_state.clone(), |_, cx| {
         cx.spawn_weak(|workspace, mut cx| async move {
             let (old_log, new_log) = futures::join!(
-                app_state.fs.load(&OLD_LOG_PATH),
-                app_state.fs.load(&LOG_PATH)
+                app_state.fs.load(&paths::OLD_LOG),
+                app_state.fs.load(&paths::LOG)
             );
 
             if let Some(workspace) = workspace.upgrade(&cx) {