plannotator-tui 0.11.1

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
//! What kind of file a changed path is: code, tests, docs, config, generated or other. The
//! file list's kind filter (`filter-kinds`) shows or hides each kind.
//!
//! Tests and generated files follow the browser app's rules exactly, so both apps agree on
//! them: Plannotator's `packages/core/file-kind.ts` (`isTestPath`, `TEST_FOLDERS`,
//! `TEST_NAME`, `DEFAULT_GENERATED_PATTERNS`). The browser calls everything else "code";
//! here that splits into code, docs, config and other, by GitHub linguist's documentation
//! and vendored conventions and common file names. A few more generated rules have no
//! counterpart in the browser yet: more lockfiles, vendored folders, protobuf output.
//!
//! Pure: it reads the path only, never the file.

/// The kinds, in the order the picker lists them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum Kind {
    Code,
    Test,
    Docs,
    Config,
    Generated,
    Other,
}

pub(crate) const KINDS: [Kind; 6] =
    [Kind::Code, Kind::Test, Kind::Docs, Kind::Config, Kind::Generated, Kind::Other];

impl Kind {
    /// The picker's name for the kind; "Code", "Tests" and "Generated" are the browser's.
    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Code => "Code",
            Self::Test => "Tests",
            Self::Docs => "Docs",
            Self::Config => "Config",
            Self::Generated => "Generated",
            Self::Other => "Other",
        }
    }

    /// Where the kind is a position in [`KINDS`].
    pub(crate) fn index(self) -> usize {
        self as usize
    }
}

mod lists;

use lists::{
    CODE_EXT, CONFIG_EXT, CONFIG_NAMES, DOCS_EXT, DOCS_FOLDERS, DOCS_NAMES, GENERATED_FOLDERS,
    GENERATED_NAMES, GENERATED_SUFFIXES, MORE_GENERATED_NAMES, MORE_GENERATED_SUFFIXES, TEST_CODE_EXT,
    TEST_FOLDERS, TEST_MARKERS,
};

/// The kind of the file at `path`, a repository path with `/` between folders.
pub(crate) fn classify(path: &str) -> Kind {
    classify_with(path, None)
}

/// [`classify`], with `.gitattributes` `linguist-generated` when git has an opinion on the
/// path: `Some(true)` makes it generated, `Some(false)` keeps it from being generated by
/// name, as in Plannotator.
pub(crate) fn classify_with(path: &str, generated: Option<bool>) -> Kind {
    let (folders, name) = match path.rsplit_once('/') {
        Some((folders, name)) => (folders.split('/').collect::<Vec<_>>(), name),
        None => (Vec::new(), path),
    };
    if generated.unwrap_or_else(|| is_generated(&folders, name)) {
        Kind::Generated
    } else if is_test(&folders, name) {
        Kind::Test
    } else {
        by_name(&folders, name)
    }
}

/// Plannotator's `isDefaultGeneratedPath`, then the rules it does not have.
fn is_generated(folders: &[&str], name: &str) -> bool {
    let suffix = |suffixes: &[&str]| suffixes.iter().any(|s| name.len() > s.len() && name.ends_with(s));
    GENERATED_NAMES.contains(&name)
        || suffix(GENERATED_SUFFIXES)
        || MORE_GENERATED_NAMES.contains(&name)
        || suffix(MORE_GENERATED_SUFFIXES)
        || folders
            .iter()
            .enumerate()
            .any(|(i, f)| GENERATED_FOLDERS.contains(f) && !(*f == "dist" && under_src(folders, i)))
}

/// Whether a folder above `folders[at]` is `src`: a `dist` there is a module of the source
/// (`src/dist/mod.rs`), not a build's output.
fn under_src(folders: &[&str], at: usize) -> bool {
    folders.iter().take(at).any(|f| *f == "src")
}

/// Plannotator's `isTestPath`: a test file name, or a test folder above it.
fn is_test(folders: &[&str], name: &str) -> bool {
    is_test_name(name)
        || folders.iter().enumerate().any(|(i, folder)| {
            TEST_FOLDERS.contains(&folder.to_lowercase().as_str())
                || is_dotnet_test_project(folder)
                || (i > 0 && folders.get(i - 1) == Some(&"src") && is_source_set_test(folder))
        })
}

