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 totals_format: String,
147 pub views: HashMap<String, ViewConfig>,
148}
149
150impl Config {
151 pub fn load() -> Result<Self> {
163 let cwd = std_env::current_dir().unwrap_or_default();
164 Self::load_from(&cwd)
165 }
166
167 pub fn load_from(start_dir: &std::path::Path) -> Result<Self> {
169 let global_config = loader::discover_global_config();
170 let mut merged = match &global_config {
171 Some(path) => loader::parse_file(path)?,
172 None => Value::Object(serde_json::Map::new()),
173 };
174
175 for local_path in loader::discover_local_configs_with_global(start_dir, global_config.as_deref()) {
176 let local = loader::parse_file(&local_path)?;
177 merged = loader::deep_merge(&merged, &local);
178 }
179
180 merged = apply_env_overrides(merged);
181
182 let mut config: Config =
183 serde_json::from_value(merged).map_err(|e| Error::Config(format!("deserialization error: {e}")))?;
184
185 config.expand_paths()?;
186 Ok(config)
187 }
188
189 fn expand_paths(&mut self) -> Result<()> {
190 self.backup_dir = expand_tilde(&self.backup_dir)?;
191 self.doing_file = expand_tilde(&self.doing_file)?;
192 self.plugins.command_path = expand_tilde(&self.plugins.command_path)?;
193 self.plugins.plugin_path = expand_tilde(&self.plugins.plugin_path)?;
194 self.template_path = expand_tilde(&self.template_path)?;
195 Ok(())
196 }
197}
198
199impl Default for Config {
200 fn default() -> Self {
201 let config_dir = dir_spec::config_home().unwrap_or_else(|| PathBuf::from(".config"));
202 let data_dir = dir_spec::data_home().unwrap_or_else(|| PathBuf::from(".local/share"));
203 Self {
204 autotag: AutotagConfig::default(),
205 backup_dir: data_dir.join("doing/doing_backup"),
206 budgets: HashMap::new(),
207 current_section: "Currently".into(),
208 date_tags: vec!["done".into(), "defer(?:red)?".into(), "waiting".into()],
209 default_tags: Vec::new(),
210 disabled_commands: Vec::new(),
211 doing_file: data_dir.join("doing/what_was_i_doing.md"),
212 doing_file_sort: SortOrder::Desc,
213 editors: EditorsConfig::default(),
214 export_templates: HashMap::new(),
215 history_size: 15,
216 include_notes: true,
217 interaction: InteractionConfig::default(),
218 interval_format: "clock".into(),
219 marker_color: "red".into(),
220 marker_tag: "flagged".into(),
221 never_finish: Vec::new(),
222 never_time: Vec::new(),
223 order: SortOrder::Asc,
224 paginate: false,
225 plugins: PluginsConfig::default(),
226 search: SearchConfig::default(),
227 shortdate_format: ShortdateFormatConfig::default(),
228 tag_sort: "name".into(),
229 template_path: config_dir.join("doing/templates"),
230 templates: HashMap::new(),
231 timer_format: "text".into(),
232 totals_format: String::new(),
233 views: HashMap::new(),
234 }
235 }
236}
237
238#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
240#[serde(default)]
241pub struct EditorsConfig {
242 pub config: Option<String>,
243 pub default: Option<String>,
244 pub doing_file: Option<String>,
245 pub pager: Option<String>,
246}
247
248#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
250#[serde(default)]
251pub struct InteractionConfig {
252 pub confirm_longer_than: String,
253}
254
255impl Default for InteractionConfig {
256 fn default() -> Self {
257 Self {
258 confirm_longer_than: "5h".into(),
259 }
260 }
261}
262
263#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
265#[serde(default)]
266pub struct PluginsConfig {
267 pub byday: BydayPluginConfig,
268 pub command_path: PathBuf,
269 pub plugin_path: PathBuf,
270}
271
272impl Default for PluginsConfig {
273 fn default() -> Self {
274 let config_dir = dir_spec::config_home().unwrap_or_else(|| PathBuf::from(".config"));
275 Self {
276 byday: BydayPluginConfig::default(),
277 command_path: config_dir.join("doing/commands"),
278 plugin_path: config_dir.join("doing/plugins"),
279 }
280 }
281}
282
283#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
285#[serde(default)]
286pub struct SearchConfig {
287 pub case: String,
288 pub distance: u32,
289 pub highlight: bool,
290 pub matching: String,
291}
292
293impl Default for SearchConfig {
294 fn default() -> Self {
295 Self {
296 case: "smart".into(),
297 distance: 3,
298 highlight: false,
299 matching: "pattern".into(),
300 }
301 }
302}
303
304#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
306#[serde(rename_all = "lowercase")]
307pub enum SortOrder {
308 #[default]
309 Asc,
310 Desc,
311}
312
313impl Display for SortOrder {
314 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
315 match self {
316 Self::Asc => write!(f, "asc"),
317 Self::Desc => write!(f, "desc"),
318 }
319 }
320}
321
322#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
324#[serde(default)]
325pub struct TemplateConfig {
326 pub count: Option<u32>,
327 pub date_format: String,
328 pub order: Option<SortOrder>,
329 pub template: String,
330 pub wrap_width: u32,
331}
332
333impl Default for TemplateConfig {
334 fn default() -> Self {
335 Self {
336 count: None,
337 date_format: "%Y-%m-%d %H:%M".into(),
338 order: None,
339 template:
340 "%boldwhite%-10shortdate %boldcyan║ %boldwhite%title%reset %interval %cyan[%10section]%reset%cyan%note%reset"
341 .into(),
342 wrap_width: 0,
343 }
344 }
345}
346
347#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
349#[serde(default)]
350pub struct ViewConfig {
351 pub count: u32,
352 pub date_format: String,
353 pub order: SortOrder,
354 pub section: String,
355 pub tags: String,
356 pub tags_bool: String,
357 pub template: String,
358 pub wrap_width: u32,
359}
360
361impl Default for ViewConfig {
362 fn default() -> Self {
363 Self {
364 count: 0,
365 date_format: String::new(),
366 order: SortOrder::Asc,
367 section: String::new(),
368 tags: String::new(),
369 tags_bool: "OR".into(),
370 template: String::new(),
371 wrap_width: 0,
372 }
373 }
374}
375
376fn apply_env_overrides(mut value: Value) -> Value {
378 let obj = match value.as_object_mut() {
379 Some(obj) => obj,
380 None => return value,
381 };
382
383 if let Ok(backup_dir) = env::DOING_BACKUP_DIR.value() {
384 obj.insert("backup_dir".into(), Value::String(backup_dir));
385 }
386
387 if let Ok(doing_file) = env::DOING_FILE.value() {
388 obj.insert("doing_file".into(), Value::String(doing_file));
389 }
390
391 if let Ok(editor) = env::DOING_EDITOR.value() {
392 let editors = obj
393 .entry("editors")
394 .or_insert_with(|| Value::Object(serde_json::Map::new()));
395 if let Some(editors_obj) = editors.as_object_mut() {
396 editors_obj.insert("default".into(), Value::String(editor));
397 }
398 }
399
400 value
401}
402
403#[cfg(test)]
404mod test {
405 use std::fs;
406
407 use super::*;
408
409 mod load_from {
410 use pretty_assertions::assert_eq;
411
412 use super::*;
413
414 #[test]
415 fn it_expands_tilde_in_paths() {
416 let dir = tempfile::tempdir().unwrap();
417 fs::write(
418 dir.path().join(".doingrc"),
419 "doing_file: ~/my_doing.md\nbackup_dir: ~/backups\n",
420 )
421 .unwrap();
422
423 let config = Config::load_from(dir.path()).unwrap();
424
425 assert!(config.doing_file.is_absolute());
426 assert!(config.doing_file.ends_with("my_doing.md"));
427 assert!(config.backup_dir.is_absolute());
428 assert!(config.backup_dir.ends_with("backups"));
429 }
430
431 #[test]
432 fn it_handles_explicit_null_values_in_config() {
433 let dir = tempfile::tempdir().unwrap();
434 fs::write(dir.path().join(".doingrc"), "search:\ncurrent_section: Working\n").unwrap();
435
436 let config = Config::load_from(dir.path()).unwrap();
437
438 assert_eq!(config.current_section, "Working");
439 assert_eq!(config.search, SearchConfig::default());
440 }
441
442 #[test]
443 fn it_loads_from_local_doingrc() {
444 let dir = tempfile::tempdir().unwrap();
445 fs::write(
446 dir.path().join(".doingrc"),
447 "current_section: Working\nhistory_size: 30\n",
448 )
449 .unwrap();
450
451 let config = Config::load_from(dir.path()).unwrap();
452
453 assert_eq!(config.current_section, "Working");
454 assert_eq!(config.history_size, 30);
455 }
456
457 #[test]
458 fn it_merges_nested_local_configs() {
459 let dir = tempfile::tempdir().unwrap();
460 let root = dir.path();
461 let child = root.join("projects/myapp");
462 fs::create_dir_all(&child).unwrap();
463 fs::write(root.join(".doingrc"), "current_section: Root\nhistory_size: 50\n").unwrap();
464 fs::write(child.join(".doingrc"), "current_section: Child\n").unwrap();
465
466 let config = Config::load_from(&child).unwrap();
467
468 assert_eq!(config.current_section, "Child");
469 assert_eq!(config.history_size, 50);
470 }
471
472 #[test]
473 fn it_preserves_defaults_for_missing_keys() {
474 let dir = tempfile::tempdir().unwrap();
475 fs::write(dir.path().join(".doingrc"), "history_size: 99\n").unwrap();
476
477 let config = Config::load_from(dir.path()).unwrap();
478
479 assert_eq!(config.history_size, 99);
480 assert_eq!(config.current_section, "Currently");
481 assert_eq!(config.marker_tag, "flagged");
482 assert_eq!(config.search.matching, "pattern");
483 }
484
485 #[test]
486 fn it_returns_defaults_when_no_config_exists() {
487 let dir = tempfile::tempdir().unwrap();
488
489 let config = Config::load_from(dir.path()).unwrap();
490
491 assert_eq!(config.current_section, "Currently");
492 assert_eq!(config.history_size, 15);
493 assert_eq!(config.order, SortOrder::Asc);
494 }
495 }
496}