Skip to main content

aoc_toolkit/application/progress/
readme.rs

1mod file;
2
3pub use file::{ReadmeWriteError, update_readme};
4
5const START_MARKER: &str = "<!-- aoc-toolkit:progress:start -->";
6const END_MARKER: &str = "<!-- aoc-toolkit:progress:end -->";
7
8#[derive(Debug, thiserror::Error)]
9pub enum ReadmeSectionError {
10    #[error("README must contain exactly one ordered pair of progress markers on separate lines")]
11    InvalidMarkers,
12
13    #[error("Generated progress Markdown contains a progress marker")]
14    GeneratedMarker,
15}
16
17/// Replaces the content between standalone progress markers.
18///
19/// # Errors
20///
21/// Returns an error if the markers are missing, duplicated, or reversed,
22/// or if the replacement contains a progress marker.
23pub fn replace_progress_section(
24    readme: &str,
25    markdown: &str,
26) -> Result<String, ReadmeSectionError> {
27    let (start, end, newline) = section_bounds(readme)?;
28    let mut updated = String::new();
29    updated.push_str(&readme[..start]);
30
31    for line in markdown.lines() {
32        if matches!(line, START_MARKER | END_MARKER) {
33            return Err(ReadmeSectionError::GeneratedMarker);
34        }
35
36        updated.push_str(line);
37        updated.push_str(newline);
38    }
39
40    updated.push_str(&readme[end..]);
41    Ok(updated)
42}
43
44fn section_bounds(readme: &str) -> Result<(usize, usize, &'static str), ReadmeSectionError> {
45    let mut start = None;
46    let mut end = None;
47    let mut newline = "\n";
48    let mut offset = 0;
49
50    for line in readme.split_inclusive('\n') {
51        let marker = line.trim_end_matches(['\r', '\n']);
52        match marker {
53            START_MARKER => {
54                if start.replace(offset + line.len()).is_some() {
55                    return Err(ReadmeSectionError::InvalidMarkers);
56                }
57
58                if line.ends_with("\r\n") {
59                    newline = "\r\n";
60                }
61            }
62            END_MARKER if end.replace(offset).is_some() => {
63                return Err(ReadmeSectionError::InvalidMarkers);
64            }
65            _ => {}
66        }
67
68        offset += line.len();
69    }
70
71    match (start, end) {
72        (Some(start), Some(end)) if start <= end => Ok((start, end, newline)),
73        _ => Err(ReadmeSectionError::InvalidMarkers),
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::{END_MARKER, ReadmeSectionError, START_MARKER, replace_progress_section};
80
81    #[test]
82    fn preserves_surrounding_content_and_is_idempotent() {
83        let original =
84            format!("# My project\n\n{START_MARKER}\nOld progress\n{END_MARKER}\n\nNotes");
85        let markdown = "### Progress\n\n| 2025 | 3/24 |\n";
86        let expected = format!("# My project\n\n{START_MARKER}\n{markdown}{END_MARKER}\n\nNotes");
87
88        let updated = replace_progress_section(&original, markdown).unwrap();
89
90        assert_eq!(updated, expected);
91        assert_eq!(
92            replace_progress_section(&updated, markdown).unwrap(),
93            updated
94        );
95    }
96
97    #[test]
98    fn uses_crlf_inside_a_crlf_section() {
99        let original = format!("Before\r\n{START_MARKER}\r\n{END_MARKER}\r\nAfter");
100        let expected = format!("Before\r\n{START_MARKER}\r\nOne\r\nTwo\r\n{END_MARKER}\r\nAfter");
101
102        assert_eq!(
103            replace_progress_section(&original, "One\nTwo\n").unwrap(),
104            expected,
105        );
106    }
107
108    #[test]
109    fn rejects_missing_reversed_duplicate_and_inline_markers() {
110        for input in [
111            "# No markers".to_owned(),
112            format!("{START_MARKER}\n"),
113            format!("{END_MARKER}\n{START_MARKER}\n"),
114            format!("{START_MARKER}\n{START_MARKER}\n{END_MARKER}\n"),
115            format!("{START_MARKER}\n{END_MARKER}\n{END_MARKER}\n"),
116            format!("Inline {START_MARKER}\n{END_MARKER}\n"),
117        ] {
118            assert!(matches!(
119                replace_progress_section(&input, "Progress"),
120                Err(ReadmeSectionError::InvalidMarkers),
121            ));
122        }
123    }
124
125    #[test]
126    fn rejects_markers_in_generated_content() {
127        let readme = format!("{START_MARKER}\n{END_MARKER}\n");
128
129        assert!(matches!(
130            replace_progress_section(&readme, END_MARKER),
131            Err(ReadmeSectionError::GeneratedMarker),
132        ));
133    }
134}