use crate::{
FileWrite, Operation, OperationState, Store, StoreError,
staging::stage_all,
write::{StagedFile, failpoint, failpoint_result},
};
use std::path::{Path, PathBuf};
pub struct Target {
pub path: PathBuf,
pub current_hash: Option<String>,
pub current: Option<String>,
pub text: Option<String>,
pub merged: bool,
}
impl Store {
pub fn execute(&self, op: &mut Operation, targets: &[Target]) -> Result<(), StoreError> {
validate_destinations(targets)?;
op.files = targets
.iter()
.map(|target| self.file_write(target))
.collect::<Result<_, _>>()?;
let staged = match stage_all(targets) {
Ok(staged) => staged,
Err(error) => {
op.state = OperationState::Failed;
op.reason = Some(format!("could not stage writes: {error}"));
self.save_operation(op)?;
return Err(error.into());
}
};
op.state = OperationState::Applying;
self.save_operation(op)?;
failpoint("after_journal");
for (index, (target, temp)) in targets.iter().zip(staged).enumerate() {
commit(&target.path, temp)?;
failpoint_after(index);
}
op.state = OperationState::Applied;
self.save_operation(op)
}
fn file_write(&self, target: &Target) -> Result<FileWrite, StoreError> {
if let Some(text) = &target.current {
self.put_blob(text)?;
}
let after_hash = target
.text
.as_deref()
.map(|text| self.put_blob(text))
.transpose()?;
Ok(FileWrite {
path: target.path.clone(),
before_hash: target.current_hash.clone(),
after_hash,
merged: target.merged,
})
}
}
fn validate_destinations(targets: &[Target]) -> Result<(), StoreError> {
let mut paths = std::collections::BTreeSet::new();
let mut resolver = crate::PathResolver::default();
for target in targets {
if !paths.insert(resolver.resolve(&target.path)?) {
return Err(StoreError::Invalid(
"multiple planned paths refer to the same destination; plan again".into(),
));
}
}
Ok(())
}
fn failpoint_after(index: usize) {
if index == 0 {
failpoint("after_first_rename");
}
}
fn commit(path: &Path, staged: Option<StagedFile>) -> std::io::Result<()> {
failpoint_result("before_commit")?;
match staged {
Some(temp) => temp.commit(path),
None => match std::fs::remove_file(path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
other => other,
},
}
}
pub fn read_current(path: &Path) -> Result<(Option<String>, Option<String>), StoreError> {
match std::fs::read_to_string(path) {
Ok(text) => {
let hash = griz_core::content_hash(&text);
Ok((Some(text), Some(hash)))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok((None, None)),
Err(error) => Err(error.into()),
}
}