zamm_yang 0.1.6

A basic, experimental code generator
Documentation
use crate::codegen::{add_indent, count_indent, CODE_WIDTH};

/// Marker for getting rustfmt to skip over this line.
pub const FMT_SKIP_MARKER: &str = "#[rustfmt::skip]";

/// Add the fmt skip marker at the same level of indent as the line is.
fn add_fmt_skip(line: &str) -> String {
    if line.len() <= CODE_WIDTH {
        line.to_owned()
    } else {
        let (indent_size, _) = count_indent(line);
        format!("{}\n{}", add_indent(indent_size, FMT_SKIP_MARKER), line)
    }
}

/// Add any relevant rustfmt skip markers for autogenerated code.
pub fn add_fmt_skips(code: &str) -> String {
    if code.is_empty() {
        return code.to_string(); // edge case to avoid inserting a superfluous newline
    }

    let mut result = String::new();
    for line in code.split('\n') {
        result.push_str(add_fmt_skip(line).as_str());
        result.push('\n');
    }
    if result.ends_with("\n\n") {
        // happens if input code already contains trailing newline
        result.pop();
    }
    result
}

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

    #[test]
    fn test_mark_fmt_empty_str() {
        assert_eq!(add_fmt_skips(""), "");
    }

    #[test]
    fn test_mark_fmt_newline_str() {
        assert_eq!(add_fmt_skips("\n"), "\n");
    }

    #[test]
    fn test_mark_fmt_short_statement() {
        assert_eq!(
            add_fmt_skips("Short line."),
            indoc! {"
            Short line.
            "}
        );
    }

    #[test]
    fn test_mark_fmt_long_statement() {
        assert_eq!(
            add_fmt_skips(indoc! {"
            A really long statement, look here. Is it just me, or is it getting crazier out there?
            "}),
            indoc! {"
            #[rustfmt::skip]
            A really long statement, look here. Is it just me, or is it getting crazier out there?
            "}
        );
    }

    #[test]
    fn test_mark_fmt_mixed_statements() {
        assert_eq!(
            add_fmt_skips(indoc! {"
            Shorty.
            A really long statement, look here. Is it just me, or is it getting crazier out there?

            Uhuh. Wow.
            "}),
            indoc! {"
            Shorty.
            #[rustfmt::skip]
            A really long statement, look here. Is it just me, or is it getting crazier out there?

            Uhuh. Wow.
            "}
        );
    }

    #[test]
    fn test_mark_fmt_indent() {
        assert_eq!(
            add_fmt_skips(indoc! {"
            Shorty {
                A really long statement, look here. Is it just me, or is it getting crazier out there?
            }
            "}),
            indoc! {"
            Shorty {
                #[rustfmt::skip]
                A really long statement, look here. Is it just me, or is it getting crazier out there?
            }
            "}
        );
    }
}