use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use vvv_core::{Address, Facts, Parsed, ReachKind, RelPath, ResolveError};
use super::{MoveSet, Reachability, Rebase, Site, Widen};
use crate::change::Change;
use crate::protocol::vocabulary::IntentLine;
use crate::report::{Document, MoveCounts};
use crate::{
EngineError, FileChange, Intent, Mutation, Notice, Planned, Respelling, SourceFile, VfsError,
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MoveIntent {
pub from: PathBuf,
pub to: PathBuf,
}
impl MoveIntent {
pub fn new(from: impl Into<PathBuf>, to: impl Into<PathBuf>) -> Self {
Self {
from: from.into(),
to: to.into(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Move {
pub intent: MoveIntent,
#[serde(flatten)]
pub state: crate::MutationState,
pub from: RelPath,
pub to: RelPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from_address: Option<Address>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub to_address: Option<Address>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notices: Vec<Notice>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub respellings: Vec<Respelling>,
pub files: Vec<FileChange>,
}
impl Mutation for Move {
fn into_mutation(self) -> crate::MutationAnswer {
crate::MutationAnswer::Move(self)
}
fn applied(&mut self, id: u64) {
self.state = crate::MutationState::Applied { history_id: id };
}
}
impl MoveIntent {
pub fn plan(self, engine: &crate::Engine) -> Result<Planned<Move>, EngineError> {
let _operation = engine.operation();
let mut graph = engine.graph()?;
self.plan_in(&mut graph, engine.workspace())
}
pub(crate) fn plan_in(
self,
graph: &mut crate::graph::Graph,
workspace: &crate::Workspace,
) -> Result<Planned<Move>, EngineError> {
let intent = &self;
let from = workspace.normalize(&intent.from);
let to = workspace.normalize(&intent.to);
if to.starts_with(&from) {
return Err(ResolveError::IntoItself {
from: from.into(),
to: to.into(),
}
.into());
}
let language = graph
.language_of(&from)
.or_else(|| graph.language_of_directory(&from))
.ok_or_else(|| EngineError::NoLanguage(from.clone().into()))?;
let ns = graph
.namespace(&language.id())
.ok_or_else(|| EngineError::NoLayout(language.id()))?;
let (layout, surgery) = (ns.layout(), ns.surgery()?);
let project = ns.project().clone();
let nodes = graph.fragments(&ns)?;
let moves = MoveSet::compute(workspace, layout, &project, &from, &to)?;
if moves.is_empty() {
return Err(VfsError::NotFound(from).into());
}
for (f, t) in moves.iter() {
let same_language = |p: &Path| {
graph
.language_of(p)
.is_some_and(|l| l.id() == language.id())
};
if !same_language(f) {
return Err(EngineError::NoLanguage(f.into()));
}
if !same_language(t) {
return Err(EngineError::NoLanguage(t.into()));
}
if workspace
.vfs()
.entry_kind(&workspace.absolute(t))?
.is_some()
&& !workspace
.vfs()
.same_entry(&workspace.absolute(f), &workspace.absolute(t))?
{
return Err(EngineError::Exists(t.into()));
}
}
let old = ns.address(&from)?;
let new = ns.address(&to)?;
let rebase = Rebase::new(&ns, old.clone(), new.clone());
let mut change = Change::new();
let mut references: Vec<(Address, Address)> = Vec::new();
for node in &nodes {
let site = Site::new(node, moves.destination(node.path()).unwrap_or(node.path()));
let (contribution, affected) = rebase.rewrite(&site)?.into_change()?;
change.merge(contribution)?;
references.extend(affected);
}
references.sort();
references.dedup();
let violations = Reachability::new(layout, ns.semantics(), &project, &old, &new)
.check(graph, &references)?;
let mut moved_mod_needs: Option<ReachKind> = None;
for violation in violations {
let is_moved_mod = violation.symbol.kind == vvv_core::SymbolKind::Module
&& violation.declaring.join(violation.symbol.name.as_str()) == new;
if is_moved_mod && violation.needs != ReachKind::Everyone {
moved_mod_needs = Some(violation.needs);
continue;
}
let candidate = graph.file(&violation.path)?;
let file = candidate.file();
let at = (
violation.path.clone(),
file.source().position(violation.symbol.name_span.start),
);
let consumers: Vec<Address> = if violation.needs == ReachKind::Everyone {
violation.consumers.clone()
} else {
vec![
violation
.consumers
.first()
.cloned()
.unwrap_or_else(|| new.clone()),
]
};
for consumer in consumers {
let widen = Widen {
symbol: &violation.symbol,
source: file.source(),
needs: violation.needs,
consumer,
notice_at: at.clone(),
};
match widen.plan(surgery) {
Ok(edit) => change.edit(file.witness(), edit)?,
Err(notice) => change.notice(notice),
}
}
}
let touched: Vec<(SourceFile, Facts)> = layout
.touched_by_move(&project, &from, &to)?
.into_iter()
.map(|path| {
let file = match graph.candidate(&path) {
Some(candidate) => candidate.file().clone(),
None => workspace.load(&path)?,
};
let facts =
file.facts(language.as_ref())
.map_err(|source| EngineError::Search {
path: path.clone().into(),
source,
})?;
Ok((file, facts))
})
.collect::<Result<_, EngineError>>()?;
let parsed: Vec<Parsed<'_>> = touched
.iter()
.map(|(file, facts)| Parsed {
path: file.path(),
source: file.source(),
facts,
})
.collect();
for side in surgery.relocate(&project, &from, &to, &parsed, moved_mod_needs)? {
let file = touched
.iter()
.find(|(file, _)| file.path() == side.path)
.ok_or_else(|| ResolveError::Missing(side.path.clone().into()))?;
change.edit(file.0.witness(), side.edit)?;
}
for (f, t) in moves.iter() {
change.move_file(graph.file(f)?.file().witness(), t)?;
}
Planned::of(
workspace,
change,
Intent::Move(intent.clone()),
|bound, files| Move {
intent: intent.clone(),
state: crate::MutationState::Preview,
from: from.into(),
to: to.into(),
from_address: Some(old),
to_address: Some(new),
notices: bound.notices,
respellings: bound.respellings,
files,
},
)
}
}
impl Document {
pub(crate) fn move_file(result: &Move) -> Self {
let mut report = Self::new();
report.title(IntentLine(&Intent::Move(MoveIntent::new(
&result.from,
&result.to,
))));
let structural = report.moved(
result.state,
&result.files,
&result.respellings,
&result.notices,
);
report.moved_summary(
result.state,
MoveCounts {
respellings: result.respellings.len(),
structural,
notices: result.notices.len(),
files: result.files.len(),
},
);
report
}
}