Merge pull request #1666 from zed-industries/settings-for-journal

Joseph T. Lyons created

Settings for journal

Change summary

Cargo.lock                      |  2 
assets/settings/default.json    | 20 ++++++--
crates/journal/Cargo.toml       |  2 
crates/journal/src/journal.rs   | 87 ++++++++++++++++++++++++++++++----
crates/settings/src/settings.rs | 37 ++++++++++++++
5 files changed, 133 insertions(+), 15 deletions(-)

Detailed changes

Cargo.lock 🔗

@@ -2946,6 +2946,8 @@ dependencies = [
  "editor",
  "gpui",
  "log",
+ "settings",
+ "shellexpand",
  "util",
  "workspace",
 ]

assets/settings/default.json 🔗

@@ -83,9 +83,19 @@
         //      "git_gutter": "hide"
         "git_gutter": "tracked_files"
     },
+    // Settings specific to journaling
+    "journal": {
+        // The path of the directory where journal entries are stored
+        "path": "~",
+        // What format to display the hours in
+        // May take 2 values:
+        // 1. hour12
+        // 2. hour24
+        "hour_format": "hour12"
+    },
     // Settings specific to the terminal
     "terminal": {
-        // What shell to use when opening a terminal. May take 3 values: 
+        // What shell to use when opening a terminal. May take 3 values:
         // 1. Use the system's default terminal configuration (e.g. $TERM).
         //      "shell": "system"
         // 2. A program:
@@ -102,7 +112,7 @@
         "shell": "system",
         // What working directory to use when launching the terminal.
         // May take 4 values:
-        // 1. Use the current file's project directory.  Will Fallback to the 
+        // 1. Use the current file's project directory.  Will Fallback to the
         //    first project directory strategy if unsuccessful
         //      "working_directory": "current_project_directory"
         // 2. Use the first project in this workspace's directory
@@ -112,7 +122,7 @@
         // 4. Always use a specific directory. This value will be shell expanded.
         //    If this path is not a valid directory the terminal will default to
         //    this platform's home directory  (if we can find it)
-        //      "working_directory": { 
+        //      "working_directory": {
         //        "always": {
         //          "directory": "~/zed/projects/"
         //        }
@@ -124,7 +134,7 @@
         // May take 4 values:
         //  1. Never blink the cursor, ignoring the terminal mode
         //         "blinking": "off",
-        //  2. Default the cursor blink to off, but allow the terminal to 
+        //  2. Default the cursor blink to off, but allow the terminal to
         //     set blinking
         //         "blinking": "terminal_controlled",
         //  3. Always blink the cursor, ignoring the terminal mode
@@ -132,7 +142,7 @@
         "blinking": "terminal_controlled",
         // Set whether Alternate Scroll mode (code: ?1007) is active by default.
         // Alternate Scroll mode converts mouse scroll events into up / down key
-        // presses when in the alternate screen (e.g. when running applications 
+        // presses when in the alternate screen (e.g. when running applications
         // like vim or  less). The terminal can still set and unset this mode.
         // May take 2 values:
         //  1. Default alternate scroll mode to on

crates/journal/Cargo.toml 🔗

@@ -15,3 +15,5 @@ workspace = { path = "../workspace" }
 chrono = "0.4"
 dirs = "4.0"
 log = { version = "0.4.16", features = ["kv_unstable_serde"] }
+settings = { path = "../settings" }
+shellexpand = "2.1.0"

crates/journal/src/journal.rs 🔗

@@ -1,7 +1,12 @@
-use chrono::{Datelike, Local, Timelike};
+use chrono::{Datelike, Local, NaiveTime, Timelike};
 use editor::{Autoscroll, Editor};
 use gpui::{actions, MutableAppContext};
-use std::{fs::OpenOptions, sync::Arc};
+use settings::{HourFormat, Settings};
+use std::{
+    fs::OpenOptions,
+    path::{Path, PathBuf},
+    sync::Arc,
+};
 use util::TryFutureExt as _;
 use workspace::AppState;
 
@@ -12,24 +17,23 @@ pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
 }
 
 pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
-    let now = Local::now();
-    let home_dir = match dirs::home_dir() {
-        Some(home_dir) => home_dir,
+    let settings = cx.global::<Settings>();
+    let journal_dir = match journal_dir(&settings) {
+        Some(journal_dir) => journal_dir,
         None => {
-            log::error!("can't determine home directory");
+            log::error!("Can't determine journal directory");
             return;
         }
     };
 
-    let journal_dir = home_dir.join("journal");
+    let now = Local::now();
     let month_dir = journal_dir
         .join(format!("{:02}", now.year()))
         .join(format!("{:02}", now.month()));
     let entry_path = month_dir.join(format!("{:02}.md", now.day()));
     let now = now.time();
-    let (pm, hour) = now.hour12();
-    let am_or_pm = if pm { "PM" } else { "AM" };
-    let entry_heading = format!("# {}:{:02} {}\n\n", hour, now.minute(), am_or_pm);
+    let hour_format = &settings.journal_overrides.hour_format;
+    let entry_heading = heading_entry(now, &hour_format);
 
     let create_entry = cx.background().spawn(async move {
         std::fs::create_dir_all(month_dir)?;
@@ -64,6 +68,7 @@ pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
                             editor.insert("\n\n", cx);
                         }
                         editor.insert(&entry_heading, cx);
+                        editor.insert("\n\n", cx);
                     });
                 }
             }
