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