aboutsummaryrefslogtreecommitdiff
path: root/mling/src/proj_mgr/checklist_reader.rs
blob: 6d115bbd3a329d0795236e493f0f0525c366610a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::{collections::HashMap, path::Path, io};

/// Reads and parses a `CHECKLIST.md` file, extracting both *values* (from
/// fenced code blocks) and *toggles* (from checkbox lines).
///
/// # Format
///
/// - **Values**: fenced code blocks where the info string is the key and
///   the first non-empty line is the value.  Example:
///   <code>\`\`\`name<br>my-cli<br>\`\`\`</code>
/// - **Toggles**: checkbox lines like `- [x] \`ns:key\`` (checked) or
///   `- [ ] \`ns:key\`` (unchecked).
///
/// Checked items are stored as `"namespace:key"`.
///
/// # Usage
///
/// ```rust,ignore
/// let reader = CheckListReader::from(&Path::new("CHECKLIST.md")).unwrap();
/// assert_eq!(reader.read_value("name"), Some("my-cli".into()));
/// assert!(reader.read_toggle("ver:0.2"));
/// assert!(!reader.read_toggle("feat:comp"));
/// assert_eq!(reader.read_toggles("feat"), vec!["feat:async"]);
/// ```
pub struct CheckListReader {
    /// Values extracted from fenced code blocks: `key → value`.
    values: HashMap<String, String>,

    /// Checked toggles: `"namespace:key" → true` (only checked items are stored).
    toggles: HashMap<String, bool>,

    /// All toggles (checked or not): `"namespace:key" → checked`.
    all_toggles: HashMap<String, bool>,
}

impl CheckListReader {
    /// Parse a CHECKLIST.md from a file path in a single left-to-right pass
    pub fn from(path: &Path) -> Result<Self, io::Error> {
        let content = std::fs::read_to_string(path)?;

        let mut reader = Self {
            values: HashMap::new(),
            toggles: HashMap::new(),
            all_toggles: HashMap::new(),
        };
        reader.parse(&content);
        Ok(reader)
    }

    /// Parse CHECKLIST.md content in a single pass.
    fn parse(&mut self, content: &str) {
        let lines: Vec<&str> = content.lines().collect();
        let mut i = 0;

        while i < lines.len() {
            let line = lines[i];

            if let Some(key) = line.strip_prefix("```").map(|s| s.trim())
                && !key.is_empty() && !key.starts_with(' ') {
                    let mut block_lines = Vec::new();
                    i += 1;
                    while i < lines.len() && !lines[i].trim_start().starts_with("```") {
                        block_lines.push(lines[i]);
                        i += 1;
                    }
                    let value = block_lines
                        .into_iter()
                        .find(|l| !l.trim().is_empty())
                        .map(|l| l.trim().to_string());
                    if let Some(val) = value {
                        self.values.insert(key.to_string(), val);
                    }
                    continue;
                }

            if let Some(toggle_key) = Self::parse_toggle_line(line) {
                let is_checked = line.contains("[x]") || line.contains("[X]");
                self.all_toggles
                    .insert(toggle_key.clone(), is_checked);
                if is_checked {
                    self.toggles.insert(toggle_key, true);
                }
            }

            i += 1;
        }
    }

    /// Extract the `namespace:key` from a toggle line.
    ///
    /// Matches: `- [x] `namespace:key`` or `- [ ] `namespace:key``
    fn parse_toggle_line(line: &str) -> Option<String> {
        let line = line.trim();
        if !line.starts_with("- [") {
            return None;
        }
        // Find the backtick-enclosed key
        let start = line.find('`')?;
        let rest = &line[start + 1..];
        let end = rest.find('`')?;
        let key = rest[..end].trim();
        if key.is_empty() {
            return None;
        }
        Some(key.to_string())
    }

    /// Read a value by its key.
    ///
    /// Returns `Some(value)` if a fenced code block with that key was found,
    /// or `None` if the key does not exist.
    #[must_use]
    pub fn read_value(&self, key: &str) -> Option<String> {
        self.values.get(key).cloned()
    }

    /// Check if a toggle (`namespace:key`) is checked.
    ///
    /// Returns `true` if the checkbox line was `- [x]`, `false` if it was
    /// `- [ ]` or the key does not exist in the file.
    #[must_use]
    pub fn read_toggle(&self, key: &str) -> bool {
        self.toggles.contains_key(key)
    }

