use std::ops::Deref;
use super::{FilePreview, Plan};
use crate::change::Change;
use crate::{EngineError, FileChange, Intent, Mutation, MutationAnswer, Workspace};
#[derive(Debug, Clone)]
pub struct Planned<T: Mutation> {
result: T,
intent: Intent,
plans: Vec<Plan>,
preview: Vec<FilePreview>,
}
impl<T: Mutation> Planned<T> {
pub(crate) fn of(
workspace: &Workspace,
change: Change,
intent: Intent,
result: impl FnOnce(crate::change::Bound, Vec<FileChange>) -> T,
) -> Result<Self, EngineError> {
let mut bound = change.bind()?;
let change_set = std::mem::take(&mut bound.change_set);
let plan = Plan::new(change_set);
let preview = plan.preview(workspace)?;
let files = plan.file_changes(&preview);
Ok(Self::new(
intent,
result(bound, files),
vec![plan],
preview.files,
))
}
pub(crate) fn new(
intent: Intent,
result: T,
plans: Vec<Plan>,
preview: Vec<FilePreview>,
) -> Self {
Self {
result,
intent,
plans,
preview,
}
}
pub fn into_inner(self) -> T {
self.result
}
pub fn into_mutation(self) -> Planned<MutationAnswer> {
Planned {
result: self.result.into_mutation(),
intent: self.intent,
plans: self.plans,
preview: self.preview,
}
}
pub fn preview(&self) -> &[FilePreview] {
&self.preview
}
pub fn is_empty(&self) -> bool {
self.plans.iter().all(Plan::is_empty)
}
pub(crate) fn into_parts(self) -> (Intent, T, Vec<Plan>) {
(self.intent, self.result, self.plans)
}
pub(crate) fn into_plans(self) -> Vec<Plan> {
self.plans
}
}
impl<T: Mutation> Deref for Planned<T> {
type Target = T;
fn deref(&self) -> &T {
&self.result
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Apply, Engine, Languages, MemoryVfs, Rename, RenameIntent};
use std::sync::Arc;
#[test]
fn history_uses_the_captured_intent_even_if_internal_presentation_data_changes() {
let intent = RenameIntent::new("old", "new");
let captured = Intent::Rename(intent.clone());
let mut planned = Planned::new(
captured.clone(),
Rename {
intent,
state: crate::MutationState::Preview,
declarations: Vec::new(),
occurrences: Vec::new(),
files: Vec::new(),
},
Vec::new(),
Vec::new(),
);
planned.result.intent.to = "presentation only".into();
let engine = Engine::new(
Workspace::new("/ws", Arc::new(MemoryVfs::new())),
Languages::new(),
);
Apply(planned.into_mutation()).apply(&engine).unwrap();
assert_eq!(
vvv_engine::Ledger::new(&engine).history().unwrap().entries[0].intent,
captured
);
}
}