Skip to main content

gitpoulpi_core/
error.rs

1use std::path::PathBuf;
2
3use serde::{Deserialize, Serialize};
4
5use crate::domain::{
6    ApplyRefusal, ConflictRefusal, LfsUnavailableReason, PushRejection, RebaseRefusal,
7    RewordRefusal, RewriteRefusal, SplitRefusal, UndoRefusal,
8};
9use crate::failure::ErrorDetail;
10
11pub type Result<T> = std::result::Result<T, Error>;
12
13#[derive(Debug, thiserror::Error)]
14pub enum Error {
15    #[error("operation not supported by this backend: {operation}")]
16    Unsupported { operation: &'static str },
17
18    #[error("repository not found at {0}")]
19    RepoNotFound(PathBuf),
20
21    #[error("working tree is not clean, operation requires a clean tree: {operation}")]
22    DirtyWorkingTree { operation: &'static str },
23
24    #[error("conflict encountered during {operation}")]
25    Conflict { operation: &'static str },
26
27    /// The remote refused a push in a way the user can act on: it has
28    /// commits we do not (`NonFastForward`), or a lease found it moved
29    /// (`StaleLease`). A variant rather than a `Backend` string because
30    /// the TUI answers it with a dialog (pull first / force with lease /
31    /// cancel), and a dialog keyed on git's English stderr would break
32    /// on the first localised git.
33    #[error("{} rejected the push of {}: {}", .0.remote, .0.branch, reject_reason(.0))]
34    PushRejected(PushRejection),
35
36    /// A grouped push or pull of `branch` is saved (stopped on conflicts,
37    /// canceled or with targets to retry): continue, retry or abort it
38    /// (`resume`) instead of starting another. Nothing was changed.
39    #[error(
40        "a grouped push or pull of {branch} is waiting (run {run_id}): continue or abort it first"
41    )]
42    RemoteGroupPending { branch: String, run_id: String },
43
44    /// A fast-forward-only pull found the branch and its upstream
45    /// diverged, or `GitBackend::fast_forward` found the branch and its
46    /// target diverged. Nothing was changed.
47    #[error("cannot fast-forward: the two have diverged")]
48    NotFastForward,
49
50    /// `reword` refused before changing anything (see
51    /// [`RewordRefusal`]). Typed because the TUI words each case
52    /// differently and the CLI reports it as a stable code.
53    #[error("cannot change that commit: {}", reword_reason(*.0))]
54    RewordRefused(RewordRefusal),
55    /// `split_commit` refused before changing anything (see
56    /// [`SplitRefusal`]).
57    #[error("cannot split that commit: {}", split_reason(*.0))]
58    SplitRefused(SplitRefusal),
59    /// A history rewrite refused before changing anything (see
60    /// [`RewriteRefusal`]); the string says which rule, path or ref.
61    #[error("cannot rewrite history: {}{}", rewrite_reason(*.0), rewrite_detail(.1))]
62    RewriteRefused(RewriteRefusal, String),
63
64    /// `apply_commit_to_worktree` refused before changing anything (see
65    /// [`ApplyRefusal`]).
66    #[error("cannot apply that commit: {}", apply_reason(*.0))]
67    ApplyRefused(ApplyRefusal),
68
69    /// An interactive rebase (or `continue`/`skip`/`abort`) refused
70    /// before changing anything (see [`RebaseRefusal`]).
71    #[error("cannot rebase: {}", rebase_reason(*.0))]
72    RebaseRefused(RebaseRefusal),
73
74    /// A conflict call (`resolve_conflict`, `unresolve_conflict`,
75    /// `operation_abort`) refused before changing anything (see
76    /// [`ConflictRefusal`]).
77    #[error("cannot resolve: {}", .0.message())]
78    ConflictRefused(ConflictRefusal),
79
80    /// An undo or redo (or a compare-and-swap ref update) refused before
81    /// changing anything (see [`UndoRefusal`]).
82    #[error("cannot undo/redo: {}", .0.message())]
83    UndoRefused(UndoRefusal),
84
85    /// An undo or redo that is risky (it would overwrite working-tree
86    /// files, or the undone commit is already on its upstream) and was
87    /// not sent with `confirmed`. Nothing was changed; the prompt names
88    /// what is at stake.
89    #[error("confirmation needed: {0}")]
90    NeedsConfirmation(String),
91
92    /// An LFS operation needs the `git-lfs` program and it is missing (or
93    /// too old). Typed so every frontend can show the install link
94    /// instead of git's raw "'lfs' is not a git command".
95    #[error("{}", .reason.message())]
96    LfsUnavailable { reason: LfsUnavailableReason },
97
98    /// The LFS remote does not implement the locking API.
99    #[error("the LFS server behind {remote} does not support file locking")]
100    LfsLockingUnsupported { remote: String },
101
102    /// `operation` was blocked by local changes, `general.auto_stash` is
103    /// `ask`, and nobody was there to answer. Nothing was changed. A UI
104    /// answers with its dialog and resends the request with
105    /// `autostash: "always"`; a CLI/MCP caller reads the message and
106    /// passes `--autostash`. Typed so the TUI never matches on git's
107    /// English stderr.
108    #[error(
109        "{operation} is blocked by local changes; stash them automatically \
110         (--autostash, or `general.auto_stash = \"always\"`) or commit or discard them first"
111    )]
112    NeedsAutoStash { operation: String },
113
114    /// The repository has a pending auto-stash (`stash` is its index in
115    /// the stash list) and `operation` would bury or tangle it. Nothing
116    /// was changed. `hint` says how to resolve it. Typed so each frontend
117    /// can point at its own resolving actions.
118    #[error("{operation} is blocked: an auto-stash (stash@{{{}}}) is still waiting; {hint}", .stash.0)]
119    PendingAutoStash {
120        operation: String,
121        stash: crate::domain::StashId,
122        hint: String,
123    },
124
125    /// The operation belongs to a feature this binary was built without
126    /// (a custom build, see `docs/user/custom-builds.md`). `feature` is the
127    /// cargo feature name (`lfs`, `worktree`, ...). Typed so each frontend
128    /// words it in its own language and the CLI reports a stable code.
129    #[error("{feature} is not built into this binary")]
130    NotBuilt { feature: &'static str },
131
132    /// The repository's authentication profile cannot be used (its file is
133    /// unreadable, the integration it names is gone, a key file is missing,
134    /// or the source is not available in this version). The transfer is
135    /// refused: it never falls back to the machine's own credentials, because
136    /// pushing to work with a personal account is the failure to avoid.
137    #[error("this repository's authentication cannot be used: {reason}")]
138    RepoAuthUnavailable { reason: String },
139
140    /// The repository's token command did not give a token: it exited
141    /// non-zero (`exit`), timed out or could not start (`exit` is `None`), or
142    /// printed nothing usable. `stderr_tail` is the end of its standard error,
143    /// already redacted (it never carries the token). The transfer is refused.
144    #[error("the token command failed{}: {stderr_tail}", exit.map(|c| format!(" (exit {c})")).unwrap_or_default())]
145    TokenCommandFailed {
146        exit: Option<i32>,
147        stderr_tail: String,
148    },
149
150    /// A file the confirmed credential helper or token command runs, inside
151    /// the repository's work tree, is not the one the person confirmed (a pull
152    /// can change a tracked script). `path` names it. The transfer is
153    /// refused until the command is confirmed again.
154    #[error("{path} changed since it was confirmed as this repository's credential command: confirm the command again")]
155    RepoAuthCommandChanged { path: String },
156
157    /// The transfer was refused credentials because git asked for a host that
158    /// is not the account's own address: `host` is where git went (a remote
159    /// URL rewritten by the repository's own `url.<x>.insteadOf`, say),
160    /// `expected` the address the account's token is bound to. The token was
161    /// **not** sent.
162    #[error("GitPoulpi did not send the account's token to {host}: it is not {expected}, the address that account is bound to")]
163    GrantRefused { host: String, expected: String },
164
165    /// git needed a credential from GitPoulpi's credential helper and got none
166    /// because the helper never reached the daemon that issued the grant (the
167    /// daemon was gone or its endpoint could not be read). Nothing was sent to
168    /// the server.
169    #[error("GitPoulpi's credential helper could not reach the daemon")]
170    CredentialHelperUnreachable,
171
172    /// A background job was canceled (`JobCancel`, or a client that asked for
173    /// cancel-on-disconnect went away). The repository is as it was before the
174    /// operation, or at its last safe point (see the cancel policy in
175    /// the background-ops design`). Every caller waiting on the
176    /// job, the one that started it and the ones that joined it, gets this.
177    #[error("canceled (job {job})")]
178    Canceled { job: u64 },
179
180    /// `JobCancel` on a job that cannot be stopped safely right now (it is
181    /// past its point of no return, or it has already ended). Nothing was
182    /// changed.
183    #[error("cannot be canceled: {}", .reason.message())]
184    NotCancellable { reason: NotCancellableReason },
185
186    /// A second request for a job that must not run twice (a clone into a
187    /// destination another clone is filling). `existing` is the job already
188    /// running.
189    #[error("already running as job {existing}")]
190    JobConflict { existing: u64 },
191
192    /// The committed workflow hooks were asked to run but this user has not
193    /// trusted them as they are now. Nothing ran. `hash` is what
194    /// `FlowTrustHooks` takes, `hooks` the exact commands.
195    #[error(
196        "the repository's workflow hooks are not trusted ({} command(s), hash {hash}); review \
197         them, then `gitpoulpi flow trust-hooks --hash {hash}`",
198        .hooks.len()
199    )]
200    HooksNotTrusted {
201        hash: String,
202        hooks: Vec<crate::workflow::HookInfo>,
203    },
204
205    /// A stage request would add files that look sensitive (a private key, a
206    /// `.env`, a recognised token) and the caller did not allow it. Nothing
207    /// was staged. `files` lists each file with its reason, never a value.
208    #[error(
209        "sensitive files were not staged: {}; ask the user, then stage again allowing \
210         sensitive files",
211        crate::privacy::summary(.files)
212    )]
213    SensitiveStage {
214        files: Vec<crate::privacy::Sensitive>,
215    },
216
217    #[error("backend error: {0}")]
218    Backend(String),
219
220    /// A backend failure with its facts attached (the command that ran, its
221    /// exit code and stderr, or libgit2's class and code), so a frontend can
222    /// say what went wrong instead of "the backend failed". `Display` is
223    /// the same text a plain `Backend` error would have.
224    #[error("backend error: {message}")]
225    Git {
226        message: String,
227        detail: Box<ErrorDetail>,
228    },
229
230    #[error("io error: {0}")]
231    Io(#[from] std::io::Error),
232}
233
234/// Why `JobCancel` refused ([`Error::NotCancellable`]).
235#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
236pub enum NotCancellableReason {
237    /// A pull past its fetch: the merge, rebase or fast-forward is writing
238    /// the index and the working tree.
239    Integrating,
240    /// Files are being rewritten in the working tree (LFS checkout).
241    RewritingFiles,
242    /// A multi-step workflow: it can only stop between steps.
243    InSteps,
244    /// A client-side job past its send: the host may already have acted
245    /// (a pull request or issue being created).
246    Sent,
247    /// Old history is being deleted (`rewrite purge`): the pins, the
248    /// reflogs and the objects go, and stopping half way would leave an
249    /// undo entry without its objects.
250    Purging,
251    /// The job has already ended.
252    Finished,
253    /// No such job (never existed, or already dropped from the list).
254    UnknownJob,
255}
256
257impl NotCancellableReason {
258    pub fn message(self) -> &'static str {
259        match self {
260            Self::Integrating => "merging - cannot stop safely",
261            Self::RewritingFiles => "rewriting files - cannot stop safely",
262            Self::InSteps => "running a multi-step workflow - cannot stop between its steps yet",
263            Self::Sent => "sent to the host, waiting for its answer",
264            Self::Purging => "deleting the old history - cannot stop safely",
265            Self::Finished => "it has already ended",
266            Self::UnknownJob => "no such job",
267        }
268    }
269}
270
271/// The cargo features `NotBuilt` can name. A name off the wire that is not
272/// in the list (a newer peer) becomes `"unknown"` rather than leaking.
273pub const BUILD_FEATURES: &[&str] = &[
274    "ai",
275    "hosting",
276    "github",
277    "gitlab",
278    "mcp",
279    "lfs",
280    "worktree",
281    "submodule",
282    "avatar-fetch",
283    "history-rewrite",
284];
285
286fn known_feature(name: &str) -> &'static str {
287    BUILD_FEATURES
288        .iter()
289        .find(|f| **f == name)
290        .copied()
291        .unwrap_or("unknown")
292}
293
294fn reject_reason(rejection: &PushRejection) -> &'static str {
295    match rejection.reason {
296        crate::domain::PushRejectReason::NonFastForward => {
297            "the remote has commits this branch does not (pull first, or force push)"
298        }
299        crate::domain::PushRejectReason::StaleLease => {
300            "the branch or tag on the remote moved since the last fetch, so the force push was refused"
301        }
302        crate::domain::PushRejectReason::ProtectedByHost => {
303            "the host's branch protection refused the push"
304        }
305        crate::domain::PushRejectReason::RemoteRefused => "the remote refused the push",
306        crate::domain::PushRejectReason::Unknown => "the remote rejected the push",
307    }
308}
309
310fn reword_reason(refusal: RewordRefusal) -> &'static str {
311    match refusal {
312        RewordRefusal::NotOnCurrentBranch => {
313            "the commit is not on the current branch (it is not HEAD or an ancestor of HEAD)"
314        }
315        RewordRefusal::OperationInProgress => {
316            "a merge, rebase, cherry-pick, revert or bisect is in progress"
317        }
318        RewordRefusal::EmptyMessage => "the new message is empty",
319        RewordRefusal::InvalidIdentity => {
320            "a name or email is empty or has a character that cannot be stored (< > or a line break)"
321        }
322        RewordRefusal::InvalidDate => "a date is not in the raw format or ISO 8601",
323    }
324}
325
326fn rewrite_detail(detail: &str) -> String {
327    if detail.is_empty() {
328        String::new()
329    } else {
330        format!(" ({detail})")
331    }
332}
333
334fn rewrite_reason(refusal: RewriteRefusal) -> &'static str {
335    use RewriteRefusal as R;
336    match refusal {
337        R::OperationInProgress => "a merge, rebase, cherry-pick, revert or bisect is in progress",
338        R::AutoStashPending => "an auto-stash is waiting to be restored",
339        R::Shallow => "this is a shallow clone, its history is incomplete",
340        R::PartialClone => "this is a partial clone and the rules read file content",
341        R::UnsupportedObjectFormat => "SHA-256 repositories are not supported",
342        R::EmptyScope => "the scope contains no commit or ref",
343        R::NoRule => "no rule is enabled",
344        R::InvalidRule => "a rule is not valid",
345        R::DirtyPathsTouched => "files the rewrite would change have uncommitted edits",
346        R::CheckedOutElsewhere => "a branch is checked out in another worktree",
347        R::ProtectedRef => "a pushed protected branch is in scope and was not included",
348        R::Stale => "the repository changed since the preview, preview again",
349        R::ToolMissing => "a tool the rules need is not installed",
350        R::ScriptFailed => "a script failed",
351        R::Purged => "the old history was purged, there is nothing to restore",
352        R::ScriptsDisabled => {
353            "this kind of script is switched off in the settings (rewrite.external_scripts)"
354        }
355        R::ScriptNotTrusted => "the script is not trusted yet",
356        R::SignatureChoiceNeeded => {
357            "signed commits are affected: choose to strip, re-sign signed or re-sign all"
358        }
359        R::ExtractModeNeeded => "choose how to extract: clone, in place or submodule",
360        R::SigningFailed => {
361            "signing does not work here (key, agent or program), check the signing setup"
362        }
363        R::LfsObjectsMissing => {
364            "LFS objects the export needs are not in the local LFS store: fetch them first"
365        }
366        R::PathCollision => "a path rule would put a file where one already exists",
367    }
368}
369
370fn apply_reason(refusal: ApplyRefusal) -> &'static str {
371    match refusal {
372        ApplyRefusal::MergeCommit => "a merge commit has no single set of changes to apply",
373    }
374}
375
376fn split_reason(refusal: SplitRefusal) -> &'static str {
377    match refusal {
378        SplitRefusal::NotOnCurrentBranch => {
379            "the commit is not on the current branch (it is not HEAD or an ancestor of HEAD)"
380        }
381        SplitRefusal::MergeCommit => "a merge commit cannot be split",
382        SplitRefusal::EmptyCommit => "the commit changes nothing",
383        SplitRefusal::OperationInProgress => {
384            "a merge, rebase, cherry-pick, revert or bisect is in progress"
385        }
386        SplitRefusal::TooFewParts => "a split needs at least two commits",
387        SplitRefusal::EmptyPart => "a new commit has no changes assigned to it",
388        SplitRefusal::EmptyMessage => "a new commit has an empty message",
389        SplitRefusal::Unassigned => "some changes are not assigned to any commit",
390        SplitRefusal::AssignedTwice => "some changes are assigned to more than one commit",
391        SplitRefusal::UnknownPiece => "a piece does not exist in the commit or cannot be selected",
392        SplitRefusal::WholeFileOnly => "that file can only be assigned as a whole",
393        SplitRefusal::SigningFailed => "signing the new commits failed",
394    }
395}
396
397fn rebase_reason(refusal: RebaseRefusal) -> &'static str {
398    match refusal {
399        RebaseRefusal::OperationInProgress => {
400            "a merge, rebase, cherry-pick, revert or bisect is already in progress"
401        }
402        RebaseRefusal::UncommittedChanges => "the working tree has uncommitted changes",
403        RebaseRefusal::NotOnCurrentBranch => {
404            "the target is not on the current branch, or HEAD is detached"
405        }
406        RebaseRefusal::MergeInRange => "the range contains a merge commit",
407        RebaseRefusal::PlanMismatch => {
408            "the plan is not exactly a reordering of the commits being rebased"
409        }
410        RebaseRefusal::SquashWithoutPredecessor => {
411            "the oldest step cannot be squash or fixup: it has nothing to combine into"
412        }
413        RebaseRefusal::EmptyRewordMessage => "a reword step has no message",
414        RebaseRefusal::NoRebaseInProgress => "no rebase is in progress",
415    }
416}
417
418/// The part of an [`Error`] a client must be able to *match on*, in a
419/// shape that crosses the IPC boundary.
420///
421/// `Error` itself is not serialisable (it wraps an `io::Error`) and most
422/// of it is only ever shown to a human, so the wire carries the message
423/// plus, for the handful of errors a frontend reacts to with more than a
424/// status line, this. A client rebuilds the typed `Error` with
425/// [`Error::from_typed`].
426#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
427pub enum TypedError {
428    PushRejected(PushRejection),
429    RemoteGroupPending {
430        branch: String,
431        run_id: String,
432    },
433    NotFastForward,
434    RewordRefused(RewordRefusal),
435    SplitRefused(SplitRefusal),
436    ApplyRefused(ApplyRefusal),
437    RewriteRefused(RewriteRefusal, String),
438    RebaseRefused(RebaseRefusal),
439    ConflictRefused(ConflictRefusal),
440    UndoRefused(UndoRefusal),
441    NeedsConfirmation(String),
442    LfsUnavailable(LfsUnavailableReason),
443    LfsLockingUnsupported {
444        remote: String,
445    },
446    NeedsAutoStash {
447        operation: String,
448    },
449    PendingAutoStash {
450        operation: String,
451        stash: crate::domain::StashId,
452        hint: String,
453    },
454    /// The feature (cargo feature name) this binary was built without.
455    NotBuilt {
456        feature: String,
457    },
458    RepoAuthUnavailable {
459        reason: String,
460    },
461    TokenCommandFailed {
462        exit: Option<i32>,
463        stderr_tail: String,
464    },
465    RepoAuthCommandChanged {
466        path: String,
467    },
468    GrantRefused {
469        host: String,
470        expected: String,
471    },
472    CredentialHelperUnreachable,
473    Canceled {
474        job: u64,
475    },
476    NotCancellable {
477        reason: NotCancellableReason,
478    },
479    JobConflict {
480        existing: u64,
481    },
482    HooksNotTrusted {
483        hash: String,
484        hooks: Vec<crate::workflow::HookInfo>,
485    },
486    SensitiveStage {
487        files: Vec<crate::privacy::Sensitive>,
488    },
489}
490
491impl Error {
492    /// The typed part of this error, if it has one.
493    pub fn typed(&self) -> Option<TypedError> {
494        match self {
495            Error::PushRejected(r) => Some(TypedError::PushRejected(r.clone())),
496            Error::RemoteGroupPending { branch, run_id } => Some(TypedError::RemoteGroupPending {
497                branch: branch.clone(),
498                run_id: run_id.clone(),
499            }),
500            Error::NotFastForward => Some(TypedError::NotFastForward),
501            Error::RewordRefused(r) => Some(TypedError::RewordRefused(*r)),
502            Error::SplitRefused(r) => Some(TypedError::SplitRefused(*r)),
503            Error::ApplyRefused(r) => Some(TypedError::ApplyRefused(*r)),
504            Error::RewriteRefused(r, d) => Some(TypedError::RewriteRefused(*r, d.clone())),
505            Error::RebaseRefused(r) => Some(TypedError::RebaseRefused(*r)),
506            Error::ConflictRefused(r) => Some(TypedError::ConflictRefused(r.clone())),
507            Error::UndoRefused(r) => Some(TypedError::UndoRefused(r.clone())),
508            Error::NeedsConfirmation(p) => Some(TypedError::NeedsConfirmation(p.clone())),
509            Error::LfsUnavailable { reason } => Some(TypedError::LfsUnavailable(reason.clone())),
510            Error::LfsLockingUnsupported { remote } => Some(TypedError::LfsLockingUnsupported {
511                remote: remote.clone(),
512            }),
513            Error::NeedsAutoStash { operation } => Some(TypedError::NeedsAutoStash {
514                operation: operation.clone(),
515            }),
516            Error::PendingAutoStash {
517                operation,
518                stash,
519                hint,
520            } => Some(TypedError::PendingAutoStash {
521                operation: operation.clone(),
522                stash: *stash,
523                hint: hint.clone(),
524            }),
525            Error::NotBuilt { feature } => Some(TypedError::NotBuilt {
526                feature: (*feature).to_string(),
527            }),
528            Error::RepoAuthUnavailable { reason } => Some(TypedError::RepoAuthUnavailable {
529                reason: reason.clone(),
530            }),
531            Error::TokenCommandFailed { exit, stderr_tail } => {
532                Some(TypedError::TokenCommandFailed {
533                    exit: *exit,
534                    stderr_tail: stderr_tail.clone(),
535                })
536            }
537            Error::RepoAuthCommandChanged { path } => {
538                Some(TypedError::RepoAuthCommandChanged { path: path.clone() })
539            }
540            Error::CredentialHelperUnreachable => Some(TypedError::CredentialHelperUnreachable),
541            Error::GrantRefused { host, expected } => Some(TypedError::GrantRefused {
542                host: host.clone(),
543                expected: expected.clone(),
544            }),
545            Error::Canceled { job } => Some(TypedError::Canceled { job: *job }),
546            Error::NotCancellable { reason } => {
547                Some(TypedError::NotCancellable { reason: *reason })
548            }
549            Error::JobConflict { existing } => Some(TypedError::JobConflict {
550                existing: *existing,
551            }),
552            Error::HooksNotTrusted { hash, hooks } => Some(TypedError::HooksNotTrusted {
553                hash: hash.clone(),
554                hooks: hooks.clone(),
555            }),
556            Error::SensitiveStage { files } => Some(TypedError::SensitiveStage {
557                files: files.clone(),
558            }),
559            _ => None,
560        }
561    }
562
563    /// The facts of the failure, when the backend recorded them.
564    pub fn detail(&self) -> Option<&ErrorDetail> {
565        match self {
566            Error::Git { detail, .. } => Some(detail),
567            Error::PushRejected(r) => r.detail.as_deref(),
568            _ => None,
569        }
570    }
571
572    /// A backend failure carrying `detail`.
573    pub fn git(message: impl Into<String>, detail: ErrorDetail) -> Self {
574        Error::Git {
575            message: message.into(),
576            detail: Box::new(detail),
577        }
578    }
579
580    /// [`Error::from_wire_message`] with the detail that travelled beside
581    /// the message, when there was one.
582    pub fn from_wire(message: String, detail: Option<ErrorDetail>) -> Self {
583        match (Self::from_wire_message(message), detail) {
584            (Error::Backend(message), Some(detail)) => Error::git(message, detail),
585            (other, _) => other,
586        }
587    }
588
589    /// An error that arrived over the wire as plain text: the daemon sent
590    /// `Error`'s own `Display`, which for a backend failure already starts
591    /// with `backend error: `. Wrapping that text in [`Error::Backend`]
592    /// again would print the prefix twice, so it is taken off first.
593    pub fn from_wire_message(message: String) -> Self {
594        match message.strip_prefix("backend error: ") {
595            Some(rest) => Error::Backend(rest.to_string()),
596            None => Error::Backend(message),
597        }
598    }
599
600    /// The inverse of [`Error::typed`].
601    pub fn from_typed(typed: TypedError) -> Self {
602        match typed {
603            TypedError::PushRejected(r) => Error::PushRejected(r),
604            TypedError::RemoteGroupPending { branch, run_id } => {
605                Error::RemoteGroupPending { branch, run_id }
606            }
607            TypedError::NotFastForward => Error::NotFastForward,
608            TypedError::RewordRefused(r) => Error::RewordRefused(r),
609            TypedError::SplitRefused(r) => Error::SplitRefused(r),
610            TypedError::ApplyRefused(r) => Error::ApplyRefused(r),
611            TypedError::RewriteRefused(r, d) => Error::RewriteRefused(r, d),
612            TypedError::RebaseRefused(r) => Error::RebaseRefused(r),
613            TypedError::ConflictRefused(r) => Error::ConflictRefused(r),
614            TypedError::UndoRefused(r) => Error::UndoRefused(r),
615            TypedError::NeedsConfirmation(p) => Error::NeedsConfirmation(p),
616            TypedError::LfsUnavailable(reason) => Error::LfsUnavailable { reason },
617            TypedError::LfsLockingUnsupported { remote } => Error::LfsLockingUnsupported { remote },
618            TypedError::NeedsAutoStash { operation } => Error::NeedsAutoStash { operation },
619            TypedError::PendingAutoStash {
620                operation,
621                stash,
622                hint,
623            } => Error::PendingAutoStash {
624                operation,
625                stash,
626                hint,
627            },
628            TypedError::NotBuilt { feature } => Error::NotBuilt {
629                feature: known_feature(&feature),
630            },
631            TypedError::RepoAuthUnavailable { reason } => Error::RepoAuthUnavailable { reason },
632            TypedError::TokenCommandFailed { exit, stderr_tail } => {
633                Error::TokenCommandFailed { exit, stderr_tail }
634            }
635            TypedError::RepoAuthCommandChanged { path } => Error::RepoAuthCommandChanged { path },
636            TypedError::GrantRefused { host, expected } => Error::GrantRefused { host, expected },
637            TypedError::CredentialHelperUnreachable => Error::CredentialHelperUnreachable,
638            TypedError::Canceled { job } => Error::Canceled { job },
639            TypedError::NotCancellable { reason } => Error::NotCancellable { reason },
640            TypedError::JobConflict { existing } => Error::JobConflict { existing },
641            TypedError::HooksNotTrusted { hash, hooks } => Error::HooksNotTrusted { hash, hooks },
642            TypedError::SensitiveStage { files } => Error::SensitiveStage { files },
643        }
644    }
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650    use crate::domain::PushRejectReason;
651
652    /// The daemon sends `Error`'s Display text; wrapping it again must not
653    /// print "backend error: backend error: ...".
654    #[test]
655    fn a_backend_error_crossing_the_wire_keeps_one_prefix() {
656        let sent = Error::Backend("x is not in commit abc".into()).to_string();
657        assert_eq!(sent, "backend error: x is not in commit abc");
658        let received = Error::from_wire_message(sent.clone());
659        assert_eq!(received.to_string(), sent);
660        // Text that never had the prefix is still wrapped once.
661        assert_eq!(
662            Error::from_wire_message("boom".into()).to_string(),
663            "backend error: boom"
664        );
665    }
666
667    /// A typed error survives the trip through JSON and back into an
668    /// `Error` - the round trip every frontend depends on to tell "the
669    /// remote diverged" from any other failure.
670    #[test]
671    fn a_typed_error_round_trips_through_json() {
672        let original = Error::PushRejected(PushRejection {
673            remote: "origin".into(),
674            branch: "main".into(),
675            reason: PushRejectReason::NonFastForward,
676            detail: None,
677        });
678        let wire = serde_json::to_string(&original.typed().unwrap()).unwrap();
679        let back = Error::from_typed(serde_json::from_str(&wire).unwrap());
680        assert!(matches!(
681            back,
682            Error::PushRejected(PushRejection { ref remote, reason: PushRejectReason::NonFastForward, .. })
683                if remote == "origin"
684        ));
685        assert!(Error::Backend("x".into()).typed().is_none());
686    }
687
688    #[test]
689    fn split_refusals_round_trip_through_json() {
690        let original = Error::SplitRefused(SplitRefusal::Unassigned);
691        let wire = serde_json::to_string(&original.typed().unwrap()).unwrap();
692        let back = Error::from_typed(serde_json::from_str(&wire).unwrap());
693        assert!(matches!(
694            back,
695            Error::SplitRefused(SplitRefusal::Unassigned)
696        ));
697        assert!(back.to_string().contains("not assigned"));
698    }
699
700    #[test]
701    fn rewrite_refusals_round_trip_through_json_with_their_detail() {
702        let original = Error::RewriteRefused(
703            RewriteRefusal::InvalidRule,
704            "rule 2: the pattern is empty".into(),
705        );
706        let wire = serde_json::to_string(&original.typed().unwrap()).unwrap();
707        let back = Error::from_typed(serde_json::from_str(&wire).unwrap());
708        match &back {
709            Error::RewriteRefused(RewriteRefusal::InvalidRule, detail) => {
710                assert_eq!(detail, "rule 2: the pattern is empty");
711            }
712            other => panic!("{other:?}"),
713        }
714        assert!(back.to_string().contains("a rule is not valid"));
715        assert!(back.to_string().contains("rule 2"));
716        // No detail: no empty parentheses.
717        let bare = Error::RewriteRefused(RewriteRefusal::NoRule, String::new());
718        assert_eq!(
719            bare.to_string(),
720            "cannot rewrite history: no rule is enabled"
721        );
722    }
723
724    #[test]
725    fn lfs_errors_round_trip_and_name_the_install_page() {
726        let original = Error::LfsUnavailable {
727            reason: LfsUnavailableReason::Missing,
728        };
729        assert!(original.to_string().contains("git-lfs.com"));
730        let wire = serde_json::to_string(&original.typed().unwrap()).unwrap();
731        let back = Error::from_typed(serde_json::from_str(&wire).unwrap());
732        assert!(matches!(
733            back,
734            Error::LfsUnavailable {
735                reason: LfsUnavailableReason::Missing
736            }
737        ));
738        let locking = Error::LfsLockingUnsupported {
739            remote: "origin".into(),
740        };
741        let wire = serde_json::to_string(&locking.typed().unwrap()).unwrap();
742        assert!(matches!(
743            Error::from_typed(serde_json::from_str(&wire).unwrap()),
744            Error::LfsLockingUnsupported { ref remote } if remote == "origin"
745        ));
746    }
747
748    #[test]
749    fn job_errors_round_trip_with_stable_kinds() {
750        let canceled = Error::Canceled { job: 7 };
751        let wire = serde_json::to_string(&canceled.typed().unwrap()).unwrap();
752        assert_eq!(wire, r#"{"Canceled":{"job":7}}"#);
753        assert!(matches!(
754            Error::from_typed(serde_json::from_str(&wire).unwrap()),
755            Error::Canceled { job: 7 }
756        ));
757        let refused = Error::NotCancellable {
758            reason: NotCancellableReason::Integrating,
759        };
760        assert!(refused.to_string().contains("merging"));
761        assert!(matches!(
762            Error::from_typed(refused.typed().unwrap()),
763            Error::NotCancellable {
764                reason: NotCancellableReason::Integrating
765            }
766        ));
767        assert!(matches!(
768            Error::from_typed(Error::JobConflict { existing: 3 }.typed().unwrap()),
769            Error::JobConflict { existing: 3 }
770        ));
771    }
772
773    #[test]
774    fn hooks_not_trusted_round_trips_with_its_commands() {
775        let original = Error::HooksNotTrusted {
776            hash: "ab".repeat(32),
777            hooks: vec![crate::workflow::HookInfo {
778                phase: "after_start".into(),
779                command: "make".into(),
780                personal: false,
781            }],
782        };
783        assert!(original.to_string().contains("not trusted"));
784        let wire = serde_json::to_string(&original.typed().unwrap()).unwrap();
785        match Error::from_typed(serde_json::from_str(&wire).unwrap()) {
786            Error::HooksNotTrusted { hash, hooks } => {
787                assert_eq!(hash.len(), 64);
788                assert_eq!(hooks[0].command, "make");
789            }
790            other => panic!("{other:?}"),
791        }
792    }
793
794    #[test]
795    fn sensitive_stage_round_trips_with_reasons_and_no_value() {
796        use crate::privacy::{Reason, Sensitive};
797        let original = Error::SensitiveStage {
798            files: vec![
799                Sensitive {
800                    path: ".env".into(),
801                    reason: Reason::Pattern(".env".into()),
802                    line: None,
803                },
804                Sensitive {
805                    path: "a.txt".into(),
806                    reason: Reason::Secret {
807                        rule: "github-token".into(),
808                        preview: "ghp_****".into(),
809                    },
810                    line: Some(3),
811                },
812            ],
813        };
814        assert!(original.to_string().contains(".env, a.txt"));
815        let wire = serde_json::to_string(&original.typed().unwrap()).unwrap();
816        match Error::from_typed(serde_json::from_str(&wire).unwrap()) {
817            Error::SensitiveStage { files } => {
818                assert_eq!(files.len(), 2);
819                assert_eq!(files[1].path, "a.txt");
820                assert_eq!(files[1].line, Some(3));
821            }
822            other => panic!("{other:?}"),
823        }
824    }
825
826    #[test]
827    fn not_built_round_trips_and_serialises_with_a_stable_kind() {
828        let original = Error::NotBuilt { feature: "lfs" };
829        assert_eq!(original.to_string(), "lfs is not built into this binary");
830        let typed = original.typed().unwrap();
831        let wire = serde_json::to_string(&typed).unwrap();
832        assert_eq!(wire, r#"{"NotBuilt":{"feature":"lfs"}}"#);
833        assert!(matches!(
834            Error::from_typed(serde_json::from_str(&wire).unwrap()),
835            Error::NotBuilt { feature: "lfs" }
836        ));
837        // A feature this build does not know is not leaked as a &'static str.
838        assert!(matches!(
839            Error::from_typed(TypedError::NotBuilt {
840                feature: "zzz".into()
841            }),
842            Error::NotBuilt { feature: "unknown" }
843        ));
844    }
845}