buildlog-consultant 0.1.3

buildlog parser and analyser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
use crate::Problem;
use debversion::Version;

/// Problem representing a generic dpkg error.
///
/// This struct is used for errors reported by the dpkg package manager
/// that don't fit into more specific categories.
#[derive(Debug)]
pub struct DpkgError(pub String);

impl Problem for DpkgError {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "dpkg-error".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "msg": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DpkgError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "dpkg error: {}", self.0)
    }
}

/// Problem representing an error during apt-get update.
///
/// This struct is used when the apt package database update process
/// fails for any reason.
#[derive(Debug, Clone)]
pub struct AptUpdateError;

impl Problem for AptUpdateError {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "apt-update-error".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({})
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for AptUpdateError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "apt update error")
    }
}

/// Problem representing a failure to fetch a package or repository data.
///
/// This struct is used when apt cannot download a package or repository
/// data from the specified URL.
#[derive(Debug, Clone)]
pub struct AptFetchFailure {
    /// The URL that apt was trying to fetch from, if available.
    pub url: Option<String>,
    /// The error message from the fetch failure.
    pub error: String,
}

impl Problem for AptFetchFailure {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "apt-file-fetch-failure".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "url": self.url,
            "error": self.error,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for AptFetchFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if let Some(url) = &self.url {
            write!(f, "apt fetch failure: {} ({})", url, self.error)
        } else {
            write!(f, "apt fetch failure: {}", self.error)
        }
    }
}

/// Problem representing a missing Release file for a repository.
///
/// This struct is used when apt cannot find the Release file for a repository,
/// which typically indicates a misconfigured or unavailable repository.
#[derive(Debug, Clone)]
pub struct AptMissingReleaseFile(pub String);

impl Problem for AptMissingReleaseFile {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "missing-release-file".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "url": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for AptMissingReleaseFile {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "apt missing release file: {}", self.0)
    }
}

/// Problem representing a package that apt cannot find.
///
/// This struct is used when apt cannot find a requested package in any
/// of the configured repositories.
#[derive(Debug, Clone)]
pub struct AptPackageUnknown(pub String);

impl Problem for AptPackageUnknown {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "apt-package-unknown".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "package": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for AptPackageUnknown {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "apt package unknown: {}", self.0)
    }
}

/// Problem representing broken package dependencies.
///
/// This struct is used when apt reports broken packages in the dependency
/// resolution process, which can occur when packages have incompatible dependencies.
#[derive(Debug, Clone)]
pub struct AptBrokenPackages {
    /// A description of the broken package situation.
    pub description: String,
    /// List of packages that are broken, if available.
    pub broken: Option<Vec<String>>,
}

impl Problem for AptBrokenPackages {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "apt-broken-packages".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "description": self.description,
            "broken": self.broken,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for AptBrokenPackages {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "apt broken packages: {}", self.description)
    }
}

/// Problem representing a missing upstream source tarball.
///
/// This struct is used when the build process cannot find the upstream
/// source tarball for a package, which is required for the build.
#[derive(Debug, Clone)]
pub struct UnableToFindUpstreamTarball {
    /// The name of the package.
    pub package: String,
    /// The version of the package for which the tarball is missing.
    pub version: Version,
}

impl Problem for UnableToFindUpstreamTarball {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "unable-to-find-upstream-tarball".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "package": self.package,
            "version": self.version.to_string(),
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UnableToFindUpstreamTarball {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Unable to find upstream tarball for {} {}",
            self.package, self.version
        )
    }
}

/// Problem representing a source format that cannot be built.
///
/// This struct is used when the source package format specified in
/// debian/source/format cannot be built for some reason.
#[derive(Debug, Clone)]
pub struct SourceFormatUnbuildable {
    /// The source format that can't be built (e.g., "3.0 (quilt)").
    pub source_format: String,
    /// The reason why the source format cannot be built.
    pub reason: String,
}

impl Problem for SourceFormatUnbuildable {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "source-format-unbuildable".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "source_format": self.source_format,
            "reason": self.reason,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for SourceFormatUnbuildable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Source format {} is unbuildable: {}",
            self.source_format, self.reason
        )
    }
}

