prosecop 0.1.0

Checks identifiers and doc comments against a repository's house style
//! A walk over the files that a command picks from the current directory, and their text.

use std::borrow::Cow;
use std::fs::File;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;

use ignore::overrides::OverrideBuilder;
use ignore::{WalkBuilder, WalkState};

use crate::lex::Lang;

/// How many threads walk and check files, past which they add more system time than they save wall time.
const THREADS: usize = 4;
/// The most paths that are checked without the walker where every one is a file.
const DIRECT_FILES: usize = 8;

/// The options and paths of a command line, which pick the files that a check walks and add to its rules.
#[derive(Clone, Default)]
pub struct Options {
    /// The paths to walk, in the order of the command line.
    pub paths: Vec<String>,
    /// The globs of `--exclude`.
    pub excludes: Vec<String>,
    /// The suffixes of `--ext`, each with its dot, or `None` for every suffix that a check reads.
    pub suffixes: Option<Vec<String>>,
    /// The words of `--forbid`, which an identifier may not have.
    pub forbid: Vec<String>,
    /// The words and compounds of `--allow`, which an identifier may have.
    pub allow: Vec<String>,
}

impl Options {
    /// The options of `args`, in which each option takes a comma-separated list as `--opt=a,b` or `--opt a,b`.
    pub fn parse(args: &[String]) -> Result<Options, String> {
        let mut options = Options::default();
        let mut args = args.iter();
        while let Some(arg) = args.next() {
            let (flag, value) = arg.split_once('=').map_or((arg.as_str(), None), |(f, v)| (f, Some(v)));
            let list = match flag {
                "--ext" => options.suffixes.get_or_insert_default(),
                "--exclude" => &mut options.excludes,
                "--forbid" => &mut options.forbid,
                "--allow" => &mut options.allow,
                _ if arg.starts_with("--") => return Err(format!("unknown option {arg}\n{}", crate::USAGE)),
                _ => {
                    options.paths.push(arg.clone());
                    continue;
                }
            };
            let value = value.or_else(|| args.next().map(String::as_str)).ok_or(format!("{flag} needs a value"))?;
            list.extend(value.split(',').map(str::trim).filter(|v| !v.is_empty()).map(String::from));
        }
        for suffix in options.suffixes.iter_mut().flatten() {
            *suffix = format!(".{}", suffix.trim_start_matches('.'));
        }
        Ok(options)
    }

    /// These options with only the suffixes of `--ext` that `reads`, or `None` where `--ext` names only others.
    pub fn reading(&self, reads: fn(Lang) -> bool) -> Option<Options> {
        let mut options = self.clone();
        if let Some(suffixes) = &mut options.suffixes {
            suffixes.retain(|s| reads_suffix(s, reads));
            if suffixes.is_empty() {
                return None;
            }
        }
        Some(options)
    }
}

/// Whether the files of `suffix`, such as `.rs`, are of a language that `reads`.
pub fn reads_suffix(suffix: &str, reads: fn(Lang) -> bool) -> bool {
    Lang::of_suffix(&format!("x{suffix}")).is_some_and(reads)
}

/// The directory that a check runs from, which is the current directory outside of tests.
///
/// A path on the command line is read from this directory. The walk honors `.gitignore` files only inside a git
/// work tree, which the walker finds by looking for `.git` in this directory and those above it.
#[derive(Default)]
pub struct Root {
    /// The directory, where an empty path is the current directory.
    pub path: PathBuf,
}

impl Root {
    /// The root at `path`.
    #[cfg(test)]
    pub fn at(path: PathBuf) -> Root {
        Root { path }
    }

