use crate::adapters::mapper::Canonical;
use crate::apply::exec::PlanInputs;
use crate::apply::ledger::{EntryKind, LedgerKey, LedgerSlot};
use crate::apply::plan::{
self, Decision, EntryPlan, EntryState, OnConflict, PlanOptions, ProjectSelection, ScopeFilter,
TargetFilter, TargetPlan,
};
use crate::apply::render::DesiredState;
use crate::apply::{ApplyEnv, ApplyReport, ApplyRequest, apply_in};
use crate::error::CoreError;
use crate::formats::NativeValue;
use crate::model::applied::{ApplyTrigger, Scope};
use crate::store::{CommitId, LogFilter, Machine, Operation, Store};
pub fn fingerprint(ax: &ApplyEnv<'_>, entry: &EntryPlan) -> Result<String, CoreError> {
let key = LedgerKey::load(ax.fs, &ax.home.state_dir())?
.unwrap_or_else(|| LedgerKey::from_bytes([0; 32]));
let value = NativeValue::Array(vec![
NativeValue::String(entry.state.as_str().to_owned()),
NativeValue::String(entry.client.unwrap_or_default().to_owned()),
NativeValue::String(entry.name.clone()),
entry.observed.clone().unwrap_or(NativeValue::Null),
entry.desired.clone().unwrap_or(NativeValue::Null),
]);
Ok(key.hash(&Canonical::of(&value)))
}
#[derive(Debug, Clone, Default)]
pub struct ThreeWay {
pub last_written: Option<String>,
pub current: Option<String>,
pub desired: Option<String>,
}
pub fn three_way(
store: Option<&Store<'_>>,
ax: &ApplyEnv<'_>,
target: &TargetPlan,
entry: &EntryPlan,
) -> Result<ThreeWay, CoreError> {
let render = |value: &Option<NativeValue>| {
value
.as_ref()
.and_then(|value| target.snippet(&entry.name, value))
};
let last_written = match entry.state {
EntryState::Collision => None,
EntryState::Drifted if entry.desired.is_some() => render(&entry.desired),
_ => match store {
Some(store) => recovered(store, ax, target, entry)?,
None => None,
},
};
Ok(ThreeWay {
last_written,
current: render(&entry.observed),
desired: render(&entry.desired),
})
}
fn recovered(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
target: &TargetPlan,
entry: &EntryPlan,
) -> Result<Option<String>, CoreError> {
let Some(client) = entry.client else {
return Ok(None);
};
let inputs = PlanInputs::load(Some(store), ax)?;
let file = target.file.to_string_lossy();
let slot = LedgerSlot {
scope: target.scope,
project_id: target.project_id.as_deref(),
file: &file,
container: &target.pointer,
};
let row = inputs
.ledger
.get(&slot, &entry.name)
.filter(|row| row.kind == EntryKind::McpEntry && row.client == client);
let Some((hash, commit)) =
row.and_then(|row| row.written_hash.as_ref().zip(row.store_commit.as_ref()))
else {
return Ok(None);
};
let Ok(base) = store.resolve(commit) else {
return Ok(None);
};
let log = store.log(&LogFilter::default())?;
let mut candidates = Vec::new();
if let Some(index) = log.iter().position(|logged| logged.id == base)
&& index > 0
{
candidates.push(log[index - 1].id.clone());
}
candidates.push(base);
let machine = Machine::load(ax.fs, &ax.home.state_dir())?;
let options = PlanOptions {
scope: match target.scope {
Scope::User => ScopeFilter::System,
Scope::Project | Scope::ProjectLocal => ScopeFilter::Project,
},
projects: match &target.project {
Some(root) => ProjectSelection::Only(root.clone()),
None => ProjectSelection::All,
},
targets: Some(vec![filter_of(target)]),
..PlanOptions::default()
};
let cx = ax.render_cx(inputs.memory.clone());
for id in candidates {
let revision = store.revision(&id)?;
let Ok(desired) = DesiredState::load(&revision, machine.as_ref().map(|m| m.id.as_str()))
else {
continue;
};
let old = plan::plan(&cx, &desired, &inputs.ledger, &inputs.key, &options)?;
for old_target in old
.targets
.iter()
.filter(|old| old.pointer == target.pointer)
{
for old_entry in &old_target.entries {
if old_entry.name != entry.name || old_entry.client != Some(client) {
continue;
}
let Some(value) = &old_entry.desired else {
continue;
};
let matches = plan::canonical(client, value)
.is_some_and(|canonical| inputs.key.hash(&canonical) == *hash);
if matches {
return Ok(old_target
.snippet(&entry.name, value)
.map(|text| target.mask(&text)));
}
}
}
}
Ok(None)
}
pub fn filter_of(target: &TargetPlan) -> TargetFilter {
TargetFilter {
scope: target.scope,
project: target.project.clone(),
file: target.file.clone(),
}
}
#[allow(clippy::too_many_arguments)]
pub fn resolve(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
filter: TargetFilter,
client: &str,
name: &str,
state: EntryState,
resolution: OnConflict,
expected: &str,
) -> Result<(ApplyReport, Option<CommitId>), CoreError> {
let entry = format!("{client}/{name}");
let summary = match (resolution, state) {
(OnConflict::Import, EntryState::Missing) => format!("resolve: respect deletion {entry}"),
(OnConflict::Import, EntryState::Collision) => format!("adopt: {entry} (import theirs)"),
(OnConflict::Import, _) => format!("adopt: {entry} drift"),
(other, _) => format!("resolve: {} {entry}", other.as_str()),
};
let request = ApplyRequest {
options: PlanOptions {
on_conflict: OnConflict::Ask,
decisions: vec![Decision {
client: client.to_owned(),
name: name.to_owned(),
resolution,
}],
targets: Some(vec![filter.clone()]),
..PlanOptions::default()
},
trigger: ApplyTrigger::Review,
};
let operation = Operation::new("entry.resolve", summary.clone());
let committed = store.transaction(operation, |tx| {
check_unchanged(tx, ax, &filter, client, name, expected)?;
let report = apply_in(tx, ax, &request)?;
tx.set_summary(summary);
Ok(report)
})?;
Ok((committed.value, committed.commit))
}
fn check_unchanged(
tx: &crate::store::Transaction<'_>,
ax: &ApplyEnv<'_>,
filter: &TargetFilter,
client: &str,
name: &str,
expected: &str,
) -> Result<(), CoreError> {
let state_dir = ax.home.state_dir();
let desired = DesiredState::load(tx, Some(&tx.machine().id))?;
let ledger = crate::apply::ledger::Ledger::load(ax.fs, &state_dir)?;
let key = LedgerKey::load(ax.fs, &state_dir)?.unwrap_or_else(|| LedgerKey::from_bytes([0; 32]));
let cx = ax.render_cx(tx.store().secret_memory().clone());
let options = PlanOptions {
targets: Some(vec![filter.clone()]),
..PlanOptions::default()
};
let now = plan::plan(&cx, &desired, &ledger, &key, &options)?;
let entry = now
.targets
.iter()
.flat_map(|target| &target.entries)
.find(|entry| entry.name == name && entry.client == Some(client));
let same = match entry {
Some(entry) => fingerprint(ax, entry)? == expected,
None => false,
};
if same {
Ok(())
} else {
Err(CoreError::new(
crate::error::ErrorCode::EntryChanged,
format!(
"{client}/{name} changed since the resolver showed it; nothing was done. Open it \
again to see the current versions"
),
))
}
}