/// Problem representing a source format that is not supported.
///
/// This struct is used when the source package format specified in
/// debian/source/format is not supported by the build environment.
#[derive(Debug, Clone)]
pub struct SourceFormatUnsupported(pub String);

impl Problem for SourceFormatUnsupported {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "source-format-unsupported".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "source_format": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for SourceFormatUnsupported {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Source format {} is unsupported", self.0)
    }
}

/// Problem representing a missing patch file.
///
/// This struct is used when a build requires a patch file that is
/// referenced in the debian/patches directory but is not found.
#[derive(Debug, Clone)]
pub struct PatchFileMissing(pub std::path::PathBuf);

impl Problem for PatchFileMissing {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "patch-file-missing".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "path": self.0.display().to_string(),
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for PatchFileMissing {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Patch file missing: {}", self.0.display())
    }
}

/// Problem representing unexpected local changes in the source package.
///
/// This struct is used when dpkg-source detects unexpected local changes
/// to upstream source code, which should be represented as patches instead.
#[derive(Debug, Clone)]
pub struct DpkgSourceLocalChanges {
    /// Path to the diff file showing the changes, if available.
    pub diff_file: Option<String>,
    /// List of files that have been changed locally, if available.
    pub files: Option<Vec<String>>,
}

impl Problem for DpkgSourceLocalChanges {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "unexpected-local-upstream-changes".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "diff_file": self.diff_file,
            "files": self.files,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DpkgSourceLocalChanges {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(files) = self.files.as_ref() {
            if files.len() < 5 {
                write!(f, "Tree has local changes: {:?}", files)?;
                return Ok(());
            }

            write!(f, "Tree has local changes: {} files", files.len())?;
        } else {
            write!(f, "Tree has local changes")?;
        }
        Ok(())
    }
}

/// Problem representing changes that cannot be represented in the source package.
///
/// This struct is used when dpkg-source detects changes that cannot be
/// represented in the chosen source format, such as mode changes in some formats.
#[derive(Debug, Clone)]
pub struct DpkgSourceUnrepresentableChanges;

impl Problem for DpkgSourceUnrepresentableChanges {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "unrepresentable-local-changes".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::Value::Null
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DpkgSourceUnrepresentableChanges {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Tree has unrepresentable changes")
    }
}

/// Problem representing unwanted binary files in the source package.
///
/// This struct is used when dpkg-source detects binary files in the source
/// package that are not allowed, which can happen when the source is dirty.
#[derive(Debug, Clone)]
pub struct DpkgUnwantedBinaryFiles;

impl Problem for DpkgUnwantedBinaryFiles {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "unwanted-binary-files".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::Value::Null
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DpkgUnwantedBinaryFiles {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Tree has unwanted binary files")
    }
}

/// Problem representing changes to binary files in the source package.
///
/// This struct is used when dpkg-source detects that binary files have been
/// changed, which cannot be properly represented in source package formats.
#[derive(Debug, Clone)]
pub struct DpkgBinaryFileChanged(pub Vec<String>);

impl Problem for DpkgBinaryFileChanged {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "binary-file-changed".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "files": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DpkgBinaryFileChanged {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Binary file changed")
    }
}

/// Problem representing a missing debian control file.
///
/// This struct is used when the debian/control file, which is required for
/// any Debian package, is missing from the source package.
#[derive(Debug, Clone)]
pub struct MissingControlFile(pub std::path::PathBuf);

impl Problem for MissingControlFile {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "missing-control-file".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::Value::Null
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for MissingControlFile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Missing control file: {}", self.0.display())
    }
}

/// Problem representing unknown Mercurial extra fields.
///
/// This struct is used when the build process encounters unknown extra fields
/// in Mercurial version control metadata.
#[derive(Debug, Clone)]
pub struct UnknownMercurialExtraFields(pub String);

impl Problem for UnknownMercurialExtraFields {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "unknown-mercurial-extra-fields".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "field": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UnknownMercurialExtraFields {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Unknown Mercurial extra field: {}", self.0)
    }
}

