use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use super::{Oid, OperationKind, ReflogPosition, RestoreOffer};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HeadState {
Branch(String),
Detached(Oid),
}
impl HeadState {
pub fn describe(&self) -> String {
match self {
HeadState::Branch(name) => name.clone(),
HeadState::Detached(oid) => format!("detached at {}", short(*oid)),
}
}
}
pub fn short(oid: Oid) -> String {
oid.to_hex()[..7].to_string()
}
pub fn short_opt(oid: Option<Oid>) -> String {
oid.map(short).unwrap_or_else(|| "nothing".to_string())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefSnapshot {
pub head: HeadState,
pub refs: BTreeMap<String, Oid>,
#[serde(default)]
pub symrefs: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefScope {
pub prefixes: Vec<String>,
}
impl RefScope {
pub fn heads() -> Self {
Self {
prefixes: vec!["refs/heads/".into()],
}
}
}
impl Default for RefScope {
fn default() -> Self {
Self {
prefixes: vec!["refs/heads/".into(), "refs/tags/".into()],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RefUpdate {
Create {
name: String,
new: Oid,
},
Update {
name: String,
old: Oid,
new: Oid,
},
Delete {
name: String,
old: Oid,
},
Verify {
name: String,
old: Oid,
},
SetHead {
old: HeadState,
new: HeadState,
},
SetSymbolic {
name: String,
old: Option<String>,
new: Option<String>,
},
}
impl RefUpdate {
pub fn inverse(&self) -> RefUpdate {
match self {
RefUpdate::Create { name, new } => RefUpdate::Delete {
name: name.clone(),
old: *new,
},
RefUpdate::Update { name, old, new } => RefUpdate::Update {
name: name.clone(),
old: *new,
new: *old,
},
RefUpdate::Delete { name, old } => RefUpdate::Create {
name: name.clone(),
new: *old,
},
RefUpdate::Verify { name, old } => RefUpdate::Verify {
name: name.clone(),
old: *old,
},
RefUpdate::SetHead { old, new } => RefUpdate::SetHead {
old: new.clone(),
new: old.clone(),
},
RefUpdate::SetSymbolic { name, old, new } => RefUpdate::SetSymbolic {
name: name.clone(),
old: new.clone(),
new: old.clone(),
},
}
}
}
pub const UNDO_PIN_PREFIX: &str = "refs/gitpoulpi/undo/";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Direction {
Undo,
Redo,
}
impl Direction {
pub fn verb(self) -> &'static str {
match self {
Direction::Undo => "undo",
Direction::Redo => "redo",
}
}
}
pub const UNDO_DISABLED_MESSAGE: &str = "Undo is turned off (Settings > General)";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum UndoRefusal {
NothingToUndo,
NothingToRedo,
InProgress {
op: String,
},
RefMoved {
name: String,
expected: Option<Oid>,
actual: Option<Oid>,
#[serde(default, skip_serializing_if = "Option::is_none")]
restore: Option<Box<ReflogPosition>>,
},
HeadMoved {
expected: HeadState,
actual: HeadState,
},
ConfigChanged {
section: String,
},
Interrupted {
entry: u64,
},
WouldOverwrite {
detail: String,
},
PathChanged {
path: String,
},
IndexChanged,
StashChanged {
commit: Oid,
},
StaleEntry {
expected_id: u64,
top_id: u64,
},
Disabled,
OperationEnded,
NotRestorable {
reason: String,
},
NameTaken {
name: String,
suggested: String,
},
AlreadyRestored,
NoSuchEntry {
id: u64,
},
Purged {
entry: u64,
},
RemoteRefMoved(Box<RemoteRefMoved>),
RemoteObjectMissing {
oid: Oid,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RemoteRefMoved {
pub remote: String,
pub name: String,
pub expected: Option<Oid>,
pub actual: Option<Oid>,
}
impl UndoRefusal {
pub fn forgettable(&self) -> bool {
matches!(
self,
UndoRefusal::Interrupted { .. }
| UndoRefusal::RefMoved { .. }
| UndoRefusal::HeadMoved { .. }
| UndoRefusal::ConfigChanged { .. }
| UndoRefusal::PathChanged { .. }
| UndoRefusal::IndexChanged
| UndoRefusal::StashChanged { .. }
| UndoRefusal::OperationEnded
| UndoRefusal::Purged { .. }
| UndoRefusal::RemoteRefMoved { .. }
| UndoRefusal::RemoteObjectMissing { .. }
)
}
pub fn message(&self) -> String {
match self {
UndoRefusal::NothingToUndo => "nothing to undo (a push, a fetch or anything else \
done on a remote server is never undone, except deleting a remote branch \
or tag)"
.into(),
UndoRefusal::NothingToRedo => "nothing to redo".into(),
UndoRefusal::Disabled => UNDO_DISABLED_MESSAGE.into(),
UndoRefusal::NotRestorable { reason } => format!("cannot restore: {reason}"),
UndoRefusal::NameTaken { name, suggested } => format!(
"the name {name} is taken now; restore under another name (for example {suggested})"
),
UndoRefusal::AlreadyRestored => {
"everything this operation removed is already back".to_string()
}
UndoRefusal::NoSuchEntry { id } => {
format!("there is no operation #{id} in the undo history")
}
UndoRefusal::OperationEnded => "the merge, rebase, cherry-pick or revert this file \
was resolved in has ended, so it cannot be put back in conflict"
.into(),
UndoRefusal::InProgress { op } => {
format!("finish or abort the {op} first")
}
UndoRefusal::RefMoved {
name,
expected,
actual,
..
} => format!(
"{} is at {}, not at {} where the operation left it; it was changed outside GitPoulpi",
name.strip_prefix("refs/heads/")
.or_else(|| name.strip_prefix("refs/tags/"))
.unwrap_or(name),
short_opt(*actual),
short_opt(*expected),
),
UndoRefusal::HeadMoved { expected, actual } => format!(
"HEAD is {}, not {} where the operation left it; it was changed outside GitPoulpi",
actual.describe(),
expected.describe()
),
UndoRefusal::ConfigChanged { section } => format!(
"the configuration section {section} was changed outside GitPoulpi since the operation"
),
UndoRefusal::Interrupted { entry } => format!(
"operation #{entry} never completed (GitPoulpi stopped while it ran); \
inspect it with `gitpoulpi undo --list` and fix the repository by hand"
),
UndoRefusal::WouldOverwrite { detail } => format!(
"local changes in the working tree would be overwritten, so nothing was moved: {}",
detail.trim()
),
UndoRefusal::PathChanged { path } => format!(
"{path} was changed since the operation (outside GitPoulpi, or by a later \
operation), so restoring it would overwrite that change; nothing was restored"
),
UndoRefusal::IndexChanged => "the index (staged changes) was changed since the \
operation, outside GitPoulpi; nothing was restored"
.to_string(),
UndoRefusal::StashChanged { commit } => format!(
"the stash {} was dropped, applied or stored outside GitPoulpi since the \
operation; the stash list was left alone",
short(*commit)
),
UndoRefusal::Purged { entry } => format!(
"the old history of operation #{entry} was purged, so it cannot be undone or redone; \
`gitpoulpi undo-forget` drops it from the undo history"
),
UndoRefusal::RemoteRefMoved(moved) => {
let RemoteRefMoved {
remote,
name,
expected,
actual,
} = &**moved;
format!(
"{} on {remote} is at {}, not at {} where the operation left it: it was changed \
on the remote since, so nothing was changed there",
display_ref_name(name),
actual.map_or_else(|| "nothing".to_string(), short),
expected.map_or_else(|| "nothing".to_string(), short),
)
}
UndoRefusal::RemoteObjectMissing { oid } => format!(
"{} is no longer in this repository (it was garbage collected), so the branch or \
tag cannot be restored on the remote with a push",
short(*oid)
),
UndoRefusal::StaleEntry {
expected_id,
top_id,
} => format!(
"the operation you saw (#{expected_id}) is no longer the latest (#{top_id} is)"
),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntrySummary {
pub id: u64,
pub kind: OperationKind,
pub label: String,
pub at: i64,
pub state: EntryState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EntryState {
Pending,
Done,
Interrupted,
Purged,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct JournalState {
pub undo: Option<EntrySummary>,
pub redo: Option<EntrySummary>,
pub blocked: Option<UndoRefusal>,
pub redo_blocked: Option<UndoRefusal>,
#[serde(default)]
pub disabled: bool,
#[serde(default)]
pub undo_count: usize,
#[serde(default)]
pub redo_count: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UndoOutcome {
pub direction: Direction,
pub entry: EntrySummary,
pub steps: Vec<String>,
pub applied: bool,
#[serde(default)]
pub needs_confirmation: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct JournalListing {
pub undo: Vec<ListedEntry>,
pub redo: Vec<ListedEntry>,
pub retired: Vec<ListedEntry>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EntrySource {
#[default]
Gitpoulpi,
Outside,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListedEntry {
#[serde(default)]
pub source: EntrySource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outside: Option<crate::journal::OutsideInfo>,
pub summary: EntrySummary,
pub changes: Vec<String>,
#[serde(default)]
pub restore: RestoreOffer,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileHash {
pub mode: u32,
pub oid: Oid,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathHash {
pub path: String,
pub worktree: Option<FileHash>,
pub index: Option<FileHash>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Snapshot {
pub tree: Oid,
pub hashes: Vec<PathHash>,
}
fn display_ref_name(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())
}