fallow-extract 3.46.0

AST extraction engine for fallow codebase intelligence (parser, complexity, SFC / Astro / MDX / CSS)
Documentation
//! Generated-file check for commands that change source text.
//!
//! A code generator writes its output again on its next run, so an edit of
//! that output does not last. The check uses the path and header rule of
//! similar-code extraction, and it also reads a header that names the
//! generator: `// Generated by <tool> from <input>. Do not edit.`

use std::path::Path;

/// The header length that the check reads.
const HEADER_BYTES: usize = 2_048;

/// Whether the file at `path` with the text `source` is generated code.
#[must_use]
pub fn is_generated_file(path: &Path, source: &str) -> bool {
    let Some(file) = path.to_str() else {
        return false;
    };
    let file = file.replace('\\', "/");
    let source = crate::strip_bom(source);
    crate::similar_code::is_generated_source(&file, source)
        || leading_comment_names_generator(source)
}

/// Whether the comments before the first code of `source` hold both
/// "generated by" and "do not edit". Only the leading comments count, so a
/// scaffold banner such as "Generated by create-app" with an unrelated
/// "do not edit" note lower in the file is not a match.
fn leading_comment_names_generator(source: &str) -> bool {
    let header = leading_comments(source).to_ascii_lowercase();
    header.contains("generated by") && header.contains("do not edit")
}

/// The whitespace, line comments and block comments at the start of
/// `source`, up to [`HEADER_BYTES`].
fn leading_comments(source: &str) -> &str {
    let mut end = 0;
    while end < source.len().min(HEADER_BYTES) {
        let rest = &source[end..];
        let trimmed = rest.trim_start();
        let comment_len = if trimmed.starts_with("//") {
            trimmed
                .find('\n')
                .map_or(trimmed.len(), |newline| newline + 1)
        } else if trimmed.starts_with("/*") {
            match trimmed.find("*/") {
                Some(close) => close + 2,
                None => trimmed.len(),
            }
        } else {
            break;
        };
        end += (rest.len() - trimmed.len()) + comment_len;
    }
    &source[..end]
}

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

    fn generated(source: &str) -> bool {
        is_generated_file(Path::new("src/operations.graphql.ts"), source)
    }

    #[test]
    fn a_header_that_names_the_generator_marks_a_generated_file() {
        assert!(generated(
            "// Generated by @effect/graphql-generator from messages.graphql. Do not edit.\nexport const a = 1;\n"
        ));
        assert!(generated(
            "/* eslint-disable */\n/**\n * Generated by orval v7.\n * Do not edit manually.\n */\nexport const a = 1;\n"
        ));
    }

    #[test]
    fn the_similar_code_rule_still_applies() {
        assert!(generated("// @generated\nexport const a = 1;\n"));
        assert!(is_generated_file(
            Path::new("src/__generated__/client.ts"),
            "export const a = 1;\n"
        ));
    }

    #[test]
    fn a_scaffold_banner_is_not_a_generated_file() {
        assert!(!generated(
            "// Generated by create-app.\nexport const a = 1;\n"
        ));
        assert!(!generated(
            "// Generated by create-app.\nexport const a = 1;\n// Do not edit the line below.\n"
        ));
        assert!(!generated("export const a = 1;\n"));
    }
}