1use thiserror::Error;
2
3#[derive(Debug)]
4pub struct FinishPreflightError {
5 pub blocker: FinishBlocker,
6 pub message: String,
7 pub pending_phases: Vec<String>,
8 pub retry_command: Option<String>,
9 pub manual_recovery_commands: Vec<String>,
10}
11
12impl std::fmt::Display for FinishPreflightError {
13 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14 f.write_str(&self.message)
15 }
16}
17
18#[derive(Debug)]
19pub struct FinishPhaseError {
20 pub phase: String,
21 pub completed_phases: Vec<String>,
22 pub pending_phases: Vec<String>,
23 pub message: String,
24 pub retry_command: Option<String>,
25 pub manual_recovery_commands: Vec<String>,
26}
27
28impl std::fmt::Display for FinishPhaseError {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.write_str(&self.message)
31 }
32}
33
34#[derive(Debug)]
35pub struct CommitPhaseError {
36 pub phase: String,
37 pub committed: bool,
38 pub pushed: bool,
39 pub published: bool,
40 pub remote_contacted: bool,
41 pub branch: String,
42 pub head_before: Option<String>,
43 pub head_after: Option<String>,
44 pub unpushed_commit_count: usize,
45 pub message: String,
46 pub retry_command: Option<String>,
47 pub manual_recovery_commands: Vec<String>,
48}
49
50impl std::fmt::Display for CommitPhaseError {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 f.write_str(&self.message)
53 }
54}
55
56#[derive(Error, Debug)]
57pub enum OakError {
58 #[error("Disk full at '{path}': no free storage is available for the repository database or its journal")]
59 DiskFull { path: String },
60
61 #[error(
62 "Repository not found. Run 'oak init' to create a repository here, or 'oak clone <repo>' to clone an existing one."
63 )]
64 RepoNotFound,
65
66 #[error("Repository already exists at this location")]
67 RepoAlreadyExists,
68
69 #[error("No commits yet")]
70 NoCommits,
71
72 #[error("Invalid hash: {0}")]
73 InvalidHash(String),
74
75 #[error("{0}")]
76 InvalidPath(String),
77
78 #[error("Blob not found: {0}")]
79 BlobNotFound(String),
80
81 #[error("Commit not found: {0}")]
82 CommitNotFound(String),
83
84 #[error("Branch not found: {0}")]
85 BranchNotFound(String),
86
87 #[error("Branch '{0}' already exists")]
88 BranchAlreadyExists(String),
89
90 #[error("Branch '{0}' is closed")]
91 BranchClosed(String),
92
93 #[error("No commits in branch")]
94 NoEdits,
95
96 #[error("Manifest not found: {0}")]
97 ManifestNotFound(String),
98
99 #[error("Working directory has uncommitted changes")]
100 UncommittedChanges,
101
102 #[error("Working tree changed while capture was in progress: {detail}. Retry the capture.")]
103 WorktreeCaptureRaced { detail: String },
104
105 #[error("Change capture does not support repository hash format {0:?}")]
106 UnsupportedChangeCaptureFormat(String),
107
108 #[error("Change capture excluded requested path {path:?}: {reason}. {remedy}")]
109 ChangeCaptureScopeExcluded {
110 path: String,
111 reason: String,
112 remedy: String,
113 },
114
115 #[error("Captured blob integrity check failed for {path:?} ({hash}): {detail}")]
116 CapturedBlobIntegrity {
117 path: String,
118 hash: String,
119 detail: String,
120 },
121
122 #[error("Captured tree integrity check failed for {hash}: {detail}")]
123 CapturedTreeIntegrity { hash: String, detail: String },
124
125 #[error("Change capture {capture_id:?} was not found. Rerun `oak change capture --json` to create a durable local lookup record.")]
126 ChangeCaptureNotFound { capture_id: String },
127
128 #[error("Change capture {capture_id:?} failed durable lookup validation: {detail}")]
129 ChangeCaptureIntegrity { capture_id: String, detail: String },
130
131 #[error("{0}")]
132 DirtyWorkingTree(String),
133
134 #[error("Conflict detected: remote has diverged. Pull changes first.")]
135 ConflictDetected,
136
137 #[error(
138 "This branch's local history isn't anchored on the remote's.\nRun 'oak pull' to converge: it re-parents the branch onto the remote and keeps your local commits (overlapping edits open the normal conflict flow).\nIf you want the remote's state instead, 'oak pull --force' re-syncs after parking local commits as '<branch>.orphaned-<timestamp>' — nothing is deleted."
139 )]
140 LocalCommitsNotInRemoteHistory,
141
142 #[error(
143 "The remote branch has commits this clone doesn't have.\nRun 'oak pull' to bring them in and converge (your local commits are kept), then push again."
144 )]
145 RemoteCommitsNotInLocalHistory,
146
147 #[error("Remote repository not configured")]
148 RemoteNotConfigured,
149
150 #[error(
151 "remote has moved to {origin} — run `oak push -r {origin}` to update this repo's remote"
152 )]
153 RemoteMoved { origin: String },
154
155 #[error("Repository '{0}' not found on server")]
156 RemoteRepoNotFound(String),
157
158 #[error("Repository '{0}' already exists on server")]
159 RemoteRepoAlreadyExists(String),
160
161 #[error("Merge failed: {0}")]
162 MergeFailed(String),
163
164 #[error(
165 "Incomplete ancestry while finding common ancestor between '{left}' and '{right}'. Missing commit(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
166 )]
167 IncompleteAncestry {
168 left: String,
169 right: String,
170 missing: String,
171 },
172
173 #[error(
174 "Incomplete manifest data while merging '{left}' with '{right}'. Missing manifest(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
175 )]
176 IncompleteManifestData {
177 left: String,
178 right: String,
179 missing: String,
180 },
181
182 #[error(
183 "Incomplete commit data while reading {context}. Missing commit(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
184 )]
185 IncompleteCommitData { context: String, missing: String },
186
187 #[error(
188 "Incomplete blob data while reading {context}. Missing blob(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
189 )]
190 IncompleteBlobData { context: String, missing: String },
191
192 #[error(
193 "No verified common ancestor found between '{left}' and '{right}'. Run 'oak fetch' or 'oak pull --force' to repair local history."
194 )]
195 NoVerifiedCommonAncestor { left: String, right: String },
196
197 #[error("Merge conflict: {0} file(s) modified on both branches since fork")]
198 MergeConflict(usize),
199
200 #[error("Merge invariant violation: {detail}")]
203 MergeInvariantViolation {
204 detail: String,
205 next_commands: Vec<String>,
206 },
207
208 #[error("Merge prediction uncertified: {detail}")]
210 MergePredictionUncertified {
211 detail: String,
212 next_commands: Vec<String>,
213 },
214
215 #[error("Integrity proof inconclusive: {detail}")]
219 IntegrityInconclusive {
220 detail: String,
221 recommended_next_commands: Vec<String>,
224 },
225
226 #[error("Clone admission token too large: {detail}")]
230 CloneAdmissionTokenTooLarge {
231 detail: String,
232 recommended_next_commands: Vec<String>,
236 },
237
238 #[error("Integrity proof not admitted: {0}")]
242 IntegrityAdmissionBusy(String),
243
244 #[error("A merge is already in progress. Use 'oak merge --continue' or 'oak merge --abort'.")]
245 MergeInProgress,
246
247 #[error("{message}")]
251 InterruptedWorktreeUpdate {
252 message: String,
253 next_commands: Vec<String>,
254 },
255
256 #[error(
264 "{}",
265 local_changes_message(command, clean_command.as_deref(), *transition, paths, *total, *in_the_way)
266 )]
267 LocalChangesWouldBeOverwritten {
268 command: String,
270 clean_command: Option<String>,
272 transition: WorktreeTransition,
273 paths: Vec<(String, String)>,
274 total: usize,
275 in_the_way: bool,
279 },
280
281 #[error("No merge in progress.")]
282 NoMergeInProgress,
283
284 #[error("Merge failed: No sync in progress.")]
286 NoSyncInProgress,
287
288 #[error("IO error: {0}")]
291 TrunkIsServerOnly(String),
292
293 #[error("Not logged in to {remote}. Run `oak login` first.")]
295 NotLoggedIn { remote: String },
296
297 #[error("Configuration error: {0}")]
300 RepoNotLinked(String),
301
302 #[error("{message}")]
306 FeedbackFailed {
307 message: String,
308 usage: bool,
310 code: ErrorCode,
311 retryable: Option<bool>,
312 next_commands: Vec<String>,
313 transition: Option<serde_json::Value>,
315 },
316
317 #[error("{message}")]
319 RootRefused {
320 reason: RootRefusal,
321 message: String,
322 paths: Vec<String>,
324 next_commands: Vec<String>,
325 },
326
327 #[error("IO error: {0}")]
328 Io(#[from] std::io::Error),
329
330 #[error("Database error: {0}")]
331 Database(String),
332
333 #[error("Serialization error: {0}")]
334 Serialization(#[from] serde_json::Error),
335
336 #[error("HTTP error: {0}")]
337 Http(String),
338
339 #[error("Server error: {0}")]
340 Server(String),
341
342 #[error(
343 "{operation} outcome is unconfirmed: {reason}. No automatic mutation retry was attempted; inspect remote state read-only before deciding whether to retry."
344 )]
345 PublicationUnconfirmed {
346 operation: String,
347 reason: String,
348 reconciliation_commands: Vec<String>,
349 },
350
351 #[error(
352 "The server at {remote} refused the request with HTTP {status}: {}",
353 if *status == 403 {
354 "the credential is not allowed to do this"
355 } else {
356 "authentication is required. Run `oak login` (or set OAK_API_KEY) and retry"
357 }
358 )]
359 AuthRequired { remote: String, status: u16 },
360
361 #[error("R2 storage error: {0}")]
362 R2(String),
363
364 #[error("Git operation error: {0}")]
365 Git(String),
366
367 #[error("Configuration error: {0}")]
368 Config(String),
369
370 #[error("{0}")]
371 FinishPreflight(Box<FinishPreflightError>),
372
373 #[error("{0}")]
374 FinishPhaseFailed(Box<FinishPhaseError>),
375
376 #[error("{0}")]
377 CommitPhaseFailed(Box<CommitPhaseError>),
378
379 #[error(
380 "Repository is locked by another process. If no other oak process is running, remove the lock file (.oak/wdlock, or .oak/publication-attempts/wdlock while publishing)"
381 )]
382 RepoLocked,
383
384 #[error("Operation '{op}' is not supported by the {backend} backend")]
385 Unsupported {
386 backend: &'static str,
387 op: &'static str,
388 },
389
390 #[error("Group '{0}' not found in this organization")]
391 GroupNotFound(String),
392
393 #[error("{0}")]
394 InvalidArgument(String),
395
396 #[error("{0}")]
403 Usage(String),
404
405 #[error("{0}")]
407 DetachedHeadCommit(String),
408
409 #[error("{0}")]
414 RestrictedContent(String),
415
416 #[error("{message}")]
423 DescriptionStale {
424 branch: String,
425 state: DescriptionStaleState,
426 message: String,
427 refresh_commands: Vec<String>,
428 },
429
430 #[error("{message}")]
433 ApprovalRefused {
434 code: ErrorCode,
436 server_code: Option<String>,
439 message: String,
440 missing: Vec<MissingApproval>,
441 hidden: usize,
443 recommended_next_commands: Vec<String>,
444 },
445
446 #[error("{message}")]
454 PushCapabilityUnavailable {
455 message: String,
456 recommended_next_commands: Vec<String>,
457 },
458
459 #[error("{} path(s) outside this checkout's directories (first: {}); add them (`oak sparse add DIR`), or remove them", paths.len(), paths.first().map(String::as_str).unwrap_or_default())]
462 PathOutsideView {
463 paths: Vec<String>,
464 recommended_next_commands: Vec<String>,
465 },
466}
467
468#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
470pub struct MissingApproval {
471 pub path: String,
473 pub owner_team: String,
475 pub approvers: Vec<String>,
477}
478
479pub type Result<T> = std::result::Result<T, OakError>;
480
481#[macro_export]
489macro_rules! closed_vocabulary {
490 (
491 $(#[$meta:meta])*
492 $vis:vis enum $name:ident { $( $(#[$vmeta:meta])* $variant:ident => $wire:literal, )+ }
493 ) => {
494 $(#[$meta])*
495 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
496 $vis enum $name { $( $(#[$vmeta])* $variant, )+ }
497
498 impl $name {
499 pub const ALL: &'static [$name] = &[ $( $name::$variant, )+ ];
501
502 pub const fn as_str(self) -> &'static str {
504 match self { $( $name::$variant => $wire, )+ }
505 }
506 }
507
508 impl std::fmt::Display for $name {
509 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510 f.write_str(self.as_str())
511 }
512 }
513
514 impl ::serde::Serialize for $name {
515 fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> {
516 serializer.serialize_str(self.as_str())
517 }
518 }
519
520 impl PartialEq<str> for $name {
521 fn eq(&self, other: &str) -> bool { self.as_str() == other }
522 }
523
524 impl PartialEq<&str> for $name {
525 fn eq(&self, other: &&str) -> bool { self.as_str() == *other }
526 }
527 };
528}
529
530closed_vocabulary! {
531 pub enum ErrorCode {
544 InvalidArgument => "invalid_argument",
546 InvalidHash => "invalid_hash",
547 ConfigurationError => "configuration_error",
548 Unsupported => "unsupported",
549 RepoNotFound => "repo_not_found",
551 RepoAlreadyExists => "repo_already_exists",
552 RepoLocked => "repo_locked",
553 NoCommits => "no_commits",
554 NoEdits => "no_edits",
555 BranchNotFound => "branch_not_found",
556 BranchAlreadyExists => "branch_already_exists",
557 BranchClosed => "branch_closed",
558 BranchIsServerOnly => "branch_is_server_only",
559 CommitNotFound => "commit_not_found",
560 BlobNotFound => "blob_not_found",
561 ManifestNotFound => "manifest_not_found",
562 GroupNotFound => "group_not_found",
563 RestrictedContent => "restricted_content",
564 DiskFull => "disk_full",
566 IoError => "io_error",
567 DatabaseError => "database_error",
568 SerializationError => "serialization_error",
569 GitError => "git_error",
570 DirtyWorktree => "dirty_worktree",
572 InterruptedWorktreeUpdate => "interrupted_worktree_update",
573 PathOutsideView => "path_outside_view",
574 LocalChangesWouldBeOverwritten => "local_changes_would_be_overwritten",
575 WorktreeCaptureRaced => "worktree_capture_raced",
577 CapturedBlobIntegrity => "captured_blob_integrity",
578 CapturedTreeIntegrity => "captured_tree_integrity",
579 ChangeCaptureNotFound => "change_capture_not_found",
580 ChangeCaptureIntegrity => "change_capture_integrity",
581 CaptureScopeExcluded => "capture_scope_excluded",
582 ConflictDetected => "conflict_detected",
584 MergeInProgress => "merge_in_progress",
585 NoMergeInProgress => "no_merge_in_progress",
586 NoSyncInProgress => "no_sync_in_progress",
587 MergeFailed => "merge_failed",
588 MergeInvariantViolation => "merge_invariant_violation",
589 MergePredictionUncertified => "merge_prediction_uncertified",
590 LocalCommitsNotInRemoteHistory => "local_commits_not_in_remote_history",
591 RemoteCommitsNotInLocalHistory => "remote_commits_not_in_local_history",
592 IncompleteAncestry => "incomplete_ancestry",
593 IncompleteManifestData => "incomplete_manifest_data",
594 IncompleteCommitData => "incomplete_commit_data",
595 IncompleteBlobData => "incomplete_blob_data",
596 NoVerifiedCommonAncestor => "no_verified_common_ancestor",
597 RemoteError => "remote_error",
599 RemoteMoved => "remote_moved",
600 RemoteRepoNotFound => "remote_repo_not_found",
601 RemoteRepoAlreadyExists => "remote_repo_already_exists",
602 AuthRequired => "auth_required",
603 AuthDenied => "auth_denied",
604 PublicationUnconfirmed => "publication_unconfirmed",
605 PushCapabilityUnavailable => "push_capability_unavailable",
606 IntegrityInconclusive => "integrity_inconclusive",
607 IntegrityAdmissionBusy => "integrity_admission_busy",
608 CloneAdmissionTokenTooLarge => "clone_admission_token_too_large",
609 FinishPreflightFailed => "finish_preflight_failed",
611 FinishPhaseFailed => "finish_phase_failed",
612 CommitPhaseFailed => "commit_phase_failed",
613 DescriptionStale => "description_stale",
614 ApprovalsRequired => "approvals_required",
616 ApprovalRefused => "approval_refused",
617 ReviewKeyRequired => "review_key_required",
618 BranchMoved => "branch_moved",
619 SelfApproval => "self_approval",
620 NotAnOwner => "not_an_owner",
621 NothingToApprove => "nothing_to_approve",
622 BoundaryNotTouched => "boundary_not_touched",
623 BoundaryOutsideView => "boundary_outside_view",
624 ServiceAccount => "service_account",
625 ApprovalInternal => "internal",
626 ApprovalNotFound => "not_found",
627 View => "view",
628 RootConflict => "root_conflict",
630 PullRequired => "pull_required",
631 HeadMoved => "head_moved",
632 FeedbackTransitionPreflightFailed => "feedback_transition_preflight_failed",
634 FeedbackTransitionUnavailable => "feedback_transition_unavailable",
635 FeedbackTransitionUnconfirmed => "feedback_transition_unconfirmed",
636 FeedbackTransitionRejected => "feedback_transition_rejected",
637 FeedbackTransitionOutputFailed => "feedback_transition_output_failed",
638 FeedbackCapabilityRequestFailed => "feedback_capability_request_failed",
639 FeedbackCapabilityUnauthorized => "feedback_capability_unauthorized",
640 FeedbackCapabilityUnavailable => "feedback_capability_unavailable",
641 FeedbackCapabilityRedirect => "feedback_capability_redirect",
642 FeedbackCapabilityInvalid => "feedback_capability_invalid",
643 FeedbackCapabilityUnsupported => "feedback_capability_unsupported",
644 RevisionConflict => "revision_conflict",
645 }
646}
647
648closed_vocabulary! {
649 pub enum FinishBlocker {
652 InvalidDescription => "invalid_description",
653 MergeInProgress => "merge_in_progress",
654 SyncInProgress => "sync_in_progress",
655 NoCurrentBranch => "no_current_branch",
656 BranchNotFound => "branch_not_found",
657 BranchClosed => "branch_closed",
658 RemoteNotConfigured => "remote_not_configured",
659 RemoteIdentityMissing => "remote_identity_missing",
660 AuthMissing => "auth_missing",
661 AuthFailed => "auth_failed",
662 RemoteRepoMissing => "remote_repo_missing",
663 RemoteUnreachable => "remote_unreachable",
664 }
665}
666
667closed_vocabulary! {
668 pub enum DescriptionStaleState {
670 PendingLocalEdit => "pending_local_edit",
671 RemoteChanged => "remote_changed",
672 RemoteUnverified => "remote_unverified",
673 LocalChanged => "local_changed",
674 }
675}
676
677closed_vocabulary! {
678 pub enum RootRefusal {
680 Conflict => "root_conflict",
681 PullRequired => "pull_required",
682 HeadMoved => "head_moved",
683 }
684}
685
686#[derive(Clone, Copy, Debug, PartialEq, Eq)]
691pub enum WorktreeTransition {
692 Pull,
694 CreateBranch,
696 Other,
698}
699
700fn local_changes_message(
701 command: &str,
702 clean_command: Option<&str>,
703 transition: WorktreeTransition,
704 paths: &[(String, String)],
705 total: usize,
706 in_the_way: bool,
707) -> String {
708 let mut message = format!(
709 "`{command}` would overwrite or remove local work in {total} path(s), so nothing was \
710 changed:"
711 );
712 for (path, why) in paths {
713 message.push_str(&format!("\n {path} ({why})"));
714 }
715 if total > paths.len() {
716 message.push_str(&format!("\n ... and {} more", total - paths.len()));
717 }
718 if in_the_way {
719 message.push_str(&format!(
720 "\nMove these out of the way (rename, move or delete them; a commit does not \
721 resolve this), then run `{command}` again."
722 ));
723 return message;
724 }
725 match transition {
726 WorktreeTransition::Pull => message.push_str(
727 "\nCommit them (`oak commit`) and run `oak pull` again: main is then merged into \
728 this branch, and a path changed on both sides is reported as a conflict to resolve \
729 instead of being overwritten.",
730 ),
731 WorktreeTransition::CreateBranch => {
732 message.push_str(
733 "\nThe new branch starts from the newer main, which has different content at \
734 these paths than your uncommitted version. Either:\n - keep your changes on \
735 the current branch and merge main into it: `oak commit`, then `oak pull` (a \
736 path changed on both sides is reported as a conflict to resolve); or",
737 );
738 match clean_command {
739 Some(clean) => message.push_str(&format!(
740 "\n - create the branch without them: `{clean}` (DISCARDS these \
741 uncommitted changes)."
742 )),
743 None => message.push_str(&format!(
744 "\n - create the branch without them: run `{command}` with `--clean` \
745 (DISCARDS these uncommitted changes)."
746 )),
747 }
748 }
749 WorktreeTransition::Other => message.push_str(&format!(
750 "\nCommit them (`oak commit`) or move them aside, then run `{command}` again."
751 )),
752 }
753 message
754}
755
756impl ErrorCode {
757 pub fn from_approval_reason(reason: &str) -> Option<ErrorCode> {
762 Self::APPROVAL_REASONS
763 .iter()
764 .copied()
765 .find(|code| code.as_str() == reason)
766 }
767
768 pub const APPROVAL_REASONS: &'static [ErrorCode] = &[
770 ErrorCode::ApprovalsRequired,
772 ErrorCode::ApprovalRefused,
773 ErrorCode::BoundaryNotTouched,
775 ErrorCode::BoundaryOutsideView,
776 ErrorCode::BranchClosed,
777 ErrorCode::BranchMoved,
778 ErrorCode::ApprovalInternal,
779 ErrorCode::NotAnOwner,
780 ErrorCode::ApprovalNotFound,
781 ErrorCode::NothingToApprove,
782 ErrorCode::ReviewKeyRequired,
783 ErrorCode::SelfApproval,
784 ErrorCode::ServiceAccount,
785 ErrorCode::View,
786 ];
787}
788
789#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
792pub enum ExitCode {
793 Failure,
795 Usage,
797 Locked,
799 WorktreeBlocked,
801 Conflict,
803 Remote,
805 MergeUncertified,
807 IntegrityInconclusive,
809}
810
811impl ExitCode {
812 pub const ALL: &'static [ExitCode] = &[
813 ExitCode::Failure,
814 ExitCode::Usage,
815 ExitCode::Locked,
816 ExitCode::WorktreeBlocked,
817 ExitCode::Conflict,
818 ExitCode::Remote,
819 ExitCode::MergeUncertified,
820 ExitCode::IntegrityInconclusive,
821 ];
822
823 pub const fn code(self) -> i32 {
824 match self {
825 ExitCode::Failure => 1,
826 ExitCode::Usage => 2,
827 ExitCode::Locked => 3,
828 ExitCode::WorktreeBlocked => 4,
829 ExitCode::Conflict => 5,
830 ExitCode::Remote => 6,
831 ExitCode::MergeUncertified => 7,
832 ExitCode::IntegrityInconclusive => 8,
833 }
834 }
835}
836
837closed_vocabulary! {
838 pub enum OakErrorKind {
843 DiskFull => "DiskFull",
844 RepoNotFound => "RepoNotFound",
845 RepoAlreadyExists => "RepoAlreadyExists",
846 NoCommits => "NoCommits",
847 InvalidHash => "InvalidHash",
848 InvalidPath => "InvalidPath",
849 BlobNotFound => "BlobNotFound",
850 CommitNotFound => "CommitNotFound",
851 BranchNotFound => "BranchNotFound",
852 BranchAlreadyExists => "BranchAlreadyExists",
853 BranchClosed => "BranchClosed",
854 NoEdits => "NoEdits",
855 ManifestNotFound => "ManifestNotFound",
856 UncommittedChanges => "UncommittedChanges",
857 WorktreeCaptureRaced => "WorktreeCaptureRaced",
858 UnsupportedChangeCaptureFormat => "UnsupportedChangeCaptureFormat",
859 ChangeCaptureScopeExcluded => "ChangeCaptureScopeExcluded",
860 CapturedBlobIntegrity => "CapturedBlobIntegrity",
861 CapturedTreeIntegrity => "CapturedTreeIntegrity",
862 ChangeCaptureNotFound => "ChangeCaptureNotFound",
863 ChangeCaptureIntegrity => "ChangeCaptureIntegrity",
864 DirtyWorkingTree => "DirtyWorkingTree",
865 ConflictDetected => "ConflictDetected",
866 LocalCommitsNotInRemoteHistory => "LocalCommitsNotInRemoteHistory",
867 RemoteCommitsNotInLocalHistory => "RemoteCommitsNotInLocalHistory",
868 RemoteNotConfigured => "RemoteNotConfigured",
869 RemoteMoved => "RemoteMoved",
870 RemoteRepoNotFound => "RemoteRepoNotFound",
871 RemoteRepoAlreadyExists => "RemoteRepoAlreadyExists",
872 MergeFailed => "MergeFailed",
873 IncompleteAncestry => "IncompleteAncestry",
874 IncompleteManifestData => "IncompleteManifestData",
875 IncompleteCommitData => "IncompleteCommitData",
876 IncompleteBlobData => "IncompleteBlobData",
877 NoVerifiedCommonAncestor => "NoVerifiedCommonAncestor",
878 MergeConflict => "MergeConflict",
879 MergeInvariantViolation => "MergeInvariantViolation",
880 MergePredictionUncertified => "MergePredictionUncertified",
881 IntegrityInconclusive => "IntegrityInconclusive",
882 CloneAdmissionTokenTooLarge => "CloneAdmissionTokenTooLarge",
883 IntegrityAdmissionBusy => "IntegrityAdmissionBusy",
884 MergeInProgress => "MergeInProgress",
885 InterruptedWorktreeUpdate => "InterruptedWorktreeUpdate",
886 NoMergeInProgress => "NoMergeInProgress",
887 Io => "Io",
888 Database => "Database",
889 Serialization => "Serialization",
890 Http => "Http",
891 Server => "Server",
892 PublicationUnconfirmed => "PublicationUnconfirmed",
893 AuthRequired => "AuthRequired",
894 R2 => "R2",
895 Git => "Git",
896 Config => "Config",
897 FinishPreflight => "FinishPreflight",
898 FinishPhaseFailed => "FinishPhaseFailed",
899 CommitPhaseFailed => "CommitPhaseFailed",
900 RepoLocked => "RepoLocked",
901 Unsupported => "Unsupported",
902 GroupNotFound => "GroupNotFound",
903 InvalidArgument => "InvalidArgument",
904 Usage => "Usage",
905 DetachedHeadCommit => "DetachedHeadCommit",
906 NoSyncInProgress => "NoSyncInProgress",
907 TrunkIsServerOnly => "TrunkIsServerOnly",
908 NotLoggedIn => "NotLoggedIn",
909 RepoNotLinked => "RepoNotLinked",
910 FeedbackFailed => "FeedbackFailed",
911 RootRefused => "RootRefused",
912 RestrictedContent => "RestrictedContent",
913 DescriptionStale => "DescriptionStale",
914 ApprovalRefused => "ApprovalRefused",
915 PushCapabilityUnavailable => "PushCapabilityUnavailable",
916 PathOutsideView => "PathOutsideView",
917 LocalChangesWouldBeOverwritten => "LocalChangesWouldBeOverwritten",
918 }
919}
920
921impl OakError {
922 pub fn in_transition(mut self, kind: WorktreeTransition) -> Self {
926 if let OakError::LocalChangesWouldBeOverwritten { transition, .. } = &mut self {
927 *transition = kind;
928 }
929 self
930 }
931
932 pub fn kind(&self) -> OakErrorKind {
934 match self {
935 OakError::DiskFull { .. } => OakErrorKind::DiskFull,
936 OakError::RepoNotFound => OakErrorKind::RepoNotFound,
937 OakError::RepoAlreadyExists => OakErrorKind::RepoAlreadyExists,
938 OakError::NoCommits => OakErrorKind::NoCommits,
939 OakError::InvalidHash(_) => OakErrorKind::InvalidHash,
940 OakError::InvalidPath(_) => OakErrorKind::InvalidPath,
941 OakError::BlobNotFound(_) => OakErrorKind::BlobNotFound,
942 OakError::CommitNotFound(_) => OakErrorKind::CommitNotFound,
943 OakError::BranchNotFound(_) => OakErrorKind::BranchNotFound,
944 OakError::BranchAlreadyExists(_) => OakErrorKind::BranchAlreadyExists,
945 OakError::BranchClosed(_) => OakErrorKind::BranchClosed,
946 OakError::NoEdits => OakErrorKind::NoEdits,
947 OakError::ManifestNotFound(_) => OakErrorKind::ManifestNotFound,
948 OakError::UncommittedChanges => OakErrorKind::UncommittedChanges,
949 OakError::WorktreeCaptureRaced { .. } => OakErrorKind::WorktreeCaptureRaced,
950 OakError::UnsupportedChangeCaptureFormat(_) => {
951 OakErrorKind::UnsupportedChangeCaptureFormat
952 }
953 OakError::ChangeCaptureScopeExcluded { .. } => OakErrorKind::ChangeCaptureScopeExcluded,
954 OakError::CapturedBlobIntegrity { .. } => OakErrorKind::CapturedBlobIntegrity,
955 OakError::CapturedTreeIntegrity { .. } => OakErrorKind::CapturedTreeIntegrity,
956 OakError::ChangeCaptureNotFound { .. } => OakErrorKind::ChangeCaptureNotFound,
957 OakError::ChangeCaptureIntegrity { .. } => OakErrorKind::ChangeCaptureIntegrity,
958 OakError::DirtyWorkingTree(_) => OakErrorKind::DirtyWorkingTree,
959 OakError::ConflictDetected => OakErrorKind::ConflictDetected,
960 OakError::LocalCommitsNotInRemoteHistory => {
961 OakErrorKind::LocalCommitsNotInRemoteHistory
962 }
963 OakError::RemoteCommitsNotInLocalHistory => {
964 OakErrorKind::RemoteCommitsNotInLocalHistory
965 }
966 OakError::RemoteNotConfigured => OakErrorKind::RemoteNotConfigured,
967 OakError::RemoteMoved { .. } => OakErrorKind::RemoteMoved,
968 OakError::RemoteRepoNotFound(_) => OakErrorKind::RemoteRepoNotFound,
969 OakError::RemoteRepoAlreadyExists(_) => OakErrorKind::RemoteRepoAlreadyExists,
970 OakError::MergeFailed(_) => OakErrorKind::MergeFailed,
971 OakError::IncompleteAncestry { .. } => OakErrorKind::IncompleteAncestry,
972 OakError::IncompleteManifestData { .. } => OakErrorKind::IncompleteManifestData,
973 OakError::IncompleteCommitData { .. } => OakErrorKind::IncompleteCommitData,
974 OakError::IncompleteBlobData { .. } => OakErrorKind::IncompleteBlobData,
975 OakError::NoVerifiedCommonAncestor { .. } => OakErrorKind::NoVerifiedCommonAncestor,
976 OakError::MergeConflict(_) => OakErrorKind::MergeConflict,
977 OakError::MergeInvariantViolation { .. } => OakErrorKind::MergeInvariantViolation,
978 OakError::MergePredictionUncertified { .. } => OakErrorKind::MergePredictionUncertified,
979 OakError::IntegrityInconclusive { .. } => OakErrorKind::IntegrityInconclusive,
980 OakError::CloneAdmissionTokenTooLarge { .. } => {
981 OakErrorKind::CloneAdmissionTokenTooLarge
982 }
983 OakError::IntegrityAdmissionBusy(_) => OakErrorKind::IntegrityAdmissionBusy,
984 OakError::MergeInProgress => OakErrorKind::MergeInProgress,
985 OakError::InterruptedWorktreeUpdate { .. } => OakErrorKind::InterruptedWorktreeUpdate,
986 OakError::LocalChangesWouldBeOverwritten { .. } => {
987 OakErrorKind::LocalChangesWouldBeOverwritten
988 }
989 OakError::NoMergeInProgress => OakErrorKind::NoMergeInProgress,
990 OakError::Io(_) => OakErrorKind::Io,
991 OakError::Database(_) => OakErrorKind::Database,
992 OakError::Serialization(_) => OakErrorKind::Serialization,
993 OakError::Http(_) => OakErrorKind::Http,
994 OakError::Server(_) => OakErrorKind::Server,
995 OakError::PublicationUnconfirmed { .. } => OakErrorKind::PublicationUnconfirmed,
996 OakError::AuthRequired { .. } => OakErrorKind::AuthRequired,
997 OakError::R2(_) => OakErrorKind::R2,
998 OakError::Git(_) => OakErrorKind::Git,
999 OakError::Config(_) => OakErrorKind::Config,
1000 OakError::FinishPreflight(_) => OakErrorKind::FinishPreflight,
1001 OakError::FinishPhaseFailed(_) => OakErrorKind::FinishPhaseFailed,
1002 OakError::CommitPhaseFailed(_) => OakErrorKind::CommitPhaseFailed,
1003 OakError::RepoLocked => OakErrorKind::RepoLocked,
1004 OakError::Unsupported { .. } => OakErrorKind::Unsupported,
1005 OakError::GroupNotFound(_) => OakErrorKind::GroupNotFound,
1006 OakError::InvalidArgument(_) => OakErrorKind::InvalidArgument,
1007 OakError::Usage(_) => OakErrorKind::Usage,
1008 OakError::DetachedHeadCommit(_) => OakErrorKind::DetachedHeadCommit,
1009 OakError::NoSyncInProgress => OakErrorKind::NoSyncInProgress,
1010 OakError::TrunkIsServerOnly(_) => OakErrorKind::TrunkIsServerOnly,
1011 OakError::NotLoggedIn { .. } => OakErrorKind::NotLoggedIn,
1012 OakError::RepoNotLinked(_) => OakErrorKind::RepoNotLinked,
1013 OakError::FeedbackFailed { .. } => OakErrorKind::FeedbackFailed,
1014 OakError::RootRefused { .. } => OakErrorKind::RootRefused,
1015 OakError::RestrictedContent(_) => OakErrorKind::RestrictedContent,
1016 OakError::DescriptionStale { .. } => OakErrorKind::DescriptionStale,
1017 OakError::ApprovalRefused { .. } => OakErrorKind::ApprovalRefused,
1018 OakError::PushCapabilityUnavailable { .. } => OakErrorKind::PushCapabilityUnavailable,
1019 OakError::PathOutsideView { .. } => OakErrorKind::PathOutsideView,
1020 }
1021 }
1022}
1023
1024#[cfg(test)]
1025mod contract_vocabulary_tests {
1026 use super::*;
1027 use std::collections::HashSet;
1028
1029 #[test]
1030 fn error_codes_are_unique_specific_snake_case() {
1031 let mut seen = HashSet::new();
1032 for code in ErrorCode::ALL {
1033 let wire = code.as_str();
1034 assert!(seen.insert(wire), "duplicate error code {wire}");
1035 assert!(
1036 !matches!(wire, "error" | "generic" | "unknown" | "failure" | "failed"),
1037 "{wire} is a generic code; every failure needs a specific one"
1038 );
1039 assert!(
1040 wire.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
1041 "{wire} is not snake_case"
1042 );
1043 }
1044 }
1045
1046 #[test]
1050 fn every_server_approval_reason_keeps_its_exact_code() {
1051 const SERVER_TABLE: &[&str] = &[
1052 "boundary_not_touched",
1053 "boundary_outside_view",
1054 "branch_closed",
1055 "branch_moved",
1056 "internal",
1057 "not_an_owner",
1058 "not_found",
1059 "nothing_to_approve",
1060 "review_key_required",
1061 "self_approval",
1062 "service_account",
1063 "view",
1064 ];
1065 for reason in SERVER_TABLE {
1066 assert_eq!(
1067 ErrorCode::from_approval_reason(reason).map(ErrorCode::as_str),
1068 Some(*reason)
1069 );
1070 }
1071 assert_eq!(
1072 ErrorCode::from_approval_reason("approvals_required"),
1073 Some(ErrorCode::ApprovalsRequired)
1074 );
1075 assert_eq!(
1076 ErrorCode::from_approval_reason("a_newer_servers_reason"),
1077 None
1078 );
1079 }
1080
1081 #[test]
1082 fn exit_codes_are_the_documented_table() {
1083 let codes: Vec<i32> = ExitCode::ALL.iter().map(|code| code.code()).collect();
1084 assert_eq!(codes, vec![1, 2, 3, 4, 5, 6, 7, 8]);
1085 }
1086
1087 #[test]
1088 fn every_kind_is_listed_once() {
1089 let unique: HashSet<_> = OakErrorKind::ALL.iter().collect();
1090 assert_eq!(unique.len(), OakErrorKind::ALL.len());
1091 }
1092}