use super::{
context::{Context, absolute},
files::{self, Failure},
};
use std::path::{Path, PathBuf};
pub struct Edit {
pub path: PathBuf,
pub read: Option<String>,
pub text: String,
}
impl Edit {
pub fn changes(&self) -> bool {
self.read.as_deref() != Some(self.text.as_str())
}
pub fn write(&self) -> Result<(), Failure> {
if !self.changes() {
return Ok(());
}
let now = match std::fs::read_to_string(&self.path) {
Ok(text) => Some(text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(Failure::new(e.to_string(), files::FIX)),
};
if now != self.read {
let message = format!(
"{} changed while setup ran, so it was not written",
self.path.display()
);
return Err(Failure::new(message, "run setup again"));
}
files::write_text(&self.path, &self.text)
}
}
pub fn same(context: &Context, one: &Path, other: &Path) -> bool {
absolute(&context.cwd, one) == absolute(&context.cwd, other)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::Scratch;
#[test]
fn an_edit_is_written_only_over_the_bytes_it_was_computed_from() {
let scratch = Scratch::new("client-edit");
scratch.plant("a.json", "before\n");
let path = scratch.path().join("a.json");
let edit = Edit {
path: path.clone(),
read: Some("before\n".into()),
text: "after\n".into(),
};
scratch.plant("a.json", "the client's own\n");
assert!(
edit.write()
.unwrap_err()
.message
.contains("changed while setup ran")
);
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"the client's own\n"
);
scratch.plant("a.json", "before\n");
assert!(edit.write().is_ok());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "after\n");
}
}