/// Problem representing a failure to verify an upstream PGP signature.
///
/// This struct is used when the build process cannot verify the PGP signature
/// of an upstream source tarball, which may indicate a security issue.
#[derive(Debug, Clone)]
pub struct UpstreamPGPSignatureVerificationFailed;

impl Problem for UpstreamPGPSignatureVerificationFailed {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "upstream-pgp-signature-verification-failed".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::Value::Null
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UpstreamPGPSignatureVerificationFailed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Upstream PGP signature verification failed")
    }
}

/// Problem representing a missing requested version in uscan.
///
/// This struct is used when the uscan tool (which checks for upstream versions)
/// cannot find a specifically requested version.
#[derive(Debug, Clone)]
pub struct UScanRequestVersionMissing(pub String);

impl Problem for UScanRequestVersionMissing {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "uscan-request-version-missing".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "version": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UScanRequestVersionMissing {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UScan request version missing: {}", self.0)
    }
}

/// Problem representing a failure in the debcargo tool.
///
/// This struct is used when the debcargo tool, which is used to package
/// Rust crates as Debian packages, encounters an error.
#[derive(Debug, Clone)]
pub struct DebcargoFailure(pub String);

impl Problem for DebcargoFailure {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "debcargo-failure".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "reason": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DebcargoFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Debcargo failure: {}", self.0)
    }
}

/// Problem representing an error parsing a debian/changelog file.
///
/// This struct is used when the build process encounters a syntax error
/// or other issue when parsing the debian/changelog file.
#[derive(Debug, Clone)]
pub struct ChangelogParseError(pub String);

impl Problem for ChangelogParseError {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "changelog-parse-error".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "reason": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for ChangelogParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Changelog parse error: {}", self.0)
    }
}

/// Problem representing a generic error in the uscan tool.
///
/// This struct is used when the uscan tool, which checks for upstream versions,
/// encounters an error that doesn't fit into more specific categories.
#[derive(Debug, Clone)]
pub struct UScanError(pub String);

impl Problem for UScanError {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "uscan-error".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "reason": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UScanError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UScan error: {}", self.0)
    }
}

/// Problem representing a failure in the uscan tool.
///
/// This struct is used when the uscan tool fails to find or process
/// upstream versions from a specific URL.
#[derive(Debug, Clone)]
pub struct UScanFailed {
    /// The URL that uscan was trying to process.
    pub url: String,
    /// The reason for the failure.
    pub reason: String,
}

impl Problem for UScanFailed {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "uscan-failed".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "url": self.url,
            "reason": self.reason,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UScanFailed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UScan failed: {}", self.reason)
    }
}

/// Problem representing inconsistency between source format and version.
///
/// This struct is used when there's an inconsistency between the source format
/// specified in debian/source/format and the version numbering scheme.
#[derive(Debug, Clone)]
pub struct InconsistentSourceFormat {
    /// Whether the version is inconsistent with the source format.
    pub version: bool,
    /// Whether the source format is inconsistent with the version.
    pub source_format: bool,
}

impl Problem for InconsistentSourceFormat {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "inconsistent-source-format".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "version": self.version,
            "source_format": self.source_format,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for InconsistentSourceFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Inconsistent source format between version and source format"
        )
    }
}

/// Problem representing an error parsing the debian/upstream/metadata file.
///
/// This struct is used when the build process cannot parse the
/// debian/upstream/metadata file, which contains information about the upstream project.
#[derive(Debug, Clone)]
pub struct UpstreamMetadataFileParseError {
    /// The path to the metadata file.
    pub path: std::path::PathBuf,
    /// The reason for the parsing failure.
    pub reason: String,
}

impl Problem for UpstreamMetadataFileParseError {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "debian-upstream-metadata-invalid".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "path": self.path.display().to_string(),
            "reason": self.reason,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UpstreamMetadataFileParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Upstream metadata file parse error: {}", self.reason)
    }
}

/// Problem representing a failure in dpkg-source when packaging source files.
///
/// This struct is used when dpkg-source cannot package the source files
/// into a source package for various reasons.
#[derive(Debug, Clone)]
pub struct DpkgSourcePackFailed(pub String);

