Skip to main content

gitpoulpi_core/domain/
undo.rs

1//! The vocabulary of undo/redo (the undo-redo design): ref
2//! snapshots and compare-and-swap ref updates (the backend primitives),
3//! plus the typed refusal and the summaries a client shows. The journal
4//! state machine that uses them is `crate::journal`.
5
6use std::collections::BTreeMap;
7
8use serde::{Deserialize, Serialize};
9
10use super::{Oid, OperationKind, ReflogPosition, RestoreOffer};
11
12/// Where HEAD points: a branch (by short name, which may be unborn) or a
13/// detached commit.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub enum HeadState {
16    Branch(String),
17    Detached(Oid),
18}
19
20impl HeadState {
21    pub fn describe(&self) -> String {
22        match self {
23            HeadState::Branch(name) => name.clone(),
24            HeadState::Detached(oid) => format!("detached at {}", short(*oid)),
25        }
26    }
27}
28
29/// The first 7 characters of an object id.
30pub fn short(oid: Oid) -> String {
31    oid.to_hex()[..7].to_string()
32}
33
34/// `short`, or `none` for a ref that does not exist.
35pub fn short_opt(oid: Option<Oid>) -> String {
36    oid.map(short).unwrap_or_else(|| "nothing".to_string())
37}
38
39/// Raw ref values and HEAD at one instant. Tags are the *tag object's*
40/// oid (not peeled), so an annotated tag can be restored byte for byte.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct RefSnapshot {
43    pub head: HeadState,
44    /// Full ref name (`refs/heads/main`) to its raw oid.
45    pub refs: BTreeMap<String, Oid>,
46    /// Symbolic refs in scope (`refs/remotes/origin/HEAD`) to the full name
47    /// of the ref they point at. Their resolved value also sits in `refs`
48    /// when the backend lists it.
49    #[serde(default)]
50    pub symrefs: BTreeMap<String, String>,
51}
52
53/// Which ref namespaces a [`RefSnapshot`] lists. The default is every
54/// branch and tag; a narrower scope is cheaper in a repository with
55/// thousands of tags.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct RefScope {
58    pub prefixes: Vec<String>,
59}
60
61impl RefScope {
62    pub fn heads() -> Self {
63        Self {
64            prefixes: vec!["refs/heads/".into()],
65        }
66    }
67}
68
69impl Default for RefScope {
70    fn default() -> Self {
71        Self {
72            prefixes: vec!["refs/heads/".into(), "refs/tags/".into()],
73        }
74    }
75}
76
77/// One step of an atomic ref transaction (`GitBackend::update_refs`).
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub enum RefUpdate {
80    /// The ref must not exist.
81    Create {
82        name: String,
83        new: Oid,
84    },
85    Update {
86        name: String,
87        old: Oid,
88        new: Oid,
89    },
90    Delete {
91        name: String,
92        old: Oid,
93    },
94    /// Fails the whole transaction unless the ref holds `old`.
95    Verify {
96        name: String,
97        old: Oid,
98    },
99    /// Re-points HEAD without touching the index or any file. `old` is
100    /// verified first (`UndoRefusal::HeadMoved`).
101    SetHead {
102        old: HeadState,
103        new: HeadState,
104    },
105    /// Makes the symbolic ref `name` (`refs/remotes/<r>/HEAD`) point at
106    /// the ref `new`, or deletes it when `new` is `None`. Applied after the
107    /// rest of the transaction (its target may be created in it), and not
108    /// verified: `old` only exists so that the update can be inverted.
109    SetSymbolic {
110        name: String,
111        old: Option<String>,
112        new: Option<String>,
113    },
114}
115
116impl RefUpdate {
117    /// The update that undoes this one, run against the state this one
118    /// left.
119    pub fn inverse(&self) -> RefUpdate {
120        match self {
121            RefUpdate::Create { name, new } => RefUpdate::Delete {
122                name: name.clone(),
123                old: *new,
124            },
125            RefUpdate::Update { name, old, new } => RefUpdate::Update {
126                name: name.clone(),
127                old: *new,
128                new: *old,
129            },
130            RefUpdate::Delete { name, old } => RefUpdate::Create {
131                name: name.clone(),
132                new: *old,
133            },
134            RefUpdate::Verify { name, old } => RefUpdate::Verify {
135                name: name.clone(),
136                old: *old,
137            },
138            RefUpdate::SetHead { old, new } => RefUpdate::SetHead {
139                old: new.clone(),
140                new: old.clone(),
141            },
142            RefUpdate::SetSymbolic { name, old, new } => RefUpdate::SetSymbolic {
143                name: name.clone(),
144                old: new.clone(),
145                new: old.clone(),
146            },
147        }
148    }
149}
150
151/// The prefix of the hidden keep-alive refs. Excluded from every listing.
152pub const UNDO_PIN_PREFIX: &str = "refs/gitpoulpi/undo/";
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155pub enum Direction {
156    Undo,
157    Redo,
158}
159
160impl Direction {
161    pub fn verb(self) -> &'static str {
162        match self {
163            Direction::Undo => "undo",
164            Direction::Redo => "redo",
165        }
166    }
167}
168
169/// What every surface says when `general.undo_enabled` is off.
170pub const UNDO_DISABLED_MESSAGE: &str = "Undo is turned off (Settings > General)";
171
172/// Why an undo or redo did not happen. Nothing was changed.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub enum UndoRefusal {
175    NothingToUndo,
176    NothingToRedo,
177    /// A merge, rebase, cherry-pick or revert is in progress.
178    InProgress {
179        op: String,
180    },
181    RefMoved {
182        name: String,
183        expected: Option<Oid>,
184        actual: Option<Oid>,
185        /// Set by the daemon: where the ref's reflog holds `expected`, so
186        /// a client can offer "restore main to where Commit left it".
187        #[serde(default, skip_serializing_if = "Option::is_none")]
188        restore: Option<Box<ReflogPosition>>,
189    },
190    HeadMoved {
191        expected: HeadState,
192        actual: HeadState,
193    },
194    /// A config section the entry touched is no longer as it left it.
195    ConfigChanged {
196        section: String,
197    },
198    /// The operation never completed (the daemon stopped half way).
199    Interrupted {
200        entry: u64,
201    },
202    /// Moving a checked-out branch would overwrite local changes in the
203    /// working tree (`reset --keep` semantics); nothing was changed.
204    WouldOverwrite {
205        detail: String,
206    },
207    /// A file the entry touched is no longer as the operation left it
208    /// (edited, staged or deleted since). Nothing was changed.
209    PathChanged {
210        path: String,
211    },
212    /// The index is no longer as the staging operation left it.
213    IndexChanged,
214    /// The stash list is no longer as the operation left it: the stash
215    /// `commit` was dropped, popped or stored outside GitPoulpi.
216    StashChanged {
217        commit: Oid,
218    },
219    /// The client named an entry that is not the top one any more.
220    StaleEntry {
221        expected_id: u64,
222        top_id: u64,
223    },
224    /// `general.undo_enabled` is off: nothing is recorded and nothing runs.
225    Disabled,
226    /// A resolved file can only be put back in conflict while the merge,
227    /// rebase, cherry-pick or revert it belongs to is still going.
228    OperationEnded,
229    /// "Restore only this": the entry has nothing to bring back, or not
230    /// without guessing. `reason` says why.
231    NotRestorable {
232        reason: String,
233    },
234    /// "Restore only this": the name the branch or tag had is taken now.
235    /// Run again with `name` set (`suggested` is free).
236    NameTaken {
237        name: String,
238        suggested: String,
239    },
240    /// "Restore only this": everything the entry removed is back already.
241    AlreadyRestored,
242    /// No such entry in the undo history.
243    NoSuchEntry {
244        id: u64,
245    },
246    /// The entry's old history was purged (`rewrite purge`): the objects it
247    /// would put back are gone.
248    Purged {
249        entry: u64,
250    },
251    /// Undoing or redoing a deletion on a remote: the branch or tag there is
252    /// no longer as the operation left it (recreated, moved or deleted by
253    /// someone else), so pushing or deleting would overwrite that. Nothing was
254    /// changed; `name` is the full ref (`refs/heads/x`).
255    RemoteRefMoved(Box<RemoteRefMoved>),
256    /// Undoing the deletion of a remote branch or tag needs its commit or tag
257    /// object, and it is no longer in this repository (it was garbage
258    /// collected), so it cannot be pushed back.
259    RemoteObjectMissing {
260        oid: Oid,
261    },
262}
263
264/// What [`UndoRefusal::RemoteRefMoved`] says (boxed there: the refusal travels
265/// in every error, and strings would make all of them bigger).
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub struct RemoteRefMoved {
268    pub remote: String,
269    /// The full ref name (`refs/heads/x`, `refs/tags/v1`).
270    pub name: String,
271    /// What the entry expected the remote to hold (`None`: nothing).
272    pub expected: Option<Oid>,
273    pub actual: Option<Oid>,
274}
275
276impl UndoRefusal {
277    /// The journal's top entry is stuck for good (the repository moved on,
278    /// or the entry never finished) and can be dropped from the journal
279    /// (`forget`) to reach the entries under it.
280    pub fn forgettable(&self) -> bool {
281        matches!(
282            self,
283            UndoRefusal::Interrupted { .. }
284                | UndoRefusal::RefMoved { .. }
285                | UndoRefusal::HeadMoved { .. }
286                | UndoRefusal::ConfigChanged { .. }
287                | UndoRefusal::PathChanged { .. }
288                | UndoRefusal::IndexChanged
289                | UndoRefusal::StashChanged { .. }
290                | UndoRefusal::OperationEnded
291                | UndoRefusal::Purged { .. }
292                | UndoRefusal::RemoteRefMoved { .. }
293                | UndoRefusal::RemoteObjectMissing { .. }
294        )
295    }
296
297    /// A sentence naming what moved, for a human.
298    pub fn message(&self) -> String {
299        match self {
300            UndoRefusal::NothingToUndo => "nothing to undo (a push, a fetch or anything else \
301                 done on a remote server is never undone, except deleting a remote branch \
302                 or tag)"
303                .into(),
304            UndoRefusal::NothingToRedo => "nothing to redo".into(),
305            UndoRefusal::Disabled => UNDO_DISABLED_MESSAGE.into(),
306            UndoRefusal::NotRestorable { reason } => format!("cannot restore: {reason}"),
307            UndoRefusal::NameTaken { name, suggested } => format!(
308                "the name {name} is taken now; restore under another name (for example {suggested})"
309            ),
310            UndoRefusal::AlreadyRestored => {
311                "everything this operation removed is already back".to_string()
312            }
313            UndoRefusal::NoSuchEntry { id } => {
314                format!("there is no operation #{id} in the undo history")
315            }
316            UndoRefusal::OperationEnded => "the merge, rebase, cherry-pick or revert this file \
317                 was resolved in has ended, so it cannot be put back in conflict"
318                .into(),
319            UndoRefusal::InProgress { op } => {
320                format!("finish or abort the {op} first")
321            }
322            UndoRefusal::RefMoved {
323                name,
324                expected,
325                actual,
326                ..
327            } => format!(
328                "{} is at {}, not at {} where the operation left it; it was changed outside GitPoulpi",
329                name.strip_prefix("refs/heads/")
330                    .or_else(|| name.strip_prefix("refs/tags/"))
331                    .unwrap_or(name),
332                short_opt(*actual),
333                short_opt(*expected),
334            ),
335            UndoRefusal::HeadMoved { expected, actual } => format!(
336                "HEAD is {}, not {} where the operation left it; it was changed outside GitPoulpi",
337                actual.describe(),
338                expected.describe()
339            ),
340            UndoRefusal::ConfigChanged { section } => format!(
341                "the configuration section {section} was changed outside GitPoulpi since the operation"
342            ),
343            UndoRefusal::Interrupted { entry } => format!(
344                "operation #{entry} never completed (GitPoulpi stopped while it ran); \
345                 inspect it with `gitpoulpi undo --list` and fix the repository by hand"
346            ),
347            UndoRefusal::WouldOverwrite { detail } => format!(
348                "local changes in the working tree would be overwritten, so nothing was moved: {}",
349                detail.trim()
350            ),
351            UndoRefusal::PathChanged { path } => format!(
352                "{path} was changed since the operation (outside GitPoulpi, or by a later \
353                 operation), so restoring it would overwrite that change; nothing was restored"
354            ),
355            UndoRefusal::IndexChanged => "the index (staged changes) was changed since the \
356                 operation, outside GitPoulpi; nothing was restored"
357                .to_string(),
358            UndoRefusal::StashChanged { commit } => format!(
359                "the stash {} was dropped, applied or stored outside GitPoulpi since the \
360                 operation; the stash list was left alone",
361                short(*commit)
362            ),
363            UndoRefusal::Purged { entry } => format!(
364                "the old history of operation #{entry} was purged, so it cannot be undone or redone; \
365                 `gitpoulpi undo-forget` drops it from the undo history"
366            ),
367            UndoRefusal::RemoteRefMoved(moved) => {
368                let RemoteRefMoved {
369                    remote,
370                    name,
371                    expected,
372                    actual,
373                } = &**moved;
374                format!(
375                "{} on {remote} is at {}, not at {} where the operation left it: it was changed \
376                 on the remote since, so nothing was changed there",
377                display_ref_name(name),
378                actual.map_or_else(|| "nothing".to_string(), short),
379                expected.map_or_else(|| "nothing".to_string(), short),
380                )
381            }
382            UndoRefusal::RemoteObjectMissing { oid } => format!(
383                "{} is no longer in this repository (it was garbage collected), so the branch or \
384                 tag cannot be restored on the remote with a push",
385                short(*oid)
386            ),
387            UndoRefusal::StaleEntry {
388                expected_id,
389                top_id,
390            } => format!(
391                "the operation you saw (#{expected_id}) is no longer the latest (#{top_id} is)"
392            ),
393        }
394    }
395}
396
397/// One entry as a client shows it.
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399pub struct EntrySummary {
400    pub id: u64,
401    pub kind: OperationKind,
402    /// `Commit "fix login" (a81b9e4)`.
403    pub label: String,
404    /// Unix seconds.
405    pub at: i64,
406    pub state: EntryState,
407}
408
409#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
410pub enum EntryState {
411    /// Written before the operation ran.
412    Pending,
413    Done,
414    /// Pending, and the operation is no longer running: it never
415    /// finished. Never undone automatically.
416    Interrupted,
417    /// A history rewrite whose old objects, pins and reflogs were purged:
418    /// kept in the list, greyed, never undone or redone.
419    Purged,
420}
421
422/// The answer to `OperationKind::JournalState`.
423#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
424pub struct JournalState {
425    pub undo: Option<EntrySummary>,
426    pub redo: Option<EntrySummary>,
427    /// Why the top undo entry cannot run right now, if it cannot.
428    pub blocked: Option<UndoRefusal>,
429    /// Same, for the top redo entry.
430    pub redo_blocked: Option<UndoRefusal>,
431    /// `general.undo_enabled` is off: no entries are recorded and the
432    /// buttons say so.
433    #[serde(default)]
434    pub disabled: bool,
435    /// How many entries the undo stack holds (what the Undo button says
436    /// "you can go back this far" with).
437    #[serde(default)]
438    pub undo_count: usize,
439    /// How many undone entries a redo can bring back.
440    #[serde(default)]
441    pub redo_count: usize,
442}
443
444/// What an undo or redo did, or would do (`dry_run`).
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446pub struct UndoOutcome {
447    pub direction: Direction,
448    pub entry: EntrySummary,
449    /// The steps, in words.
450    pub steps: Vec<String>,
451    /// False for a dry run.
452    pub applied: bool,
453    /// Set on a dry run when the real run needs `confirmed`: why.
454    #[serde(default)]
455    pub needs_confirmation: Option<String>,
456}
457
458/// The answer to `OperationKind::JournalList`.
459#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
460pub struct JournalListing {
461    /// Oldest first; `redo` entries are listed newest-undone last.
462    pub undo: Vec<ListedEntry>,
463    pub redo: Vec<ListedEntry>,
464    /// With `all`: entries no longer redoable whose data is still pinned.
465    pub retired: Vec<ListedEntry>,
466}
467
468/// Who made the operation an entry records.
469#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
470#[serde(rename_all = "lowercase")]
471pub enum EntrySource {
472    /// GitPoulpi itself (a window, the CLI, an MCP tool).
473    #[default]
474    Gitpoulpi,
475    /// A shell or an AI agent, found by the ref snapshot diff.
476    Outside,
477}
478
479#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
480pub struct ListedEntry {
481    /// `gitpoulpi`, or `outside` for a change made outside GitPoulpi.
482    #[serde(default)]
483    pub source: EntrySource,
484    /// For an outside entry: the reflog's reason and committer.
485    #[serde(default, skip_serializing_if = "Option::is_none")]
486    pub outside: Option<crate::journal::OutsideInfo>,
487    pub summary: EntrySummary,
488    /// `refs/heads/main: a81b9e4 -> 3f2a1c0`, one per changed ref.
489    pub changes: Vec<String>,
490    /// What "restore only this" would bring back (empty `items` and a
491    /// `not_restorable` reason when nothing).
492    #[serde(default)]
493    pub restore: RestoreOffer,
494}
495
496/// One file's recorded state on one side (index or working tree): the git
497/// file mode (`0o100644`, `0o100755`, `0o120000`) and the blob id of the
498/// **raw** bytes (no clean filter: CRLF and LFS pointers stay as they are).
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
500pub struct FileHash {
501    pub mode: u32,
502    pub oid: Oid,
503}
504
505/// The index and working-tree state of one file, `None` where it is
506/// absent. Compared with `==` for the undo/redo preconditions.
507#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
508pub struct PathHash {
509    pub path: String,
510    pub worktree: Option<FileHash>,
511    pub index: Option<FileHash>,
512}
513
514/// A safety snapshot (`GitBackend::snapshot_create`): a tree holding
515/// `index/<path>` and `worktree/<path>` for every file under the paths it
516/// was made for, plus the same information as `hashes`, sorted by path.
517/// Keep `tree` alive with a pin ref (any ref may point at a tree).
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519pub struct Snapshot {
520    pub tree: Oid,
521    pub hashes: Vec<PathHash>,
522}
523
524/// `refs/heads/x` as `x`, `refs/tags/v1` as `tag v1`.
525fn display_ref_name(name: &str) -> String {
526    name.strip_prefix("refs/heads/")
527        .map(str::to_string)
528        .or_else(|| name.strip_prefix("refs/tags/").map(|t| format!("tag {t}")))
529        .unwrap_or_else(|| name.to_string())
530}