Skip to main content

blyte_cli/
plan_section.rs

1//! Extract a task section from a plan file.
2
3#[derive(Copy, Clone, PartialEq, Eq)]
4enum Fence {
5    None,
6    Backticks(usize),
7    Tildes(usize),
8}
9
10impl Fence {
11    fn from_opening(trimmed_start: &str) -> Option<Fence> {
12        let bt = trimmed_start.chars().take_while(|&c| c == '`').count();
13        if bt >= 3 && !trimmed_start[bt..].contains('`') {
14            return Some(Fence::Backticks(bt));
15        }
16        let tl = trimmed_start.chars().take_while(|&c| c == '~').count();
17        if tl >= 3 {
18            return Some(Fence::Tildes(tl));
19        }
20        None
21    }
22
23    fn is_closing(&self, trimmed_start: &str) -> bool {
24        match *self {
25            Fence::None => false,
26            Fence::Backticks(min) => {
27                let bt = trimmed_start.chars().take_while(|&c| c == '`').count();
28                bt >= min && trimmed_start[bt..].trim().is_empty()
29            }
30            Fence::Tildes(min) => {
31                let tl = trimmed_start.chars().take_while(|&c| c == '~').count();
32                tl >= min && trimmed_start[tl..].trim().is_empty()
33            }
34        }
35    }
36}
37
38/// The section of `plan` whose heading matches `task`, including the heading line, up to (not
39/// including) the next heading of the same or a higher level (fewer or equal `#`), or the end.
40/// A heading matches when its text after the `#`s, trimmed, equals `task` trimmed, or starts with
41/// `task` followed by `:`, ` -`, ` —` or ` (`. Example: task "Task B2" matches
42/// "### Task B2: the parser" and "### Task B2", but not "### Task B20".
43/// Headings inside fenced code blocks (``` or ~~~) are ignored.
44/// Returns None if no heading matches; if several match, the first.
45pub fn extract(plan: &str, task: &str) -> Option<String> {
46    let task_trimmed = task.trim();
47    if task_trimmed.is_empty() {
48        return None;
49    }
50
51    let mut fence = Fence::None;
52    let mut matched_start: Option<usize> = None;
53    let mut matched_level: usize = 0;
54    let mut matched_end: Option<usize> = None;
55
56    let mut offset = 0;
57    for line in plan.split_inclusive('\n') {
58        let line_offset = offset;
59        offset += line.len();
60
61        let line_content = line.trim_end_matches(['\r', '\n']);
62        let trimmed_start = line_content.trim_start();
63
64        if fence == Fence::None {
65            if let Some(opened) = Fence::from_opening(trimmed_start) {
66                fence = opened;
67                continue;
68            }
69
70            if let Some((hashes, heading_text)) = parse_atx_heading(trimmed_start) {
71                if matched_start.is_none() {
72                    if heading_matches(heading_text, task_trimmed) {
73                        matched_start = Some(line_offset);
74                        matched_level = hashes;
75                    }
76                } else if hashes <= matched_level {
77                    matched_end = Some(line_offset);
78                    break;
79                }
80            }
81        } else if fence.is_closing(trimmed_start) {
82            fence = Fence::None;
83        }
84    }
85
86    matched_start.map(|start| {
87        let end = matched_end.unwrap_or(plan.len());
88        plan[start..end].to_string()
89    })
90}
91
92/// Explain why a task section was not found in `plan`, if due to code block fence issues.
93/// Used only after `extract` returned `None`.
94pub fn explain_missing(plan: &str, task: &str) -> Option<String> {
95    let task_trimmed = task.trim();
96    if task_trimmed.is_empty() {
97        return None;
98    }
99
100    let mut fence = Fence::None;
101    let mut fence_open_line: usize = 0;
102
103    for (idx, line) in plan.split_inclusive('\n').enumerate() {
104        let line_num = idx + 1;
105        let line_content = line.trim_end_matches(['\r', '\n']);
106        let trimmed_start = line_content.trim_start();
107
108        if fence == Fence::None {
109            if let Some(opened) = Fence::from_opening(trimmed_start) {
110                fence = opened;
111                fence_open_line = line_num;
112                continue;
113            }
114        } else if fence.is_closing(trimmed_start) {
115            fence = Fence::None;
116        } else if let Some((_, heading_text)) = parse_atx_heading(trimmed_start) {
117            if heading_matches(heading_text, task_trimmed) {
118                return Some(format!(
119                    "the heading at line {line_num} is inside a code block that opens at line {fence_open_line}; an inner fence may have closed an outer one early (nest with a longer fence such as ```` around ```)"
120                ));
121            }
122        }
123    }
124
125    if fence != Fence::None {
126        Some(format!(
127            "the code block that opens at line {fence_open_line} is never closed, so headings after it are not read"
128        ))
129    } else {
130        None
131    }
132}
133
134fn parse_atx_heading(trimmed_start: &str) -> Option<(usize, &str)> {
135    let hashes = trimmed_start.chars().take_while(|&c| c == '#').count();
136    if hashes > 0 {
137        let after = &trimmed_start[hashes..];
138        if after.starts_with(' ') || after.starts_with('\t') || after.is_empty() {
139            let heading_raw = after.trim();
140            let heading_text = if let Some(stripped) = heading_raw.strip_suffix('#') {
141                let stripped_all = stripped.trim_end_matches('#');
142                if stripped_all.ends_with(' ')
143                    || stripped_all.ends_with('\t')
144                    || stripped_all.is_empty()
145                {
146                    stripped_all.trim()
147                } else {
148                    heading_raw
149                }
150            } else {
151                heading_raw
152            };
153            return Some((hashes, heading_text));
154        }
155    }
156    None
157}
158
159fn heading_matches(heading_text: &str, task_trimmed: &str) -> bool {
160    if heading_text == task_trimmed {
161        return true;
162    }
163    if let Some(rest) = heading_text.strip_prefix(task_trimmed) {
164        if rest.starts_with(':')
165            || rest.starts_with(" -")
166            || rest.starts_with(" —")
167            || rest.starts_with(" (")
168        {
169            return true;
170        }
171    }
172    false
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn match_with_colon_returns_through_line_before_next_heading() {
181        let plan = "\
182# Intro
183Some overview.
184
185### Task B2: the parser
186Parse the input tokens.
187Handle error cases.
188
189### Task B3: code generation
190Generate bytecode.
191";
192        let extracted = extract(plan, "Task B2");
193        assert_eq!(
194            extracted,
195            Some(
196                "### Task B2: the parser\nParse the input tokens.\nHandle error cases.\n\n"
197                    .to_string()
198            )
199        );
200    }
201
202    #[test]
203    fn exact_task_name_match() {
204        let plan = "\
205### Task B2
206Parse the input tokens.
207
208### Task B3
209Other.
210";
211        let extracted = extract(plan, "Task B2");
212        assert_eq!(
213            extracted,
214            Some("### Task B2\nParse the input tokens.\n\n".to_string())
215        );
216    }
217
218    #[test]
219    fn variations_of_matching_delimiters() {
220        let hyphen = extract("### Task B2 - the parser\nbody\n### End\n", "Task B2");
221        assert_eq!(hyphen, Some("### Task B2 - the parser\nbody\n".to_string()));
222
223        let em_dash = extract("### Task B2 — the parser\nbody\n### End\n", "Task B2");
224        assert_eq!(
225            em_dash,
226            Some("### Task B2 — the parser\nbody\n".to_string())
227        );
228
229        let paren = extract("### Task B2 (the parser)\nbody\n### End\n", "Task B2");
230        assert_eq!(paren, Some("### Task B2 (the parser)\nbody\n".to_string()));
231    }
232
233    #[test]
234    fn task_b2_does_not_match_task_b20_and_returns_b2_when_both_exist() {
235        let plan = "\
236### Task B20: twenty
237This is task 20.
238
239### Task B2: two
240This is task 2.
241
242### Task B3: three
243This is task 3.
244";
245        let extracted = extract(plan, "Task B2");
246        assert_eq!(
247            extracted,
248            Some("### Task B2: two\nThis is task 2.\n\n".to_string())
249        );
250    }
251
252    #[test]
253    fn higher_level_heading_ends_section_subheading_does_not() {
254        let plan = "\
255### Task B2: the parser
256Parser description.
257
258#### Implementation notes
259Some detailed steps here.
260
261##### Deep note
262Even deeper.
263
264## Architecture
265Next high-level section.
266";
267        let extracted = extract(plan, "Task B2");
268        assert_eq!(
269            extracted,
270            Some(
271                "### Task B2: the parser\nParser description.\n\n#### Implementation notes\nSome detailed steps here.\n\n##### Deep note\nEven deeper.\n\n".to_string()
272            )
273        );
274    }
275
276    #[test]
277    fn heading_inside_backtick_fence_is_not_a_heading() {
278        let plan = "\
279Here is a code example:
280```markdown
281### Task B2: fake
282Inside fence.
283```
284
285### Task B2: real
286Real body.
287
288### Task B3
289After.
290";
291        let extracted = extract(plan, "Task B2");
292        assert_eq!(
293            extracted,
294            Some("### Task B2: real\nReal body.\n\n".to_string())
295        );
296    }
297
298    #[test]
299    fn heading_inside_tilde_fence_is_not_a_heading() {
300        let plan = "\
301~~~
302### Task B2: fake
303Inside tilde fence.
304~~~
305";
306        assert_eq!(extract(plan, "Task B2"), None);
307    }
308
309    #[test]
310    fn fence_inside_section_does_not_end_section_on_nested_heading() {
311        let plan = "\
312### Task B2
313```markdown
314## Not a real section break
315```
316Still in Task B2.
317
318### Task B3
319End.
320";
321        let extracted = extract(plan, "Task B2");
322        assert_eq!(
323            extracted,
324            Some(
325                "### Task B2\n```markdown\n## Not a real section break\n```\nStill in Task B2.\n\n"
326                    .to_string()
327            )
328        );
329    }
330
331    #[test]
332    fn section_at_end_of_file_returns_to_the_end() {
333        let plan = "\
334# Overview
335Some text.
336
337### Task B2: the parser
338All the way to EOF";
339        let extracted = extract(plan, "Task B2");
340        assert_eq!(
341            extracted,
342            Some("### Task B2: the parser\nAll the way to EOF".to_string())
343        );
344
345        let plan_with_nl = "\
346# Overview
347
348### Task B2: the parser
349All the way to EOF with newline.
350";
351        let extracted2 = extract(plan_with_nl, "Task B2");
352        assert_eq!(
353            extracted2,
354            Some("### Task B2: the parser\nAll the way to EOF with newline.\n".to_string())
355        );
356    }
357
358    #[test]
359    fn no_match_returns_none() {
360        let plan = "\
361# Overview
362### Task A1
363### Task A2
364";
365        assert_eq!(extract(plan, "Task B2"), None);
366        assert_eq!(extract("", "Task B2"), None);
367        assert_eq!(extract(plan, ""), None);
368    }
369
370    #[test]
371    fn returns_first_match_if_several_match() {
372        let plan = "\
373### Task B2: first
374First implementation.
375
376### Task B2: second
377Second implementation.
378";
379        let extracted = extract(plan, "Task B2");
380        assert_eq!(
381            extracted,
382            Some("### Task B2: first\nFirst implementation.\n\n".to_string())
383        );
384    }
385
386    #[test]
387    fn explain_missing_oc5_shape_unclosed_fence() {
388        let plan = "\
389# Intro
390Some text.
391```markdown
392Line 4
393```bash
394Line 6
395```
396Line 8
397```
398Line 10
399### Task X: y
400Line 12
401";
402        assert_eq!(extract(plan, "Task X"), None);
403        assert_eq!(
404            explain_missing(plan, "Task X"),
405            Some(
406                "the heading at line 11 is inside a code block that opens at line 9; an inner fence may have closed an outer one early (nest with a longer fence such as ```` around ```)".to_string()
407            )
408        );
409    }
410
411    #[test]
412    fn explain_missing_heading_inside_closed_fence() {
413        let plan = "\
414# Intro
415```
416### Task X
417```
418Other text.
419";
420        assert_eq!(extract(plan, "Task X"), None);
421        assert_eq!(
422            explain_missing(plan, "Task X"),
423            Some(
424                "the heading at line 3 is inside a code block that opens at line 2; an inner fence may have closed an outer one early (nest with a longer fence such as ```` around ```)".to_string()
425            )
426        );
427    }
428
429    #[test]
430    fn explain_missing_unclosed_fence_without_matching_heading() {
431        let plan = "\
432# Intro
433```
434Some code that never closes.
435";
436        assert_eq!(extract(plan, "Task X"), None);
437        assert_eq!(
438            explain_missing(plan, "Task X"),
439            Some(
440                "the code block that opens at line 2 is never closed, so headings after it are not read".to_string()
441            )
442        );
443    }
444
445    #[test]
446    fn explain_missing_no_fences_and_no_matching_heading() {
447        let plan = "\
448# Intro
449Some text.
450### Other Task
451More text.
452";
453        assert_eq!(extract(plan, "Task X"), None);
454        assert_eq!(explain_missing(plan, "Task X"), None);
455    }
456
457    #[test]
458    fn explain_missing_heading_inside_tilde_fence() {
459        let plan = "\
460# Intro
461~~~
462### Task X
463~~~
464Other text.
465";
466        assert_eq!(extract(plan, "Task X"), None);
467        assert_eq!(
468            explain_missing(plan, "Task X"),
469            Some(
470                "the heading at line 3 is inside a code block that opens at line 2; an inner fence may have closed an outer one early (nest with a longer fence such as ```` around ```)".to_string()
471            )
472        );
473    }
474}