/// Plannotator's `TEST_NAME`, case-insensitive: `foo.test.ts`, `foo_test.go`,
/// `Button.stories.tsx`, `test_foo.py`, `conftest.py`, `tests.py`, `foo.snap`.
fn is_test_name(name: &str) -> bool {
    let lower = name.to_lowercase();
    let dotfile = lower.starts_with('.');
    if let Some((stem, ext)) = lower.rsplit_once('.')
        && TEST_CODE_EXT.contains(&ext)
    {
        let marked = TEST_MARKERS.iter().any(|marker| {
            stem.strip_suffix(marker)
                .and_then(|s| s.strip_suffix('.'))
                .is_some_and(|before| !before.is_empty())
        });
        if marked && !dotfile {
            return true;
        }
        if stem.strip_suffix("_test").is_some_and(|before| !before.is_empty()) {
            return true;
        }
    }
    let stories = lower.find(".stories.").is_some_and(|at| at > 0 && lower.len() > at + ".stories.".len());
    (stories && !dotfile)
        || lower.strip_prefix("test_").and_then(|s| s.strip_suffix(".py")).is_some_and(|s| !s.is_empty())
        || lower == "conftest.py"
        || lower == "tests.py"
        || lower.strip_suffix(".snap").is_some_and(|s| !s.is_empty())
}

/// .NET test projects, `Acme.Tests` and `Acme.UnitTests` (case-sensitive, as in the browser).
fn is_dotnet_test_project(folder: &str) -> bool {
    [".Tests", ".UnitTests"].iter().any(|end| folder.strip_suffix(end).is_some_and(|s| !s.is_empty()))
}

/// Gradle and Kotlin source sets right under `src`: `androidTest`, `integrationTest`.
fn is_source_set_test(folder: &str) -> bool {
    let mut chars = folder.chars();
    folder.len() > "Test".len()
        && folder.ends_with("Test")
        && chars.next().is_some_and(|c| c.is_ascii_lowercase())
        && chars.all(|c| c.is_ascii_alphanumeric())
}

/// Not generated and not a test: config, docs, code or other, by name and extension. A
/// documentation name (`README`, `LICENSE-MIT`) counts only without a code or data
/// extension, so `security.ts` stays code and `.github/workflows/security.yml` config, and
/// without any extension only capitalised, so `scripts/install` is not documentation. Code
/// and data in a docs folder stay code and config.
fn by_name(folders: &[&str], name: &str) -> Kind {
    let lower = name.to_lowercase();
    let dotfile = lower.starts_with('.');
    let ext =
        lower.rsplit_once('.').map(|(_, ext)| ext).filter(|_| !dotfile || lower.matches('.').count() > 1);
    let stem = lower.split('.').next().unwrap_or_default();
    let requirements = lower.starts_with("requirements") && ext == Some("txt");
    if CONFIG_NAMES.contains(&lower.as_str())
        || stem == "dockerfile"
        || lower.starts_with("docker-compose")
        || requirements
        || is_tool_config(&lower)
    {
        return Kind::Config;
    }
    if ext.is_some_and(|e| DOCS_EXT.contains(&e)) {
        return Kind::Docs;
    }
    if ext.is_some_and(|e| TEST_CODE_EXT.contains(&e) || CODE_EXT.contains(&e)) {
        return Kind::Code;
    }
    if dotfile || ext.is_some_and(|e| CONFIG_EXT.contains(&e)) {
        return Kind::Config;
    }
    let capitalised = name.chars().next().is_some_and(char::is_uppercase);
    let doc_name = (ext.is_some() || capitalised)
        && DOCS_NAMES.iter().any(|doc| {
            stem.strip_prefix(doc).is_some_and(|rest| rest.is_empty() || rest.starts_with(['-', '_']))
        });
    if doc_name || folders.iter().any(|f| DOCS_FOLDERS.contains(&f.to_lowercase().as_str())) {
        return Kind::Docs;
    }
    Kind::Other
}

/// A tool's own config file in a code language: `vite.config.ts`, `jest.config.js`,
/// `.eslintrc.cjs`, `babel.config.json`.
fn is_tool_config(lower: &str) -> bool {
    let Some((stem, _)) = lower.rsplit_once('.') else { return false };
    stem.ends_with(".config") || (stem.starts_with('.') && stem.ends_with("rc"))
}

#[cfg(test)]
mod tests;