use crate::apply::ApplyEnv;
use crate::apply::rollback::{apply_commits, initial_commit};
use crate::error::{CoreError, ErrorCode};
use crate::store::diff::entity_of;
use crate::store::restore::{RestoreReport, RestoreRequest, restore_as};
use crate::store::{CommitId, Machine, Store};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PendingKind {
Added,
Changed,
Removed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingStoreChange {
pub entity: String,
pub kind: PendingKind,
}
#[derive(Debug, Clone)]
pub struct PendingStore {
pub base: CommitId,
pub head: CommitId,
pub changes: Vec<PendingStoreChange>,
}
fn discardable(file: &str) -> bool {
file == "clients.toml"
|| file
.strip_prefix("servers/")
.is_some_and(|name| name.ends_with(".toml") && !name.contains('/'))
}
pub fn pending(store: &Store<'_>, ax: &ApplyEnv<'_>) -> Result<Option<PendingStore>, CoreError> {
let Some(machine) = Machine::load(ax.fs, &ax.home.state_dir())? else {
return Ok(None);
};
let head = store.head()?;
let base = match apply_commits(store, &machine.id)?.first() {
Some(last) => last.id.clone(),
None => initial_commit(store, &head)?,
};
let at_base = store.revision(&base)?;
let at_head = store.revision(&head)?;
let mut changes = Vec::new();
for file in store.changed_files(&base, &head)? {
if !discardable(&file) {
continue;
}
let kind = match (at_base.read_bytes(&file)?, at_head.read_bytes(&file)?) {
(None, Some(_)) => PendingKind::Added,
(Some(_), None) => PendingKind::Removed,
(Some(old), Some(new)) if old != new => PendingKind::Changed,
_ => continue,
};
changes.push(PendingStoreChange {
entity: entity_of(&file),
kind,
});
}
Ok(Some(PendingStore {
base,
head,
changes,
}))
}
pub fn discard(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
pending: &PendingStore,
entities: Option<&[String]>,
) -> Result<Option<RestoreReport>, CoreError> {
let chosen: Vec<String> = match entities {
None => pending
.changes
.iter()
.map(|change| change.entity.clone())
.collect(),
Some(entities) => {
let mut chosen: Vec<String> = Vec::new();
for entity in entities {
if !pending
.changes
.iter()
.any(|change| &change.entity == entity)
{
return Err(CoreError::new(
ErrorCode::NotFound,
format!("{entity} has no pending change to discard"),
));
}
if !chosen.contains(entity) {
chosen.push(entity.clone());
}
}
chosen
}
};
if chosen.is_empty() {
return Ok(None);
}
let summary = match chosen.as_slice() {
[one] => format!("discard: {one}"),
many => format!("discard: {} pending changes", many.len()),
};
let request = RestoreRequest {
target: pending.base.clone(),
entities: chosen,
confirmed: false,
apply: false,
};
restore_as(
store,
ax,
&request,
"store.discard",
summary,
Some(&pending.head),
)
.map(Some)
}