cuno-tools 0.2.0

cuno fmt and cuno lint (clang-format / clang-tidy).
Documentation
//! The one answer to "may cuno write this file": every command that writes
//! in the project asks here, so a rule found missing in one writer (a link
//! written through, a hand-written file overwritten) is added once.

use std::fmt;
use std::io;
use std::path::Path;

/// Why cuno does not write a file.
#[derive(Debug)]
pub enum Refusal {
    /// A link, which could lead outside the project.
    Link,
    /// Something other than a file (a directory).
    NotAFile,
    /// Not one of the package's files.
    OutsidePackage,
    /// A file cuno did not write, which is the user's.
    HandWritten,
    /// Something is already there, where cuno writes only a new file.
    Exists,
    /// It could not be read to decide.
    Unreadable(io::Error),
}

impl fmt::Display for Refusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Refusal::Link => f.write_str("it is a link, which cuno does not write through"),
            Refusal::NotAFile => f.write_str("it is not a file"),
            Refusal::OutsidePackage => f.write_str("it is not the package's"),
            Refusal::HandWritten => f.write_str("cuno did not write it"),
            Refusal::Exists => f.write_str("it is already there"),
            Refusal::Unreadable(e) => write!(f, "{e}"),
        }
    }
}

impl Refusal {
    /// The refusal as a clause after the file's name: "`x.h`, which is a
    /// link cuno does not write through".
    pub fn which(&self) -> String {
        match self {
            Refusal::Link => "which is a link cuno does not write through".to_owned(),
            Refusal::NotAFile => "which is not a file".to_owned(),
            Refusal::OutsidePackage => "which is not the package's".to_owned(),
            Refusal::HandWritten => "which cuno did not write".to_owned(),
            Refusal::Exists => "which is already there".to_owned(),
            Refusal::Unreadable(e) => format!("which cannot be read: {e}"),
        }
    }
}

/// What a path is, without following a link.
fn kind(path: &Path) -> Result<Option<std::fs::FileType>, Refusal> {
    match std::fs::symlink_metadata(path) {
        Ok(meta) => Ok(Some(meta.file_type())),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(Refusal::Unreadable(e)),
    }
}

/// Whether cuno may rewrite `path`, a file of the package's code (`cuno
/// fmt`, `cuno lint --fix`): one `ours` accepts, that is a file and not a
/// link (`docs/en/specs/dev-tools.md`, "Target files").
pub fn code(path: &Path, ours: &dyn Fn(&Path) -> bool) -> Result<(), Refusal> {
    match kind(path)? {
        Some(kind) if kind.is_symlink() => Err(Refusal::Link),
        Some(kind) if !kind.is_file() => Err(Refusal::NotAFile),
        _ if !ours(path) => Err(Refusal::OutsidePackage),
        _ => Ok(()),
    }
}

/// Whether cuno may write `path`, a file it generates (`.clang-format`,
/// `.clang-tidy`): absent, or a file, not a link, whose first line is
/// `marker`, as cuno writes it (`docs/en/specs/dev-tools.md`,
/// "Configuration").
pub fn generated(path: &Path, marker: &str) -> Result<(), Refusal> {
    match kind(path)? {
        None => Ok(()),
        Some(kind) if kind.is_symlink() => Err(Refusal::Link),
        Some(kind) if !kind.is_file() => Err(Refusal::NotAFile),
        Some(_) => {
            let held = std::fs::read(path).map_err(Refusal::Unreadable)?;
            let first = held.split(|b| *b == b'\n').next().unwrap_or_default();
            if first.strip_suffix(b"\r").unwrap_or(first) == marker.as_bytes() {
                Ok(())
            } else {
                Err(Refusal::HandWritten)
            }
        }
    }
}

/// Whether cuno may create `path` as a new file (`cuno init`): only when
/// nothing is there, not even a link (`docs/en/specs/commands.md`, "`cuno
/// init [path]`"). The caller creates it so that it fails rather than
/// write over one made since.
pub fn absent(path: &Path) -> Result<(), Refusal> {
    match kind(path)? {
        None => Ok(()),
        Some(_) => Err(Refusal::Exists),
    }
}

/// Whether cuno may add lines to the end of `path`, a file of the user's
/// (`cuno init`'s `.gitignore`): a file, not a link.
pub fn appendable(path: &Path) -> Result<(), Refusal> {
    match kind(path)? {
        Some(kind) if kind.is_symlink() => Err(Refusal::Link),
        Some(kind) if !kind.is_file() => Err(Refusal::NotAFile),
        _ => Ok(()),
    }
}

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

    const MARKER: &str = "# Generated by cuno";

    /// A new file may be created only where nothing is, a directory or a
    /// file being there alike; lines may be added only to a file.
    ///
    /// Mutation: let `absent` accept a file that is there, or `appendable`
    /// a directory; this test fails.
    #[test]
    fn a_new_file_only_where_nothing_is() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.txt");
        assert!(absent(&file).is_ok());
        std::fs::write(&file, "").unwrap();
        assert!(matches!(absent(&file), Err(Refusal::Exists)));
        assert!(matches!(absent(dir.path()), Err(Refusal::Exists)));
        assert!(appendable(&file).is_ok());
        assert!(matches!(appendable(dir.path()), Err(Refusal::NotAFile)));
    }

    /// A file of the package may be rewritten; one `ours` rejects, or a
    /// directory, may not.
    ///
    /// Mutation: skip asking `ours`, or accept a directory; this test fails.
    #[test]
    fn code_is_a_file_of_the_package() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.cpp");
        std::fs::write(&file, "").unwrap();
        assert!(code(&file, &|_| true).is_ok());
        assert!(matches!(
            code(&file, &|_| false),
            Err(Refusal::OutsidePackage)
        ));
        assert!(matches!(
            code(dir.path(), &|_| true),
            Err(Refusal::NotAFile)
        ));
    }

    /// A generated file may be written when it is absent or cuno's own,
    /// and not when the user wrote it, in either line ending.
    ///
    /// Mutation: accept a file without the marker, or refuse an absent one,
    /// or one whose marker line ends in `\r\n`; this test fails.
    #[test]
    fn generated_is_absent_or_marked() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".clang-format");
        assert!(generated(&path, MARKER).is_ok());
        std::fs::write(&path, format!("{MARKER}\r\nBasedOnStyle: LLVM\n")).unwrap();
        assert!(generated(&path, MARKER).is_ok());
        std::fs::write(&path, "BasedOnStyle: LLVM\n").unwrap();
        assert!(matches!(
            generated(&path, MARKER),
            Err(Refusal::HandWritten)
        ));
        assert!(matches!(
            generated(dir.path(), MARKER),
            Err(Refusal::NotAFile)
        ));
    }

    /// A link is refused by both, whatever it names, even a directory of
    /// the package. A junction stands in for a link: it is one to the file
    /// system, and any account can make it.
    ///
    /// Mutation: follow a link to see what it names; this test fails.
    #[cfg(windows)]
    #[test]
    fn a_link_is_never_written() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = dir.path().join("link");
        let made = std::process::Command::new("cmd")
            .args(["/C", "mklink", "/J"])
            .arg(&link)
            .arg(&real)
            .output()
            .unwrap();
        assert!(made.status.success(), "{made:?}");
        assert!(matches!(code(&link, &|_| true), Err(Refusal::Link)));
        assert!(matches!(generated(&link, MARKER), Err(Refusal::Link)));
        std::fs::remove_dir(&link).unwrap();
    }
}