1use git2::{ErrorClass, ErrorCode};
7use std::path::PathBuf;
8use thiserror::Error;
9
10pub type Git2DBResult<T> = std::result::Result<T, Git2DBError>;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum LfsErrorKind {
16 InvalidPointer,
18 ParseError,
20 HashConversion,
22 MissingXetMerkle,
30 SizeMismatch,
32 HashMismatch,
34 SmudgeFailed,
36 IoError,
38 NotInRepository,
40}
41
42#[derive(Error, Debug)]
44pub enum Git2DBError {
45 #[error("Git operation failed: {message} (class: {class:?}, code: {code:?})")]
47 GitOperation {
48 class: ErrorClass,
49 code: ErrorCode,
50 message: String,
51 recoverable: bool,
52 },
53
54 #[error("Repository error at {path:?}: {message}")]
56 Repository { path: PathBuf, message: String },
57
58 #[error("Submodule operation failed for '{name}': {message}")]
60 Submodule { name: String, message: String },
61
62 #[error("Reference resolution failed for '{reference}': {message}")]
64 Reference { reference: String, message: String },
65
66 #[error("Authentication failed for {url}: {message}")]
68 Authentication { url: String, message: String },
69
70 #[error("Network operation failed: {message}")]
72 Network { message: String },
73
74 #[error("Configuration error: {message}")]
76 Configuration { message: String },
77
78 #[error("Invalid path: {path:?} - {message}")]
80 InvalidPath { path: PathBuf, message: String },
81
82 #[error("Invalid repository '{name}': {message}")]
84 InvalidRepository { name: String, message: String },
85
86 #[error("Worktree already exists at {path:?}. Use 'remove' to delete it first.")]
88 WorktreeExists { path: PathBuf },
89
90 #[error("Operation cancelled: {operation}")]
92 Cancelled { operation: String },
93
94 #[error("Invalid operation: {message}")]
96 InvalidOperation { message: String },
97
98 #[error("Internal error: {message}")]
100 Internal { message: String },
101
102 #[error("{0}")]
106 MergeConflictReport(#[from] crate::merge::ConflictReport),
107
108 #[error("LFS error ({kind:?}): {message}")]
110 Lfs { kind: LfsErrorKind, message: String },
111
112 #[error("IO error: {0}")]
114 Io(#[from] std::io::Error),
115
116 #[error("JSON error: {0}")]
118 Json(#[from] serde_json::Error),
119
120 #[error("External error: {0}")]
122 External(#[from] anyhow::Error),
123}
124
125impl Git2DBError {
126 pub fn message(&self) -> String {
128 match self {
129 Self::GitOperation { message, .. }
130 | Self::Repository { message, .. }
131 | Self::Submodule { message, .. }
132 | Self::Reference { message, .. }
133 | Self::Authentication { message, .. }
134 | Self::Network { message, .. }
135 | Self::Configuration { message, .. }
136 | Self::InvalidPath { message, .. }
137 | Self::InvalidRepository { message, .. }
138 | Self::InvalidOperation { message }
139 | Self::Internal { message }
140 | Self::Lfs { message, .. } => message.clone(),
141 Self::MergeConflictReport(report) => report.to_string(),
142 Self::WorktreeExists { path } => {
143 format!("Worktree already exists at {}", path.display())
144 }
145 Self::Cancelled { operation } => format!("Operation cancelled: {operation}"),
146 Self::Io(e) => e.to_string(),
147 Self::Json(e) => e.to_string(),
148 Self::External(e) => e.to_string(),
149 }
150 }
151
152 pub fn class(&self) -> Option<ErrorClass> {
154 match self {
155 Self::GitOperation { class, .. } => Some(*class),
156 _ => None,
157 }
158 }
159
160 pub fn code(&self) -> Option<ErrorCode> {
162 match self {
163 Self::GitOperation { code, .. } => Some(*code),
164 _ => None,
165 }
166 }
167
168 pub fn from_git_error(err: git2::Error) -> Self {
170 let class = err.class();
171 let code = err.code();
172 let message = err.message().to_owned();
173
174 let recoverable = matches!(class, ErrorClass::Net | ErrorClass::Http | ErrorClass::Ssh);
175
176 Self::GitOperation {
177 class,
178 code,
179 message,
180 recoverable,
181 }
182 }
183
184 pub fn repository<P: Into<PathBuf>, S: Into<String>>(path: P, message: S) -> Self {
186 Self::Repository {
187 path: path.into(),
188 message: message.into(),
189 }
190 }
191
192 pub fn submodule<N: Into<String>, M: Into<String>>(name: N, message: M) -> Self {
194 Self::Submodule {
195 name: name.into(),
196 message: message.into(),
197 }
198 }
199
200 pub fn reference<R: Into<String>, M: Into<String>>(reference: R, message: M) -> Self {
202 Self::Reference {
203 reference: reference.into(),
204 message: message.into(),
205 }
206 }
207
208 pub fn authentication<U: Into<String>, M: Into<String>>(url: U, message: M) -> Self {
210 Self::Authentication {
211 url: url.into(),
212 message: message.into(),
213 }
214 }
215
216 pub fn network<S: Into<String>>(message: S) -> Self {
218 Self::Network {
219 message: message.into(),
220 }
221 }
222
223 pub fn configuration<S: Into<String>>(message: S) -> Self {
225 Self::Configuration {
226 message: message.into(),
227 }
228 }
229
230 pub fn invalid_path<P: Into<PathBuf>, M: Into<String>>(path: P, message: M) -> Self {
232 Self::InvalidPath {
233 path: path.into(),
234 message: message.into(),
235 }
236 }
237
238 pub fn invalid_repository<N: Into<String>, M: Into<String>>(name: N, message: M) -> Self {
240 Self::InvalidRepository {
241 name: name.into(),
242 message: message.into(),
243 }
244 }
245
246 pub fn worktree_exists<P: Into<PathBuf>>(path: P) -> Self {
248 Self::WorktreeExists { path: path.into() }
249 }
250
251 pub fn is_worktree_exists(&self) -> bool {
253 matches!(self, Self::WorktreeExists { .. })
254 }
255
256 pub fn cancelled<S: Into<String>>(operation: S) -> Self {
258 Self::Cancelled {
259 operation: operation.into(),
260 }
261 }
262
263 pub fn invalid_operation<S: Into<String>>(message: S) -> Self {
265 Self::InvalidOperation {
266 message: message.into(),
267 }
268 }
269
270 pub fn internal<S: Into<String>>(message: S) -> Self {
272 Self::Internal {
273 message: message.into(),
274 }
275 }
276
277 pub fn lfs<S: Into<String>>(kind: LfsErrorKind, message: S) -> Self {
279 Self::Lfs {
280 kind,
281 message: message.into(),
282 }
283 }
284
285 pub fn lfs_kind(&self) -> Option<LfsErrorKind> {
287 match self {
288 Self::Lfs { kind, .. } => Some(*kind),
289 _ => None,
290 }
291 }
292
293 pub fn merge_conflict<S: Into<String>>(message: S) -> Self {
295 Self::GitOperation {
296 class: ErrorClass::Merge,
297 code: ErrorCode::Conflict,
298 message: message.into(),
299 recoverable: true,
300 }
301 }
302
303 pub fn is_recoverable(&self) -> bool {
305 match self {
306 Self::GitOperation { recoverable, .. } => *recoverable,
307 Self::Network { .. } | Self::Authentication { .. } => true,
308 _ => false,
309 }
310 }
311}
312
313impl From<git2::Error> for Git2DBError {
314 fn from(err: git2::Error) -> Self {
315 Self::from_git_error(err)
316 }
317}
318
319#[macro_export]
321macro_rules! repo_error {
322 ($path:expr, $msg:expr) => {
323 $crate::errors::Git2DBError::repository($path, $msg)
324 };
325 ($path:expr, $fmt:expr, $($arg:tt)*) => {
326 $crate::errors::Git2DBError::repository($path, format!($fmt, $($arg)*))
327 };
328}
329
330#[macro_export]
332macro_rules! submodule_error {
333 ($name:expr, $msg:expr) => {
334 $crate::errors::Git2DBError::submodule($name, $msg)
335 };
336 ($name:expr, $fmt:expr, $($arg:tt)*) => {
337 $crate::errors::Git2DBError::submodule($name, format!($fmt, $($arg)*))
338 };
339}
340
341#[macro_export]
343macro_rules! ref_error {
344 ($reference:expr, $msg:expr) => {
345 $crate::errors::Git2DBError::reference($reference, $msg)
346 };
347 ($reference:expr, $fmt:expr, $($arg:tt)*) => {
348 $crate::errors::Git2DBError::reference($reference, format!($fmt, $($arg)*))
349 };
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn test_git_operation_error_classification() {
358 let net_error =
360 git2::Error::new(ErrorCode::GenericError, ErrorClass::Net, "Network timeout");
361 let err = Git2DBError::from_git_error(net_error);
362
363 if let Git2DBError::GitOperation {
364 class,
365 code,
366 recoverable,
367 ..
368 } = err
369 {
370 assert_eq!(class, ErrorClass::Net);
371 assert_eq!(code, ErrorCode::GenericError);
372 assert!(recoverable);
373 } else {
374 panic!("Expected GitOperation error");
375 }
376 }
377
378 #[test]
379 fn test_git_operation_non_recoverable_errors() {
380 let repo_error = git2::Error::new(
382 ErrorCode::NotFound,
383 ErrorClass::Repository,
384 "Repository not found",
385 );
386 let err = Git2DBError::from_git_error(repo_error);
387
388 if let Git2DBError::GitOperation {
389 class,
390 code,
391 recoverable,
392 ..
393 } = err
394 {
395 assert_eq!(class, ErrorClass::Repository);
396 assert_eq!(code, ErrorCode::NotFound);
397 assert!(!recoverable);
398 } else {
399 panic!("Expected GitOperation error");
400 }
401 }
402
403 #[test]
404 fn test_repository_error_creation() {
405 let path = PathBuf::from("/test/path");
406 let err = Git2DBError::repository(&path, "Test error message");
407
408 if let Git2DBError::Repository {
409 path: ref err_path,
410 ref message,
411 } = err
412 {
413 assert_eq!(err_path, &path);
414 assert_eq!(message, "Test error message");
415 } else {
416 panic!("Expected Repository error");
417 }
418
419 assert!(!err.is_recoverable());
420 }
421
422 #[test]
423 fn test_submodule_error_creation() {
424 let err = Git2DBError::submodule("test-module", "Failed to initialize");
425
426 if let Git2DBError::Submodule {
427 ref name,
428 ref message,
429 } = err
430 {
431 assert_eq!(name, "test-module");
432 assert_eq!(message, "Failed to initialize");
433 } else {
434 panic!("Expected Submodule error");
435 }
436
437 assert!(!err.is_recoverable());
438 }
439
440 #[test]
441 fn test_reference_error_creation() {
442 let err = Git2DBError::reference("refs/heads/main", "Reference not found");
443
444 if let Git2DBError::Reference { reference, message } = err {
445 assert_eq!(reference, "refs/heads/main");
446 assert_eq!(message, "Reference not found");
447 } else {
448 panic!("Expected Reference error");
449 }
450 }
451
452 #[test]
453 fn test_authentication_error_creation() {
454 let err =
455 Git2DBError::authentication("https://github.com/test/repo.git", "Invalid credentials");
456
457 if let Git2DBError::Authentication {
458 ref url,
459 ref message,
460 } = err
461 {
462 assert_eq!(url, "https://github.com/test/repo.git");
463 assert_eq!(message, "Invalid credentials");
464 } else {
465 panic!("Expected Authentication error");
466 }
467
468 assert!(err.is_recoverable());
469 }
470
471 #[test]
472 fn test_network_error_creation() {
473 let err = Git2DBError::network("Connection timeout");
474
475 if let Git2DBError::Network { ref message } = err {
476 assert_eq!(message, "Connection timeout");
477 } else {
478 panic!("Expected Network error");
479 }
480
481 assert!(err.is_recoverable());
482 }
483
484 #[test]
485 fn test_configuration_error_creation() {
486 let err = Git2DBError::configuration("Invalid signature configuration");
487
488 if let Git2DBError::Configuration { ref message } = err {
489 assert_eq!(message, "Invalid signature configuration");
490 } else {
491 panic!("Expected Configuration error");
492 }
493
494 assert!(!err.is_recoverable());
495 }
496
497 #[test]
498 fn test_invalid_path_error_creation() {
499 let path = PathBuf::from("../../../etc/passwd");
500 let err = Git2DBError::invalid_path(&path, "Path traversal detected");
501
502 if let Git2DBError::InvalidPath {
503 path: ref err_path,
504 ref message,
505 } = err
506 {
507 assert_eq!(err_path, &path);
508 assert_eq!(message, "Path traversal detected");
509 } else {
510 panic!("Expected InvalidPath error");
511 }
512
513 assert!(!err.is_recoverable());
514 }
515
516 #[test]
517 fn test_invalid_repository_error_creation() {
518 let err = Git2DBError::invalid_repository("name with spaces", "Invalid characters in name");
519
520 if let Git2DBError::InvalidRepository {
521 ref name,
522 ref message,
523 } = err
524 {
525 assert_eq!(name, "name with spaces");
526 assert_eq!(message, "Invalid characters in name");
527 } else {
528 panic!("Expected InvalidRepository error");
529 }
530
531 assert!(!err.is_recoverable());
532 }
533
534 #[test]
535 fn test_cancelled_error_creation() {
536 let err = Git2DBError::cancelled("clone operation");
537
538 if let Git2DBError::Cancelled { ref operation } = err {
539 assert_eq!(operation, "clone operation");
540 } else {
541 panic!("Expected Cancelled error");
542 }
543
544 assert!(!err.is_recoverable());
545 }
546
547 #[test]
548 fn test_internal_error_creation() {
549 let err = Git2DBError::internal("Unexpected null pointer");
550
551 if let Git2DBError::Internal { ref message } = err {
552 assert_eq!(message, "Unexpected null pointer");
553 } else {
554 panic!("Expected Internal error");
555 }
556
557 assert!(!err.is_recoverable());
558 }
559
560 #[test]
561 fn test_error_display_formatting() {
562 let err = Git2DBError::repository("/test/path", "Test message");
563 let display_str = format!("{err}");
564 assert!(display_str.contains("/test/path"));
565 assert!(display_str.contains("Test message"));
566
567 let git_err = Git2DBError::from_git_error(git2::Error::new(
568 ErrorCode::NotFound,
569 ErrorClass::Repository,
570 "Not found",
571 ));
572 let git_display = format!("{git_err}");
573 assert!(git_display.contains("Git operation failed"));
574 assert!(git_display.contains("Not found"));
575 }
576
577 #[test]
578 fn test_error_from_io_error() {
579 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
580 let err: Git2DBError = io_err.into();
581
582 if let Git2DBError::Io(_) = err {
583 } else {
585 panic!("Expected Io error");
586 }
587
588 assert!(!err.is_recoverable());
589 }
590
591 #[test]
592 fn test_error_from_serde_json_error() {
593 let json_result = serde_json::from_str::<serde_json::Value>("invalid json");
594 let json_err = match json_result {
595 Err(e) => e,
596 Ok(_) => panic!("Expected JSON parsing to fail"),
597 };
598 let err: Git2DBError = json_err.into();
599
600 if let Git2DBError::Json(_) = err {
601 } else {
603 panic!("Expected Json error");
604 }
605 }
606
607 #[test]
608 fn test_error_from_anyhow_error() {
609 let anyhow_err = anyhow::anyhow!("Some external error");
610 let err: Git2DBError = anyhow_err.into();
611
612 if let Git2DBError::External(_) = err {
613 } else {
615 panic!("Expected External error");
616 }
617 }
618
619 #[test]
620 fn test_error_macros() {
621 let repo_err = repo_error!("/test/path", "Repository error");
622 if let Git2DBError::Repository {
623 ref path,
624 ref message,
625 } = repo_err
626 {
627 assert_eq!(path, &PathBuf::from("/test/path"));
628 assert_eq!(message, "Repository error");
629 } else {
630 panic!("Expected Repository error from macro");
631 }
632
633 let formatted_repo_err = repo_error!("/test/path", "Error code: {}", 404);
634 if let Git2DBError::Repository { ref message, .. } = formatted_repo_err {
635 assert_eq!(message, "Error code: 404");
636 } else {
637 panic!("Expected Repository error from macro with formatting");
638 }
639
640 let submodule_err = submodule_error!("test-module", "Submodule error");
641 if let Git2DBError::Submodule {
642 ref name,
643 ref message,
644 } = submodule_err
645 {
646 assert_eq!(name, "test-module");
647 assert_eq!(message, "Submodule error");
648 } else {
649 panic!("Expected Submodule error from macro");
650 }
651
652 let ref_err = ref_error!("refs/heads/main", "Reference error");
653 if let Git2DBError::Reference {
654 ref reference,
655 ref message,
656 } = ref_err
657 {
658 assert_eq!(reference, "refs/heads/main");
659 assert_eq!(message, "Reference error");
660 } else {
661 panic!("Expected Reference error from macro");
662 }
663 }
664
665 #[test]
666 fn test_comprehensive_recoverable_classification() {
667 let test_cases = vec![
668 (Git2DBError::network("test"), true),
669 (Git2DBError::authentication("url", "test"), true),
670 (Git2DBError::repository("/test", "test"), false),
671 (Git2DBError::configuration("test"), false),
672 (Git2DBError::invalid_path("/test", "test"), false),
673 (Git2DBError::invalid_repository("test", "test"), false),
674 (Git2DBError::cancelled("test"), false),
675 (Git2DBError::internal("test"), false),
676 ];
677
678 for (error, expected_recoverable) in test_cases {
679 assert_eq!(
680 error.is_recoverable(),
681 expected_recoverable,
682 "Recoverable classification failed for: {error:?}"
683 );
684 }
685 }
686}