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}
408
409#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
410pub enum EntryState {
411 Pending,
413 Done,
414 Interrupted,
417 Purged,
420}
421
422#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
424pub struct JournalState {
425 pub undo: Option<EntrySummary>,
426 pub redo: Option<EntrySummary>,
427 pub blocked: Option<UndoRefusal>,
429 pub redo_blocked: Option<UndoRefusal>,
431 #[serde(default)]
434 pub disabled: bool,
435 #[serde(default)]
438 pub undo_count: usize,
439 #[serde(default)]
441 pub redo_count: usize,
442}
443
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446pub struct UndoOutcome {
447 pub direction: Direction,
448 pub entry: EntrySummary,
449 pub steps: Vec<String>,
451 pub applied: bool,
453 #[serde(default)]
455 pub needs_confirmation: Option<String>,
456}
457
458#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
460pub struct JournalListing {
461 pub undo: Vec<ListedEntry>,
463 pub redo: Vec<ListedEntry>,
464 pub retired: Vec<ListedEntry>,
466}
467
468#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
470#[serde(rename_all = "lowercase")]
471pub enum EntrySource {
472 #[default]
474 Gitpoulpi,
475 Outside,
477}
478
479#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
480pub struct ListedEntry {
481 #[serde(default)]
483 pub source: EntrySource,
484 #[serde(default, skip_serializing_if = "Option::is_none")]
486 pub outside: Option<crate::journal::OutsideInfo>,
487 pub summary: EntrySummary,
488 pub changes: Vec<String>,
490 #[serde(default)]
493 pub restore: RestoreOffer,
494}
495
496#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
500pub struct FileHash {
501 pub mode: u32,
502 pub oid: Oid,
503}
504
505#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519pub struct Snapshot {
520 pub tree: Oid,
521 pub hashes: Vec<PathHash>,
522}
523
524fn 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}