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/// rust = "https://rust-lang.org"
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]
92rust = "https://rust-lang.org"
93github = { url = "https://github.com", aliases = ["gh"] }
94
95[urls.linkedin]
96url = "https://linkedin.com"
97aliases = ["li"]
98
99[groups]
100socials = ["gh", "li"]
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]
378rust = "https://rust-lang.org"
379"#;
380        let config: Config = toml::from_str(toml).unwrap();
381        let entry = config.urls.get("rust").unwrap();
382        assert_eq!(entry.url(), "https://rust-lang.org");
383        assert!(entry.aliases().is_empty());
384    }
385
386    #[test]
387    fn test_parse_expanded_table() {
388        let toml = r#"
389[urls.linkedin]
390url = "https://linkedin.com"
391aliases = ["li", "ln"]
392"#;
393        let config: Config = toml::from_str(toml).unwrap();
394        let entry = config.urls.get("linkedin").unwrap();
395        assert_eq!(entry.url(), "https://linkedin.com");
396        assert_eq!(entry.aliases(), &["li", "ln"]);
397    }
398
399    #[test]
400    fn test_parse_hybrid_config() {
401        let toml = r#"
402[urls]
403rust = "https://rust-lang.org"
404github = { url = "https://github.com", aliases = ["gh"] }
405
406[urls.linkedin]
407url = "https://linkedin.com"
408aliases = ["li"]
409
410[groups]
411socials = ["gh", "li"]
412"#;
413        let config: Config = toml::from_str(toml).unwrap();
414        assert_eq!(config.urls.len(), 3);
415        assert_eq!(
416            config.urls.get("rust").unwrap().url(),
417            "https://rust-lang.org"
418        );
419        assert_eq!(config.urls.get("github").unwrap().aliases(), &["gh"]);
420        assert_eq!(config.urls.get("linkedin").unwrap().aliases(), &["li"]);
421        assert!(config.validate().is_empty());
422    }
423
424    #[test]
425    fn test_parse_empty_config() {
426        let config: Config = toml::from_str("").unwrap();
427        assert!(config.urls.is_empty());
428        assert!(config.groups.is_empty());
429    }
430
431    #[test]
432    fn test_config_roundtrip() {
433        let mut config = Config::default();
434        config.urls.insert(
435            "example".to_string(),
436            UrlEntry::Full {
437                url: "https://example.com".to_string(),
438                aliases: vec!["ex".to_string()],
439            },
440        );
441        config
442            .groups
443            .insert("g".to_string(), vec!["ex".to_string()]);
444
445        let serialized = toml::to_string(&config).unwrap();
446        let deserialized: Config = toml::from_str(&serialized).unwrap();
447
448        assert_eq!(config.urls.len(), deserialized.urls.len());
449        assert_eq!(config.groups, deserialized.groups);
450    }
451
452    #[test]
453    fn test_default_config_parses() {
454        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
455        assert!(!config.urls.is_empty());
456        assert!(!config.groups.is_empty());
457    }
458
459    #[test]
460    fn test_valid_config_has_no_warnings() {
461        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
462        assert!(config.validate().is_empty());
463    }
464
465    #[test]
466    fn test_resolve_by_url_name() {
467        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
468        assert_eq!(config.resolve("rust"), Some("https://rust-lang.org"));
469    }
470
471    #[test]
472    fn test_resolve_by_alias() {
473        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
474        assert_eq!(config.resolve("gh"), Some("https://github.com"));
475    }
476
477    #[test]
478    fn test_resolve_unknown() {
479        let config: Config = toml::from_str(DEFAULT_CONFIG).unwrap();
480        assert_eq!(config.resolve("nope"), None);
481    }
482
483    #[test]
484    fn test_duplicate_alias_warns() {
485        let toml = r#"
486[urls]
487a = { url = "https://a.com", aliases = ["x"] }
488b = { url = "https://b.com", aliases = ["x"] }
489"#;
490        let config: Config = toml::from_str(toml).unwrap();
491        let warnings = config.validate();
492        assert_eq!(warnings.len(), 1);
493        assert!(warnings[0].contains("x"));
494    }
495
496    #[test]
497    fn test_alias_shadows_url_name_warns() {
498        let toml = r#"
499[urls]
500github = { url = "https://github.com", aliases = ["rust"] }
501rust = "https://rust-lang.org"
502"#;
503        let config: Config = toml::from_str(toml).unwrap();
504        let warnings = config.validate();
505        assert!(!warnings.is_empty());
506        assert!(warnings.iter().any(|w| w.contains("shadows")));
507    }
508
509    #[test]
510    fn test_broken_group_entry_warns() {
511        let toml = r#"
512[urls]
513real = "https://example.com"
514
515[groups]
516dev = ["real", "ghost"]
517"#;
518        let config: Config = toml::from_str(toml).unwrap();
519        let warnings = config.validate();
520        assert_eq!(warnings.len(), 1);
521        assert!(warnings[0].contains("ghost"));
522    }
523
524    #[test]
525    fn test_rename_url_cascades_groups() {
526        let toml = r#"
527[urls]
528github = "https://github.com"
529
530[groups]
531dev = ["github"]
532"#;
533        let mut config: Config = toml::from_str(toml).unwrap();
534        config.rename_url("github", "gh-link").unwrap();
535        assert!(config.urls.contains_key("gh-link"));
536        assert!(!config.urls.contains_key("github"));
537        assert_eq!(config.groups.get("dev"), Some(&vec!["gh-link".to_string()]));
538    }
539
540    #[test]
541    fn test_rename_alias_cascades_groups() {
542        let toml = r#"
543[urls]
544github = { url = "https://github.com", aliases = ["gh"] }
545
546[groups]
547dev = ["gh"]
548all = ["gh", "other"]
549"#;
550        let mut config: Config = toml::from_str(toml).unwrap();
551        config.rename_alias("gh", "github-alias").unwrap();
552        let entry = config.urls.get("github").unwrap();
553        assert!(entry.has_alias("github-alias"));
554        assert!(!entry.has_alias("gh"));
555        assert_eq!(
556            config.groups.get("dev"),
557            Some(&vec!["github-alias".to_string()])
558        );
559        let all = config.groups.get("all").unwrap();
560        assert!(all.contains(&"github-alias".to_string()));
561        assert!(all.contains(&"other".to_string()));
562    }
563
564    #[test]
565    fn test_rename_nonexistent_url_errors() {
566        let mut config = Config::default();
567        assert!(config.rename_url("nope", "new").is_err());
568    }
569
570    #[test]
571    fn test_rename_nonexistent_alias_errors() {
572        let mut config = Config::default();
573        assert!(config.rename_alias("nope", "new").is_err());
574    }
575
576    #[test]
577    fn test_rename_url_collision_errors() {
578        let toml = r#"
579[urls]
580a = "https://a.com"
581b = "https://b.com"
582"#;
583        let mut config: Config = toml::from_str(toml).unwrap();
584        let result = config.rename_url("a", "b");
585        assert!(result.is_err());
586        assert!(result.unwrap_err().to_string().contains("already exists"));
587        assert!(config.urls.contains_key("a"));
588        assert!(config.urls.contains_key("b"));
589    }
590
591    #[test]
592    fn test_rename_alias_collision_errors() {
593        let toml = r#"
594[urls]
595a = { url = "https://a.com", aliases = ["x"] }
596b = { url = "https://b.com", aliases = ["y"] }
597"#;
598        let mut config: Config = toml::from_str(toml).unwrap();
599        let result = config.rename_alias("x", "y");
600        assert!(result.is_err());
601        assert!(result.unwrap_err().to_string().contains("already exists"));
602    }
603
604    #[test]
605    fn test_rename_url_to_existing_alias_errors() {
606        let toml = r#"
607[urls]
608github = { url = "https://github.com", aliases = ["gh"] }
609other = "https://other.com"
610"#;
611        let mut config: Config = toml::from_str(toml).unwrap();
612        let result = config.rename_url("other", "gh");
613        assert!(result.is_err());
614        assert!(
615            result
616                .unwrap_err()
617                .to_string()
618                .contains("already exists as an alias")
619        );
620        assert!(config.urls.contains_key("other"));
621    }
622
623    #[test]
624    fn test_rename_alias_to_existing_url_errors() {
625        let toml = r#"
626[urls]
627github = { url = "https://github.com", aliases = ["gh"] }
628other = "https://other.com"
629"#;
630        let mut config: Config = toml::from_str(toml).unwrap();
631        let result = config.rename_alias("gh", "other");
632        assert!(result.is_err());
633        assert!(
634            result
635                .unwrap_err()
636                .to_string()
637                .contains("already exists as a url name")
638        );
639        assert!(config.urls.get("github").unwrap().has_alias("gh"));
640    }
641
642    #[test]
643    fn test_rename_url_same_name_is_noop() {
644        let toml = r#"
645[urls]
646a = "https://a.com"
647"#;
648        let mut config: Config = toml::from_str(toml).unwrap();
649        config.rename_url("a", "a").unwrap();
650        assert_eq!(config.urls.get("a").unwrap().url(), "https://a.com");
651    }
652
653    #[test]
654    fn test_delete_url_cascades() {
655        let toml = r#"
656[urls]
657github = { url = "https://github.com", aliases = ["gh", "g"] }
658rust = "https://rust-lang.org"
659
660[groups]
661dev = ["gh", "github"]
662"#;
663        let mut config: Config = toml::from_str(toml).unwrap();
664        config.delete_url("github").unwrap();
665        assert!(!config.urls.contains_key("github"));
666        assert!(config.urls.contains_key("rust"));
667        // Group entries for both the url name and its aliases are removed
668        assert!(!config.groups.contains_key("dev"));
669    }
670
671    #[test]
672    fn test_delete_url_partial_group_cleanup() {
673        let toml = r#"
674[urls]
675github = { url = "https://github.com", aliases = ["gh"] }
676rust = "https://rust-lang.org"
677
678[groups]
679dev = ["gh", "rust"]
680"#;
681        let mut config: Config = toml::from_str(toml).unwrap();
682        config.delete_url("github").unwrap();
683        let dev = config.groups.get("dev").unwrap();
684        assert_eq!(dev, &vec!["rust".to_string()]);
685    }
686
687    #[test]
688    fn test_delete_alias_cascades_to_groups() {
689        let toml = r#"
690[urls]
691github = { url = "https://github.com", aliases = ["gh"] }
692
693[groups]
694dev = ["gh"]
695"#;
696        let mut config: Config = toml::from_str(toml).unwrap();
697        config.delete_alias("gh").unwrap();
698        // Alias removed from url entry
699        assert!(config.urls.get("github").unwrap().aliases().is_empty());
700        // Group with only "gh" is now empty and removed
701        assert!(!config.groups.contains_key("dev"));
702    }
703
704    #[test]
705    fn test_delete_group() {
706        let toml = r#"
707[groups]
708dev = ["gh"]
709"#;
710        let mut config: Config = toml::from_str(toml).unwrap();
711        config.delete_group("dev").unwrap();
712        assert!(!config.groups.contains_key("dev"));
713    }
714
715    #[test]
716    fn test_rename_group_collision_errors() {
717        let toml = r#"
718[groups]
719a = ["x"]
720b = ["y"]
721"#;
722        let mut config: Config = toml::from_str(toml).unwrap();
723        let result = config.rename_group("a", "b");
724        assert!(result.is_err());
725        assert!(result.unwrap_err().to_string().contains("already exists"));
726        assert!(config.groups.contains_key("a"));
727        assert!(config.groups.contains_key("b"));
728    }
729
730    #[test]
731    fn test_rename_group_cascades() {
732        let toml = r#"
733[groups]
734dev = ["gh", "rust"]
735"#;
736        let mut config: Config = toml::from_str(toml).unwrap();
737        config.rename_group("dev", "development").unwrap();
738        assert!(!config.groups.contains_key("dev"));
739        assert_eq!(
740            config.groups.get("development"),
741            Some(&vec!["gh".to_string(), "rust".to_string()])
742        );
743    }
744
745    #[test]
746    fn test_delete_nonexistent_errors() {
747        let mut config = Config::default();
748        assert!(config.delete_url("nope").is_err());
749        assert!(config.delete_alias("nope").is_err());
750        assert!(config.delete_group("nope").is_err());
751    }
752}