impl Problem for DpkgSourcePackFailed {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "dpkg-source-pack-failed".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "reason": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DpkgSourcePackFailed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Dpkg source pack failed: {}", self.0)
    }
}

/// Problem representing an invalid version string in a package.
///
/// This struct is used when dpkg encounters a version string that
/// doesn't follow the Debian version format rules.
#[derive(Debug, Clone)]
pub struct DpkgBadVersion {
    /// The invalid version string.
    pub version: String,
    /// The reason why the version is invalid, if available.
    pub reason: Option<String>,
}

impl Problem for DpkgBadVersion {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "dpkg-bad-version".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "version": self.version,
            "reason": self.reason,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DpkgBadVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(reason) = &self.reason {
            write!(f, "Version {} is invalid: {}", self.version, reason)
        } else {
            write!(f, "Version {} is invalid", self.version)
        }
    }
}

/// Problem representing a missing Rust crate in debcargo.
///
/// This struct is used when debcargo cannot find a Rust crate
/// that is required for the build.
#[derive(Debug, Clone)]
pub struct MissingDebcargoCrate {
    /// The name of the missing Rust crate.
    pub cratename: String,
    /// The version of the crate that is required, if specified.
    pub version: Option<String>,
}

impl Problem for MissingDebcargoCrate {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "debcargo-missing-crate".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "crate": self.cratename,
            "version": self.version,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for MissingDebcargoCrate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(version) = &self.version {
            write!(
                f,
                "debcargo can't find crate {} (version: {})",
                self.cratename, version
            )
        } else {
            write!(f, "debcargo can't find crate {}", self.cratename)
        }
    }
}

impl MissingDebcargoCrate {
    /// Creates a MissingDebcargoCrate instance from a string.
    ///
    /// Parses a string in the format "cratename=version" or just "cratename"
    /// to create a new instance.
    ///
    /// # Arguments
    /// * `text` - The string to parse
    ///
    /// # Returns
    /// A new MissingDebcargoCrate instance
    pub fn from_string(text: &str) -> Self {
        let text = text.trim();
        if let Some((cratename, version)) = text.split_once('=') {
            Self {
                cratename: cratename.trim().to_string(),
                version: Some(version.trim().to_string()),
            }
        } else {
            Self {
                cratename: text.to_string(),
                version: None,
            }
        }
    }
}

/// Problem representing a missing pristine-tar tree reference.
///
/// This struct is used when a pristine-tar operation cannot find
/// a referenced tree in the git repository.
#[derive(Debug, Clone)]
pub struct PristineTarTreeMissing(pub String);

impl Problem for PristineTarTreeMissing {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "pristine-tar-missing-tree".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "treeish": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for PristineTarTreeMissing {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Pristine-tar tree missing: {}", self.0)
    }
}

/// Problem representing a missing revision in version control.
///
/// This struct is used when a build process references a revision
/// in version control that does not exist.
#[derive(Debug, Clone)]
pub struct MissingRevision(pub Vec<u8>);

impl Problem for MissingRevision {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "missing-revision".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "revision": String::from_utf8_lossy(&self.0),
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for MissingRevision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Missing revision: {}", String::from_utf8_lossy(&self.0))
    }
}

/// Problem representing a Rust crate dependency predicate that debcargo cannot handle.
///
/// This struct is used when debcargo cannot represent a predicate in a Rust
/// crate dependency, such as certain prerelease version constraints.
#[derive(Debug)]
pub struct DebcargoUnacceptablePredicate {
    /// The name of the crate with the unacceptable predicate.
    pub cratename: String,
    /// The predicate that cannot be represented.
    pub predicate: String,
}

impl Problem for DebcargoUnacceptablePredicate {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "debcargo-unacceptable-predicate".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "crate": self.cratename,
            "predicate": self.predicate,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DebcargoUnacceptablePredicate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Cannot represent prerelease part of dependency: {}",
            self.predicate
        )
    }
}

