1use std::path::PathBuf;
27
28use thiserror::Error;
29
30mod diff;
31mod notes;
32mod object;
33mod refs;
34mod revision;
35mod summary;
36
37pub use diff::DiffError;
38pub use notes::NotesError;
39pub use object::{ObjectError, PromisorFetchFailure};
40pub use refs::RefError;
41pub use revision::RevisionError;
42pub use summary::ErrorSummary;
43
44pub use crate::git_dir::GitDirPathOperation;
45pub use crate::midx_error::MidxError;
46pub use crate::repo::RepositoryError;
47pub use crate::worktree::io_error::WorktreePathOperation;
48
49#[derive(Debug, Clone, PartialEq, Eq, Error)]
51#[error(
52 "lock file {} already exists",
53 crate::git_path::user_display_path(.path.as_path())
54)]
55pub struct LockHeldError {
56 pub path: PathBuf,
58 pub holder: Option<crate::lockfile::LockHolder>,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct Cancelled;
65
66impl std::fmt::Display for Cancelled {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.write_str("operation cancelled")
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74#[non_exhaustive]
75pub enum PathIoOperation {
76 GitDir(GitDirPathOperation),
78 Worktree(WorktreePathOperation),
80}
81
82#[derive(Debug)]
84pub struct PathIoError {
85 pub operation: PathIoOperation,
87 pub path: Option<PathBuf>,
89 pub source: std::io::Error,
91}
92
93fn preserve_io_error(source: &std::io::Error) -> std::io::Error {
95 if let Some(raw) = source.raw_os_error() {
96 std::io::Error::from_raw_os_error(raw)
97 } else {
98 std::io::Error::new(source.kind(), source.to_string())
99 }
100}
101
102impl std::fmt::Display for PathIoError {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 f.write_str(&self.message())
105 }
106}
107
108impl std::error::Error for PathIoError {
109 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
110 Some(&self.source)
111 }
112}
113
114impl PathIoError {
115 #[must_use]
117 pub fn worktree(
118 path: impl Into<String>,
119 operation: WorktreePathOperation,
120 source: std::io::Error,
121 ) -> Self {
122 Self {
123 operation: PathIoOperation::Worktree(operation),
124 path: Some(PathBuf::from(path.into())),
125 source,
126 }
127 }
128
129 #[must_use]
131 pub fn git_dir(
132 path: impl Into<String>,
133 operation: GitDirPathOperation,
134 source: std::io::Error,
135 ) -> Self {
136 Self {
137 operation: PathIoOperation::GitDir(operation),
138 path: Some(PathBuf::from(path.into())),
139 source,
140 }
141 }
142
143 #[must_use]
145 pub fn message(&self) -> String {
146 let path = self
147 .path
148 .as_ref()
149 .map(|p| p.to_string_lossy().into_owned())
150 .unwrap_or_default();
151 match self.operation {
152 PathIoOperation::Worktree(op) => {
153 crate::worktree::io_error::format_worktree_path_io_message(&path, op, &self.source)
154 }
155 PathIoOperation::GitDir(op) => {
156 crate::git_dir::io_error::format_git_dir_io_message(&path, op, &self.source)
157 }
158 }
159 }
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum BadNumericSource {
165 InvalidUnit,
167 OutOfRange,
169}
170
171impl BadNumericSource {
172 fn detail(self) -> &'static str {
173 match self {
174 Self::InvalidUnit => "invalid unit",
175 Self::OutOfRange => "out of range",
176 }
177 }
178}
179
180impl std::fmt::Display for BadNumericSource {
181 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182 f.write_str(self.detail())
183 }
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub enum OverwriteReason {
189 LocalChanges,
191 Untracked,
193}
194
195impl std::fmt::Display for OverwriteReason {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 match self {
198 Self::LocalChanges => f.write_str("local_changes"),
199 Self::Untracked => f.write_str("untracked"),
200 }
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
209#[non_exhaustive]
210pub enum RemoteUnreadableReason {
211 RepositoryNotFound,
214 Transport {
217 detail: String,
219 },
220 HttpStatus {
223 status: u16,
225 },
226 NotGitServer {
229 status: u16,
231 content_type: Option<String>,
233 },
234 NoHandshake,
237 ResponseTruncated,
240}
241
242impl RemoteUnreadableReason {
243 #[must_use]
246 pub fn slug(&self) -> &'static str {
247 match self {
248 Self::RepositoryNotFound => "repository_not_found",
249 Self::Transport { .. } => "transport",
250 Self::HttpStatus { .. } => "http_status",
251 Self::NotGitServer { .. } => "not_git_server",
252 Self::NoHandshake => "no_handshake",
253 Self::ResponseTruncated => "response_truncated",
254 }
255 }
256}
257
258pub(crate) fn remote_unreadable_message(
259 url: Option<&str>,
260 reason: &RemoteUnreadableReason,
261) -> String {
262 let target = url.map_or_else(|| "the remote".to_owned(), |u| format!("'{u}'"));
263 match reason {
264 RemoteUnreadableReason::RepositoryNotFound => {
265 format!("could not find repository at {target}")
266 }
267 RemoteUnreadableReason::Transport { detail } => {
268 format!("could not reach {target}: {detail}")
269 }
270 RemoteUnreadableReason::HttpStatus { status } => match url {
271 Some(u) => format!("HTTP {status} from {u}"),
272 None => format!("HTTP {status} from the remote"),
273 },
274 RemoteUnreadableReason::NotGitServer {
275 status,
276 content_type,
277 } => {
278 let got = match content_type
279 .as_deref()
280 .map(|ct| ct.split(';').next().unwrap_or(ct).trim())
281 .filter(|ct| !ct.is_empty())
282 {
283 Some(ct) => format!("{status} {ct}"),
284 None => status.to_string(),
285 };
286 format!("{target} did not answer like a Git server (got {got})")
287 }
288 RemoteUnreadableReason::NoHandshake => {
289 format!("could not read from {target}: no Git protocol response")
290 }
291 RemoteUnreadableReason::ResponseTruncated => {
292 format!("{target} closed the connection before sending the pack")
293 }
294 }
295}
296
297pub(crate) fn remote_transport_message(url: Option<&str>, detail: &str) -> String {
299 match url {
300 Some(u) => format!("could not reach {u}: {detail}"),
301 None => format!("transport failure: {detail}"),
302 }
303}
304
305pub(crate) fn remote_http_status_message(url: Option<&str>, status: u16) -> String {
307 match url {
308 Some(u) => format!("HTTP {status} from {u}"),
309 None => format!("HTTP {status} from the remote"),
310 }
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Error)]
315#[non_exhaustive]
316pub enum AuthFailure {
317 #[error("no credential provider is configured")]
319 NoCredentialProvider,
320 #[error("{detail}")]
323 CredentialsUnavailable {
324 detail: String,
327 helpers: Vec<String>,
331 },
332 #[error("the credential helper returned no usable username and password")]
334 UnusableCredentials,
335 #[error("the URL cannot be described to a credential helper")]
337 UrlNotDescribable,
338 #[error("unsupported authentication scheme: {}", schemes.join(", "))]
340 UnsupportedScheme {
341 schemes: Vec<String>,
343 },
344 #[error("the server rejected the credentials")]
346 Rejected,
347}
348
349impl AuthFailure {
350 #[must_use]
352 pub fn is_rejected(&self) -> bool {
353 matches!(self, Self::Rejected)
354 }
355
356 #[must_use]
364 pub fn from_fill_error(err: Error) -> Self {
365 let helpers = match &err {
366 Error::Remote(crate::remote::RemoteError::CredentialsUnavailable { helpers }) => {
367 helpers.clone()
368 }
369 _ => Vec::new(),
370 };
371 Self::CredentialsUnavailable {
372 detail: err.to_string(),
373 helpers,
374 }
375 }
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
380#[non_exhaustive]
381pub enum WorktreeOperation {
382 Switch,
384 Pick,
386 Merge,
388 RebaseExec,
390 Rebase,
392}
393
394impl std::fmt::Display for WorktreeOperation {
395 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396 f.write_str(match self {
397 Self::Switch => "switching",
398 Self::Pick => "picking",
399 Self::Merge => "merging",
400 Self::RebaseExec => "rebasing with --exec",
401 Self::Rebase => "rebasing",
402 })
403 }
404}
405
406#[derive(Debug, Error, Clone, PartialEq)]
408#[non_exhaustive]
409pub enum ConfigError {
410 #[error("bad config line {line} in {location}")]
412 BadConfigLine {
413 location: String,
415 line: usize,
417 },
418
419 #[error("bad config line {line} in file '{file}'")]
421 BadConfigLineInFile {
422 file: String,
424 line: usize,
426 },
427
428 #[error("missing value for '{key}'")]
430 MissingValue {
431 key: String,
433 },
434
435 #[error("bad config variable '{key}' in file '{file}' at line {line}")]
437 BadConfigVariable {
438 key: String,
440 file: String,
442 line: usize,
444 },
445
446 #[error("key '{key}' is not set")]
448 KeyNotSet {
449 key: String,
451 },
452
453 #[error("bad numeric config value '{value}' for '{key}': {reason}")]
455 BadNumericValue {
456 key: String,
458 value: String,
460 reason: BadNumericSource,
462 },
463
464 #[error("bad numeric config value '{value}' for '{key}' in file {file}: {reason}")]
466 BadNumericValueInFile {
467 key: String,
469 value: String,
471 file: String,
473 reason: BadNumericSource,
475 },
476
477 #[error("bad config variable '{key}' in file '{file}' at line {line}")]
479 BadConfigVariableAtLine {
480 key: String,
482 file: String,
484 line: usize,
486 },
487
488 #[error("unable to parse '{key}' from command-line config")]
490 UnableToParseFromCommandLine {
491 key: String,
493 },
494
495 #[error(
499 "remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"
500 )]
501 RemoteUrlInHasconfigInclude,
502
503 #[error("exceeded maximum include depth (depth {depth} exceeds limit {limit})")]
505 IncludeDepthExceeded {
506 depth: usize,
508 limit: usize,
510 },
511
512 #[error("{}", invalid_key_message(key, *reason))]
515 InvalidKey {
516 key: String,
518 reason: InvalidKeyReason,
520 },
521
522 #[error("invalid section name: {section}")]
524 InvalidSectionName {
525 section: String,
527 },
528
529 #[error("invalid value-pattern regex '{pattern}': {reason}")]
531 InvalidValuePattern {
532 pattern: String,
534 reason: String,
536 },
537
538 #[error("invalid key pattern '{pattern}': {source}")]
540 InvalidPattern {
541 pattern: String,
543 #[source]
545 source: regex::Error,
546 },
547
548 #[error("unknown repository format version: {version}")]
550 UnsupportedRepositoryFormatVersion {
551 version: u32,
553 },
554
555 #[error("config cache lock poisoned")]
557 ConfigCacheLockPoisoned,
558
559 #[error("config session lock poisoned")]
561 ConfigSessionLockPoisoned,
562
563 #[error("config session missing after refresh")]
565 ConfigSessionMissingAfterRefresh,
566
567 #[error("invalid list prefix '{prefix}'")]
569 InvalidListPrefix {
570 prefix: String,
572 },
573
574 #[error("unknown value '{value}' for '{key}'")]
577 UnknownValue {
578 key: String,
580 value: String,
582 },
583
584 #[error("invalid number of threads ({value}) for '{key}'")]
586 InvalidThreadCount {
587 key: String,
589 value: i64,
591 },
592
593 #[error("bogus count in GIT_CONFIG_COUNT: '{value}'")]
595 InvalidEnvironmentCount {
596 value: String,
598 },
599
600 #[error("missing config key GIT_CONFIG_KEY_{index}")]
602 MissingEnvironmentKey {
603 index: usize,
605 },
606
607 #[error("bogus format in GIT_CONFIG_PARAMETERS")]
609 MalformedConfigParameters,
610
611 #[error("relative config includes must come from files")]
614 RelativeIncludeOutsideFile,
615
616 #[error("not in a git repository")]
618 RepositoryRequired,
619
620 #[error("could not determine global config path")]
622 NoGlobalConfigPath,
623
624 #[error("'{value}' is not a date for '{key}'")]
627 InvalidDate {
628 key: String,
630 value: String,
632 },
633
634 #[error("could not lock config file {path}: File exists")]
636 ConfigFileLocked {
637 path: String,
639 },
640
641 #[error("cannot overwrite multiple values with a single value for '{key}'")]
643 MultipleValues {
644 key: String,
646 },
647
648 #[error(
650 "worktree config is only allowed when extensions.worktreeConfig is enabled in the common config"
651 )]
652 WorktreeConfigNotEnabled,
653
654 #[error("section '{section}' not found")]
656 SectionNotFound {
657 section: String,
659 },
660
661 #[error("no multi-line comment allowed")]
663 MultilineCommentNotAllowed,
664
665 #[error(
667 "invalid value '{value}' for 'status.showUntrackedFiles' (expected no, normal, all, boolean words, or integer 0 vs nonzero)"
668 )]
669 InvalidUntrackedFilesMode {
670 value: String,
672 },
673
674 #[error(
676 "invalid value '{value}' for 'merge.directoryRenames' (expected true, false or conflict)"
677 )]
678 InvalidDirectoryRenames {
679 value: String,
681 },
682
683 #[error("{source} for '{key}'")]
686 InvalidValue {
687 key: String,
689 #[source]
691 source: ConfigValueError,
692 },
693}
694
695#[derive(Debug, Error, Clone, PartialEq, Eq)]
702#[non_exhaustive]
703pub enum ConfigValueError {
704 #[error("bad boolean config value '{value}'")]
706 InvalidBool {
707 value: String,
709 },
710
711 #[error("empty integer value")]
713 EmptyInteger,
714
715 #[error("invalid integer: '{value}'")]
717 InvalidInteger {
718 value: String,
720 },
721
722 #[error("integer overflow: '{value}'")]
724 IntegerOverflow {
725 value: String,
727 },
728
729 #[error("bad color value '{value}'")]
731 InvalidColor {
732 value: String,
734 },
735}
736
737impl ConfigValueError {
738 #[must_use]
748 pub fn for_key(self, key: impl Into<String>) -> ConfigError {
749 ConfigError::InvalidValue {
750 key: key.into(),
751 source: self,
752 }
753 }
754}
755
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758#[non_exhaustive]
759pub enum InvalidKeyReason {
760 LineBreak,
762 MissingSection,
764 MissingVariable,
766 InvalidSection,
769 InvalidVariable,
772}
773
774fn invalid_key_message(key: &str, reason: InvalidKeyReason) -> String {
775 match reason {
776 InvalidKeyReason::LineBreak => format!(
777 "invalid key: '{}'",
778 key.replace('\n', "\\n").replace('\r', "\\r")
779 ),
780 InvalidKeyReason::MissingSection => format!("key does not contain a section: '{key}'"),
781 InvalidKeyReason::MissingVariable => {
782 format!("key does not contain variable name: '{key}'")
783 }
784 InvalidKeyReason::InvalidSection => format!("invalid key (bad section): '{key}'"),
785 InvalidKeyReason::InvalidVariable => format!("invalid key (bad variable name): '{key}'"),
786 }
787}
788
789impl From<crate::config::GitConfigIntStrictError> for BadNumericSource {
790 fn from(value: crate::config::GitConfigIntStrictError) -> Self {
791 match value {
792 crate::config::GitConfigIntStrictError::InvalidUnit => Self::InvalidUnit,
793 crate::config::GitConfigIntStrictError::OutOfRange => Self::OutOfRange,
794 }
795 }
796}
797
798#[derive(Debug, Error, Clone, PartialEq, Eq)]
801#[non_exhaustive]
802pub enum SubmoduleError {
803 #[error("submodule path is empty")]
805 EmptyPath,
806
807 #[error("submodule path '{path}' passes through symbolic link '{component}'")]
810 SymlinkInPath {
811 path: String,
813 component: String,
815 },
816
817 #[error("git dir {} of submodule '{name}' does not end with its name", .git_dir.display())]
819 GitDirNameMismatch {
820 name: String,
822 git_dir: std::path::PathBuf,
824 },
825
826 #[error("git dir of submodule '{name}' lies inside another submodule's git dir")]
828 GitDirNested {
829 name: String,
831 },
832
833 #[error("submodule git dir {} has no modules/ segment", .git_dir.display())]
835 GitDirOutsideModules {
836 git_dir: std::path::PathBuf,
838 },
839
840 #[error("encoded submodule git dir {} has '/' after modules/", .git_dir.display())]
842 GitDirSegmentHasSlash {
843 git_dir: std::path::PathBuf,
845 },
846
847 #[error("git dir {} of submodule '{name}' is already used by another submodule", .git_dir.display())]
849 GitDirInUse {
850 name: String,
852 git_dir: std::path::PathBuf,
854 },
855
856 #[error("git dir {} of submodule '{name}' differs only in case from another submodule's", .git_dir.display())]
859 GitDirCaseConflict {
860 name: String,
862 git_dir: std::path::PathBuf,
864 },
865
866 #[error("could not choose a git dir for submodule '{name}'")]
868 GitDirUnavailable {
869 name: String,
871 },
872
873 #[error("submodule.{name}.gitdir is not set (submodulePathConfig is enabled)")]
875 GitDirNotConfigured {
876 name: String,
878 },
879
880 #[error("could not read HEAD of submodule '{path}'")]
882 HeadUnreadable {
883 path: String,
885 },
886
887 #[error("submodule at '{path}' is not checked out")]
889 NotCheckedOut {
890 path: String,
892 },
893
894 #[error("HEAD of submodule '{path}' does not point to a readable commit")]
896 HeadCommitMissing {
897 path: String,
899 },
900}
901
902impl ConfigError {
903 #[must_use]
905 pub fn message_body(&self) -> String {
906 self.to_string()
907 }
908}
909
910#[derive(Debug, Error, Clone, PartialEq, Eq)]
912#[non_exhaustive]
913pub enum RefLockError {
914 #[error(
916 "cannot lock ref '{refname}': there is a non-empty directory '{path}' blocking reference '{refname}'"
917 )]
918 DirectoryInTheWay {
919 refname: String,
921 path: String,
923 },
924
925 #[error("Unable to create '{lock_path}': File exists.")]
927 PackedRefsLockHeld {
928 lock_path: String,
930 },
931}
932
933#[derive(Debug, Error, Clone, PartialEq, Eq)]
935#[non_exhaustive]
936pub enum FilterError {
937 #[error("{path}: {phase} filter '{driver}' failed")]
939 ExternalFilterFailed {
940 driver: String,
942 path: String,
944 phase: FilterPhase,
946 },
947
948 #[error("{path}: cannot start {phase} filter '{driver}' ({program}): {detail}")]
951 ExternalFilterSpawnFailed {
952 driver: String,
954 path: String,
956 phase: FilterPhase,
958 program: String,
960 kind: std::io::ErrorKind,
962 detail: String,
964 },
965
966 #[error("{path}: {detail}")]
968 NotFilteredProperly {
969 path: String,
971 detail: String,
973 },
974
975 #[error("true/false are no valid working-tree-encodings")]
977 InvalidWorkingTreeEncoding,
978
979 #[error("{detail}")]
981 LineEndingWouldChange {
982 detail: String,
984 },
985
986 #[error("{path}: filter delayed the checkout, which this operation does not support")]
988 DelayedCheckoutUnsupported {
989 path: String,
991 },
992
993 #[error("filter command exited with status {status}")]
995 Failed {
996 status: i32,
998 },
999}
1000
1001#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1003pub enum FilterPhase {
1004 Smudge,
1006 Clean,
1008}
1009
1010impl std::fmt::Display for FilterPhase {
1011 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1012 match self {
1013 Self::Smudge => f.write_str("smudge"),
1014 Self::Clean => f.write_str("clean"),
1015 }
1016 }
1017}
1018
1019#[derive(Debug, Clone, PartialEq, Eq)]
1021pub enum SparseCheckoutWarning {
1022 UnrecognizedPattern {
1024 pattern: String,
1026 },
1027 UnrecognizedNegativePattern {
1029 pattern: String,
1031 },
1032 RepeatedPattern {
1034 pattern: String,
1036 },
1037 DisablingConePatternMatching,
1039}
1040
1041impl SparseCheckoutWarning {
1042 #[must_use]
1044 pub fn body(&self) -> String {
1045 match self {
1046 Self::UnrecognizedPattern { pattern } => {
1047 format!("unrecognized pattern: '{pattern}'")
1048 }
1049 Self::UnrecognizedNegativePattern { pattern } => {
1050 format!("unrecognized negative pattern: '{pattern}'")
1051 }
1052 Self::RepeatedPattern { pattern } => format!(
1053 "your sparse-checkout file may have issues: pattern '{pattern}' is repeated"
1054 ),
1055 Self::DisablingConePatternMatching => "disabling cone pattern matching".to_owned(),
1056 }
1057 }
1058
1059 #[must_use]
1061 pub fn format_line(&self) -> String {
1062 crate::diagnostics::warning_line(&self.body())
1063 }
1064}
1065
1066#[derive(Debug, Error, Clone, PartialEq, Eq)]
1068#[non_exhaustive]
1069pub enum ApplyError {
1070 #[error("corrupt patch at {input}:{line}")]
1072 CorruptPatch {
1073 input: String,
1075 line: usize,
1077 },
1078
1079 #[error(
1081 "patch failed: context mismatch at hunk {hunk_index} (expected near line {expected_line})"
1082 )]
1083 ContextMismatch {
1084 hunk_index: usize,
1086 expected_line: usize,
1088 },
1089
1090 #[error("patch failed: overlapping hunks at hunk {hunk_index}")]
1092 HunksOverlap {
1093 hunk_index: usize,
1095 },
1096
1097 #[error("patch failed: unexpected end of file at hunk {hunk_index}")]
1099 UnexpectedEof {
1100 hunk_index: usize,
1102 },
1103
1104 #[error("diff path is not valid UTF-8")]
1106 PathNotUtf8,
1107
1108 #[error("unable to find filename in traditional patch")]
1110 MissingFilename,
1111
1112 #[error("malformed {side} path in diff --git header: {path}")]
1114 MalformedHeaderPath {
1115 side: PatchSide,
1117 path: String,
1119 },
1120
1121 #[error("invalid mode on line {line}: {text}")]
1123 InvalidMode {
1124 line: usize,
1126 text: String,
1128 },
1129
1130 #[error("invalid hunk header: {header}")]
1132 InvalidHunkHeader {
1133 header: String,
1135 },
1136
1137 #[error(transparent)]
1139 BinaryPatch(#[from] BinaryPatchError),
1140
1141 #[error("patch failed: {path}:{line}")]
1143 PatchFailed {
1144 path: String,
1146 line: usize,
1148 },
1149
1150 #[error("could not apply patch to {path}: {message}")]
1152 Failed {
1153 path: String,
1155 message: String,
1157 },
1158
1159 #[error("'{path}' is not in the index")]
1161 NotInIndex {
1162 path: String,
1164 },
1165
1166 #[error("binary patch data missing for '{path}'")]
1168 BinaryDataMissing {
1169 path: String,
1171 },
1172
1173 #[error("operation cancelled")]
1175 Cancelled,
1176}
1177
1178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1180#[non_exhaustive]
1181pub enum PatchSide {
1182 Old,
1184 New,
1186}
1187
1188impl std::fmt::Display for PatchSide {
1189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1190 f.write_str(match self {
1191 Self::Old => "old",
1192 Self::New => "new",
1193 })
1194 }
1195}
1196
1197#[derive(Debug, Error, Clone, PartialEq, Eq)]
1199#[non_exhaustive]
1200pub enum BinaryPatchError {
1201 #[error("unsupported binary patch section: '{header}'")]
1203 UnsupportedSection {
1204 header: String,
1206 },
1207 #[error("invalid binary patch section size: '{size}'")]
1209 InvalidSectionSize {
1210 size: String,
1212 },
1213 #[error("empty binary patch payload line")]
1215 EmptyLine,
1216 #[error("invalid binary patch line length marker: '{marker}'")]
1218 InvalidLineLength {
1219 marker: char,
1221 },
1222 #[error("invalid binary patch base85")]
1225 InvalidBase85,
1226 #[error("failed to inflate binary patch payload: {detail}")]
1228 Inflate {
1229 detail: String,
1231 },
1232 #[error("binary patch literal size {actual} != declared {declared}")]
1234 SizeMismatch {
1235 actual: usize,
1237 declared: usize,
1239 },
1240 #[error("binary patch delta requires a base blob")]
1242 DeltaWithoutBase,
1243 #[error("binary patch has no reverse section")]
1245 NoReverseSection,
1246}
1247
1248#[derive(Debug, Error, Clone, PartialEq, Eq)]
1250#[non_exhaustive]
1251pub enum PathspecFromFileParseError {
1252 #[error("invalid UTF-8 in pathspec-from-file (NUL mode)")]
1254 InvalidUtf8InNulRecord,
1255 #[error("pathspec-from-file: line is not NUL terminated: {line}")]
1257 QuotedLineInNulMode {
1258 line: String,
1260 },
1261 #[error("invalid C-style quoting: {line}")]
1263 InvalidCStyleQuoting {
1264 line: String,
1266 },
1267 #[error("invalid escape at end of string")]
1269 InvalidEscapeAtEnd,
1270 #[error("truncated octal escape")]
1272 TruncatedOctalEscape,
1273 #[error("invalid octal bytes")]
1275 InvalidOctalBytes,
1276 #[error("invalid octal escape value")]
1278 InvalidOctalValue,
1279 #[error("invalid escape sequence \\{escape}")]
1281 InvalidEscapeSequence {
1282 escape: char,
1284 },
1285 #[error("invalid UTF-8 in quoted pathspec")]
1287 InvalidUtf8InQuotedLine,
1288}
1289
1290#[derive(Debug, Error, Clone, PartialEq, Eq)]
1292#[non_exhaustive]
1293pub enum PathspecResolveError {
1294 #[error("invalid path ''")]
1296 EmptyPathspec,
1297 #[error("{elt}: '{path}' is outside repository at '{work_tree}'")]
1299 OutsideRepository {
1300 elt: String,
1302 path: String,
1304 work_tree: String,
1306 },
1307 #[error(transparent)]
1309 FromFile(#[from] PathspecFromFileParseError),
1310 #[error("this operation needs a working tree")]
1312 NeedsWorkTree,
1313 #[error(transparent)]
1315 InvalidGlobals(#[from] crate::pathspec::PathspecGlobalsError),
1316}
1317
1318#[derive(Debug, Error, Clone, PartialEq, Eq)]
1320#[non_exhaustive]
1321pub enum AttrPathspecError {
1322 #[error("attr requirement list is empty")]
1324 Empty,
1325 #[error("a pathspec may contain at most one attr clause")]
1327 MultipleAttrClauses,
1328 #[error("'{name}' is not a usable attribute name")]
1330 InvalidName {
1331 name: String,
1333 },
1334 #[error("attr value ends with a dangling escape")]
1336 DanglingEscape,
1337 #[error("attr values may only escape ','")]
1339 UnsupportedEscape,
1340}
1341
1342#[derive(Debug, Error, Clone, PartialEq, Eq)]
1344#[non_exhaustive]
1345pub enum PathOutsideRepoError {
1346 #[error("'{subpath}' is outside repository at '{repo_root}'")]
1348 OutsideRepository {
1349 path: String,
1351 subpath: String,
1353 repo_root: String,
1355 },
1356}
1357
1358#[derive(Debug, Error)]
1360#[non_exhaustive]
1361pub enum NotARepositoryReason {
1362 #[error("{}", crate::git_path::path_for_error_message(path))]
1364 NoRepositoryAt {
1365 path: std::path::PathBuf,
1367 },
1368 #[error(
1370 "invalid gitfile format: {} is not a regular file",
1371 crate::git_path::path_for_error_message(path)
1372 )]
1373 GitfileNotRegularFile {
1374 path: std::path::PathBuf,
1376 },
1377 #[error("invalid gitfile format")]
1379 GitfileMissingGitdir {
1380 path: std::path::PathBuf,
1382 },
1383 #[error("{error}")]
1385 GitfileUnreadable {
1386 path: std::path::PathBuf,
1388 error: std::io::Error,
1390 },
1391}
1392
1393pub(crate) fn maintenance_running_message(holder: &crate::maintenance::GcLockHolder) -> String {
1394 match (holder.pid, holder.host.as_deref()) {
1395 (Some(pid), Some(host)) => {
1396 format!("repository maintenance is already running (process {pid} on {host})")
1397 }
1398 (Some(pid), None) => format!("repository maintenance is already running (process {pid})"),
1399 _ => "repository maintenance is already running".to_owned(),
1400 }
1401}
1402
1403pub(crate) fn restore_unmerged_message(paths: &[String]) -> String {
1404 match paths {
1405 [path] => format!("path '{path}' is unmerged"),
1406 _ => format!(
1407 "paths are unmerged: {}",
1408 paths
1409 .iter()
1410 .map(|p| format!("'{p}'"))
1411 .collect::<Vec<_>>()
1412 .join(", ")
1413 ),
1414 }
1415}
1416
1417#[derive(Debug, Error)]
1422#[non_exhaustive]
1423pub enum ObjectReadFailure {
1424 #[error("I/O error: {0}")]
1426 Io(#[from] std::io::Error),
1427 #[error("zlib error: {detail}")]
1429 Zlib {
1430 detail: String,
1432 },
1433 #[error("corrupt object: {detail}")]
1435 CorruptObject {
1436 detail: String,
1438 },
1439 #[error("object stream ended after {actual} of {expected} bytes")]
1441 ObjectStreamTruncated {
1442 expected: u64,
1444 actual: u64,
1446 },
1447 #[error("unknown object type '{name}'")]
1449 UnknownObjectType {
1450 name: String,
1452 },
1453 #[error("header for {oid} too long, exceeds 32 bytes")]
1455 ObjectHeaderTooLong {
1456 oid: String,
1458 },
1459 #[error("delta chain too deep (limit {limit})")]
1461 DeltaChainTooDeep {
1462 limit: usize,
1464 },
1465 #[error("refusing to write invalid {kind} object: {}", .check.report_line())]
1467 InvalidObject {
1468 kind: crate::objects::ObjectKind,
1470 check: crate::fsck_standalone::FsckError,
1472 },
1473}
1474
1475impl ObjectReadFailure {
1476 pub(crate) fn try_from_object_read_error(err: Error) -> std::result::Result<Self, Error> {
1483 match err {
1484 Error::Io(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(Self::Io(e)),
1485 Error::Object(ObjectError::Zlib { detail }) => Ok(Self::Zlib { detail }),
1486 Error::Object(ObjectError::Corrupt { detail }) => Ok(Self::CorruptObject { detail }),
1487 Error::Object(ObjectError::StreamTruncated { expected, actual }) => {
1488 Ok(Self::ObjectStreamTruncated { expected, actual })
1489 }
1490 Error::Object(ObjectError::UnknownType { name }) => {
1491 Ok(Self::UnknownObjectType { name })
1492 }
1493 Error::Object(ObjectError::HeaderTooLong { oid }) => {
1494 Ok(Self::ObjectHeaderTooLong { oid })
1495 }
1496 Error::Object(ObjectError::DeltaChainTooDeep { limit }) => {
1497 Ok(Self::DeltaChainTooDeep { limit })
1498 }
1499 Error::Object(ObjectError::Invalid { kind, check }) => {
1500 Ok(Self::InvalidObject { kind, check })
1501 }
1502 other => Err(other),
1503 }
1504 }
1505}
1506
1507#[derive(Debug, Error)]
1524#[non_exhaustive]
1525pub enum Error {
1526 #[error(transparent)]
1528 Repository(#[from] RepositoryError),
1529
1530 #[error(transparent)]
1532 Object(#[from] ObjectError),
1533
1534 #[error(transparent)]
1536 Index(crate::index::IndexError),
1537
1538 #[error(transparent)]
1540 Ref(#[from] RefError),
1541
1542 #[error(transparent)]
1544 Revision(#[from] RevisionError),
1545
1546 #[error(transparent)]
1548 Config(#[from] ConfigError),
1549
1550 #[error(transparent)]
1552 Worktree(#[from] crate::worktree::WorktreeError),
1553
1554 #[error(transparent)]
1556 Diff(#[from] DiffError),
1557
1558 #[error(transparent)]
1560 Commit(crate::porcelain::commit_error::CommitError),
1561
1562 #[error(transparent)]
1564 Merge(crate::porcelain::merge_error::MergeError),
1565
1566 #[error(transparent)]
1568 History(crate::history::HistoryError),
1569
1570 #[error(transparent)]
1572 Stash(crate::porcelain::stash_error::StashError),
1573
1574 #[error(transparent)]
1576 Branch(#[from] crate::porcelain::branch_error::BranchError),
1577
1578 #[error(transparent)]
1580 Tag(#[from] crate::porcelain::tag::TagError),
1581
1582 #[error(transparent)]
1584 Notes(#[from] NotesError),
1585
1586 #[error(transparent)]
1588 Remote(crate::remote::RemoteError),
1589
1590 #[error(transparent)]
1592 Hook(crate::hooks::HookError),
1593
1594 #[error("I/O error: {0}")]
1596 Io(#[from] std::io::Error),
1597
1598 #[error(transparent)]
1606 LockHeld(#[from] LockHeldError),
1607
1608 #[error("operation cancelled")]
1613 Cancelled,
1614}
1615
1616impl Error {
1617 #[must_use]
1637 pub fn kind_name(&self) -> &'static str {
1638 match self {
1639 Self::Repository(e) => e.kind_name(),
1640 Self::Object(e) => e.kind_name(),
1641 Self::Index(e) => e.kind_name(),
1642 Self::Ref(e) => e.kind_name(),
1643 Self::Revision(e) => e.kind_name(),
1644 Self::Config(..) => "config",
1645 Self::Worktree(e) => e.kind_name(),
1646 Self::Diff(e) => e.kind_name(),
1647 Self::Commit(e) => e.kind_name(),
1648 Self::Merge(e) => e.kind_name(),
1649 Self::History(..) => "history",
1650 Self::Stash(e) => e.kind_name(),
1651 Self::Branch(e) => e.kind_name(),
1652 Self::Tag(e) => e.kind_name(),
1653 Self::Notes(e) => e.kind_name(),
1654 Self::Remote(e) => e.kind_name(),
1655 Self::Hook(..) => "hook",
1656 Self::Io(..) => "io",
1657 Self::LockHeld(..) => "lock_held",
1658 Self::Cancelled => "cancelled",
1659 }
1660 }
1661
1662 #[must_use]
1673 pub fn area(&self) -> &'static str {
1674 match self {
1675 Self::Repository(..) => "repository",
1676 Self::Object(..) => "object",
1677 Self::Index(..) => "index",
1678 Self::Ref(..) => "ref",
1679 Self::Revision(..) => "revision",
1680 Self::Config(..) => "config",
1681 Self::Worktree(..) => "worktree",
1682 Self::Diff(..) => "diff",
1683 Self::Commit(..) => "commit",
1684 Self::Merge(..) => "merge",
1685 Self::History(..) => "history",
1686 Self::Stash(..) => "stash",
1687 Self::Branch(..) => "branch",
1688 Self::Tag(..) => "tag",
1689 Self::Notes(..) => "notes",
1690 Self::Remote(..) => "remote",
1691 Self::Hook(..) => "hook",
1692 Self::Io(..) => "io",
1693 Self::LockHeld(..) => "lock_held",
1694 Self::Cancelled => "cancelled",
1695 }
1696 }
1697
1698 #[must_use]
1701 pub fn dirty_worktree(operation: WorktreeOperation, mut affected_paths: Vec<String>) -> Self {
1702 affected_paths.sort();
1703 affected_paths.dedup();
1704 Self::Worktree(crate::worktree::WorktreeError::DirtyWorktree {
1705 operation,
1706 paths: affected_paths,
1707 })
1708 }
1709
1710 #[must_use]
1713 pub fn would_overwrite(reason: OverwriteReason, mut affected_paths: Vec<String>) -> Self {
1714 affected_paths.sort();
1715 affected_paths.dedup();
1716 let message = match reason {
1717 OverwriteReason::LocalChanges => {
1718 "you have uncommitted changes — commit them before switching".into()
1719 }
1720 OverwriteReason::Untracked => {
1721 let first = affected_paths
1722 .first()
1723 .map(String::as_str)
1724 .unwrap_or("<path>");
1725 format!("untracked file '{first}' would be overwritten — move or remove it first")
1726 }
1727 };
1728 Self::Worktree(crate::worktree::WorktreeError::WouldOverwrite {
1729 reason,
1730 paths: affected_paths,
1731 message,
1732 })
1733 }
1734
1735 #[must_use]
1737 pub fn remote_unreadable(url: impl Into<String>, reason: RemoteUnreadableReason) -> Self {
1738 Self::Remote(crate::remote::RemoteError::unreadable(url, reason))
1739 }
1740
1741 #[must_use]
1743 pub fn is_remote_unreadable(&self) -> bool {
1744 match self {
1745 Self::Remote(e) => e.is_remote_unreadable(),
1746 _ => false,
1747 }
1748 }
1749
1750 #[must_use]
1752 pub fn lock_held(&self) -> Option<&LockHeldError> {
1753 match self {
1754 Self::LockHeld(err) => Some(err),
1755 _ => None,
1756 }
1757 }
1758
1759 #[must_use]
1761 pub fn path_io(&self) -> Option<PathIoError> {
1762 let io = match self {
1763 Self::Worktree(crate::worktree::WorktreeError::PathIo(io)) => io,
1764 Self::Repository(RepositoryError::GitDirPathIo(io)) => io,
1765 _ => return None,
1766 };
1767 Some(PathIoError {
1768 operation: io.operation,
1769 path: io.path.clone(),
1770 source: preserve_io_error(&io.source),
1771 })
1772 }
1773
1774 #[must_use]
1778 pub fn is_worktree_file_in_use(&self) -> bool {
1779 matches!(
1780 self,
1781 Self::Worktree(crate::worktree::WorktreeError::PathIo(io))
1782 if matches!(io.operation, PathIoOperation::Worktree(_))
1783 && crate::worktree::io_error::is_file_in_use(&io.source)
1784 )
1785 }
1786
1787 #[must_use]
1790 pub fn is_git_dir_file_in_use(&self) -> bool {
1791 match self {
1792 Self::Repository(RepositoryError::GitDirPathIo(io)) => match io.operation {
1793 PathIoOperation::GitDir(operation) => {
1794 crate::git_dir::io_error::is_git_dir_transient_contention(operation, &io.source)
1795 }
1796 PathIoOperation::Worktree(_) => false,
1797 },
1798 _ => false,
1799 }
1800 }
1801
1802 #[must_use]
1804 pub fn is_cancelled(&self) -> bool {
1805 match self {
1806 Self::Cancelled => true,
1807 Self::History(e) => e.is_cancelled(),
1808 Self::Worktree(e) => e.is_cancelled(),
1809 Self::Io(err)
1810 if err.to_string() == crate::transport::stateless_http::TRANSPORT_IO_CANCELLED =>
1811 {
1812 true
1813 }
1814 _ => false,
1815 }
1816 }
1817
1818 #[must_use]
1821 pub fn is_damaged_object(&self) -> bool {
1822 match self {
1823 Self::Object(
1824 ObjectError::Zlib { .. }
1825 | ObjectError::Corrupt { .. }
1826 | ObjectError::CorruptLoose { .. }
1827 | ObjectError::CorruptPacked { .. },
1828 ) => true,
1829 Self::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => true,
1830 _ => false,
1831 }
1832 }
1833
1834 pub(crate) fn is_object_read_wrap_source(&self) -> bool {
1835 match self {
1836 Self::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => true,
1837 Self::Object(
1838 ObjectError::Zlib { .. }
1839 | ObjectError::Corrupt { .. }
1840 | ObjectError::StreamTruncated { .. }
1841 | ObjectError::UnknownType { .. }
1842 | ObjectError::HeaderTooLong { .. }
1843 | ObjectError::DeltaChainTooDeep { .. }
1844 | ObjectError::Invalid { .. },
1845 ) => true,
1846 _ => false,
1847 }
1848 }
1849
1850 #[must_use]
1852 pub(crate) fn wrap_loose_read_failure(
1853 oid: crate::objects::ObjectId,
1854 path: std::path::PathBuf,
1855 err: Error,
1856 ) -> Error {
1857 if matches!(err, Self::Object(ObjectError::CorruptLoose { .. })) {
1858 return err;
1859 }
1860 if !err.is_object_read_wrap_source() {
1861 return err;
1862 }
1863 match ObjectReadFailure::try_from_object_read_error(err) {
1864 Ok(source) => Self::Object(ObjectError::CorruptLoose {
1865 oid,
1866 path,
1867 source: Box::new(source),
1868 }),
1869 Err(err) => err,
1870 }
1871 }
1872
1873 #[must_use]
1875 pub(crate) fn wrap_packed_read_failure(
1876 oid: crate::objects::ObjectId,
1877 pack: std::path::PathBuf,
1878 offset: u64,
1879 err: Error,
1880 ) -> Error {
1881 if matches!(err, Self::Object(ObjectError::CorruptPacked { .. })) {
1882 return err;
1883 }
1884 if !err.is_object_read_wrap_source() {
1885 return err;
1886 }
1887 match ObjectReadFailure::try_from_object_read_error(err) {
1888 Ok(source) => Self::Object(ObjectError::CorruptPacked {
1889 oid,
1890 pack,
1891 offset,
1892 source: Box::new(source),
1893 }),
1894 Err(err) => err,
1895 }
1896 }
1897
1898 #[must_use]
1900 pub fn invalid_path_component(
1901 path: impl Into<String>,
1902 reason: crate::path_validate::PathComponentError,
1903 ) -> Self {
1904 Self::Worktree(crate::worktree::WorktreeError::InvalidPathComponent {
1905 path: path.into(),
1906 reason,
1907 })
1908 }
1909
1910 #[must_use]
1912 pub fn wants_fatal_prefix(&self) -> bool {
1913 use crate::worktree::WorktreeError;
1914 matches!(
1915 self,
1916 Error::Config(_)
1917 | Error::Worktree(
1918 WorktreeError::Submodule(_)
1919 | WorktreeError::Filter(_)
1920 | WorktreeError::OutsideRepo(_)
1921 )
1922 | Error::Ref(RefError::Lock(_))
1923 )
1924 }
1925
1926 #[must_use]
1928 pub fn git_stderr_message(&self) -> String {
1929 match self {
1930 Error::Diff(DiffError::Apply(ApplyError::CorruptPatch { .. })) => {
1931 crate::diagnostics::error_line(&self.to_string())
1932 }
1933 Error::Worktree(crate::worktree::WorktreeError::WouldOverwrite { message, .. }) => {
1934 message.clone()
1935 }
1936 e if e.wants_fatal_prefix() => crate::diagnostics::fatal_line(&e.to_string()),
1937 other => other.to_string(),
1938 }
1939 }
1940}
1941
1942impl From<crate::hooks::HookError> for Error {
1943 fn from(err: crate::hooks::HookError) -> Self {
1944 Self::Hook(err)
1945 }
1946}
1947
1948impl From<crate::porcelain::commit_error::CommitError> for Error {
1949 fn from(err: crate::porcelain::commit_error::CommitError) -> Self {
1950 Self::Commit(err)
1951 }
1952}
1953
1954impl From<crate::porcelain::merge_error::MergeError> for Error {
1955 fn from(err: crate::porcelain::merge_error::MergeError) -> Self {
1956 Self::Merge(err)
1957 }
1958}
1959
1960impl From<crate::history::HistoryError> for Error {
1961 fn from(err: crate::history::HistoryError) -> Self {
1962 Self::History(err)
1963 }
1964}
1965
1966impl From<crate::porcelain::stash_error::StashError> for Error {
1967 fn from(err: crate::porcelain::stash_error::StashError) -> Self {
1968 Self::Stash(err)
1969 }
1970}
1971
1972impl From<crate::remote::RemoteError> for Error {
1973 fn from(err: crate::remote::RemoteError) -> Self {
1974 Self::Remote(err)
1975 }
1976}
1977
1978impl From<crate::ident::CommitIdentityError> for Error {
1979 fn from(err: crate::ident::CommitIdentityError) -> Self {
1980 crate::porcelain::commit_error::CommitError::from(err).into()
1981 }
1982}
1983
1984impl From<crate::refs::store::RefStoreError> for Error {
1985 fn from(err: crate::refs::store::RefStoreError) -> Self {
1986 match err {
1987 crate::refs::store::RefStoreError::GitDirPathIo {
1988 path,
1989 operation,
1990 os_error,
1991 } => RepositoryError::git_dir_path_io(
1992 path,
1993 operation,
1994 crate::refs::store::RefStoreError::git_dir_io_source(os_error),
1995 )
1996 .into(),
1997 crate::refs::store::RefStoreError::Hook(hook) => Error::Hook(hook.into_hook_error()),
1998 other => Error::Ref(RefError::Store(other)),
1999 }
2000 }
2001}
2002
2003impl From<RefLockError> for Error {
2004 fn from(err: RefLockError) -> Self {
2005 Self::Ref(RefError::Lock(err))
2006 }
2007}
2008
2009impl From<crate::reftable::ReftableError> for Error {
2010 fn from(err: crate::reftable::ReftableError) -> Self {
2011 Self::Ref(RefError::Reftable(err))
2012 }
2013}
2014
2015impl From<crate::rev_parse_error::RevParseError> for Error {
2016 fn from(err: crate::rev_parse_error::RevParseError) -> Self {
2017 Self::Revision(RevisionError::Parse(err))
2018 }
2019}
2020
2021impl From<crate::rev_list_error::RevListError> for Error {
2022 fn from(err: crate::rev_list_error::RevListError) -> Self {
2023 Self::Revision(RevisionError::List(err))
2024 }
2025}
2026
2027impl From<ApplyError> for Error {
2028 fn from(err: ApplyError) -> Self {
2029 match err {
2030 ApplyError::Cancelled => Self::Cancelled,
2031 other => Self::Diff(DiffError::Apply(other)),
2032 }
2033 }
2034}
2035
2036impl From<crate::userdiff::FuncnamePatternError> for Error {
2037 fn from(err: crate::userdiff::FuncnamePatternError) -> Self {
2038 Self::Diff(DiffError::FuncnamePattern(err))
2039 }
2040}
2041
2042impl From<crate::porcelain::hunk_select::HunkSelectError> for Error {
2043 fn from(err: crate::porcelain::hunk_select::HunkSelectError) -> Self {
2044 Self::Diff(DiffError::HunkSelection(err))
2045 }
2046}
2047
2048impl From<FilterError> for Error {
2049 fn from(err: FilterError) -> Self {
2050 Self::Worktree(crate::worktree::WorktreeError::Filter(err))
2051 }
2052}
2053
2054impl From<SubmoduleError> for Error {
2055 fn from(err: SubmoduleError) -> Self {
2056 Self::Worktree(crate::worktree::WorktreeError::Submodule(err))
2057 }
2058}
2059
2060impl From<PathOutsideRepoError> for Error {
2061 fn from(err: PathOutsideRepoError) -> Self {
2062 Self::Worktree(crate::worktree::WorktreeError::OutsideRepo(err))
2063 }
2064}
2065
2066impl From<PathspecFromFileParseError> for Error {
2067 fn from(err: PathspecFromFileParseError) -> Self {
2068 Self::Worktree(crate::worktree::WorktreeError::PathspecFromFile(err))
2069 }
2070}
2071
2072impl From<crate::bitmap_walk::BitmapWalkError> for Error {
2073 fn from(err: crate::bitmap_walk::BitmapWalkError) -> Self {
2074 Self::Object(ObjectError::BitmapWalk(err))
2075 }
2076}
2077
2078impl From<crate::bitmap_walk::BitmapWalkUnsupported> for Error {
2079 fn from(err: crate::bitmap_walk::BitmapWalkUnsupported) -> Self {
2080 Self::Object(ObjectError::BitmapWalk(err.into()))
2081 }
2082}
2083
2084impl From<crate::pack_bitmap::BitmapError> for Error {
2085 fn from(err: crate::pack_bitmap::BitmapError) -> Self {
2086 Self::Object(ObjectError::BitmapWalk(err.into()))
2087 }
2088}
2089
2090impl From<crate::object_inspect::ResolveError> for Error {
2091 fn from(err: crate::object_inspect::ResolveError) -> Self {
2092 Self::Revision(RevisionError::Resolve(err))
2093 }
2094}
2095
2096impl From<MidxError> for Error {
2097 fn from(err: MidxError) -> Self {
2098 Self::Object(ObjectError::Midx(err))
2099 }
2100}
2101
2102impl From<crate::offload::OffloadError> for Error {
2103 fn from(err: crate::offload::OffloadError) -> Self {
2104 Self::Object(ObjectError::Offload(err))
2105 }
2106}
2107
2108impl From<crate::objects::TreeEntryError> for Error {
2109 fn from(err: crate::objects::TreeEntryError) -> Self {
2110 Self::Object(ObjectError::InvalidTreeEntry(err))
2111 }
2112}
2113
2114impl From<crate::ident::SignatureError> for Error {
2115 fn from(err: crate::ident::SignatureError) -> Self {
2116 Self::Object(ObjectError::InvalidSignature(err))
2117 }
2118}
2119
2120impl From<crate::config::ident_resolve::IdentityError> for Error {
2121 fn from(err: crate::config::ident_resolve::IdentityError) -> Self {
2122 Self::Commit(crate::porcelain::commit_error::CommitError::Identity(err))
2123 }
2124}
2125
2126impl From<crate::ident::AuthorArgError> for Error {
2127 fn from(err: crate::ident::AuthorArgError) -> Self {
2128 Self::History(crate::history::HistoryError::InvalidAuthor(err))
2129 }
2130}
2131
2132impl From<crate::change_id::ChangeIdError> for Error {
2133 fn from(err: crate::change_id::ChangeIdError) -> Self {
2134 Self::Commit(crate::porcelain::commit_error::CommitError::ChangeId(err))
2135 }
2136}
2137
2138impl From<crate::tree_sha256::TreeSha256ClaimError> for Error {
2139 fn from(err: crate::tree_sha256::TreeSha256ClaimError) -> Self {
2140 Self::Tag(crate::porcelain::tag::TagError::TreeSha256Claim(err))
2141 }
2142}
2143
2144impl From<Cancelled> for Error {
2145 fn from(_: Cancelled) -> Self {
2146 Self::Cancelled
2147 }
2148}
2149
2150impl From<crate::worktree::LinkedWorktreeError> for Error {
2151 fn from(value: crate::worktree::LinkedWorktreeError) -> Self {
2152 Self::Worktree(value.into())
2153 }
2154}
2155
2156impl From<PathIoError> for Error {
2157 fn from(value: PathIoError) -> Self {
2158 match value.operation {
2159 PathIoOperation::Worktree(_) => {
2160 Self::Worktree(crate::worktree::WorktreeError::PathIo(value))
2161 }
2162 PathIoOperation::GitDir(_) => Self::Repository(RepositoryError::GitDirPathIo(value)),
2163 }
2164 }
2165}
2166
2167impl From<crate::lockfile::LockError> for Error {
2168 #[cold]
2171 fn from(err: crate::lockfile::LockError) -> Self {
2172 use crate::lockfile::{LockError, LockHolder};
2173 match err {
2174 LockError::Held { path } => Self::LockHeld(LockHeldError {
2175 holder: LockHolder::read(&path),
2176 path,
2177 }),
2178 LockError::Io { source, .. } => Self::Io(source),
2179 }
2180 }
2181}
2182
2183impl From<crate::serve::ServeError> for Error {
2184 fn from(err: crate::serve::ServeError) -> Self {
2185 Self::Remote(crate::remote::RemoteError::Serve(err))
2186 }
2187}
2188
2189impl From<crate::snapshot_checkout::CheckoutError> for Error {
2190 fn from(err: crate::snapshot_checkout::CheckoutError) -> Self {
2191 Self::Remote(crate::remote::RemoteError::Snapshot(err))
2192 }
2193}
2194
2195impl From<crate::clone::CloneError> for Error {
2196 fn from(err: crate::clone::CloneError) -> Self {
2197 Self::Remote(crate::remote::RemoteError::Clone(Box::new(err)))
2198 }
2199}
2200
2201impl From<crate::porcelain::pull::PullError> for Error {
2202 fn from(err: crate::porcelain::pull::PullError) -> Self {
2203 Self::Merge(crate::porcelain::merge_error::MergeError::Pull(err))
2204 }
2205}
2206
2207impl From<crate::remote::push_plan::PushPlanError> for Error {
2208 fn from(err: crate::remote::push_plan::PushPlanError) -> Self {
2209 Self::Remote(crate::remote::RemoteError::PushPlan(err))
2210 }
2211}
2212
2213impl From<crate::history::RebaseSessionError> for Error {
2214 fn from(err: crate::history::RebaseSessionError) -> Self {
2215 match err {
2216 crate::history::RebaseSessionError::NothingToCommit => {
2217 Self::Commit(crate::porcelain::commit_error::CommitError::NothingToCommit)
2218 }
2219 other => Self::History(crate::history::HistoryError::RebaseSession(Box::new(other))),
2220 }
2221 }
2222}
2223
2224impl From<crate::porcelain::stash_error::StashPushValidationError> for Error {
2225 fn from(err: crate::porcelain::stash_error::StashPushValidationError) -> Self {
2226 Self::Stash(crate::porcelain::stash_error::StashError::PushValidation(
2227 err,
2228 ))
2229 }
2230}
2231
2232impl From<crate::bundle::BundleError> for Error {
2233 fn from(err: crate::bundle::BundleError) -> Self {
2234 use crate::bundle::BundleError;
2235 match err {
2236 BundleError::Cancelled => Self::Cancelled,
2237 BundleError::ObjectNotFound { name } => Self::Object(ObjectError::NotFound { name }),
2238 other => Self::Remote(crate::remote::RemoteError::Bundle(other)),
2239 }
2240 }
2241}
2242
2243impl From<crate::fetch_request::FetchRefspecError> for Error {
2244 fn from(e: crate::fetch_request::FetchRefspecError) -> Self {
2245 Self::Remote(crate::remote::RemoteError::FetchRefspec(e))
2246 }
2247}
2248
2249pub type Result<T> = std::result::Result<T, Error>;
2251
2252#[cfg(feature = "serde-models")]
2255impl serde::Serialize for Error {
2256 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2257 where
2258 S: serde::Serializer,
2259 {
2260 use crate::worktree::WorktreeError;
2261 use serde::ser::SerializeStruct;
2262
2263 match self {
2264 Self::LockHeld(lock) => {
2265 let mut out = serializer.serialize_struct("Error", 5)?;
2266 out.serialize_field("kind", self.kind_name())?;
2267 out.serialize_field("area", self.area())?;
2268 out.serialize_field("message", &self.to_string())?;
2269 out.serialize_field(
2270 "path",
2271 &crate::git_path::user_display_path(lock.path.as_path()),
2272 )?;
2273 if let Some(holder) = lock.holder {
2274 out.serialize_field(
2275 "holder",
2276 &LockHolderSerde {
2277 pid: holder.pid,
2278 running: holder.running,
2279 },
2280 )?;
2281 }
2282 out.end()
2283 }
2284 Self::Worktree(WorktreeError::WouldOverwrite { reason, paths, .. }) => {
2285 let mut out = serializer.serialize_struct("Error", 5)?;
2286 out.serialize_field("kind", self.kind_name())?;
2287 out.serialize_field("area", self.area())?;
2288 out.serialize_field("message", &self.to_string())?;
2289 out.serialize_field("reason", &reason.to_string())?;
2290 out.serialize_field("paths", paths)?;
2291 out.end()
2292 }
2293 Self::Worktree(WorktreeError::DirtyWorktree { operation, paths }) => {
2294 let mut out = serializer.serialize_struct("Error", 5)?;
2295 out.serialize_field("kind", self.kind_name())?;
2296 out.serialize_field("area", self.area())?;
2297 out.serialize_field("message", &self.to_string())?;
2298 out.serialize_field("operation", &operation.to_string())?;
2299 out.serialize_field("paths", paths)?;
2300 out.end()
2301 }
2302 Self::Worktree(WorktreeError::UnmergedConflictMarkers { paths }) => {
2303 let mut out = serializer.serialize_struct("Error", 4)?;
2304 out.serialize_field("kind", self.kind_name())?;
2305 out.serialize_field("area", self.area())?;
2306 out.serialize_field("message", &self.to_string())?;
2307 out.serialize_field("paths", paths)?;
2308 out.end()
2309 }
2310 Self::Stash(stash) => stash.serialize(serializer),
2311 _ => {
2312 let mut out = serializer.serialize_struct("Error", 3)?;
2313 out.serialize_field("kind", self.kind_name())?;
2314 out.serialize_field("area", self.area())?;
2315 out.serialize_field("message", &self.to_string())?;
2316 out.end()
2317 }
2318 }
2319 }
2320}
2321
2322#[cfg(test)]
2323mod object_read_failure_tests {
2324 use super::{Error, ObjectError, ObjectReadFailure};
2325
2326 #[test]
2327 fn try_from_object_read_error_rejects_unrelated_umbrella_variants() {
2328 assert!(matches!(
2329 ObjectReadFailure::try_from_object_read_error(Error::Cancelled),
2330 Err(Error::Cancelled)
2331 ));
2332 }
2333
2334 #[test]
2335 fn try_from_object_read_error_maps_decode_variants() {
2336 assert!(matches!(
2337 ObjectReadFailure::try_from_object_read_error(Error::Object(ObjectError::Zlib {
2338 detail: "bad".into()
2339 })),
2340 Ok(ObjectReadFailure::Zlib { .. })
2341 ));
2342 }
2343}
2344
2345#[cfg(test)]
2346mod umbrella_area_tests {
2347 use super::{
2348 ConfigError, DiffError, Error, ErrorSummary, LockHeldError, NotesError, ObjectError,
2349 RefError, RepositoryError, RevisionError,
2350 };
2351 use crate::history::HistoryError;
2352 use crate::hooks::{HookError, HookOutput};
2353 use crate::index::IndexError;
2354 use crate::porcelain::branch_error::BranchError;
2355 use crate::porcelain::commit_error::CommitError;
2356 use crate::porcelain::merge_error::MergeError;
2357 use crate::porcelain::stash_error::StashError;
2358 use crate::porcelain::tag::TagError;
2359 use crate::remote::RemoteError;
2360 use crate::worktree::WorktreeError;
2361
2362 fn area_by_variant(err: &Error) -> &'static str {
2365 match err {
2366 Error::Repository(_) => "repository",
2367 Error::Object(_) => "object",
2368 Error::Index(_) => "index",
2369 Error::Ref(_) => "ref",
2370 Error::Revision(_) => "revision",
2371 Error::Config(_) => "config",
2372 Error::Worktree(_) => "worktree",
2373 Error::Diff(_) => "diff",
2374 Error::Commit(_) => "commit",
2375 Error::Merge(_) => "merge",
2376 Error::History(_) => "history",
2377 Error::Stash(_) => "stash",
2378 Error::Branch(_) => "branch",
2379 Error::Tag(_) => "tag",
2380 Error::Notes(_) => "notes",
2381 Error::Remote(_) => "remote",
2382 Error::Hook(_) => "hook",
2383 Error::Io(_) => "io",
2384 Error::LockHeld(_) => "lock_held",
2385 Error::Cancelled => "cancelled",
2386 }
2387 }
2388
2389 const AREAS: &[&str] = &[
2390 "repository",
2391 "object",
2392 "index",
2393 "ref",
2394 "revision",
2395 "config",
2396 "worktree",
2397 "diff",
2398 "commit",
2399 "merge",
2400 "history",
2401 "stash",
2402 "branch",
2403 "tag",
2404 "notes",
2405 "remote",
2406 "hook",
2407 "io",
2408 "lock_held",
2409 "cancelled",
2410 ];
2411
2412 fn one_error_per_area() -> Vec<Error> {
2413 vec![
2414 Error::Repository(RepositoryError::RequiresWorkTree),
2415 Error::Object(ObjectError::InvalidId {
2416 input: "xyz".into(),
2417 }),
2418 Error::Index(IndexError::CacheTreeCorrupt),
2419 Error::Ref(RefError::UnbornHead),
2420 Error::Revision(RevisionError::NotFound {
2421 spec: "nope".into(),
2422 }),
2423 Error::Config(ConfigError::ConfigCacheLockPoisoned),
2424 Error::Worktree(WorktreeError::RemovePathsRequired),
2425 Error::Diff(DiffError::BlameWorktreeBareRepository),
2426 Error::Commit(CommitError::EmptyCommitMessage),
2427 Error::Merge(MergeError::NotFastForward),
2428 Error::History(HistoryError::EmptyMessage),
2429 Error::Stash(StashError::NoInitialCommit),
2430 Error::Branch(BranchError::NoPreviousBranch),
2431 Error::Tag(TagError::EmptyMessage),
2432 Error::Notes(NotesError::AlreadyExists {
2433 object: crate::objects::ObjectId::zero(),
2434 }),
2435 Error::Remote(RemoteError::HttpUnavailable),
2436 Error::Hook(HookError::Failed {
2437 hook_name: "pre-commit".into(),
2438 status: 1,
2439 output: HookOutput::default(),
2440 }),
2441 Error::Io(std::io::Error::other("disk")),
2442 Error::LockHeld(LockHeldError {
2443 path: ".git/index.lock".into(),
2444 holder: None,
2445 }),
2446 Error::Cancelled,
2447 ]
2448 }
2449
2450 #[test]
2451 fn umbrella_error_has_one_variant_per_area() {
2452 let samples = one_error_per_area();
2453 assert_eq!(samples.len(), AREAS.len());
2454 let mut seen = std::collections::HashSet::new();
2455 for (err, expected) in samples.iter().zip(AREAS) {
2456 assert_eq!(area_by_variant(err), *expected);
2457 assert_eq!(err.area(), *expected, "{err:?}");
2458 assert!(seen.insert(err.area()), "area {expected} listed twice");
2459 assert!(!err.kind_name().is_empty());
2460 }
2461 }
2462
2463 #[test]
2464 fn area_errors_convert_into_their_umbrella_variant() {
2465 let cases: Vec<(Error, &str)> = vec![
2466 (RepositoryError::RequiresWorkTree.into(), "repository"),
2467 (RefError::UnbornHead.into(), "ref"),
2468 (
2469 RevisionError::NotFound { spec: "x".into() }.into(),
2470 "revision",
2471 ),
2472 (CommitError::EmptyCommitMessage.into(), "commit"),
2473 (MergeError::NotFastForward.into(), "merge"),
2474 (HistoryError::EmptyMessage.into(), "history"),
2475 (StashError::NoInitialCommit.into(), "stash"),
2476 (BranchError::NoPreviousBranch.into(), "branch"),
2477 (TagError::EmptyMessage.into(), "tag"),
2478 (RemoteError::HttpUnavailable.into(), "remote"),
2479 (IndexError::CacheTreeCorrupt.into(), "index"),
2480 (WorktreeError::RemovePathsRequired.into(), "worktree"),
2481 ];
2482 for (err, area) in cases {
2483 assert_eq!(err.area(), area, "{err:?}");
2484 }
2485 }
2486
2487 #[test]
2488 fn error_summary_keeps_kind_area_message_and_cancellation() {
2489 let summary = ErrorSummary::from(&Error::Ref(RefError::UnbornHead));
2490 assert_eq!(summary.kind(), Error::Ref(RefError::UnbornHead).kind_name());
2491 assert_eq!(summary.area(), "ref");
2492 assert_eq!(
2493 summary.message(),
2494 Error::Ref(RefError::UnbornHead).to_string()
2495 );
2496 assert_eq!(summary.to_string(), summary.message());
2497 assert!(!summary.is_cancelled());
2498
2499 let cancelled = ErrorSummary::from(Error::Cancelled);
2500 assert!(cancelled.is_cancelled());
2501 assert_eq!(cancelled.kind(), "cancelled");
2502 assert_eq!(cancelled.area(), "cancelled");
2503 assert_eq!(cancelled.clone(), cancelled);
2504 assert_eq!(
2505 std::mem::size_of::<ErrorSummary>(),
2506 std::mem::size_of::<usize>()
2507 );
2508 }
2509}
2510
2511#[cfg(feature = "serde-models")]
2512#[derive(serde::Serialize)]
2513struct LockHolderSerde {
2514 pid: u64,
2515 running: bool,
2516}