Skip to main content

cuno_tools/
lib.rs

1//! `cuno fmt` and `cuno lint` (clang-format / clang-tidy).
2//!
3//! See `docs/en/specs/dev-tools.md`.
4
5pub mod format;
6pub mod targets;
7pub mod tidy;
8pub mod write;
9
10use std::fmt;
11use std::io;
12use std::path::Path;
13
14use cuno_manifest::Manifest;
15
16/// Why an editor file was left as it was.
17#[derive(Debug)]
18pub enum EditorFileWarning {
19    /// A file cuno did not write is there: it is the user's.
20    Kept(&'static str),
21    /// It could not be written, or is not a file (a link, a directory).
22    Failed(&'static str, io::Error),
23}
24
25impl fmt::Display for EditorFileWarning {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            EditorFileWarning::Kept(file) => write!(
29                f,
30                "kept the hand-written `{file}`; remove it to have cuno write it from Cuno.toml"
31            ),
32            EditorFileWarning::Failed(file, e) => write!(f, "could not write {file}: {e}"),
33        }
34    }
35}
36
37/// Writes the files editors read so they format and analyse as cuno does,
38/// at the project `root`: `.clang-format` from `[fmt]` and `.clang-tidy`
39/// from `[lint]`. Only a file cuno
40/// wrote, which starts with its marker, is overwritten, and only when its
41/// content changes; a file the user wrote, a link or a directory is left
42/// and warned about (`docs/en/specs/dev-tools.md`, "Configuration").
43pub fn write_editor_files(root: &Path, manifest: &Manifest) -> Vec<EditorFileWarning> {
44    let lang = manifest.package.lang;
45    let format = format::clang_format_config(&manifest.fmt, lang);
46    let tidy = tidy::clang_tidy_file(&manifest.lint);
47    [
48        write_generated(root, format::FILE, format::MARKER, &format),
49        write_generated(root, tidy::FILE, tidy::MARKER, &tidy),
50    ]
51    .into_iter()
52    .filter_map(Result::err)
53    .collect()
54}
55
56/// Writes `content` to `root/file` unless something other than a file cuno
57/// generated (first line `marker`) is there, or it already holds `content`.
58fn write_generated(
59    root: &Path,
60    file: &'static str,
61    marker: &str,
62    content: &str,
63) -> Result<(), EditorFileWarning> {
64    let path = root.join(file);
65    // Never followed: a link would have cuno write outside the project.
66    match write::generated(&path, marker) {
67        Ok(()) => {}
68        Err(write::Refusal::HandWritten) => return Err(EditorFileWarning::Kept(file)),
69        Err(write::Refusal::Unreadable(e)) => return Err(EditorFileWarning::Failed(file, e)),
70        Err(other) => {
71            return Err(EditorFileWarning::Failed(
72                file,
73                io::Error::other(other.to_string()),
74            ));
75        }
76    }
77    match std::fs::read(&path) {
78        Ok(held) if held == content.as_bytes() => return Ok(()),
79        Ok(_) => {}
80        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
81        Err(e) => return Err(EditorFileWarning::Failed(file, e)),
82    }
83    std::fs::write(&path, content).map_err(|e| EditorFileWarning::Failed(file, e))
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    const MARKER: &str = "# generated";
91
92    /// A missing file is written, an unchanged one left alone, a generated
93    /// one rewritten, and a hand-written one or a directory kept and
94    /// warned about.
95    ///
96    /// Mutation: overwrite a file without the marker, follow or overwrite
97    /// a non-file, or rewrite an unchanged file; this test fails.
98    #[test]
99    fn only_a_generated_file_is_overwritten() {
100        let dir = tempfile::tempdir().unwrap();
101        let root = dir.path();
102        let path = root.join(".x");
103        let new = format!("{MARKER}\nA: 1\n");
104        write_generated(root, ".x", MARKER, &new).unwrap();
105        assert_eq!(std::fs::read_to_string(&path).unwrap(), new);
106
107        // Unchanged: not written again, so its time stays an hour back.
108        let past = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
109        std::fs::File::options()
110            .write(true)
111            .open(&path)
112            .unwrap()
113            .set_modified(past)
114            .unwrap();
115        write_generated(root, ".x", MARKER, &new).unwrap();
116        assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), past);
117
118        let newer = format!("{MARKER}\nA: 2\n");
119        write_generated(root, ".x", MARKER, &newer).unwrap();
120        assert_eq!(std::fs::read_to_string(&path).unwrap(), newer);
121
122        std::fs::write(&path, "BasedOnStyle: Google\n").unwrap();
123        let kept = write_generated(root, ".x", MARKER, &newer).unwrap_err();
124        assert!(matches!(kept, EditorFileWarning::Kept(".x")), "{kept:?}");
125        assert_eq!(
126            std::fs::read_to_string(&path).unwrap(),
127            "BasedOnStyle: Google\n"
128        );
129
130        std::fs::remove_file(&path).unwrap();
131        std::fs::create_dir(&path).unwrap();
132        let failed = write_generated(root, ".x", MARKER, &newer).unwrap_err();
133        assert!(
134            matches!(failed, EditorFileWarning::Failed(".x", _)),
135            "{failed:?}"
136        );
137    }
138
139    /// A junction where the file should be is not written through.
140    ///
141    /// Mutation: follow links; this test fails.
142    #[cfg(windows)]
143    #[test]
144    fn a_link_is_not_followed() {
145        let dir = tempfile::tempdir().unwrap();
146        let outside = tempfile::tempdir().unwrap();
147        let made = std::process::Command::new("cmd")
148            .args(["/C", "mklink", "/J"])
149            .arg(dir.path().join(".x"))
150            .arg(outside.path())
151            .output()
152            .unwrap();
153        assert!(made.status.success(), "{made:?}");
154        let failed = write_generated(dir.path(), ".x", MARKER, "x").unwrap_err();
155        assert!(failed.to_string().contains("link"), "{failed}");
156        std::fs::remove_dir(dir.path().join(".x")).unwrap();
157    }
158}