pub mod format;
pub mod tidy;
use std::fmt;
use std::io;
use std::path::Path;
use cuno_manifest::Manifest;
#[derive(Debug)]
pub enum EditorFileWarning {
Kept(&'static str),
Failed(&'static str, io::Error),
}
impl fmt::Display for EditorFileWarning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EditorFileWarning::Kept(file) => write!(
f,
"kept the hand-written `{file}`; remove it to have cuno write it from cuno.toml"
),
EditorFileWarning::Failed(file, e) => write!(f, "could not write {file}: {e}"),
}
}
}
pub fn write_editor_files(root: &Path, manifest: &Manifest) -> Vec<EditorFileWarning> {
let lang = manifest.package.lang;
let format = format::clang_format_config(&manifest.fmt, lang);
let tidy = tidy::clang_tidy_file(&manifest.lint);
[
write_generated(root, format::FILE, format::MARKER, &format),
write_generated(root, tidy::FILE, tidy::MARKER, &tidy),
]
.into_iter()
.filter_map(Result::err)
.collect()
}
fn write_generated(
root: &Path,
file: &'static str,
marker: &str,
content: &str,
) -> Result<(), EditorFileWarning> {
let path = root.join(file);
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(EditorFileWarning::Failed(file, e)),
Ok(meta) if !meta.file_type().is_file() => {
let what = if meta.file_type().is_symlink() {
"it is a link, which cuno does not follow"
} else {
"it is not a file"
};
return Err(EditorFileWarning::Failed(file, io::Error::other(what)));
}
Ok(_) => {
let existing = std::fs::read(&path).map_err(|e| EditorFileWarning::Failed(file, e))?;
if existing == content.as_bytes() {
return Ok(());
}
let first = existing.split(|b| *b == b'\n').next().unwrap_or_default();
if first.strip_suffix(b"\r").unwrap_or(first) != marker.as_bytes() {
return Err(EditorFileWarning::Kept(file));
}
}
}
std::fs::write(&path, content).map_err(|e| EditorFileWarning::Failed(file, e))
}
#[cfg(test)]
mod tests {
use super::*;
const MARKER: &str = "# generated";
#[test]
fn only_a_generated_file_is_overwritten() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let path = root.join(".x");
let new = format!("{MARKER}\nA: 1\n");
write_generated(root, ".x", MARKER, &new).unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), new);
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
std::fs::File::options()
.write(true)
.open(&path)
.unwrap()
.set_modified(past)
.unwrap();
write_generated(root, ".x", MARKER, &new).unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), past);
let newer = format!("{MARKER}\nA: 2\n");
write_generated(root, ".x", MARKER, &newer).unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), newer);
std::fs::write(&path, "BasedOnStyle: Google\n").unwrap();
let kept = write_generated(root, ".x", MARKER, &newer).unwrap_err();
assert!(matches!(kept, EditorFileWarning::Kept(".x")), "{kept:?}");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"BasedOnStyle: Google\n"
);
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
let failed = write_generated(root, ".x", MARKER, &newer).unwrap_err();
assert!(
matches!(failed, EditorFileWarning::Failed(".x", _)),
"{failed:?}"
);
}
#[cfg(windows)]
#[test]
fn a_link_is_not_followed() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let made = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(dir.path().join(".x"))
.arg(outside.path())
.output()
.unwrap();
assert!(made.status.success(), "{made:?}");
let failed = write_generated(dir.path(), ".x", MARKER, "x").unwrap_err();
assert!(failed.to_string().contains("link"), "{failed}");
std::fs::remove_dir(dir.path().join(".x")).unwrap();
}
}