1pub mod env;
24pub mod loader;
25pub mod paths;
26
27use std::{
28 collections::HashMap,
29 env as std_env,
30 fmt::{Display, Formatter},
31 path::PathBuf,
32};
33
34use doing_error::{Error, Result};
35pub use doing_time::ShortdateFormatConfig;
36use serde::{Deserialize, Serialize};
37use serde_json::Value;
38
39use crate::paths::expand_tilde;
40
41#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
47pub struct AutotagConfig {
48 pub mappings: HashMap<String, String>,
50 pub synonyms: HashMap<String, Vec<String>>,
51 pub transform: Vec<String>,
52 pub whitelist: Vec<String>,
53}
54
55impl<'de> serde::Deserialize<'de> for AutotagConfig {
56 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
57 where
58 D: serde::Deserializer<'de>,
59 {
60 let value: serde_json::Value = serde::Deserialize::deserialize(deserializer)?;
61
62 let obj = match value.as_object() {
63 Some(obj) => obj,
64 None => return Ok(Self::default()),
65 };
66
67 let mut config = Self::default();
68
69 for (key, val) in obj {
70 match key.as_str() {
71 "synonyms" => {
72 if let Ok(v) = serde_json::from_value(val.clone()) {
73 config.synonyms = v;
74 }
75 }
76 "transform" => {
77 if let Ok(v) = serde_json::from_value(val.clone()) {
78 config.transform = v;
79 }
80 }
81 "whitelist" => {
82 if let Ok(v) = serde_json::from_value(val.clone()) {
83 config.whitelist = v;
84 }
85 }
86 _ => {
87 if let Some(tag) = val.as_str() {
89 config.mappings.insert(key.clone(), tag.to_string());
90 }
91 }
92 }
93 }
94
95 Ok(config)
96 }
97}
98
99#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
101#[serde(default)]
102pub struct BydayPluginConfig {
103 pub item_width: u32,
104}
105
106impl Default for BydayPluginConfig {
107 fn default() -> Self {
108 Self {
109 item_width: 60,
110 }
111 }
112}
113
114#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
116#[serde(default)]
117pub struct Config {
118 pub autotag: AutotagConfig,
119 pub backup_dir: PathBuf,
120 pub budgets: HashMap<String, String>,
121 pub current_section: String,
122 pub date_tags: Vec<String>,
123 pub default_tags: Vec<String>,
124 pub disabled_commands: Vec<String>,
125 pub doing_file: PathBuf,
126 pub doing_file_sort: SortOrder,
127 pub editors: EditorsConfig,
128 pub export_templates: HashMap<String, Option<TemplateConfig>>,
129 pub history_size: u32,
130 pub include_notes: bool,
131 pub interaction: InteractionConfig,
132 pub interval_format: String,
133 pub marker_color: String,
134 pub marker_tag: String,
135 pub never_finish: Vec<String>,
136 pub never_time: Vec<String>,
137 pub order: SortOrder,
138 pub paginate: bool,
139 pub plugins: PluginsConfig,
140 pub search: SearchConfig,
141 pub shortdate_format: ShortdateFormatConfig,
142 pub tag_sort: String,
143 pub template_path: PathBuf,
144 pub templates: HashMap<String, TemplateConfig>,
145 pub timer_format: String,
146 pub views: HashMap<String, ViewConfig>,
147}
148
149impl Config {
150 pub fn load() -> Result<Self> {
162 let cwd = std_env::current_dir().unwrap_or_default();
163 Self::load_from(&cwd)
164 }
165
166 pub fn load_from(start_dir: &std::path::Path) -> Result<Self> {
168 let mut merged = match loader::discover_global_config() {
169 Some(path) => loader::parse_file(&path)?,
170 None => Value::Object(serde_json::Map::new()),
171 };
172
173 for local_path in loader::discover_local_configs(start_dir) {
174 let local = loader::parse_file(&local_path)?;
175 merged = loader::deep_merge(&merged, &local);
176 }
177
178 merged = apply_env_overrides(merged);
179
180 let mut config: Config =
181 serde_json::from_value(merged).map_err(|e| Error::Config(format!("deserialization error: {e}")))?;
182
183 config.expand_paths();
184 Ok(config)
185 }
186
187 fn expand_paths(&mut self) {
188 self.backup_dir = expand_tilde(&self.backup_dir);
189 self.doing_file = expand_tilde(&self.doing_file);
190 self.plugins.command_path = expand_tilde(&self.plugins.command_path);
191 self.plugins.plugin_path = expand_tilde(&self.plugins.plugin_path);
192 self.template_path = expand_tilde(&self.template_path);
193 }
194}
195
196impl Default for Config {
197 fn default() -> Self {
198 let config_dir = dir_spec::config_home().unwrap_or_else(|| PathBuf::from(".config"));
199 let data_dir = dir_spec::data_home().unwrap_or_else(|| PathBuf::from(".local/share"));
200 Self {
201 autotag: AutotagConfig::default(),
202 backup_dir: data_dir.join("doing/doing_backup"),
203 budgets: HashMap::new(),
204 current_section: "Currently".into(),
205 date_tags: vec!["done".into(), "defer(?:red)?".into(), "waiting".into()],
206 default_tags: Vec::new(),
207 disabled_commands: Vec::new(),
208 doing_file: data_dir.join("doing/what_was_i_doing.md"),
209 doing_file_sort: SortOrder::Desc,
210 editors: EditorsConfig::default(),
211 export_templates: HashMap::new(),
212 history_size: 15,
213 include_notes: true,
214 interaction: InteractionConfig::default(),
215 interval_format: "clock".into(),
216 marker_color: "red".into(),
217 marker_tag: "flagged".into(),
218 never_finish: Vec::new(),
219 never_time: Vec::new(),
220 order: SortOrder::Asc,
221 paginate: false,
222 plugins: PluginsConfig::default(),
223 search: SearchConfig::default(),
224 shortdate_format: ShortdateFormatConfig::default(),
225 tag_sort: "name".into(),
226 template_path: config_dir.join("doing/templates"),
227 templates: HashMap::new(),
228 timer_format: "text".into(),
229 views: HashMap::new(),
230 }
231 }
232}
233
234#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
236#[serde(default)]
237pub struct EditorsConfig {
238 pub config: Option<String>,
239 pub default: Option<String>,
240 pub doing_file: Option<String>,
241 pub pager: Option<String>,
242}
243
244#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
246#[serde(default)]
247pub struct InteractionConfig {
248 pub confirm_longer_than: String,
249}
250
251impl Default for InteractionConfig {
252 fn default() -> Self {
253 Self {
254 confirm_longer_than: "5h".into(),
255 }
256 }
257}
258
259#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
261#[serde(default)]
262pub struct PluginsConfig {
263 pub byday: BydayPluginConfig,
264 pub command_path: PathBuf,
265 pub plugin_path: PathBuf,
266}
267
268impl Default for PluginsConfig {
269 fn default() -> Self {
270 let config_dir = dir_spec::config_home().unwrap_or_else(|| PathBuf::from(".config"));
271 Self {
272 byday: BydayPluginConfig::default(),
273 command_path: config_dir.join("doing/commands"),
274 plugin_path: config_dir.join("doing/plugins"),
275 }
276 }
277}
278
279#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
281#[serde(default)]
282pub struct SearchConfig {
283 pub case: String,
284 pub distance: u32,
285 pub highlight: bool,
286 pub matching: String,
287}
288
289impl Default for SearchConfig {
290 fn default() -> Self {
291 Self {
292 case: "smart".into(),
293 distance: 3,
294 highlight: false,
295 matching: "pattern".into(),
296 }
297 }
298}
299
300#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
302#[serde(rename_all = "lowercase")]
303pub enum SortOrder {
304 #[default]
305 Asc,
306 Desc,
307}
308
309impl Display for SortOrder {
310 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
311 match self {
312 Self::Asc => write!(f, "asc"),
313 Self::Desc => write!(f, "desc"),
314 }
315 }
316}
317
318#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
320#[serde(default)]
321pub struct TemplateConfig {
322 pub count: Option<u32>,
323 pub date_format: String,
324 pub order: Option<SortOrder>,
325 pub template: String,
326 pub wrap_width: u32,
327}
328
329impl Default for TemplateConfig {
330 fn default() -> Self {
331 Self {
332 count: None,
333 date_format: "%Y-%m-%d %H:%M".into(),
334 order: None,
335 template:
336 "%boldwhite%-10shortdate %boldcyan║ %boldwhite%title%reset %interval %cyan[%10section]%reset%cyan%note%reset"
337 .into(),
338 wrap_width: 0,
339 }
340 }
341}
342
343#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
345#[serde(default)]
346pub struct ViewConfig {
347 pub count: u32,
348 pub date_format: String,
349 pub order: SortOrder,
350 pub section: String,
351 pub tags: String,
352 pub tags_bool: String,
353 pub template: String,
354 pub wrap_width: u32,
355}
356
357impl Default for ViewConfig {
358 fn default() -> Self {
359 Self {
360 count: 0,
361 date_format: String::new(),
362 order: SortOrder::Asc,
363 section: String::new(),
364 tags: String::new(),
365 tags_bool: "OR".into(),
366 template: String::new(),
367 wrap_width: 0,
368 }
369 }
370}
371
372fn apply_env_overrides(mut value: Value) -> Value {
374 let obj = match value.as_object_mut() {
375 Some(obj) => obj,
376 None => return value,
377 };
378
379 if let Ok(backup_dir) = env::DOING_BACKUP_DIR.value() {
380 obj.insert("backup_dir".into(), Value::String(backup_dir));
381 }
382
383 if let Ok(doing_file) = env::DOING_FILE.value() {
384 obj.insert("doing_file".into(), Value::String(doing_file));
385 }
386
387 if let Ok(editor) = env::DOING_EDITOR.value() {
388 let editors = obj
389 .entry("editors")
390 .or_insert_with(|| Value::Object(serde_json::Map::new()));
391 if let Some(editors_obj) = editors.as_object_mut() {
392 editors_obj.insert("default".into(), Value::String(editor));
393 }
394 }
395
396 value
397}
398
399#[cfg(test)]
400mod test {
401 use std::fs;
402
403 use super::*;
404
405 mod load_from {
406 use pretty_assertions::assert_eq;
407
408 use super::*;
409
410 #[test]
411 fn it_expands_tilde_in_paths() {
412 let dir = tempfile::tempdir().unwrap();
413 fs::write(
414 dir.path().join(".doingrc"),
415 "doing_file: ~/my_doing.md\nbackup_dir: ~/backups\n",
416 )
417 .unwrap();
418
419 let config = Config::load_from(dir.path()).unwrap();
420
421 assert!(config.doing_file.is_absolute());
422 assert!(config.doing_file.ends_with("my_doing.md"));
423 assert!(config.backup_dir.is_absolute());
424 assert!(config.backup_dir.ends_with("backups"));
425 }
426
427 #[test]
428 fn it_handles_explicit_null_values_in_config() {
429 let dir = tempfile::tempdir().unwrap();
430 fs::write(dir.path().join(".doingrc"), "search:\ncurrent_section: Working\n").unwrap();
431
432 let config = Config::load_from(dir.path()).unwrap();
433
434 assert_eq!(config.current_section, "Working");
435 assert_eq!(config.search, SearchConfig::default());
436 }
437
438 #[test]
439 fn it_loads_from_local_doingrc() {
440 let dir = tempfile::tempdir().unwrap();
441 fs::write(
442 dir.path().join(".doingrc"),
443 "current_section: Working\nhistory_size: 30\n",
444 )
445 .unwrap();
446
447 let config = Config::load_from(dir.path()).unwrap();
448
449 assert_eq!(config.current_section, "Working");
450 assert_eq!(config.history_size, 30);
451 }
452
453 #[test]
454 fn it_merges_nested_local_configs() {
455 let dir = tempfile::tempdir().unwrap();
456 let root = dir.path();
457 let child = root.join("projects/myapp");
458 fs::create_dir_all(&child).unwrap();
459 fs::write(root.join(".doingrc"), "current_section: Root\nhistory_size: 50\n").unwrap();
460 fs::write(child.join(".doingrc"), "current_section: Child\n").unwrap();
461
462 let config = Config::load_from(&child).unwrap();
463
464 assert_eq!(config.current_section, "Child");
465 assert_eq!(config.history_size, 50);
466 }
467
468 #[test]
469 fn it_preserves_defaults_for_missing_keys() {
470 let dir = tempfile::tempdir().unwrap();
471 fs::write(dir.path().join(".doingrc"), "history_size: 99\n").unwrap();
472
473 let config = Config::load_from(dir.path()).unwrap();
474
475 assert_eq!(config.history_size, 99);
476 assert_eq!(config.current_section, "Currently");
477 assert_eq!(config.marker_tag, "flagged");
478 assert_eq!(config.search.matching, "pattern");
479 }
480
481 #[test]
482 fn it_returns_defaults_when_no_config_exists() {
483 let dir = tempfile::tempdir().unwrap();
484
485 let config = Config::load_from(dir.path()).unwrap();
486
487 assert_eq!(config.current_section, "Currently");
488 assert_eq!(config.history_size, 15);
489 assert_eq!(config.order, SortOrder::Asc);
490 }
491 }
492}