1use std::collections::BTreeMap;
7
8use serde::{Deserialize, Serialize};
9
10use super::{Oid, OperationKind, ReflogPosition, RestoreOffer};
11
12#[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
29pub fn short(oid: Oid) -> String {
31 oid.to_hex()[..7].to_string()
32}
33
34pub fn short_opt(oid: Option<Oid>) -> String {
36 oid.map(short).unwrap_or_else(|| "nothing".to_string())
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct RefSnapshot {
43 pub head: HeadState,
44 pub refs: BTreeMap<String, Oid>,
46 #[serde(default)]
50 pub symrefs: BTreeMap<String, String>,
51}
52
53#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub enum RefUpdate {
80 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 Verify {
96 name: String,
97 old: Oid,
98 },
99 SetHead {
102 old: HeadState,
103 new: HeadState,
104 },
105 SetSymbolic {
110 name: String,
111 old: Option<String>,
112 new: Option<String>,
113 },
114}
115
116impl RefUpdate {
117 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
151pub 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
169pub const UNDO_DISABLED_MESSAGE: &str = "Undo is turned off (Settings > General)";
171
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub enum UndoRefusal {
175 NothingToUndo,
176 NothingToRedo,
177 InProgress {
179 op: String,
180 },
181 RefMoved {
182 name: String,
183 expected: Option<Oid>,
184 actual: Option<Oid>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
188 restore: Option<Box<ReflogPosition>>,
189 },
190 HeadMoved {
191 expected: HeadState,
192 actual: HeadState,
193 },
194 ConfigChanged {
196 section: String,
197 },
198 Interrupted {
200 entry: u64,
201 },
202 WouldOverwrite {
205 detail: String,
206 },
207 PathChanged {
210 path: String,
211 },
212 IndexChanged,
214 StashChanged {
217 commit: Oid,
218 },
219 StaleEntry {
221 expected_id: u64,
222 top_id: u64,
223 },
224 Disabled,
226 OperationEnded,
229 NotRestorable {
232 reason: String,
233 },
234 NameTaken {
237 name: String,
238 suggested: String,
239 },
240 AlreadyRestored,
242 NoSuchEntry {
244 id: u64,
245 },
246 Purged {
249 entry: u64,
250 },
251 RemoteRefMoved(Box<RemoteRefMoved>),
256 RemoteObjectMissing {
260 oid: Oid,
261 },
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub struct RemoteRefMoved {
268 pub remote: String,
269 pub name: String,
271 pub expected: Option<Oid>,
273 pub actual: Option<Oid>,
274}
275
276impl UndoRefusal {
277 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399pub struct EntrySummary {
400 pub id: u64,
401 pub kind: OperationKind,
402 pub label: String,
404 pub at: i64,
406 pub state: EntryState,
407 #[serde(default, skip_serializing_if = "Option::is_none")]
409 pub origin: Option<Box<SequenceOrigin>>,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
417pub struct SequenceOrigin {
418 pub name: String,
419 pub run_id: u64,
420 pub step: u32,
421 pub of: u32,
422}
423
424impl SequenceOrigin {
425 pub fn tag(&self) -> String {
427 format!(
428 "sequence:{}#{} {}/{}",
429 self.name, self.run_id, self.step, self.of
430 )
431 }
432}
433
434#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
436pub struct SequenceMember {
437 pub id: u64,
438 pub kind: OperationKind,
439 pub step: u32,
440 pub label: String,
441}
442
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446pub struct SequenceGroup {
447 pub name: String,
448 pub run_id: u64,
449 pub of: u32,
451 pub entries: Vec<SequenceMember>,
453}
454
455#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
456pub enum EntryState {
457 Pending,
459 Done,
460 Interrupted,
463 Purged,
466}
467
468#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
470pub struct JournalState {
471 pub undo: Option<EntrySummary>,
472 pub redo: Option<EntrySummary>,
473 pub blocked: Option<UndoRefusal>,
475 pub redo_blocked: Option<UndoRefusal>,
477 #[serde(default)]
480 pub disabled: bool,
481 #[serde(default)]
484 pub undo_count: usize,
485 #[serde(default)]
487 pub redo_count: usize,
488 #[serde(default, skip_serializing_if = "Option::is_none")]
490 pub sequence: Option<Box<SequenceGroup>>,
491}
492
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
495pub struct UndoOutcome {
496 pub direction: Direction,
497 pub entry: EntrySummary,
498 pub steps: Vec<String>,
500 pub applied: bool,
502 #[serde(default)]
504 pub needs_confirmation: Option<String>,
505}
506
507#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
509pub struct JournalListing {
510 pub undo: Vec<ListedEntry>,
512 pub redo: Vec<ListedEntry>,
513 pub retired: Vec<ListedEntry>,
515}
516
517#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(rename_all = "lowercase")]
520pub enum EntrySource {
521 #[default]
523 Gitpoulpi,
524 Outside,
526}
527
528#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
529pub struct ListedEntry {
530 #[serde(default)]
532 pub source: EntrySource,
533 #[serde(default, skip_serializing_if = "Option::is_none")]
535 pub outside: Option<crate::journal::OutsideInfo>,
536 pub summary: EntrySummary,
537 pub changes: Vec<String>,
539 #[serde(default)]
542 pub restore: RestoreOffer,
543}
544
545#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
549pub struct FileHash {
550 pub mode: u32,
551 pub oid: Oid,
552}
553
554#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
557pub struct PathHash {
558 pub path: String,
559 pub worktree: Option<FileHash>,
560 pub index: Option<FileHash>,
561}
562
563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
568pub struct Snapshot {
569 pub tree: Oid,
570 pub hashes: Vec<PathHash>,
571}
572
573fn display_ref_name(name: &str) -> String {
575 name.strip_prefix("refs/heads/")
576 .map(str::to_string)
577 .or_else(|| name.strip_prefix("refs/tags/").map(|t| format!("tag {t}")))
578 .unwrap_or_else(|| name.to_string())
579}