prosecop 0.1.0

Checks identifiers and doc comments against a repository's house style
//! The rulesets that prosecop checks against, built in or read from a directory, and the kinds of text they check.
//!
//! A built-in ruleset is named for the writer whose habits it targets, at a generation, such as `claude@5` for the
//! Claude 5 models. Its files live in a directory of that name and are compiled into the binary. A directory of a
//! repository's own rules has the same layout, and is named by its path.

use std::path::Path;

/// A kind of text that a ruleset checks, by the file of its rules.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
    Identifiers,
    Docs,
    /// The string literals of code that are shaped like sentences, such as messages.
    Strings,
}

impl Kind {
    pub const ALL: [Kind; 3] = [Kind::Identifiers, Kind::Docs, Kind::Strings];

    /// The name of the file of the rules of this kind.
    pub fn file(self) -> &'static str {
        match self {
            Kind::Identifiers => "identifiers.txt",
            Kind::Docs => "docs.txt",
            Kind::Strings => "strings.txt",
        }
    }

    /// The kind whose file `name` is, with or without its `.txt`.
    fn of_file(name: &str) -> Option<Kind> {
        Kind::ALL.into_iter().find(|kind| kind.file() == name || kind.file().strip_suffix(".txt") == Some(name))
    }
}

/// A set of rules, by its name, the text of the rules of each kind it has, and its advice for forbidden words.
#[derive(Default)]
pub struct Ruleset {
    pub name: String,
    /// One forbidden word per line, then `except PATH ...` or `allow COMPOUND ...`, then `# reason`.
    pub identifiers: Option<String>,
    /// The rules found by pattern in docs, in the format that `claude@5/docs.txt` describes.
    pub docs: Option<String>,
    /// The rules found by pattern in string literals, in the format of `docs`.
    pub strings: Option<String>,
    /// The advice printed after the forbidden words found.
    pub identifiers_advice: String,
    /// The advice printed after the broken rules of strings found.
    pub strings_advice: String,
}

impl Ruleset {
    /// The text of the rules of `kind`, where this ruleset has them.
    pub fn rules(&self, kind: Kind) -> Option<&str> {
        match kind {
            Kind::Identifiers => self.identifiers.as_deref(),
            Kind::Docs => self.docs.as_deref(),
            Kind::Strings => self.strings.as_deref(),
        }
    }
}

/// The built-in rulesets, by name, with the text of their files.
const BUILT_IN: &[(&str, &[(&str, &str)])] = &[(
    "claude@5",
    &[
        ("identifiers.txt", include_str!("claude@5/identifiers.txt")),
        ("docs.txt", include_str!("claude@5/docs.txt")),
        ("strings.txt", include_str!("claude@5/strings.txt")),
        ("identifiers-advice.txt", include_str!("claude@5/identifiers-advice.txt")),
        ("strings-advice.txt", include_str!("claude@5/strings-advice.txt")),
    ],
)];

/// The ruleset that `arg` names, and the one kind it picks, if it names the file of one.
///
/// - A path that exists is a directory of rules. A path whose directory exists names one rules file in that
///   directory, which may be missing.
/// - Any other argument is a built-in name, such as `claude@5`, or a built-in name and a file, such as
///   `claude@5/docs.txt`.
/// - A rules file may be named without its `.txt`, such as `claude@5/docs`.
pub fn resolve(arg: &str) -> Result<(Ruleset, Option<Kind>), String> {
    let path = Path::new(arg);
    let in_dir = path.parent().is_some_and(|p| p.is_dir()) && path.file_name().is_some_and(|n| n != "..");
    if path.exists() || in_dir && !arg.ends_with('/') {
        let (dir, kind) = match path.is_dir() {
            true => (path, None),
            false => (path.parent().unwrap_or(Path::new(".")), Some(kind_of(arg, path)?)),
        };
        let read = |name: &str| {
            let file = dir.join(name);
            file.exists().then(|| std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display())))
        };
        let ruleset = Ruleset {
            name: dir.display().to_string(),
            identifiers: read(Kind::Identifiers.file()).transpose()?,
            docs: read(Kind::Docs.file()).transpose()?,
            strings: read(Kind::Strings.file()).transpose()?,
            identifiers_advice: read("identifiers-advice.txt").transpose()?.unwrap_or_default(),
            strings_advice: read("strings-advice.txt").transpose()?.unwrap_or_default(),
        };
        if Kind::ALL.into_iter().all(|kind| ruleset.rules(kind).is_none()) {
            return Err(format!("{arg} has no rules: expected {}", files()));
        }
        return Ok((ruleset, kind));
    }
    let (name, file) = arg.split_once('/').map_or((arg, None), |(n, f)| (n, Some(f)));
    let Some((name, files)) = BUILT_IN.iter().find(|(n, _)| *n == name) else {
        let names: Vec<&str> = BUILT_IN.iter().map(|(n, _)| *n).collect();
        return Err(format!("{arg} is neither a built-in ruleset, which are {}, nor a path", names.join(", ")));
    };
    let kind = file.map(|f| kind_of(arg, Path::new(f))).transpose()?;
    let text = |file: &str| files.iter().find(|(f, _)| *f == file).map(|(_, text)| text.to_string());
    let ruleset = Ruleset {
        name: name.to_string(),
        identifiers: text(Kind::Identifiers.file()),
        docs: text(Kind::Docs.file()),
        strings: text(Kind::Strings.file()),
        identifiers_advice: text("identifiers-advice.txt").unwrap_or_default(),
        strings_advice: text("strings-advice.txt").unwrap_or_default(),
    };
    Ok((ruleset, kind))
}

/// The kind of the rules file at `path`, which `arg` names.
fn kind_of(arg: &str, path: &Path) -> Result<Kind, String> {
    let name = path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
    Kind::of_file(&name).ok_or_else(|| format!("{arg}: a rules file is {}", files()))
}

/// The names of the rules files of every kind, as `a, b or c`.
fn files() -> String {
    let names: Vec<&str> = Kind::ALL.into_iter().map(Kind::file).collect();
    match names.split_last() {
        Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")),
        _ => names.concat(),
    }
}