aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
mod file;

pub use file::{ReadmeWriteError, update_readme};

const START_MARKER: &str = "<!-- aoc-toolkit:progress:start -->";
const END_MARKER: &str = "<!-- aoc-toolkit:progress:end -->";

#[derive(Debug, thiserror::Error)]
pub enum ReadmeSectionError {
    #[error("README must contain exactly one ordered pair of progress markers on separate lines")]
    InvalidMarkers,

    #[error("Generated progress Markdown contains a progress marker")]
    GeneratedMarker,
}

/// Replaces the content between standalone progress markers.
///
/// # Errors
///
/// Returns an error if the markers are missing, duplicated, or reversed,
/// or if the replacement contains a progress marker.
pub fn replace_progress_section(
    readme: &str,
    markdown: &str,
) -> Result<String, ReadmeSectionError> {
    let (start, end, newline) = section_bounds(readme)?;
    let mut updated = String::new();
    updated.push_str(&readme[..start]);

    for line in markdown.lines() {
        if matches!(line, START_MARKER | END_MARKER) {
            return Err(ReadmeSectionError::GeneratedMarker);
        }

        updated.push_str(line);
        updated.push_str(newline);
    }

    updated.push_str(&readme[end..]);
    Ok(updated)
}

fn section_bounds(readme: &str) -> Result<(usize, usize, &'static str), ReadmeSectionError> {
    let mut start = None;
    let mut end = None;
    let mut newline = "\n";
    let mut offset = 0;

    for line in readme.split_inclusive('\n') {
        let marker = line.trim_end_matches(['\r', '\n']);
        match marker {
            START_MARKER => {
                if start.replace(offset + line.len()).is_some() {
                    return Err(ReadmeSectionError::InvalidMarkers);
                }

                if line.ends_with("\r\n") {
                    newline = "\r\n";
                }
            }
            END_MARKER if end.replace(offset).is_some() => {
                return Err(ReadmeSectionError::InvalidMarkers);
            }
            _ => {}
        }

        offset += line.len();
    }

    match (start, end) {
        (Some(start), Some(end)) if start <= end => Ok((start, end, newline)),
        _ => Err(ReadmeSectionError::InvalidMarkers),
    }
}

#[cfg(test)]
mod tests {
    use super::{END_MARKER, ReadmeSectionError, START_MARKER, replace_progress_section};

    #[test]
    fn preserves_surrounding_content_and_is_idempotent() {
        let original =
            format!("# My project\n\n{START_MARKER}\nOld progress\n{END_MARKER}\n\nNotes");
        let markdown = "### Progress\n\n| 2025 | 3/24 |\n";
        let expected = format!("# My project\n\n{START_MARKER}\n{markdown}{END_MARKER}\n\nNotes");

        let updated = replace_progress_section(&original, markdown).unwrap();

        assert_eq!(updated, expected);
        assert_eq!(
            replace_progress_section(&updated, markdown).unwrap(),
            updated
        );
    }

    #[test]
    fn uses_crlf_inside_a_crlf_section() {
        let original = format!("Before\r\n{START_MARKER}\r\n{END_MARKER}\r\nAfter");
        let expected = format!("Before\r\n{START_MARKER}\r\nOne\r\nTwo\r\n{END_MARKER}\r\nAfter");

        assert_eq!(
            replace_progress_section(&original, "One\nTwo\n").unwrap(),
            expected,
        );
    }

    #[test]
    fn rejects_missing_reversed_duplicate_and_inline_markers() {
        for input in [
            "# No markers".to_owned(),
            format!("{START_MARKER}\n"),
            format!("{END_MARKER}\n{START_MARKER}\n"),
            format!("{START_MARKER}\n{START_MARKER}\n{END_MARKER}\n"),
            format!("{START_MARKER}\n{END_MARKER}\n{END_MARKER}\n"),
            format!("Inline {START_MARKER}\n{END_MARKER}\n"),
        ] {
            assert!(matches!(
                replace_progress_section(&input, "Progress"),
                Err(ReadmeSectionError::InvalidMarkers),
            ));
        }
    }

    #[test]
    fn rejects_markers_in_generated_content() {
        let readme = format!("{START_MARKER}\n{END_MARKER}\n");

        assert!(matches!(
            replace_progress_section(&readme, END_MARKER),
            Err(ReadmeSectionError::GeneratedMarker),
        ));
    }
}