    /// The value of `check` for each file under the paths of `options`, or under the root, sorted by path.
    ///
    /// - `check` runs on the walker's threads, with a buffer that each thread reuses.
    /// - A walk skips what `.gitignore` covers and what an `--exclude` glob matches, but a path named in `options`
    ///   is walked even so, as by ripgrep.
    /// - An `--exclude` glob is matched against the path from the root.
    /// - A `--ext` keeps the files of its suffixes.
    /// - A file is reported by the path that it was reached through, so a path outside the root keeps its `..` or
    ///   its leading `/`.
    pub fn walk<R: Send>(
        &self,
        options: &Options,
        check: impl Fn(&str, &mut Vec<u8>) -> R + Sync,
    ) -> Result<Vec<(String, R)>, String> {
        let (excludes, suffixes) = (&options.excludes, &options.suffixes);
        let mut paths: Vec<String> = options.paths.iter().map(|p| self.relative(&self.path.join(p))).collect();
        if paths.is_empty() {
            paths.push(".".into());
        }
        let picked = |path: &str| suffixes.as_ref().is_none_or(|s| s.iter().any(|s| path.ends_with(s.as_str())));
        let roots: Vec<PathBuf> = paths.iter().map(|p| self.path.join(p)).collect();
        let mut found = Vec::new();
        // A few files are checked on this thread, since starting the walker's threads takes longer.
        if roots.len() <= DIRECT_FILES && roots.iter().all(|r| r.is_file()) {
            let mut buffer = Vec::new();
            found.extend(paths.into_iter().filter(|p| picked(p)).map(|p| (check(&p, &mut buffer), p)));
        } else {
            // The globs are matched as text after the root, which is `.` for the current directory.
            let top = if self.path.as_os_str().is_empty() { Path::new(".") } else { &self.path };
            let mut overrides = OverrideBuilder::new(top);
            for exclude in excludes {
                overrides.add(&format!("!{}", display(Path::new(exclude)))).map_err(|e| e.to_string())?;
            }
            let mut builder = WalkBuilder::new(&roots[0]);
            for root in &roots[1..] {
                builder.add(root);
            }
            let overrides = overrides.build().map_err(|e| e.to_string())?;
            builder.hidden(false).threads(THREADS).overrides(overrides).filter_entry(|e| e.file_name() != ".git");
            let all = Mutex::new(Vec::new());
            builder.build_parallel().run(|| {
                let mut buffer = Vec::new();
                let (all, check, picked) = (&all, &check, &picked);
                Box::new(move |entry| {
                    // Only regular files are opened, since opening a FIFO could block.
                    if let Ok(entry) = entry
                        && entry.file_type().is_some_and(|t| t.is_file())
                    {
                        let path = self.relative(entry.path());
                        if picked(&path) {
                            let result = check(&path, &mut buffer);
                            all.lock().unwrap_or_else(|e| e.into_inner()).push((result, path));
                        }
                    }
                    WalkState::Continue
                })
            });
            found = all.into_inner().unwrap_or_else(|e| e.into_inner());
        }
        found.sort_unstable_by(|a, b| a.1.cmp(&b.1));
        // A path under two of the paths that `args` name is walked twice.
        found.dedup_by(|a, b| a.1 == b.1);
        Ok(found.into_iter().map(|(result, path)| (path, result)).collect())
    }

    /// The text of `path` from the root where the root contains it, or else as it is.
    fn relative(&self, path: &Path) -> String {
        display(path.strip_prefix(&self.path).unwrap_or(path))
    }
}

/// The text of `path` without its `.` parts, so that `./a/b` and `a/b` are reported as the same file.
///
/// The separator is always `/`, because the rules split paths on `/` and a glob reads `\` as an escape.
fn display(path: &Path) -> String {
    let parts: PathBuf = path.components().filter(|c| *c != Component::CurDir).collect();
    match parts.as_os_str().is_empty() {
        true => ".".into(),
        false if cfg!(windows) => parts.to_string_lossy().replace('\\', "/"),
        false => parts.to_string_lossy().into_owned(),
    }
}

/// The text of the regular file at `root/path`, read into `buffer`, with Python's universal newlines.
///
/// It is `None` where the path is not a regular file or cannot be read. Invalid UTF-8 becomes U+FFFD. The size comes from the open file, so the file is stat'ed once.
pub fn read<'a>(root: &Path, path: &str, buffer: &'a mut Vec<u8>) -> Option<Cow<'a, str>> {
    let file = File::open(root.join(path)).ok()?;
    let metadata = file.metadata().ok()?;
    if !metadata.is_file() {
        return None;
    }
    buffer.clear();
    buffer.reserve_exact(metadata.len() as usize);
    // Reading through `take` stops at the size without another read call to find the end.
    file.take(metadata.len()).read_to_end(buffer).ok()?;
    let text = match std::str::from_utf8(buffer) {
        Ok(text) => Cow::Borrowed(text),
        Err(_) => String::from_utf8_lossy(buffer),
    };
    if memchr::memchr(b'\r', text.as_bytes()).is_none() {
        return Some(text);
    }
    Some(Cow::Owned(text.replace("\r\n", "\n").replace('\r', "\n")))
}