Skip to main content

bookmarks_core/
config.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::path::Path;
5
6const DEFAULT_EDITOR: &str = "vi";
7
8/// A URL entry: either a plain URL string or a table with url + optional aliases.
9///
10/// In TOML this means all three forms work:
11/// ```toml
12/// [urls]
13/// dkdc-bookmarks = "https://github.com/lostmygithubaccount/bookmarks"
14/// github = { url = "https://github.com", aliases = ["gh"] }
15///
16/// [urls.linkedin]
17/// url = "https://linkedin.com"
18/// aliases = ["li", "ln"]
19/// ```
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
21#[serde(untagged)]
22pub enum UrlEntry {
23    Simple(String),
24    Full {
25        url: String,
26        #[serde(default, skip_serializing_if = "Vec::is_empty")]
27        aliases: Vec<String>,
28    },
29}
30
31impl UrlEntry {
32    pub fn url(&self) -> &str {
33        match self {
34            UrlEntry::Simple(url) => url,
35            UrlEntry::Full { url, .. } => url,
36        }
37    }
38
39    pub fn aliases(&self) -> &[String] {
40        match self {
41            UrlEntry::Simple(_) => &[],
42            UrlEntry::Full { aliases, .. } => aliases,
43        }
44    }
45
46    pub fn set_url(&mut self, new_url: String) {
47        match self {
48            UrlEntry::Simple(url) => *url = new_url,
49            UrlEntry::Full { url, .. } => *url = new_url,
50        }
51    }
52
53    pub fn add_alias(&mut self, alias: String) {
54        match self {
55            UrlEntry::Simple(url) => {
56                *self = UrlEntry::Full {
57                    url: url.clone(),
58                    aliases: vec![alias],
59                };
60            }
61            UrlEntry::Full { aliases, .. } => {
62                if !aliases.contains(&alias) {
63                    aliases.push(alias);
64                }
65            }
66        }
67    }
68
69    pub fn remove_alias(&mut self, alias: &str) {
70        if let UrlEntry::Full { aliases, .. } = self {
71            aliases.retain(|a| a != alias);
72        }
73    }
74
75    pub fn has_alias(&self, alias: &str) -> bool {
76        self.aliases().iter().any(|a| a == alias)
77    }
78}
79
80#[derive(Debug, Serialize, Deserialize, Default)]
81pub struct Config {
82    #[serde(default)]
83    pub urls: HashMap<String, UrlEntry>,
84    #[serde(default)]
85    pub groups: HashMap<String, Vec<String>>,
86}
87
88pub const DEFAULT_CONFIG: &str = r#"# https://github.com/lostmygithubaccount/bookmarks
89# bookmarks config file
90
91[urls]
92dkdc-bookmarks = "https://github.com/lostmygithubaccount/bookmarks"
93github = { url = "https://github.com", aliases = ["gh"] }
94
95[urls.linkedin]
96url = "https://linkedin.com"
97aliases = ["li"]
98
99[groups]
100socials = ["gh", "linkedin"]
101"#;
102
103impl Config {
104    /// Build a reverse lookup: alias → url_name.
105    fn alias_map(&self) -> HashMap<&str, &str> {
106        let mut map = HashMap::new();
107        for (name, entry) in &self.urls {
108            for alias in entry.aliases() {
109                map.insert(alias.as_str(), name.as_str());
110            }
111        }
112        map
113    }
114
115    /// Resolve a name (url name or alias) to a URL string.
116    pub fn resolve(&self, name: &str) -> Option<&str> {
117        // Direct url name
118        if let Some(entry) = self.urls.get(name) {
119            return Some(entry.url());
120        }
121        // Alias lookup
122        for entry in self.urls.values() {
123            if entry.has_alias(name) {
124                return Some(entry.url());
125            }
126        }
127        None
128    }
129
130    /// Check if a name is a known url name or alias.
131    pub fn contains(&self, name: &str) -> bool {
132        self.resolve(name).is_some()
133    }
134
135    pub fn validate(&self) -> Vec<String> {
136        let mut warnings = Vec::new();
137
138        // Check for duplicate aliases across urls
139        let mut seen_aliases: HashMap<&str, &str> = HashMap::new();
140        for (url_name, entry) in &self.urls {
141            for alias in entry.aliases() {
142                if let Some(other) = seen_aliases.get(alias.as_str()) {
143                    warnings.push(format!(
144                        "alias '{alias}' is defined on both '{url_name}' and '{other}'"
145                    ));
146                } else {
147                    seen_aliases.insert(alias.as_str(), url_name.as_str());
148                }
149                // Alias shadows a url name
150                if self.urls.contains_key(alias.as_str()) {
151                    warnings.push(format!(
152                        "alias '{alias}' on '{url_name}' shadows url name '{alias}'"
153                    ));
154                }
155            }
156        }
157
158        // Check group entries
159        for (group, entries) in &self.groups {
160            for entry in entries {
161                if !self.contains(entry) {
162                    warnings.push(format!(
163                        "group '{group}' contains '{entry}' which is not a url name or alias"
164                    ));
165                }
166            }
167        }
168
169        warnings
170    }
171
172    /// Rename a url key and cascade to group entries that reference it by name.
173    pub fn rename_url(&mut self, old: &str, new: &str) -> Result<()> {
174        if old == new {
175            anyhow::ensure!(self.urls.contains_key(old), "url '{old}' not found");
176            return Ok(());
177        }
178        if self.urls.contains_key(new) {
179            anyhow::bail!("url '{new}' already exists");
180        }
181        // Check if new name collides with an existing alias
182        let alias_map = self.alias_map();
183        if alias_map.contains_key(new) {
184            anyhow::bail!("'{new}' already exists as an alias");
185        }
186        let entry = self
187            .urls
188            .remove(old)
189            .with_context(|| format!("url '{old}' not found"))?;
190        self.urls.insert(new.to_string(), entry);
191
192        // Update group entries that reference the old url name
193        for entries in self.groups.values_mut() {
194            for e in entries.iter_mut() {
195                if e == old {
196                    *e = new.to_string();
197                }
198            }
199        }
200
201        Ok(())
202    }
203
204    /// Rename an alias and cascade to group entries.
205    pub fn rename_alias(&mut self, old: &str, new: &str) -> Result<()> {
206        if old == new {
207            return Ok(());
208        }
209        if self.urls.contains_key(new) {
210            anyhow::bail!("'{new}' already exists as a url name");
211        }
212        let alias_map = self.alias_map();
213        if alias_map.contains_key(new) {
214            anyhow::bail!("alias '{new}' already exists");
215        }
216
217        // Find which url owns this alias
218        let url_name = alias_map
219            .get(old)
220            .with_context(|| format!("alias '{old}' not found"))?
221            .to_string();
222
223        let entry = self.urls.get_mut(&url_name).unwrap();
224        entry.remove_alias(old);
225        entry.add_alias(new.to_string());
226
227        // Update group entries
228        for entries in self.groups.values_mut() {
229            for e in entries.iter_mut() {
230                if e == old {
231                    *e = new.to_string();
232                }
233            }
234        }
235
236        Ok(())
237    }
238
239    /// Delete a url and clean up group references to it and its aliases.
240    pub fn delete_url(&mut self, name: &str) -> Result<()> {
241        let entry = self
242            .urls
243            .remove(name)
244            .with_context(|| format!("url '{name}' not found"))?;
245        // Collect the url name + all its aliases for group cleanup
246        let mut to_remove: Vec<String> = vec![name.to_string()];
247        to_remove.extend(entry.aliases().iter().cloned());
248        for entries in self.groups.values_mut() {
249            entries.retain(|e| !to_remove.contains(e));
250        }
251        self.groups.retain(|_, entries| !entries.is_empty());
252        Ok(())
253    }
254
255    /// Delete an alias from its parent url and clean up group references.
256    pub fn delete_alias(&mut self, alias: &str) -> Result<()> {
257        let alias_map = self.alias_map();
258        let url_name = alias_map
259            .get(alias)
260            .with_context(|| format!("alias '{alias}' not found"))?
261            .to_string();
262
263        self.urls.get_mut(&url_name).unwrap().remove_alias(alias);
264
265        for entries in self.groups.values_mut() {
266            entries.retain(|e| e != alias);
267        }
268        self.groups.retain(|_, entries| !entries.is_empty());
269        Ok(())
270    }
271
272    /// Rename a group key.
273    pub fn rename_group(&mut self, old: &str, new: &str) -> Result<()> {
274        if old != new && self.groups.contains_key(new) {
275            anyhow::bail!("group '{new}' already exists");
276        }
277        let entries = self
278            .groups
279            .remove(old)
280            .with_context(|| format!("group '{old}' not found"))?;
281        self.groups.insert(new.to_string(), entries);
282        Ok(())
283    }
284
285    /// Delete a group.
286    pub fn delete_group(&mut self, name: &str) -> Result<()> {
287        self.groups
288            .remove(name)
289            .with_context(|| format!("group '{name}' not found"))?;
290        Ok(())
291    }
292}
293
294pub fn edit_config(config_path: &Path) -> Result<()> {
295    let editor = std::env::var("EDITOR").unwrap_or_else(|_| DEFAULT_EDITOR.to_string());
296
297    println!("Opening {} with {}...", config_path.display(), editor);
298
299    let status = std::process::Command::new(&editor)
300        .arg(config_path)
301        .status()
302        .with_context(|| format!("Editor {editor} not found in PATH"))?;
303
304    if !status.success() {
305        anyhow::bail!("Editor exited with non-zero status");
306    }
307
308    Ok(())
309}
310
311pub fn print_config(config: &Config) {
312    if !config.urls.is_empty() {
313        println!("urls:");
314        println!();
315
316        let mut entries: Vec<_> = config.urls.iter().collect();
317        entries.sort_unstable_by_key(|(k, _)| k.as_str());
318
319        let max_key_len = entries.iter().map(|(k, _)| k.len()).max().unwrap_or(0);
320
321        for (name, entry) in &entries {
322            let aliases = entry.aliases();
323            if aliases.is_empty() {
324                println!("• {name:<max_key_len$} | {}", entry.url());
325            } else {
326                println!(
327                    "• {name:<max_key_len$} | {} (aliases: {})",
328                    entry.url(),
329                    aliases.join(", ")
330                );
331            }
332        }
333
334        println!();
335    }
336
337    if !config.groups.is_empty() {
338        println!("groups:");
339        println!();
340
341        let mut entries: Vec<_> = config.groups.iter().collect();
342        entries.sort_unstable_by_key(|(k, _)| k.as_str());
343
344        let max_key_len = entries.iter().map(|(k, _)| k.len()).max().unwrap_or(0);
345
346        for (name, group_entries) in &entries {
347            println!("• {name:<max_key_len$} | [{}]", group_entries.join(", "));
348        }
349
350        println!();
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn test_parse_valid_config() {
360        let toml = r#"
361[urls]
362github = { url = "https://github.com", aliases = ["gh"] }
363
364[groups]
365dev = ["gh"]
366"#;
367        let config: Config = toml::from_str(toml).unwrap();
368        let entry = config.urls.get("github").unwrap();
369        assert_eq!(entry.url(), "https://github.com");
370        assert_eq!(entry.aliases(), &["gh"]);
371        assert_eq!(config.groups.get("dev"), Some(&vec!["gh".to_string()]));
372    }
373
374    #[test]
375    fn test_parse_simple_url() {
376        let toml = r#"
377[urls]
378dkdc-bookmarks = "https://github.com/lostmygithubaccount/bookmarks"
379"#;
380        let config: Config = toml::from_str(toml).unwrap();
381        let entry = config.urls.get("dkdc-bookmarks").unwrap();
382        assert_eq!(
383            entry.url(),
384            "https://github.com/lostmygithubaccount/bookmarks"
385        );
386        assert!(entry.aliases().is_empty());
387    }
388
389    #[test]
390    fn test_parse_expanded_table() {
391        let toml = r#"
392[urls.linkedin]
393url = "https://linkedin.com"
394aliases = ["li", "ln"]
395"#;
396        let config: Config = toml::from_str(toml).unwrap();
397        let entry = config.urls.get("linkedin").unwrap();
398        assert_eq!(entry.url(), "https://linkedin.com");
399        assert_eq!(entry.aliases(), &["li", "ln"]);
400    }
401
402    #[test]
403    fn test_parse_hybrid_config() {
404        let toml = r#"
405[urls]
406dkdc-bookmarks = "https://github.com/lostmygithubaccount/bookmarks"
407github = { url = "https://github.com", aliases = ["gh"] }
408
409[urls.linkedin]
410url = "https://linkedin.com"
411aliases = ["li"]
412
413[groups]
414socials = ["gh", "linkedin"]
415"#;
416        let config: Config = toml::from_str(toml).unwrap();
417        assert_eq!(config.urls.len(), 3);
418        assert_eq!(
419            config.urls.get("dkdc-bookmarks").unwrap().url(),
420            "https://github.com/lostmygithubaccount/bookmarks"
421        );
422        assert_eq!(config.urls.get("github").unwrap().aliases(), &["gh"]);
423        assert_eq!(config.urls.get("linkedin").unwrap().aliases(), &["li"]);
424        assert!(config.validate().is_empty());
425    }
426
427    #[test]
428    fn test_parse_empty_config() {
429        let config: Config = toml::from_str("").unwrap();
430        assert!(config.urls.is_empty());
431        assert!(config.groups.is_empty());
432    }
433
434    #[test]
435    fn test_config_roundtrip() {
436        let mut config = Config::default();
437        config.urls.insert(
438            "example".to_string(),
439            UrlEntry::Full {
440                url: "https://example.com".to_string(),
441                aliases: vec!["ex".to_string()],
442            },
443        );
444        config
445            .groups
446            .insert("g".to_string(), vec!["ex".to_string()]);
447
448        let serialized = toml::to_string(&config).unwrap();
449        let deserialized: Config = toml::from_str(&serialized).unwrap();
450
451        assert_eq!(config.urls.len(), deserialized.urls.len());
452        assert_eq!(config.groups, deserialized.groups);
453    }
454
455    #[test]
456    fn test_default_config_parses() {
457        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
458        assert!(!config.urls.is_empty());
459        assert!(!config.groups.is_empty());
460    }
461
462    #[test]
463    fn test_valid_config_has_no_warnings() {
464        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
465        assert!(config.validate().is_empty());
466    }
467
468    #[test]
469    fn test_resolve_by_url_name() {
470        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
471        assert_eq!(
472            config.resolve("dkdc-bookmarks"),
473            Some("https://github.com/lostmygithubaccount/bookmarks")
474        );
475    }
476
477    #[test]
478    fn test_resolve_by_alias() {
479        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
480        assert_eq!(config.resolve("gh"), Some("https://github.com"));
481    }
482
483    #[test]
484    fn test_resolve_unknown() {
485        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
486        assert_eq!(config.resolve("nope"), None);
487    }
488
489    #[test]
490    fn test_duplicate_alias_warns() {
491        let toml = r#"
492[urls]
493a = { url = "https://a.com", aliases = ["x"] }
494b = { url = "https://b.com", aliases = ["x"] }
495"#;
496        let config: Config = toml::from_str(toml).unwrap();
497        let warnings = config.validate();
498        assert_eq!(warnings.len(), 1);
499        assert!(warnings[0].contains("x"));
500    }
501
502    #[test]
503    fn test_alias_shadows_url_name_warns() {
504        let toml = r#"
505[urls]
506github = { url = "https://github.com", aliases = ["dkdc-bookmarks"] }
507dkdc-bookmarks = "https://github.com/lostmygithubaccount/bookmarks"
508"#;
509        let config: Config = toml::from_str(toml).unwrap();
510        let warnings = config.validate();
511        assert!(!warnings.is_empty());
512        assert!(warnings.iter().any(|w| w.contains("shadows")));
513    }
514
515    #[test]
516    fn test_broken_group_entry_warns() {
517        let toml = r#"
518[urls]
519real = "https://example.com"
520
521[groups]
522dev = ["real", "ghost"]
523"#;
524        let config: Config = toml::from_str(toml).unwrap();
525        let warnings = config.validate();
526        assert_eq!(warnings.len(), 1);
527        assert!(warnings[0].contains("ghost"));
528    }
529
530    #[test]
531    fn test_rename_url_cascades_groups() {
532        let toml = r#"
533[urls]
534github = "https://github.com"
535
536[groups]
537dev = ["github"]
538"#;
539        let mut config: Config = toml::from_str(toml).unwrap();
540        config.rename_url("github", "gh-link").unwrap();
541        assert!(config.urls.contains_key("gh-link"));
542        assert!(!config.urls.contains_key("github"));
543        assert_eq!(config.groups.get("dev"), Some(&vec!["gh-link".to_string()]));
544    }
545
546    #[test]
547    fn test_rename_alias_cascades_groups() {
548        let toml = r#"
549[urls]
550github = { url = "https://github.com", aliases = ["gh"] }
551
552[groups]
553dev = ["gh"]
554all = ["gh", "other"]
555"#;
556        let mut config: Config = toml::from_str(toml).unwrap();
557        config.rename_alias("gh", "github-alias").unwrap();
558        let entry = config.urls.get("github").unwrap();
559        assert!(entry.has_alias("github-alias"));
560        assert!(!entry.has_alias("gh"));
561        assert_eq!(
562            config.groups.get("dev"),
563            Some(&vec!["github-alias".to_string()])
564        );
565        let all = config.groups.get("all").unwrap();
566        assert!(all.contains(&"github-alias".to_string()));
567        assert!(all.contains(&"other".to_string()));
568    }
569
570    #[test]
571    fn test_rename_nonexistent_url_errors() {
572        let mut config = Config::default();
573        assert!(config.rename_url("nope", "new").is_err());
574    }
575
576    #[test]
577    fn test_rename_nonexistent_alias_errors() {
578        let mut config = Config::default();
579        assert!(config.rename_alias("nope", "new").is_err());
580    }
581
582    #[test]
583    fn test_rename_url_collision_errors() {
584        let toml = r#"
585[urls]
586a = "https://a.com"
587b = "https://b.com"
588"#;
589        let mut config: Config = toml::from_str(toml).unwrap();
590        let result = config.rename_url("a", "b");
591        assert!(result.is_err());
592        assert!(result.unwrap_err().to_string().contains("already exists"));
593        assert!(config.urls.contains_key("a"));
594        assert!(config.urls.contains_key("b"));
595    }
596
597    #[test]
598    fn test_rename_alias_collision_errors() {
599        let toml = r#"
600[urls]
601a = { url = "https://a.com", aliases = ["x"] }
602b = { url = "https://b.com", aliases = ["y"] }
603"#;
604        let mut config: Config = toml::from_str(toml).unwrap();
605        let result = config.rename_alias("x", "y");
606        assert!(result.is_err());
607        assert!(result.unwrap_err().to_string().contains("already exists"));
608    }
609
610    #[test]
611    fn test_rename_url_to_existing_alias_errors() {
612        let toml = r#"
613[urls]
614github = { url = "https://github.com", aliases = ["gh"] }
615other = "https://other.com"
616"#;
617        let mut config: Config = toml::from_str(toml).unwrap();
618        let result = config.rename_url("other", "gh");
619        assert!(result.is_err());
620        assert!(
621            result
622                .unwrap_err()
623                .to_string()
624                .contains("already exists as an alias")
625        );
626        assert!(config.urls.contains_key("other"));
627    }
628
629    #[test]
630    fn test_rename_alias_to_existing_url_errors() {
631        let toml = r#"
632[urls]
633github = { url = "https://github.com", aliases = ["gh"] }
634other = "https://other.com"
635"#;
636        let mut config: Config = toml::from_str(toml).unwrap();
637        let result = config.rename_alias("gh", "other");
638        assert!(result.is_err());
639        assert!(
640            result
641                .unwrap_err()
642                .to_string()
643                .contains("already exists as a url name")
644        );
645        assert!(config.urls.get("github").unwrap().has_alias("gh"));
646    }
647
648    #[test]
649    fn test_rename_url_same_name_is_noop() {
650        let toml = r#"
651[urls]
652a = "https://a.com"
653"#;
654        let mut config: Config = toml::from_str(toml).unwrap();
655        config.rename_url("a", "a").unwrap();
656        assert_eq!(config.urls.get("a").unwrap().url(), "https://a.com");
657    }
658
659    #[test]
660    fn test_delete_url_cascades() {
661        let toml = r#"
662[urls]
663github = { url = "https://github.com", aliases = ["gh", "g"] }
664dkdc-bookmarks = "https://github.com/lostmygithubaccount/bookmarks"
665
666[groups]
667dev = ["gh", "github"]
668"#;
669        let mut config: Config = toml::from_str(toml).unwrap();
670        config.delete_url("github").unwrap();
671        assert!(!config.urls.contains_key("github"));
672        assert!(config.urls.contains_key("dkdc-bookmarks"));
673        // Group entries for both the url name and its aliases are removed
674        assert!(!config.groups.contains_key("dev"));
675    }
676
677    #[test]
678    fn test_delete_url_partial_group_cleanup() {
679        let toml = r#"
680[urls]
681github = { url = "https://github.com", aliases = ["gh"] }
682dkdc-bookmarks = "https://github.com/lostmygithubaccount/bookmarks"
683
684[groups]
685dev = ["gh", "dkdc-bookmarks"]
686"#;
687        let mut config: Config = toml::from_str(toml).unwrap();
688        config.delete_url("github").unwrap();
689        let dev = config.groups.get("dev").unwrap();
690        assert_eq!(dev, &vec!["dkdc-bookmarks".to_string()]);
691    }
692
693    #[test]
694    fn test_delete_alias_cascades_to_groups() {
695        let toml = r#"
696[urls]
697github = { url = "https://github.com", aliases = ["gh"] }
698
699[groups]
700dev = ["gh"]
701"#;
702        let mut config: Config = toml::from_str(toml).unwrap();
703        config.delete_alias("gh").unwrap();
704        // Alias removed from url entry
705        assert!(config.urls.get("github").unwrap().aliases().is_empty());
706        // Group with only "gh" is now empty and removed
707        assert!(!config.groups.contains_key("dev"));
708    }
709
710    #[test]
711    fn test_delete_group() {
712        let toml = r#"
713[groups]
714dev = ["gh"]
715"#;
716        let mut config: Config = toml::from_str(toml).unwrap();
717        config.delete_group("dev").unwrap();
718        assert!(!config.groups.contains_key("dev"));
719    }
720
721    #[test]
722    fn test_rename_group_collision_errors() {
723        let toml = r#"
724[groups]
725a = ["x"]
726b = ["y"]
727"#;
728        let mut config: Config = toml::from_str(toml).unwrap();
729        let result = config.rename_group("a", "b");
730        assert!(result.is_err());
731        assert!(result.unwrap_err().to_string().contains("already exists"));
732        assert!(config.groups.contains_key("a"));
733        assert!(config.groups.contains_key("b"));
734    }
735
736    #[test]
737    fn test_rename_group_cascades() {
738        let toml = r#"
739[groups]
740dev = ["gh", "dkdc-bookmarks"]
741"#;
742        let mut config: Config = toml::from_str(toml).unwrap();
743        config.rename_group("dev", "development").unwrap();
744        assert!(!config.groups.contains_key("dev"));
745        assert_eq!(
746            config.groups.get("development"),
747            Some(&vec!["gh".to_string(), "dkdc-bookmarks".to_string()])
748        );
749    }
750
751    #[test]
752    fn test_delete_nonexistent_errors() {
753        let mut config = Config::default();
754        assert!(config.delete_url("nope").is_err());
755        assert!(config.delete_alias("nope").is_err());
756        assert!(config.delete_group("nope").is_err());
757    }
758}