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