/// Problem representing a Rust crate dependency comparator that debcargo cannot handle.
///
/// This struct is used when debcargo cannot represent a version comparison operator
/// in a Rust crate dependency, such as certain complex version constraints.
#[derive(Debug)]
pub struct DebcargoUnacceptableComparator {
    /// The name of the crate with the unacceptable comparator.
    pub cratename: String,
    /// The comparator that cannot be represented.
    pub comparator: String,
}

impl Problem for DebcargoUnacceptableComparator {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "debcargo-unacceptable-comparator".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "crate": self.cratename,
            "comparator": self.comparator,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for DebcargoUnacceptableComparator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Cannot represent prerelease part of dependency: {}",
            self.comparator
        )
    }
}

/// Problem representing a "too many requests" error from uscan.
///
/// This struct is used when uscan receives a rate limiting response
/// from a server it is checking for upstream versions.
#[derive(Debug)]
pub struct UScanTooManyRequests(pub String);

impl Problem for UScanTooManyRequests {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "uscan-too-many-requests".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "reason": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UScanTooManyRequests {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UScan too many requests: {}", self.0)
    }
}

/// Problem representing unsatisfied conflicts in apt dependencies.
///
/// This struct is used when apt cannot resolve package conflicts
/// during the dependency resolution process.
#[derive(Debug)]
pub struct UnsatisfiedAptConflicts(pub String);

impl Problem for UnsatisfiedAptConflicts {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "unsatisfied-apt-conflicts".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "relations": self.0,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UnsatisfiedAptConflicts {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "unsatisfied apt conflicts: {}", self.0)
    }
}

impl std::error::Error for UnsatisfiedAptConflicts {}

/// Problem representing an architecture not in the supported architecture list.
///
/// This struct is used when a build is attempted for an architecture that
/// is not in the list of architectures supported by the package.
#[derive(Debug, Clone)]
pub struct ArchitectureNotInList {
    /// The architecture being built for.
    pub arch: String,
    /// The list of supported architectures.
    pub arch_list: Vec<String>,
}

impl Problem for ArchitectureNotInList {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "arch-not-in-list".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "arch": self.arch,
            "arch_list": self.arch_list,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for ArchitectureNotInList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Architecture {} not a build arch", self.arch)
    }
}

/// Problem representing unsatisfied dependencies in apt.
///
/// This struct is used when apt cannot satisfy the dependencies
/// required for a package installation.
#[derive(Debug)]
pub struct UnsatisfiedAptDependencies(pub String);

impl Problem for UnsatisfiedAptDependencies {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "unsatisfied-apt-dependencies".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "relations": self.0
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for UnsatisfiedAptDependencies {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "unsatisfied apt dependencies: {}", self.0)
    }
}

/// Problem representing insufficient disk space for a build.
///
/// This struct is used when a build process determines that there is
/// not enough disk space available to complete the build.
#[derive(Debug)]
pub struct InsufficientDiskSpace {
    /// The amount of disk space needed for the build in KiB.
    pub needed: i64,
    /// The amount of free disk space available in KiB.
    pub free: i64,
}

impl Problem for InsufficientDiskSpace {
    fn kind(&self) -> std::borrow::Cow<'_, str> {
        "insufficient-disk-space".into()
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "needed": self.needed,
            "free": self.free,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Display for InsufficientDiskSpace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Insufficient disk space for build. Need: {} KiB, free: {} KiB",
            self.needed, self.free
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Problem;

    #[test]
    fn test_dpkg_source_local_changes_trait() {
        let problem = DpkgSourceLocalChanges {
            diff_file: Some("/tmp/diff.patch".to_string()),
            files: Some(vec!["file1.txt".to_string(), "file2.txt".to_string()]),
        };
        let json = problem.json();
        assert_eq!(json["diff_file"], "/tmp/diff.patch");
        assert_eq!(json["files"], serde_json::json!(["file1.txt", "file2.txt"]));
    }

    #[test]
    fn test_uscan_too_many_requests_trait() {
        let problem = UScanTooManyRequests("rate limit exceeded".to_string());
        let json = problem.json();
        assert_eq!(json["reason"], "rate limit exceeded");
    }
}