Skip to main content

cuno_tools/
write.rs

1//! The one answer to "may cuno write this file": every command that writes
2//! in the project asks here, so a rule found missing in one writer (a link
3//! written through, a hand-written file overwritten) is added once.
4
5use std::fmt;
6use std::io;
7use std::path::Path;
8
9/// Why cuno does not write a file.
10#[derive(Debug)]
11pub enum Refusal {
12    /// A link, which could lead outside the project.
13    Link,
14    /// Something other than a file (a directory).
15    NotAFile,
16    /// Not one of the package's files.
17    OutsidePackage,
18    /// A file cuno did not write, which is the user's.
19    HandWritten,
20    /// Something is already there, where cuno writes only a new file.
21    Exists,
22    /// It could not be read to decide.
23    Unreadable(io::Error),
24}
25
26impl fmt::Display for Refusal {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Refusal::Link => f.write_str("it is a link, which cuno does not write through"),
30            Refusal::NotAFile => f.write_str("it is not a file"),
31            Refusal::OutsidePackage => f.write_str("it is not the package's"),
32            Refusal::HandWritten => f.write_str("cuno did not write it"),
33            Refusal::Exists => f.write_str("it is already there"),
34            Refusal::Unreadable(e) => write!(f, "{e}"),
35        }
36    }
37}
38
39impl Refusal {
40    /// The refusal as a clause after the file's name: "`x.h`, which is a
41    /// link cuno does not write through".
42    pub fn which(&self) -> String {
43        match self {
44            Refusal::Link => "which is a link cuno does not write through".to_owned(),
45            Refusal::NotAFile => "which is not a file".to_owned(),
46            Refusal::OutsidePackage => "which is not the package's".to_owned(),
47            Refusal::HandWritten => "which cuno did not write".to_owned(),
48            Refusal::Exists => "which is already there".to_owned(),
49            Refusal::Unreadable(e) => format!("which cannot be read: {e}"),
50        }
51    }
52}
53
54/// What a path is, without following a link.
55fn kind(path: &Path) -> Result<Option<std::fs::FileType>, Refusal> {
56    match std::fs::symlink_metadata(path) {
57        Ok(meta) => Ok(Some(meta.file_type())),
58        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
59        Err(e) => Err(Refusal::Unreadable(e)),
60    }
61}
62
63/// Whether cuno may rewrite `path`, a file of the package's code (`cuno
64/// fmt`, `cuno lint --fix`): one `ours` accepts, that is a file and not a
65/// link (`docs/en/specs/dev-tools.md`, "Target files").
66pub fn code(path: &Path, ours: &dyn Fn(&Path) -> bool) -> Result<(), Refusal> {
67    match kind(path)? {
68        Some(kind) if kind.is_symlink() => Err(Refusal::Link),
69        Some(kind) if !kind.is_file() => Err(Refusal::NotAFile),
70        _ if !ours(path) => Err(Refusal::OutsidePackage),
71        _ => Ok(()),
72    }
73}
74
75/// Whether cuno may write `path`, a file it generates (`.clang-format`,
76/// `.clang-tidy`): absent, or a file, not a link, whose first line is
77/// `marker`, as cuno writes it (`docs/en/specs/dev-tools.md`,
78/// "Configuration").
79pub fn generated(path: &Path, marker: &str) -> Result<(), Refusal> {
80    match kind(path)? {
81        None => Ok(()),
82        Some(kind) if kind.is_symlink() => Err(Refusal::Link),
83        Some(kind) if !kind.is_file() => Err(Refusal::NotAFile),
84        Some(_) => {
85            let held = std::fs::read(path).map_err(Refusal::Unreadable)?;
86            let first = held.split(|b| *b == b'\n').next().unwrap_or_default();
87            if first.strip_suffix(b"\r").unwrap_or(first) == marker.as_bytes() {
88                Ok(())
89            } else {
90                Err(Refusal::HandWritten)
91            }
92        }
93    }
94}
95
96/// Whether cuno may create `path` as a new file (`cuno init`): only when
97/// nothing is there, not even a link (`docs/en/specs/commands.md`, "`cuno
98/// init [path]`"). The caller creates it so that it fails rather than
99/// write over one made since.
100pub fn absent(path: &Path) -> Result<(), Refusal> {
101    match kind(path)? {
102        None => Ok(()),
103        Some(_) => Err(Refusal::Exists),
104    }
105}
106
107/// Whether cuno may add lines to the end of `path`, a file of the user's
108/// (`cuno init`'s `.gitignore`): a file, not a link.
109pub fn appendable(path: &Path) -> Result<(), Refusal> {
110    match kind(path)? {
111        Some(kind) if kind.is_symlink() => Err(Refusal::Link),
112        Some(kind) if !kind.is_file() => Err(Refusal::NotAFile),
113        _ => Ok(()),
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    const MARKER: &str = "# Generated by cuno";
122
123    /// A new file may be created only where nothing is, a directory or a
124    /// file being there alike; lines may be added only to a file.
125    ///
126    /// Mutation: let `absent` accept a file that is there, or `appendable`
127    /// a directory; this test fails.
128    #[test]
129    fn a_new_file_only_where_nothing_is() {
130        let dir = tempfile::tempdir().unwrap();
131        let file = dir.path().join("a.txt");
132        assert!(absent(&file).is_ok());
133        std::fs::write(&file, "").unwrap();
134        assert!(matches!(absent(&file), Err(Refusal::Exists)));
135        assert!(matches!(absent(dir.path()), Err(Refusal::Exists)));
136        assert!(appendable(&file).is_ok());
137        assert!(matches!(appendable(dir.path()), Err(Refusal::NotAFile)));
138    }
139
140    /// A file of the package may be rewritten; one `ours` rejects, or a
141    /// directory, may not.
142    ///
143    /// Mutation: skip asking `ours`, or accept a directory; this test fails.
144    #[test]
145    fn code_is_a_file_of_the_package() {
146        let dir = tempfile::tempdir().unwrap();
147        let file = dir.path().join("a.cpp");
148        std::fs::write(&file, "").unwrap();
149        assert!(code(&file, &|_| true).is_ok());
150        assert!(matches!(
151            code(&file, &|_| false),
152            Err(Refusal::OutsidePackage)
153        ));
154        assert!(matches!(
155            code(dir.path(), &|_| true),
156            Err(Refusal::NotAFile)
157        ));
158    }
159
160    /// A generated file may be written when it is absent or cuno's own,
161    /// and not when the user wrote it, in either line ending.
162    ///
163    /// Mutation: accept a file without the marker, or refuse an absent one,
164    /// or one whose marker line ends in `\r\n`; this test fails.
165    #[test]
166    fn generated_is_absent_or_marked() {
167        let dir = tempfile::tempdir().unwrap();
168        let path = dir.path().join(".clang-format");
169        assert!(generated(&path, MARKER).is_ok());
170        std::fs::write(&path, format!("{MARKER}\r\nBasedOnStyle: LLVM\n")).unwrap();
171        assert!(generated(&path, MARKER).is_ok());
172        std::fs::write(&path, "BasedOnStyle: LLVM\n").unwrap();
173        assert!(matches!(
174            generated(&path, MARKER),
175            Err(Refusal::HandWritten)
176        ));
177        assert!(matches!(
178            generated(dir.path(), MARKER),
179            Err(Refusal::NotAFile)
180        ));
181    }
182
183    /// A link is refused by both, whatever it names, even a directory of
184    /// the package. A junction stands in for a link: it is one to the file
185    /// system, and any account can make it.
186    ///
187    /// Mutation: follow a link to see what it names; this test fails.
188    #[cfg(windows)]
189    #[test]
190    fn a_link_is_never_written() {
191        let dir = tempfile::tempdir().unwrap();
192        let real = dir.path().join("real");
193        std::fs::create_dir(&real).unwrap();
194        let link = dir.path().join("link");
195        let made = std::process::Command::new("cmd")
196            .args(["/C", "mklink", "/J"])
197            .arg(&link)
198            .arg(&real)
199            .output()
200            .unwrap();
201        assert!(made.status.success(), "{made:?}");
202        assert!(matches!(code(&link, &|_| true), Err(Refusal::Link)));
203        assert!(matches!(generated(&link, MARKER), Err(Refusal::Link)));
204        std::fs::remove_dir(&link).unwrap();
205    }
206}