1pub mod format;
6pub mod tidy;
7
8use std::fmt;
9use std::io;
10use std::path::Path;
11
12use cuno_manifest::Manifest;
13
14#[derive(Debug)]
16pub enum EditorFileWarning {
17 Kept(&'static str),
19 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
35pub 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
54fn 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 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 #[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 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 #[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}