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 #[error("{} rejected the push of {}: {}", .0.remote, .0.branch, reject_reason(.0))]
34 PushRejected(PushRejection),
35
36 #[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 #[error("cannot fast-forward: the two have diverged")]
48 NotFastForward,
49
50 #[error("cannot change that commit: {}", reword_reason(*.0))]
54 RewordRefused(RewordRefusal),
55 #[error("cannot split that commit: {}", split_reason(*.0))]
58 SplitRefused(SplitRefusal),
59 #[error("cannot rewrite history: {}{}", rewrite_reason(*.0), rewrite_detail(.1))]
62 RewriteRefused(RewriteRefusal, String),
63
64 #[error("cannot apply that commit: {}", apply_reason(*.0))]
67 ApplyRefused(ApplyRefusal),
68
69 #[error("cannot rebase: {}", rebase_reason(*.0))]
72 RebaseRefused(RebaseRefusal),
73
74 #[error("cannot resolve: {}", .0.message())]
78 ConflictRefused(ConflictRefusal),
79
80 #[error("cannot undo/redo: {}", .0.message())]
83 UndoRefused(UndoRefusal),
84
85 #[error("confirmation needed: {0}")]
90 NeedsConfirmation(String),
91
92 #[error("{}", .reason.message())]
96 LfsUnavailable { reason: LfsUnavailableReason },
97
98 #[error("the LFS server behind {remote} does not support file locking")]
100 LfsLockingUnsupported { remote: String },
101
102 #[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 #[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 #[error("{feature} is not built into this binary")]
130 NotBuilt { feature: &'static str },
131
132 #[error("this repository's authentication cannot be used: {reason}")]
138 RepoAuthUnavailable { reason: String },
139
140 #[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 #[error("{path} changed since it was confirmed as this repository's credential command: confirm the command again")]
155 RepoAuthCommandChanged { path: String },
156
157 #[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 #[error("GitPoulpi's credential helper could not reach the daemon")]
170 CredentialHelperUnreachable,
171
172 #[error("canceled (job {job})")]
178 Canceled { job: u64 },
179
180 #[error("cannot be canceled: {}", .reason.message())]
184 NotCancellable { reason: NotCancellableReason },
185
186 #[error("already running as job {existing}")]
190 JobConflict { existing: u64 },
191
192 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
236pub enum NotCancellableReason {
237 Integrating,
240 RewritingFiles,
242 InSteps,
244 Sent,
247 Purging,
251 Finished,
253 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
271pub 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#[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 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 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 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 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 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 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 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 #[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 assert_eq!(
662 Error::from_wire_message("boom".into()).to_string(),
663 "backend error: boom"
664 );
665 }
666
667 #[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 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 assert!(matches!(
839 Error::from_typed(TypedError::NotBuilt {
840 feature: "zzz".into()
841 }),
842 Error::NotBuilt { feature: "unknown" }
843 ));
844 }
845}