Skip to main content

mps/
ref_resolver.rs

1//! Bidirectional epoch-ref ↔ human-ref translator.
2//!
3//! Mirrors Ruby's `MPS::RefResolver` exactly.
4//!
5//! Human ref format:
6//!   Top-level:  `{type}-{n}`           e.g. `task-1`, `note-2`, `mps-1`
7//!   Nested:     `{parent_human}.{idx}` e.g. `mps-1.1`, `task-2.3`
8//!
9//! The resolver is ephemeral — instantiated per-request from a parsed elements map.
10
11use std::collections::HashMap;
12use indexmap::IndexMap;
13use crate::elements::{Element, ElementKind};
14
15pub struct RefResolver {
16    epoch_to_human: HashMap<String, String>,
17    human_to_epoch: HashMap<String, String>,
18}
19
20impl RefResolver {
21    /// Build a resolver from a parsed elements map (as produced by `parser::parse_file`).
22    pub fn new(elements: &IndexMap<String, Element>) -> Self {
23        let mut r = RefResolver {
24            epoch_to_human: HashMap::new(),
25            human_to_epoch: HashMap::new(),
26        };
27        r.build_maps(elements);
28        r
29    }
30
31    /// Return the human ref for an epoch ref, or None if not mapped.
32    pub fn to_human(&self, epoch_ref: &str) -> Option<&str> {
33        self.epoch_to_human.get(epoch_ref).map(|s| s.as_str())
34    }
35
36    /// Return the epoch ref for a human ref, or None if not mapped.
37    pub fn to_epoch(&self, human_ref: &str) -> Option<&str> {
38        self.human_to_epoch.get(human_ref).map(|s| s.as_str())
39    }
40
41    /// Resolve either form. Human refs are translated; epoch refs are validated and returned as-is.
42    #[allow(dead_code)]
43    pub fn resolve<'a>(&'a self, ref_str: &'a str) -> Option<&'a str> {
44        if let Some(epoch) = self.human_to_epoch.get(ref_str) {
45            return Some(epoch.as_str());
46        }
47        if self.epoch_to_human.contains_key(ref_str) {
48            return Some(ref_str);
49        }
50        None
51    }
52
53    fn build_maps(&mut self, elements: &IndexMap<String, Element>) {
54        if elements.is_empty() { return; }
55
56        // Sort by ref-path parts numerically (mirrors Ruby's sort_by { k.split(".").map(&:to_i) })
57        let mut sorted: Vec<(&String, &Element)> = elements.iter().collect();
58        sorted.sort_by(|(a, _), (b, _)| {
59            let a_parts: Vec<u64> = a.split('.').filter_map(|s| s.parse().ok()).collect();
60            let b_parts: Vec<u64> = b.split('.').filter_map(|s| s.parse().ok()).collect();
61            a_parts.cmp(&b_parts)
62        });
63
64        // root_depth = number of segments in the synthetic root wrapper ref (always 1: just the epoch)
65        let root_depth = sorted.first().map(|(k, _)| k.split('.').count()).unwrap_or(1);
66        let mut type_counters: HashMap<String, usize> = HashMap::new();
67
68        for (epoch_ref, el) in &sorted {
69            let seg_count = epoch_ref.split('.').count();
70            let depth = seg_count - root_depth; // 0 = root, 1 = top-level, 2+ = nested
71
72            if depth == 0 { continue; } // skip synthetic root @mps wrapper
73
74            let human = if depth == 1 {
75                // Top-level: skip Unknown elements (mirrors Ruby behaviour)
76                if el.kind() == ElementKind::Unknown { continue; }
77                let type_name = el.sign().to_string();
78                let n = type_counters.entry(type_name.clone()).or_insert(0);
79                *n += 1;
80                format!("{}-{}", type_name, n)
81            } else {
82                // Nested: parent_epoch is all segments except the last
83                let parts: Vec<&str> = epoch_ref.splitn(seg_count, '.').collect();
84                let parent_epoch = parts[..parts.len() - 1].join(".");
85                let child_idx = parts[parts.len() - 1];
86                match self.epoch_to_human.get(&parent_epoch) {
87                    Some(parent_human) => format!("{}.{}", parent_human, child_idx),
88                    None => continue, // parent not mapped → skip
89                }
90            };
91
92            self.epoch_to_human.insert(epoch_ref.to_string(), human.clone());
93            self.human_to_epoch.insert(human, epoch_ref.to_string());
94        }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::parser;
102
103    fn parse(content: &str) -> IndexMap<String, Element> {
104        let wrapped = format!("@mps[]{{\n{}\n}}", content);
105        parser::parse_wrapped(&wrapped, 20260101).unwrap()
106    }
107
108    #[test]
109    fn test_empty_elements() {
110        let els = parse("");
111        let r = RefResolver::new(&els);
112        // Only root wrapper — nothing mapped (depth 0 skipped)
113        assert!(r.epoch_to_human.is_empty());
114    }
115
116    #[test]
117    fn test_top_level_task() {
118        let els = parse("@task[work]{ Do thing }");
119        let r = RefResolver::new(&els);
120        assert_eq!(r.to_human("20260101.1"), Some("task-1"));
121        assert_eq!(r.to_epoch("task-1"), Some("20260101.1"));
122    }
123
124    #[test]
125    fn test_sequential_types() {
126        let els = parse("@task{ A }\n@note{ B }\n@task{ C }");
127        let r = RefResolver::new(&els);
128        assert_eq!(r.to_human("20260101.1"), Some("task-1"));
129        assert_eq!(r.to_human("20260101.2"), Some("note-1"));
130        assert_eq!(r.to_human("20260101.3"), Some("task-2"));
131    }
132
133    #[test]
134    fn test_nested_inside_mps() {
135        let els = parse("@mps{\n  @task{ Nested }\n  @note{ also }\n}");
136        let r = RefResolver::new(&els);
137        // mps-1 is the @mps group
138        assert_eq!(r.to_human("20260101.1"), Some("mps-1"));
139        // task inside = mps-1.1, note inside = mps-1.2
140        assert_eq!(r.to_human("20260101.1.1"), Some("mps-1.1"));
141        assert_eq!(r.to_human("20260101.1.2"), Some("mps-1.2"));
142    }
143
144    #[test]
145    fn test_resolve_accepts_both_forms() {
146        let els = parse("@task{ A }");
147        let r = RefResolver::new(&els);
148        assert_eq!(r.resolve("task-1"), Some("20260101.1"));
149        assert_eq!(r.resolve("20260101.1"), Some("20260101.1"));
150        assert_eq!(r.resolve("bogus"), None);
151    }
152
153    #[test]
154    fn test_unknown_element_skipped() {
155        let els = parse("@widget{ unknown }\n@task{ real }");
156        let r = RefResolver::new(&els);
157        // widget at .1 should be skipped; task at .2 should be task-1
158        assert!(r.to_human("20260101.1").is_none());
159        assert_eq!(r.to_human("20260101.2"), Some("task-1"));
160    }
161
162    #[test]
163    fn test_roundtrip() {
164        let els = parse("@task[work]{ A }\n@note{ B }");
165        let r = RefResolver::new(&els);
166        for epoch_ref in r.epoch_to_human.keys() {
167            let human = r.to_human(epoch_ref).unwrap();
168            let back  = r.to_epoch(human).unwrap();
169            assert_eq!(back, epoch_ref.as_str());
170        }
171    }
172}