    /// Get all toggles under a given `namespace` that are checked.
    ///
    /// For example, `read_toggles("feat")` returns all checked keys starting
    /// with `"feat:"`, such as `["feat:comp", "feat:parser"]`.
    #[must_use]
    pub fn read_toggles(&self, namespace: &str) -> Vec<String> {
        let prefix = format!("{namespace}:");
        let mut keys: Vec<String> = self
            .toggles
            .keys()
            .filter(|k| k.starts_with(&prefix))
            .cloned()
            .collect();
        keys.sort();
        keys
    }

    /// Get ALL toggles (checked or not) under a namespace.
    ///
    /// Useful for iterating all available options.
    #[must_use]
    pub fn all_toggles(&self, namespace: &str) -> Vec<String> {
        let prefix = format!("{namespace}:");
        let mut keys: Vec<String> = self
            .all_toggles
            .keys()
            .filter(|k| k.starts_with(&prefix))
            .cloned()
            .collect();
        keys.sort();
        keys
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_md() -> &'static str {
        r#"> Some intro

## Question 1: What is your project name?

```name
my-cli
```

## Question 2: Which version?

- [x] `ver:0.2`

## Question 3: Features?

- [ ] `feat:structural_renderer`
- [x] `feat:comp`
- [x] `feat:parser`
- [ ] `feat:async`

```other
some value
```
"#
    }

    #[test]
    fn test_read_value() {
        let mut reader = CheckListReader {
            values: HashMap::new(),
            toggles: HashMap::new(),
            all_toggles: HashMap::new(),
        };
        reader.parse(sample_md());
        assert_eq!(reader.read_value("name"), Some("my-cli".into()));
        assert_eq!(reader.read_value("other"), Some("some value".into()));
        assert_eq!(reader.read_value("nonexistent"), None);
    }

    #[test]
    fn test_read_toggle() {
        let mut reader = CheckListReader {
            values: HashMap::new(),
            toggles: HashMap::new(),
            all_toggles: HashMap::new(),
        };
        reader.parse(sample_md());
        assert!(reader.read_toggle("ver:0.2"));
        assert!(reader.read_toggle("feat:comp"));
        assert!(reader.read_toggle("feat:parser"));
        assert!(!reader.read_toggle("feat:structural_renderer"));
        assert!(!reader.read_toggle("feat:async"));
        assert!(!reader.read_toggle("nonexistent:key"));
    }

    #[test]
    fn test_read_toggles() {
        let mut reader = CheckListReader {
            values: HashMap::new(),
            toggles: HashMap::new(),
            all_toggles: HashMap::new(),
        };
        reader.parse(sample_md());
        let feat_toggles = reader.read_toggles("feat");
        assert_eq!(feat_toggles, vec!["feat:comp", "feat:parser"]);
    }

    #[test]
    fn test_all_toggles() {
        let mut reader = CheckListReader {
            values: HashMap::new(),
            toggles: HashMap::new(),
            all_toggles: HashMap::new(),
        };
        reader.parse(sample_md());
        let all = reader.all_toggles("feat");
        assert_eq!(
            all,
            vec![
                "feat:async",
                "feat:comp",
                "feat:parser",
                "feat:structural_renderer",
            ]
        );
    }

    #[test]
    fn test_from_path() {
        // Write a temp CHECKLIST.md, read it, then clean up
        let dir = std::env::temp_dir().join("mling_checklist_test");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("CHECKLIST.md");
        std::fs::write(&path, sample_md()).unwrap();

        let reader = CheckListReader::from(&path).unwrap();
        assert_eq!(reader.read_value("name"), Some("my-cli".into()));
        assert!(reader.read_toggle("ver:0.2"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_empty_file() {
        let mut reader = CheckListReader {
            values: HashMap::new(),
            toggles: HashMap::new(),
            all_toggles: HashMap::new(),
        };
        reader.parse("");
        assert_eq!(reader.read_value("anything"), None);
        assert!(!reader.read_toggle("ns:key"));
        assert!(reader.read_toggles("ns").is_empty());
    }

    #[test]
    fn test_no_toggle_or_value_lines() {
        let md = "# Just a heading\n\nSome text\n\n```code\nstill not a value\n```\n";
        let mut reader = CheckListReader {
            values: HashMap::new(),
            toggles: HashMap::new(),
            all_toggles: HashMap::new(),
        };
        reader.parse(md);
        // "code" isn't a valid value key (it's used as a language tag, not a name/value key)
        // but our parser treats ANY ```key as a value block. This is correct behavior —
        // malformed CHECKLIST.md may produce unexpected values.
        assert_eq!(reader.read_value("code"), Some("still not a value".into()));
    }
}