use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::domain::{
short, short_opt, ConflictEntry, Direction, EntrySource, EntryState, EntrySummary, HeadState,
JournalState, ListedEntry, Oid, OperationKind, PathHash, RefSnapshot, RefUpdate, Snapshot,
UndoRefusal, UNDO_PIN_PREFIX,
};
pub const DEFAULT_MAX_ENTRIES: usize = 100;
pub const MAX_RETIRED: usize = 20;
pub const JOURNAL_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Pin {
pub name: String,
pub oid: Oid,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefChange {
pub name: String,
pub old: Option<Oid>,
pub new: Option<Oid>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RemoteRefChange {
pub remote: String,
pub name: String,
pub old: Option<Oid>,
pub new: Option<Oid>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeadChange {
pub old: HeadState,
pub new: HeadState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfigChange {
pub section: String,
pub old: Vec<(String, String)>,
pub new: Vec<(String, String)>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Effect {
#[default]
Refs,
Files,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathChange {
pub paths: Vec<String>,
pub before: Snapshot,
pub after: Snapshot,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexChange {
pub before: Oid,
pub after: Oid,
#[serde(default)]
pub known: Option<(String, Oid)>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConflictChange {
pub entry: ConflictEntry,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpStateChange {
pub before: String,
pub after: String,
pub before_sum: Option<String>,
pub after_sum: Option<String>,
pub aborts: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StashRecord {
pub commit: Oid,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SymrefChange {
pub name: String,
pub old: Option<String>,
pub new: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StashChange {
pub added: Vec<StashRecord>,
pub removed: Vec<StashRecord>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutsideInfo {
pub message: String,
#[serde(default)]
pub committer: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JournalEntry {
pub id: u64,
pub kind: OperationKind,
pub label: String,
pub at: i64,
pub state: EntryState,
#[serde(default)]
pub head: Option<HeadChange>,
pub require_head: bool,
pub refs: Vec<RefChange>,
#[serde(default)]
pub config: Vec<ConfigChange>,
#[serde(default)]
pub pins: Vec<Pin>,
#[serde(default)]
pub effect: Effect,
#[serde(default)]
pub files: Option<PathChange>,
#[serde(default)]
pub index: Option<IndexChange>,
#[serde(default)]
pub stash: Option<StashChange>,
#[serde(default)]
pub symrefs: Vec<SymrefChange>,
#[serde(default)]
pub conflict: Option<ConflictChange>,
#[serde(default)]
pub opstate: Option<OpStateChange>,
#[serde(default)]
pub outside: Option<OutsideInfo>,
#[serde(default)]
pub remote_refs: Vec<RemoteRefChange>,
}
impl JournalEntry {
pub fn summary(&self) -> EntrySummary {
EntrySummary {
id: self.id,
kind: self.kind,
label: self.label.clone(),
at: self.at,
state: self.state,
}
}
pub fn listed(&self) -> ListedEntry {
ListedEntry {
source: if self.kind == OperationKind::Outside {
EntrySource::Outside
} else {
EntrySource::Gitpoulpi
},
outside: self.outside.clone(),
restore: self.restore_offer(),
summary: self.summary(),
changes: self
.refs
.iter()
.map(|c| {
format!(
"{}: {} -> {}",
c.name,
short_opt(c.old),
if matches!(self.state, EntryState::Done | EntryState::Purged) {
short_opt(c.new)
} else {
"?".to_string()
}
)
})
.chain(self.remote_refs.iter().map(|r| {
format!(
"{}/{}: {} -> {}",
r.remote,
r.name,
short_opt(r.old),
short_opt(r.new)
)
}))
.chain(
self.index
.iter()
.map(|i| format!("index: {} -> {}", short(i.before), short(i.after))),
)
.chain(
self.files
.iter()
.map(|f| format!("files: {}", paths_in_words(&f.paths))),
)
.chain(self.stash.iter().flat_map(|st| {
st.added
.iter()
.map(|r| format!("stash: + {}", short(r.commit)))
.chain(
st.removed
.iter()
.map(|r| format!("stash: - {}", short(r.commit))),
)
}))
.collect(),
}
}
}
pub fn paths_in_words(paths: &[String]) -> String {
const SHOWN: usize = 3;
let mut text = paths
.iter()
.take(SHOWN)
.cloned()
.collect::<Vec<_>>()
.join(", ");
if paths.len() > SHOWN {
text.push_str(&format!(" and {} more", paths.len() - SHOWN));
}
text
}
pub fn pin_name(ns: &str, id: u64, n: usize) -> String {
format!("{UNDO_PIN_PREFIX}{ns}{id}/{n}")
}
pub fn pin_namespace(git_dir: &std::path::Path) -> String {
pin_namespace_in(git_dir, None)
}
pub fn env_pin_prefix(env: &str) -> String {
format!("e{}/", env_tag(env))
}
pub fn env_tag(env: &str) -> String {
let hash = env.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
});
format!("{:08x}", hash as u32)
}
pub fn pin_namespace_in(git_dir: &std::path::Path, env: Option<&str>) -> String {
let prefix = env.map(env_pin_prefix).unwrap_or_default();
let linked = git_dir
.parent()
.and_then(|p| p.file_name())
.is_some_and(|n| n == "worktrees");
let Some(name) = git_dir.file_name().filter(|_| linked) else {
return prefix;
};
let name = name.to_string_lossy();
let safe: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
});
format!("{prefix}wt-{safe}-{:08x}/", hash as u32)
}
pub fn pin_in_namespace(ns: &str, rest: &str) -> bool {
let (env, wt) = match ns.find('/') {
Some(i) if !ns.starts_with("wt-") => ns.split_at(i + 1),
_ => ("", ns),
};
let Some(rest) = rest.strip_prefix(env) else {
return false;
};
if wt.is_empty() {
rest.starts_with(|c: char| c.is_ascii_digit())
} else {
rest.starts_with(wt)
}
}
#[derive(Debug, Clone)]
pub struct RepoFacts {
pub snapshot: RefSnapshot,
pub in_progress: Option<String>,
pub config: BTreeMap<String, Vec<(String, String)>>,
pub index_tree: Option<Oid>,
pub files: BTreeMap<u64, Vec<PathHash>>,
pub stashes: Vec<Oid>,
pub index_sum: Option<String>,
pub unmerged: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Step {
UpdateRefs(Vec<RefUpdate>),
Checkout { to: HeadState, from: HeadState },
SetConfig {
section: String,
to: Vec<(String, String)>,
from: Vec<(String, String)>,
},
MoveHeadKeep { branch: String, from: Oid, to: Oid },
RestoreIndex { to: Oid, from: Oid },
RestorePaths {
paths: Vec<String>,
to: Oid,
from: Oid,
},
StashStore { commit: Oid, message: String },
StashDrop { commit: Oid, message: String },
Unresolve {
path: String,
entry: ConflictEntry,
resolved: Oid,
},
RestoreOpState { to: String, from: String },
RemoteRef {
remote: String,
name: String,
to: Option<Oid>,
from: Option<Oid>,
},
}
impl Step {
pub fn inverse(&self) -> Step {
match self {
Step::UpdateRefs(updates) => {
Step::UpdateRefs(updates.iter().rev().map(RefUpdate::inverse).collect())
}
Step::Checkout { to, from } => Step::Checkout {
to: from.clone(),
from: to.clone(),
},
Step::SetConfig { section, to, from } => Step::SetConfig {
section: section.clone(),
to: from.clone(),
from: to.clone(),
},
Step::MoveHeadKeep { branch, from, to } => Step::MoveHeadKeep {
branch: branch.clone(),
from: *to,
to: *from,
},
Step::RestoreIndex { to, from } => Step::RestoreIndex {
to: *from,
from: *to,
},
Step::RestorePaths { paths, to, from } => Step::RestorePaths {
paths: paths.clone(),
to: *from,
from: *to,
},
Step::StashStore { commit, message } => Step::StashDrop {
commit: *commit,
message: message.clone(),
},
Step::StashDrop { commit, message } => Step::StashStore {
commit: *commit,
message: message.clone(),
},
Step::RestoreOpState { to, from } => Step::RestoreOpState {
to: from.clone(),
from: to.clone(),
},
Step::RemoteRef {
remote,
name,
to,
from,
} => Step::RemoteRef {
remote: remote.clone(),
name: name.clone(),
to: *from,
from: *to,
},
Step::Unresolve { path, resolved, .. } => Step::RestorePaths {
paths: vec![path.clone()],
to: *resolved,
from: *resolved,
},
}
}
fn describe(&self) -> Vec<String> {
match self {
Step::Checkout { to, .. } => vec![format!("check out {}", to.describe())],
Step::MoveHeadKeep { branch, from, to } => vec![format!(
"move {branch} from {} to {}, updating the working tree",
short(*from),
short(*to)
)],
Step::RestoreIndex { .. } => {
vec!["restore the index (the staged changes)".to_string()]
}
Step::RestorePaths { paths, .. } => vec![format!(
"restore {} from the safety snapshot (working tree and index): {}",
if paths.len() == 1 {
"1 path".to_string()
} else {
format!("{} paths", paths.len())
},
paths_in_words(paths)
)],
Step::Unresolve { path, .. } => vec![format!(
"put {path} back in conflict (its three versions return to the index)"
)],
Step::RemoteRef {
remote, name, to, ..
} => vec![match to {
Some(oid) => format!(
"re-create {} on {remote} at {} (pushed to the remote, without force)",
display_ref(name),
short(*oid)
),
None => format!("delete {} on {remote} again", display_ref(name)),
}],
Step::RestoreOpState { .. } => vec![
"restore the index with its conflicts and the operation's state (merge, \
cherry-pick or revert in progress)"
.to_string(),
],
Step::StashStore { commit, message } => vec![format!(
"put the stash \"{}\" ({}) back on the stash list",
message,
short(*commit)
)],
Step::StashDrop { commit, message } => vec![format!(
"drop the stash \"{}\" ({})",
message,
short(*commit)
)],
Step::SetConfig { section, to, .. } => {
if to.is_empty() {
vec![format!("remove the configuration section {section}")]
} else {
vec![format!("restore the configuration section {section}")]
}
}
Step::UpdateRefs(updates) => updates
.iter()
.filter_map(|u| match u {
RefUpdate::Create { name, new } if !name.starts_with(UNDO_PIN_PREFIX) => {
Some(format!("create {} at {}", display_ref(name), short(*new)))
}
RefUpdate::Update { name, old, new } => Some(format!(
"move {} from {} to {}",
display_ref(name),
short(*old),
short(*new)
)),
RefUpdate::Delete { name, old } if !name.starts_with(UNDO_PIN_PREFIX) => Some(
format!("delete {} (was {})", display_ref(name), short(*old)),
),
RefUpdate::SetHead { new, .. } => {
Some(format!("point HEAD at {}", new.describe()))
}
_ => None,
})
.collect(),
}
}
}
fn display_ref(name: &str) -> String {
name.strip_prefix("refs/heads/")
.map(str::to_string)
.or_else(|| name.strip_prefix("refs/tags/").map(|t| format!("tag {t}")))
.unwrap_or_else(|| name.to_string())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
pub direction: Direction,
pub entry: EntrySummary,
pub steps: Vec<Step>,
pub new_pins: Vec<Pin>,
}
impl Plan {
pub fn describe(&self) -> Vec<String> {
self.steps.iter().flat_map(Step::describe).collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Journal {
pub version: u32,
pub next_id: u64,
pub undo: Vec<JournalEntry>,
pub redo: Vec<JournalEntry>,
pub retired: Vec<JournalEntry>,
#[serde(default)]
pub pin_ns: String,
}
impl Default for Journal {
fn default() -> Self {
Self {
version: JOURNAL_VERSION,
next_id: 1,
undo: Vec::new(),
redo: Vec::new(),
retired: Vec::new(),
pin_ns: String::new(),
}
}
}
pub type Dropped = Vec<JournalEntry>;
impl Journal {
#[allow(clippy::too_many_arguments)]
pub fn begin(
&mut self,
kind: OperationKind,
label: String,
at: i64,
head: Option<HeadState>,
require_head: bool,
before: Vec<(String, Option<Oid>)>,
) -> u64 {
let id = self.next_id;
self.next_id += 1;
self.undo.push(JournalEntry {
id,
kind,
label,
at,
state: EntryState::Pending,
head: head.map(|head| HeadChange {
old: head.clone(),
new: head,
}),
require_head,
refs: before
.into_iter()
.map(|(name, old)| RefChange {
name,
old,
new: None,
})
.collect(),
config: Vec::new(),
pins: Vec::new(),
effect: Effect::Refs,
files: None,
index: None,
stash: None,
symrefs: Vec::new(),
conflict: None,
opstate: None,
outside: None,
remote_refs: Vec::new(),
});
id
}
#[allow(clippy::too_many_arguments)]
pub fn record_outside(
&mut self,
change: &OutsideChange,
head_now: &HeadState,
label: String,
at: i64,
pins: Vec<Pin>,
max_entries: usize,
) -> (u64, Dropped) {
let id = self.next_id;
self.next_id += 1;
let effect = change.effect(head_now);
let head = change.head.clone().unwrap_or(HeadChange {
old: head_now.clone(),
new: head_now.clone(),
});
let head_moved = head.old != head.new;
self.undo.push(JournalEntry {
id,
kind: OperationKind::Outside,
label,
at,
state: EntryState::Done,
head: Some(head),
require_head: head_moved || effect == Effect::Files,
refs: change.refs.clone(),
config: Vec::new(),
pins,
effect,
files: None,
index: None,
stash: change.stash.clone(),
symrefs: Vec::new(),
conflict: None,
opstate: None,
outside: Some(OutsideInfo {
message: change.message.clone(),
committer: change.committer.clone(),
}),
remote_refs: Vec::new(),
});
self.retired.append(&mut self.redo);
let mut dropped = Vec::new();
while self.undo.len() > max_entries.max(1) {
dropped.push(self.undo.remove(0));
}
while self.retired.len() > MAX_RETIRED {
dropped.push(self.retired.remove(0));
}
(id, dropped)
}
pub fn entry_mut(&mut self, id: u64) -> Option<&mut JournalEntry> {
self.undo.iter_mut().find(|e| e.id == id)
}
pub fn finish(
&mut self,
id: u64,
head_new: Option<HeadState>,
refs: Vec<RefChange>,
config: Vec<ConfigChange>,
max_entries: usize,
) -> Dropped {
if let Some(entry) = self.entry_mut(id) {
entry.state = EntryState::Done;
if let (Some(head), Some(new)) = (entry.head.as_mut(), head_new) {
head.new = new;
}
entry.refs = refs;
entry.config = config;
}
self.retired.append(&mut self.redo);
let mut dropped = Vec::new();
while self.undo.len() > max_entries.max(1) {
dropped.push(self.undo.remove(0));
}
while self.retired.len() > MAX_RETIRED {
dropped.push(self.retired.remove(0));
}
dropped
}
pub fn drop_resolutions(&mut self, keep_newest: Option<usize>) -> Dropped {
let mut dropped = Vec::new();
let is_resolution = |e: &JournalEntry| {
e.kind == OperationKind::ResolveConflict
|| e.opstate.as_ref().is_some_and(|o| !o.aborts)
};
let keep = keep_newest.unwrap_or(0);
let total = self.undo.iter().filter(|e| is_resolution(e)).count();
let mut excess = total.saturating_sub(keep);
for stack in [&mut self.redo, &mut self.retired] {
let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(stack)
.into_iter()
.partition(|e| is_resolution(e) && keep_newest.is_none());
*stack = kept;
dropped.extend(gone);
}
let mut kept = Vec::new();
for entry in std::mem::take(&mut self.undo) {
if is_resolution(&entry) && excess > 0 {
excess -= 1;
dropped.push(entry);
} else {
kept.push(entry);
}
}
self.undo = kept;
dropped
}
pub fn all_entries(&self) -> impl Iterator<Item = &JournalEntry> {
self.undo
.iter()
.chain(self.redo.iter())
.chain(self.retired.iter())
}
pub fn mark_purged(&mut self, ids: &[u64]) -> Vec<Pin> {
let mut pins = Vec::new();
for entry in self
.undo
.iter_mut()
.chain(self.redo.iter_mut())
.chain(self.retired.iter_mut())
{
if ids.contains(&entry.id) && entry.state == EntryState::Done {
entry.state = EntryState::Purged;
pins.append(&mut entry.pins);
}
}
pins
}
pub fn abort(&mut self, id: u64) -> Option<JournalEntry> {
let at = self.undo.iter().position(|e| e.id == id)?;
Some(self.undo.remove(at))
}
pub fn recover(&mut self) -> bool {
let mut changed = false;
for entry in self.undo.iter_mut().chain(self.redo.iter_mut()) {
if entry.state == EntryState::Pending {
entry.state = EntryState::Interrupted;
changed = true;
}
}
changed
}
pub fn top(&self, direction: Direction) -> Option<&JournalEntry> {
match direction {
Direction::Undo => self.undo.last(),
Direction::Redo => self.redo.last(),
}
}
pub fn top_config_sections(&self, direction: Direction) -> Vec<String> {
self.top(direction)
.map(|e| e.config.iter().map(|c| c.section.clone()).collect())
.unwrap_or_default()
}
pub fn plan(
&self,
direction: Direction,
facts: &RepoFacts,
expect: Option<u64>,
) -> Result<Plan, UndoRefusal> {
let entry = self.top(direction).ok_or(match direction {
Direction::Undo => UndoRefusal::NothingToUndo,
Direction::Redo => UndoRefusal::NothingToRedo,
})?;
check_preconditions(entry, direction, facts, expect)?;
Ok(self.build_steps(entry, direction, facts))
}
fn build_steps(&self, entry: &JournalEntry, direction: Direction, facts: &RepoFacts) -> Plan {
let undo = direction == Direction::Undo;
let heads = head_ends(entry, undo);
let head_move = heads.filter(|(at, to)| at != to);
let (stash_drops, stash_stores) = stash_ends(entry, undo);
let mut new_pins: Vec<Pin> = Vec::new();
let want_pin = |oid: Oid, new_pins: &mut Vec<Pin>| {
let known = entry
.pins
.iter()
.chain(new_pins.iter())
.any(|p| p.oid == oid);
if !known {
new_pins.push(Pin {
name: pin_name(&self.pin_ns, entry.id, entry.pins.len() + new_pins.len()),
oid,
});
}
};
let mut updates: Vec<RefUpdate> = Vec::new();
for change in &entry.refs {
let (from, to) = oriented(undo, change.old, change.new);
if let Some(oid) = from {
want_pin(oid, &mut new_pins);
}
match (from, to) {
(None, Some(new)) => updates.push(RefUpdate::Create {
name: change.name.clone(),
new,
}),
(Some(old), Some(new)) => updates.push(RefUpdate::Update {
name: change.name.clone(),
old,
new,
}),
(Some(old), None) => updates.push(RefUpdate::Delete {
name: change.name.clone(),
old,
}),
(None, None) => {}
}
}
for change in &entry.symrefs {
let (at, to) = oriented(undo, &change.old, &change.new);
updates.push(RefUpdate::SetSymbolic {
name: change.name.clone(),
old: at.clone(),
new: to.clone(),
});
}
if let Some((HeadState::Detached(oid), _)) = heads {
if entry.require_head || head_move.is_some() {
want_pin(*oid, &mut new_pins);
}
}
let mut keeps: Vec<(String, Oid, Oid)> = Vec::new();
let moves_files = entry.effect == Effect::Files
|| matches!(
entry.kind,
OperationKind::FastForward | OperationKind::FetchRefAsBranch
);
if moves_files {
if let HeadState::Branch(branch) = &facts.snapshot.head {
let full = format!("refs/heads/{branch}");
updates.retain(|u| match u {
RefUpdate::Update { name, old, new } if *name == full => {
keeps.push((branch.clone(), *old, *new));
false
}
_ => true,
});
}
}
let mut steps: Vec<Step> = Vec::new();
for change in &entry.remote_refs {
let (from, to) = oriented(undo, change.old, change.new);
steps.push(Step::RemoteRef {
remote: change.remote.clone(),
name: change.name.clone(),
to,
from,
});
}
let pin_creates: Vec<RefUpdate> = new_pins
.iter()
.map(|p| RefUpdate::Create {
name: p.name.clone(),
new: p.oid,
})
.collect();
let detached_history = entry.effect == Effect::Files
&& entry.refs.is_empty()
&& matches!(
heads,
Some((HeadState::Detached(_), HeadState::Detached(_)))
);
let checks_out = detached_history
|| matches!(
entry.kind,
OperationKind::Checkout | OperationKind::BranchCreateTracking
)
|| (entry.kind == OperationKind::Outside && head_move.is_some())
|| (entry.kind == OperationKind::FlowRun && head_move.is_some());
let flow_order = entry.kind == OperationKind::FlowRun && checks_out;
let mut late_updates: Vec<RefUpdate> = Vec::new();
let mut checkout_step = None;
if checks_out {
if let Some((head_at, head_to)) = head_move {
checkout_step = Some(Step::Checkout {
to: head_to.clone(),
from: head_at.clone(),
});
}
}
if checks_out && undo {
let mut early_creates = pin_creates;
if flow_order {
let (early, late): (Vec<_>, Vec<_>) = std::mem::take(&mut updates)
.into_iter()
.partition(|u| matches!(u, RefUpdate::Create { .. }));
early_creates.extend(early);
updates = late;
}
if !early_creates.is_empty() {
steps.push(Step::UpdateRefs(early_creates));
}
steps.extend(checkout_step.take());
if !updates.is_empty() {
steps.push(Step::UpdateRefs(updates));
}
} else {
if flow_order {
let (late, early): (Vec<_>, Vec<_>) = std::mem::take(&mut updates)
.into_iter()
.partition(|u| matches!(u, RefUpdate::Delete { .. }));
late_updates = late;
updates = early;
}
if !checks_out {
if let Some((head_at, head_to)) = head_move {
updates.push(RefUpdate::SetHead {
old: head_at.clone(),
new: head_to.clone(),
});
}
}
updates.extend(pin_creates);
if !updates.is_empty() {
steps.push(Step::UpdateRefs(updates));
}
}
let unresolve = match (&entry.conflict, &entry.files) {
(Some(c), Some(f)) if undo => f.paths.first().map(|path| Step::Unresolve {
path: path.clone(),
entry: c.entry.clone(),
resolved: f.after.tree,
}),
_ => None,
};
let files_step = unresolve.or_else(|| {
entry.files.as_ref().map(|f| {
let (at, to) = oriented(undo, &f.before, &f.after);
Step::RestorePaths {
paths: f.paths.clone(),
to: to.tree,
from: at.tree,
}
})
});
let files_first = !undo && entry.effect == Effect::Files;
if files_first {
steps.extend(files_step.clone());
}
for (branch, from, to) in keeps {
steps.push(Step::MoveHeadKeep { branch, from, to });
}
for change in &entry.config {
let (at, to) = oriented(undo, &change.old, &change.new);
steps.push(Step::SetConfig {
section: change.section.clone(),
to: to.clone(),
from: at.clone(),
});
}
steps.extend(checkout_step);
if !late_updates.is_empty() {
steps.push(Step::UpdateRefs(late_updates));
}
if let Some(ix) = &entry.index {
let (at, to) = oriented(undo, ix.before, ix.after);
steps.push(Step::RestoreIndex { to, from: at });
}
if !files_first {
steps.extend(files_step);
}
if let Some(os) = &entry.opstate {
let (at, to) = oriented(undo, &os.before, &os.after);
steps.push(Step::RestoreOpState {
to: to.clone(),
from: at.clone(),
});
}
for r in stash_drops {
steps.push(Step::StashDrop {
commit: r.commit,
message: r.message.clone(),
});
}
for r in stash_stores {
steps.push(Step::StashStore {
commit: r.commit,
message: r.message.clone(),
});
}
Plan {
direction,
entry: entry.summary(),
steps,
new_pins,
}
}
pub fn commit(&mut self, plan: &Plan) {
let (from, to) = match plan.direction {
Direction::Undo => (&mut self.undo, &mut self.redo),
Direction::Redo => (&mut self.redo, &mut self.undo),
};
if let Some(mut entry) = from.pop() {
entry.pins.extend(plan.new_pins.iter().cloned());
to.push(entry);
}
}
pub fn state(&self, facts: Option<&RepoFacts>) -> JournalState {
let blocked =
|direction: Direction| facts.and_then(|f| self.plan(direction, f, None).err());
JournalState {
undo: self.undo.last().map(JournalEntry::summary),
redo: self.redo.last().map(JournalEntry::summary),
blocked: self.undo.last().and_then(|_| blocked(Direction::Undo)),
redo_blocked: self.redo.last().and_then(|_| blocked(Direction::Redo)),
disabled: false,
undo_count: self.undo.len(),
redo_count: self.redo.len(),
}
}
}
fn first_difference(expected: &[PathHash], actual: &[PathHash]) -> Option<String> {
let actual_by_path: BTreeMap<&str, &PathHash> =
actual.iter().map(|h| (h.path.as_str(), h)).collect();
for want in expected {
if actual_by_path.get(want.path.as_str()) != Some(&want) {
return Some(want.path.clone());
}
}
let expected_paths: std::collections::BTreeSet<&str> =
expected.iter().map(|h| h.path.as_str()).collect();
actual
.iter()
.find(|h| !expected_paths.contains(h.path.as_str()))
.map(|h| h.path.clone())
}
fn check_preconditions(
entry: &JournalEntry,
direction: Direction,
facts: &RepoFacts,
expect: Option<u64>,
) -> Result<(), UndoRefusal> {
if let Some(expected_id) = expect {
if expected_id != entry.id {
return Err(UndoRefusal::StaleEntry {
expected_id,
top_id: entry.id,
});
}
}
if let (EntryState::Pending, Some(op)) = (entry.state, &facts.in_progress) {
return Err(UndoRefusal::InProgress { op: op.clone() });
}
if entry.state == EntryState::Purged {
return Err(UndoRefusal::Purged { entry: entry.id });
}
if entry.state != EntryState::Done {
return Err(UndoRefusal::Interrupted { entry: entry.id });
}
if let Some(os) = &entry.opstate {
let undo = direction == Direction::Undo;
let running_at = !os.aborts || !undo;
match (&facts.in_progress, running_at) {
(Some(op), false) => return Err(UndoRefusal::InProgress { op: op.clone() }),
(None, true) => return Err(UndoRefusal::OperationEnded),
_ => {}
}
let (at_sum, _) = oriented(undo, &os.before_sum, &os.after_sum);
if facts.index_sum != *at_sum {
return Err(UndoRefusal::IndexChanged);
}
} else {
match (&facts.in_progress, entry.conflict.is_some()) {
(Some(op), false) => return Err(UndoRefusal::InProgress { op: op.clone() }),
(None, true) if !facts.unmerged => return Err(UndoRefusal::OperationEnded),
_ => {}
}
}
let undo = direction == Direction::Undo;
let heads = head_ends(entry, undo);
if let (true, Some((head_at, _))) = (entry.require_head, heads) {
if &facts.snapshot.head != head_at {
return Err(UndoRefusal::HeadMoved {
expected: head_at.clone(),
actual: facts.snapshot.head.clone(),
});
}
}
for change in &entry.refs {
let (at, _) = oriented(undo, change.old, change.new);
let actual = facts.snapshot.refs.get(&change.name).copied();
if actual != at {
return Err(UndoRefusal::RefMoved {
restore: None,
name: change.name.clone(),
expected: at,
actual,
});
}
}
for change in &entry.config {
let (at, _) = oriented(undo, &change.old, &change.new);
let actual = facts
.config
.get(&change.section)
.cloned()
.unwrap_or_default();
if sorted(&actual) != sorted(at) {
return Err(UndoRefusal::ConfigChanged {
section: change.section.clone(),
});
}
}
if let Some(ix) = &entry.index {
let (at, _) = oriented(undo, ix.before, ix.after);
if facts.index_tree != Some(at) {
return Err(UndoRefusal::IndexChanged);
}
}
let (stash_drops, stash_stores) = stash_ends(entry, undo);
for r in stash_drops {
if !facts.stashes.contains(&r.commit) {
return Err(UndoRefusal::StashChanged { commit: r.commit });
}
}
for r in stash_stores {
if facts.stashes.contains(&r.commit) {
return Err(UndoRefusal::StashChanged { commit: r.commit });
}
}
if let Some(f) = &entry.files {
let (at, _) = oriented(undo, &f.before, &f.after);
let now = facts.files.get(&entry.id).map(Vec::as_slice).unwrap_or(&[]);
if let Some(path) = first_difference(&at.hashes, now) {
return Err(UndoRefusal::PathChanged { path });
}
}
Ok(())
}
fn oriented<T>(undo: bool, old: T, new: T) -> (T, T) {
if undo {
(new, old)
} else {
(old, new)
}
}
fn head_ends(entry: &JournalEntry, undo: bool) -> Option<(&HeadState, &HeadState)> {
entry.head.as_ref().map(|h| oriented(undo, &h.old, &h.new))
}
fn stash_ends(entry: &JournalEntry, undo: bool) -> (&[StashRecord], &[StashRecord]) {
match &entry.stash {
Some(st) => oriented(undo, st.removed.as_slice(), st.added.as_slice()),
None => (&[], &[]),
}
}
fn sorted(pairs: &[(String, String)]) -> Vec<(String, String)> {
let mut v = pairs.to_vec();
v.sort();
v
}
pub fn diff_snapshots(before: &RefSnapshot, after: &RefSnapshot) -> Vec<RefChange> {
let mut out = Vec::new();
for (name, old) in &before.refs {
match after.refs.get(name) {
Some(new) if new == old => {}
new => out.push(RefChange {
name: name.clone(),
old: Some(*old),
new: new.copied(),
}),
}
}
for (name, new) in &after.refs {
if !before.refs.contains_key(name) {
out.push(RefChange {
name: name.clone(),
old: None,
new: Some(*new),
});
}
}
out
}
mod outside;
pub use outside::{
diff as diff_outside, CaptureScope, OutsideChange, OutsideDiff, OutsideSnapshot,
WorktreeRecord, OUTSIDE_SNAPSHOT_VERSION,
};
mod restore;
pub use restore::{
plan_restore, readd_lines, valid_ref_name, RestoreAction, RestoreFacts, RestorePlan,
};
#[cfg(test)]
mod tests;