@@ -74,3 +79,65 @@ pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
     })
     .detach();
 }
+
+fn journal_dir(settings: &Settings) -> Option<PathBuf> {
+    let journal_dir = settings
+        .journal_overrides
+        .path
+        .as_ref()
+        .unwrap_or(settings.journal_defaults.path.as_ref()?);
+
+    let expanded_journal_dir = shellexpand::full(&journal_dir) //TODO handle this better
+        .ok()
+        .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
+
+    return expanded_journal_dir;
+}
+
+fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
+    match hour_format {
+        Some(HourFormat::Hour24) => {
+            let hour = now.hour();
+            format!("# {}:{:02}", hour, now.minute())
+        }
+        _ => {
+            let (pm, hour) = now.hour12();
+            let am_or_pm = if pm { "PM" } else { "AM" };
+            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    mod heading_entry_tests {
+        use super::super::*;
+
+        #[test]
+        fn test_heading_entry_defaults_to_hour_12() {
+            let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
+            let actual_heading_entry = heading_entry(naive_time, &None);
+            let expected_heading_entry = "# 3:00 PM";
+
+            assert_eq!(actual_heading_entry, expected_heading_entry);
+        }
+
+        #[test]
+        fn test_heading_entry_is_hour_12() {
+            let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
+            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
+            let expected_heading_entry = "# 3:00 PM";
+
+            assert_eq!(actual_heading_entry, expected_heading_entry);
+        }
+
+        #[test]
+        fn test_heading_entry_is_hour_24() {
+            let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
+            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
+            let expected_heading_entry = "# 15:00";
+
+            assert_eq!(actual_heading_entry, expected_heading_entry);
+        }
+    }
+}

crates/settings/src/settings.rs 🔗

@@ -37,6 +37,8 @@ pub struct Settings {
     pub editor_overrides: EditorSettings,
     pub git: GitSettings,
     pub git_overrides: GitSettings,
+    pub journal_defaults: JournalSettings,
+    pub journal_overrides: JournalSettings,
     pub terminal_defaults: TerminalSettings,
     pub terminal_overrides: TerminalSettings,
     pub language_defaults: HashMap<Arc<str>, EditorSettings>,
@@ -122,6 +124,34 @@ pub enum Autosave {
     OnWindowChange,
 }
 
+#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
+pub struct JournalSettings {
+    pub path: Option<String>,
+    pub hour_format: Option<HourFormat>,
+}
+
+impl Default for JournalSettings {
+    fn default() -> Self {
+        Self {
+            path: Some("~".into()),
+            hour_format: Some(Default::default()),
+        }
+    }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum HourFormat {
+    Hour12,
+    Hour24,
+}
+
+impl Default for HourFormat {
+    fn default() -> Self {
+        Self::Hour12
+    }
+}
+
 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
 pub struct TerminalSettings {
     pub shell: Option<Shell>,
@@ -216,6 +246,8 @@ pub struct SettingsFileContent {
     #[serde(flatten)]
     pub editor: EditorSettings,
     #[serde(default)]
+    pub journal: JournalSettings,
+    #[serde(default)]
     pub terminal: TerminalSettings,
     #[serde(default)]
     pub git: Option<GitSettings>,
@@ -278,6 +310,8 @@ impl Settings {
             editor_overrides: Default::default(),
             git: defaults.git.unwrap(),
             git_overrides: Default::default(),
+            journal_defaults: defaults.journal,
+            journal_overrides: Default::default(),
             terminal_defaults: defaults.terminal,
             terminal_overrides: Default::default(),
             language_defaults: defaults.languages,
@@ -330,6 +364,7 @@ impl Settings {
 
         self.editor_overrides = data.editor;
         self.git_overrides = data.git.unwrap_or_default();
+        self.journal_overrides = data.journal;
         self.terminal_defaults.font_size = data.terminal.font_size;
         self.terminal_overrides.copy_on_select = data.terminal.copy_on_select;
         self.terminal_overrides = data.terminal;
@@ -416,6 +451,8 @@ impl Settings {
                 enable_language_server: Some(true),
             },
             editor_overrides: Default::default(),
+            journal_defaults: Default::default(),
+            journal_overrides: Default::default(),
             terminal_defaults: Default::default(),
             terminal_overrides: Default::default(),
             git: Default::default(),