Skip to main content

kimun_notes/settings/
workspace_config.rs

1use chrono::{DateTime, Utc};
2use kimun_core::nfs::filename::{InvalidFilenameError, validate_filename};
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone)]
8pub enum WorkspaceConfigError {
9    DuplicateWorkspace {
10        name: String,
11        existing_path: PathBuf,
12    },
13    InvalidName {
14        name: String,
15        error: InvalidFilenameError,
16    },
17}
18
19impl std::fmt::Display for WorkspaceConfigError {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        match self {
22            WorkspaceConfigError::DuplicateWorkspace {
23                name,
24                existing_path,
25            } => {
26                write!(
27                    f,
28                    "Workspace '{}' already exists at {:?}",
29                    name, existing_path
30                )
31            }
32            WorkspaceConfigError::InvalidName { error, .. } => {
33                write!(f, "Workspace {error}")
34            }
35        }
36    }
37}
38
39impl std::error::Error for WorkspaceConfigError {}
40
41#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
42pub struct GlobalConfig {
43    pub current_workspace: String,
44}
45
46#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
47pub struct WorkspaceEntry {
48    pub path: PathBuf,
49    #[serde(default, skip_serializing)]
50    pub last_paths: Vec<String>,
51    pub created: DateTime<Utc>,
52    #[serde(default)]
53    pub quick_note_path: Option<String>,
54    #[serde(default)]
55    pub inbox_path: Option<String>,
56    /// Absolute resolved path for runtime use. Not serialized — `path` is
57    /// written to disk as the user configured it (relative, ~/..., or absolute).
58    #[serde(skip)]
59    pub resolved_path: Option<PathBuf>,
60}
61
62impl WorkspaceEntry {
63    /// Returns the resolved absolute path if available, otherwise the original path.
64    pub fn effective_path(&self) -> &PathBuf {
65        self.resolved_path.as_ref().unwrap_or(&self.path)
66    }
67
68    pub fn effective_quick_note_path(&self) -> String {
69        self.quick_note_path
70            .clone()
71            .unwrap_or_else(|| kimun_core::nfs::VaultPath::root().to_string())
72    }
73
74    pub fn effective_inbox_path(&self) -> String {
75        self.inbox_path
76            .clone()
77            .unwrap_or_else(|| kimun_core::DEFAULT_INBOX_PATH.to_string())
78    }
79}
80
81#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
82pub struct WorkspaceConfig {
83    pub global: GlobalConfig,
84    pub workspaces: HashMap<String, WorkspaceEntry>,
85}
86
87impl WorkspaceConfig {
88    pub fn new_empty() -> Self {
89        Self {
90            global: GlobalConfig {
91                current_workspace: String::new(),
92            },
93            workspaces: HashMap::new(),
94        }
95    }
96
97    pub fn add_workspace(
98        &mut self,
99        name: String,
100        path: PathBuf,
101    ) -> Result<(), WorkspaceConfigError> {
102        if let Err(error) = validate_filename(&name) {
103            return Err(WorkspaceConfigError::InvalidName {
104                name: name.clone(),
105                error,
106            });
107        }
108        if self.workspaces.contains_key(&name) {
109            return Err(WorkspaceConfigError::DuplicateWorkspace {
110                name: name.clone(),
111                existing_path: self.workspaces[&name].path.clone(),
112            });
113        }
114
115        let entry = WorkspaceEntry {
116            path,
117            last_paths: Vec::new(),
118            created: Utc::now(),
119            quick_note_path: None,
120            inbox_path: None,
121            resolved_path: None,
122        };
123
124        self.workspaces.insert(name.clone(), entry);
125
126        // Set as current if it's the first workspace
127        if self.workspaces.len() == 1 {
128            self.global.current_workspace = name.clone();
129        }
130
131        Ok(())
132    }
133
134    pub fn get_current_workspace(&self) -> Option<&WorkspaceEntry> {
135        self.workspaces.get(&self.global.current_workspace)
136    }
137
138    pub fn get_workspace(&self, name: &str) -> Option<&WorkspaceEntry> {
139        self.workspaces.get(name)
140    }
141
142    pub fn from_phase1_migration(workspace_dir: PathBuf, last_paths: Vec<String>) -> Self {
143        let mut config = Self::new_empty();
144
145        let entry = WorkspaceEntry {
146            path: workspace_dir,
147            last_paths,
148            created: Utc::now(),
149            quick_note_path: None,
150            inbox_path: None,
151            resolved_path: None,
152        };
153
154        config.workspaces.insert("default".to_string(), entry);
155        config.global.current_workspace = "default".to_string();
156
157        config
158    }
159}
160
161#[cfg(test)]
162mod validate_tests {
163    use super::*;
164
165    #[test]
166    fn add_workspace_rejects_disallowed_chars() {
167        let mut wc = WorkspaceConfig::new_empty();
168        let err = wc
169            .add_workspace("bad/name".to_string(), PathBuf::from("/tmp/x"))
170            .unwrap_err();
171        match err {
172            WorkspaceConfigError::InvalidName { name, .. } => assert_eq!(name, "bad/name"),
173            _ => panic!("expected InvalidName"),
174        }
175    }
176
177    #[test]
178    fn add_workspace_rejects_windows_reserved() {
179        let mut wc = WorkspaceConfig::new_empty();
180        assert!(
181            wc.add_workspace("con".to_string(), PathBuf::from("/tmp/x"))
182                .is_err()
183        );
184    }
185
186    #[test]
187    fn add_workspace_accepts_simple_names() {
188        let mut wc = WorkspaceConfig::new_empty();
189        assert!(
190            wc.add_workspace("notes".to_string(), PathBuf::from("/tmp/x"))
191                .is_ok()
192        );
193    }
194}