Skip to main content

doing_config/
lib.rs

1//! Configuration loading and types for the doing CLI.
2//!
3//! This crate handles discovering, parsing, merging, and deserializing the
4//! doing configuration from multiple sources:
5//!
6//! 1. **Global config** — `$DOING_CONFIG`, XDG config home, or `~/.doingrc`.
7//! 2. **Local configs** — `.doingrc` files walked from filesystem root to `$CWD`
8//!    (each layer deep-merges over the previous).
9//! 3. **Environment variables** — `DOING_FILE`, `DOING_BACKUP_DIR`, `DOING_EDITOR`,
10//!    and others override individual fields (see [`env`]).
11//!
12//! Config files may be YAML, TOML, or JSON (with comments). The merged result is
13//! deserialized into [`Config`], which provides typed access to all settings with
14//! sensible defaults.
15//!
16//! # Usage
17//!
18//! ```no_run
19//! let config = doing_config::Config::load().unwrap();
20//! println!("doing file: {}", config.doing_file.display());
21//! ```
22
23pub 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/// Autotag configuration for automatic tag assignment.
42///
43/// Supports both structured format (synonyms/transform/whitelist) and Ruby-style
44/// simple key-value mappings where `word = "tag"` means: if "word" appears in the
45/// title, add `@tag`.
46#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
47pub struct AutotagConfig {
48  /// Ruby-style simple mappings: word -> tag name
49  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          // Ruby-style mapping: word = "tag"
88          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/// Configuration for the byday plugin.
100#[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/// Top-level configuration for the doing application.
115#[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  /// Load the fully resolved configuration.
151  ///
152  /// Discovery order:
153  /// 1. Parse global config file (env var -> XDG -> `~/.doingrc`).
154  /// 2. Parse local `.doingrc` files (walked root-to-leaf from CWD).
155  /// 3. Deep-merge all layers (local overrides global).
156  /// 4. Apply environment variable overrides.
157  /// 5. Deserialize into `Config` (serde fills defaults for missing keys).
158  /// 6. Expand `~` in path fields.
159  ///
160  /// Missing config files produce defaults, not errors.
161  pub fn load() -> Result<Self> {
162    let cwd = std_env::current_dir().unwrap_or_default();
163    Self::load_from(&cwd)
164  }
165
166  /// Load configuration using a specific directory for local config discovery.
167  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) -> Result<()> {
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    Ok(())
194  }
195}
196
197impl Default for Config {
198  fn default() -> Self {
199    let config_dir = dir_spec::config_home().unwrap_or_else(|| PathBuf::from(".config"));
200    let data_dir = dir_spec::data_home().unwrap_or_else(|| PathBuf::from(".local/share"));
201    Self {
202      autotag: AutotagConfig::default(),
203      backup_dir: data_dir.join("doing/doing_backup"),
204      budgets: HashMap::new(),
205      current_section: "Currently".into(),
206      date_tags: vec!["done".into(), "defer(?:red)?".into(), "waiting".into()],
207      default_tags: Vec::new(),
208      disabled_commands: Vec::new(),
209      doing_file: data_dir.join("doing/what_was_i_doing.md"),
210      doing_file_sort: SortOrder::Desc,
211      editors: EditorsConfig::default(),
212      export_templates: HashMap::new(),
213      history_size: 15,
214      include_notes: true,
215      interaction: InteractionConfig::default(),
216      interval_format: "clock".into(),
217      marker_color: "red".into(),
218      marker_tag: "flagged".into(),
219      never_finish: Vec::new(),
220      never_time: Vec::new(),
221      order: SortOrder::Asc,
222      paginate: false,
223      plugins: PluginsConfig::default(),
224      search: SearchConfig::default(),
225      shortdate_format: ShortdateFormatConfig::default(),
226      tag_sort: "name".into(),
227      template_path: config_dir.join("doing/templates"),
228      templates: HashMap::new(),
229      timer_format: "text".into(),
230      views: HashMap::new(),
231    }
232  }
233}
234
235/// Editor configuration for various contexts.
236#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
237#[serde(default)]
238pub struct EditorsConfig {
239  pub config: Option<String>,
240  pub default: Option<String>,
241  pub doing_file: Option<String>,
242  pub pager: Option<String>,
243}
244
245/// Interaction settings for user prompts.
246#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
247#[serde(default)]
248pub struct InteractionConfig {
249  pub confirm_longer_than: String,
250}
251
252impl Default for InteractionConfig {
253  fn default() -> Self {
254    Self {
255      confirm_longer_than: "5h".into(),
256    }
257  }
258}
259
260/// Plugin paths and plugin-specific settings.
261#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
262#[serde(default)]
263pub struct PluginsConfig {
264  pub byday: BydayPluginConfig,
265  pub command_path: PathBuf,
266  pub plugin_path: PathBuf,
267}
268
269impl Default for PluginsConfig {
270  fn default() -> Self {
271    let config_dir = dir_spec::config_home().unwrap_or_else(|| PathBuf::from(".config"));
272    Self {
273      byday: BydayPluginConfig::default(),
274      command_path: config_dir.join("doing/commands"),
275      plugin_path: config_dir.join("doing/plugins"),
276    }
277  }
278}
279
280/// Search behavior settings.
281#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
282#[serde(default)]
283pub struct SearchConfig {
284  pub case: String,
285  pub distance: u32,
286  pub highlight: bool,
287  pub matching: String,
288}
289
290impl Default for SearchConfig {
291  fn default() -> Self {
292    Self {
293      case: "smart".into(),
294      distance: 3,
295      highlight: false,
296      matching: "pattern".into(),
297    }
298  }
299}
300
301/// The order in which items are sorted.
302#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
303#[serde(rename_all = "lowercase")]
304pub enum SortOrder {
305  #[default]
306  Asc,
307  Desc,
308}
309
310impl Display for SortOrder {
311  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
312    match self {
313      Self::Asc => write!(f, "asc"),
314      Self::Desc => write!(f, "desc"),
315    }
316  }
317}
318
319/// A named display template.
320#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
321#[serde(default)]
322pub struct TemplateConfig {
323  pub count: Option<u32>,
324  pub date_format: String,
325  pub order: Option<SortOrder>,
326  pub template: String,
327  pub wrap_width: u32,
328}
329
330impl Default for TemplateConfig {
331  fn default() -> Self {
332    Self {
333      count: None,
334      date_format: "%Y-%m-%d %H:%M".into(),
335      order: None,
336      template:
337        "%boldwhite%-10shortdate %boldcyan║ %boldwhite%title%reset  %interval  %cyan[%10section]%reset%cyan%note%reset"
338          .into(),
339      wrap_width: 0,
340    }
341  }
342}
343
344/// A named custom view.
345#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
346#[serde(default)]
347pub struct ViewConfig {
348  pub count: u32,
349  pub date_format: String,
350  pub order: SortOrder,
351  pub section: String,
352  pub tags: String,
353  pub tags_bool: String,
354  pub template: String,
355  pub wrap_width: u32,
356}
357
358impl Default for ViewConfig {
359  fn default() -> Self {
360    Self {
361      count: 0,
362      date_format: String::new(),
363      order: SortOrder::Asc,
364      section: String::new(),
365      tags: String::new(),
366      tags_bool: "OR".into(),
367      template: String::new(),
368      wrap_width: 0,
369    }
370  }
371}
372
373/// Apply environment variable overrides to a config value tree.
374fn apply_env_overrides(mut value: Value) -> Value {
375  let obj = match value.as_object_mut() {
376    Some(obj) => obj,
377    None => return value,
378  };
379
380  if let Ok(backup_dir) = env::DOING_BACKUP_DIR.value() {
381    obj.insert("backup_dir".into(), Value::String(backup_dir));
382  }
383
384  if let Ok(doing_file) = env::DOING_FILE.value() {
385    obj.insert("doing_file".into(), Value::String(doing_file));
386  }
387
388  if let Ok(editor) = env::DOING_EDITOR.value() {
389    let editors = obj
390      .entry("editors")
391      .or_insert_with(|| Value::Object(serde_json::Map::new()));
392    if let Some(editors_obj) = editors.as_object_mut() {
393      editors_obj.insert("default".into(), Value::String(editor));
394    }
395  }
396
397  value
398}
399
400#[cfg(test)]
401mod test {
402  use std::fs;
403
404  use super::*;
405
406  mod load_from {
407    use pretty_assertions::assert_eq;
408
409    use super::*;
410
411    #[test]
412    fn it_expands_tilde_in_paths() {
413      let dir = tempfile::tempdir().unwrap();
414      fs::write(
415        dir.path().join(".doingrc"),
416        "doing_file: ~/my_doing.md\nbackup_dir: ~/backups\n",
417      )
418      .unwrap();
419
420      let config = Config::load_from(dir.path()).unwrap();
421
422      assert!(config.doing_file.is_absolute());
423      assert!(config.doing_file.ends_with("my_doing.md"));
424      assert!(config.backup_dir.is_absolute());
425      assert!(config.backup_dir.ends_with("backups"));
426    }
427
428    #[test]
429    fn it_handles_explicit_null_values_in_config() {
430      let dir = tempfile::tempdir().unwrap();
431      fs::write(dir.path().join(".doingrc"), "search:\ncurrent_section: Working\n").unwrap();
432
433      let config = Config::load_from(dir.path()).unwrap();
434
435      assert_eq!(config.current_section, "Working");
436      assert_eq!(config.search, SearchConfig::default());
437    }
438
439    #[test]
440    fn it_loads_from_local_doingrc() {
441      let dir = tempfile::tempdir().unwrap();
442      fs::write(
443        dir.path().join(".doingrc"),
444        "current_section: Working\nhistory_size: 30\n",
445      )
446      .unwrap();
447
448      let config = Config::load_from(dir.path()).unwrap();
449
450      assert_eq!(config.current_section, "Working");
451      assert_eq!(config.history_size, 30);
452    }
453
454    #[test]
455    fn it_merges_nested_local_configs() {
456      let dir = tempfile::tempdir().unwrap();
457      let root = dir.path();
458      let child = root.join("projects/myapp");
459      fs::create_dir_all(&child).unwrap();
460      fs::write(root.join(".doingrc"), "current_section: Root\nhistory_size: 50\n").unwrap();
461      fs::write(child.join(".doingrc"), "current_section: Child\n").unwrap();
462
463      let config = Config::load_from(&child).unwrap();
464
465      assert_eq!(config.current_section, "Child");
466      assert_eq!(config.history_size, 50);
467    }
468
469    #[test]
470    fn it_preserves_defaults_for_missing_keys() {
471      let dir = tempfile::tempdir().unwrap();
472      fs::write(dir.path().join(".doingrc"), "history_size: 99\n").unwrap();
473
474      let config = Config::load_from(dir.path()).unwrap();
475
476      assert_eq!(config.history_size, 99);
477      assert_eq!(config.current_section, "Currently");
478      assert_eq!(config.marker_tag, "flagged");
479      assert_eq!(config.search.matching, "pattern");
480    }
481
482    #[test]
483    fn it_returns_defaults_when_no_config_exists() {
484      let dir = tempfile::tempdir().unwrap();
485
486      let config = Config::load_from(dir.path()).unwrap();
487
488      assert_eq!(config.current_section, "Currently");
489      assert_eq!(config.history_size, 15);
490      assert_eq!(config.order, SortOrder::Asc);
491    }
492  }
493}