cargo-vet 0.10.3

Supply-chain security for Rust
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
// The `#[derive(Diagnostic)]` proc macro unfortunately currently generates
// spurious `unused_assignemnts` diagnostics in rust 1.92+, which cannot be
// easily annotated. (see https://github.com/zkat/miette/issues/458)
#![allow(unused_assignments)]

use std::{
    ffi::OsString,
    fmt::{Debug, Display},
    num::ParseIntError,
    path::{PathBuf, StripPrefixError},
    string::FromUtf8Error,
    sync::Arc,
};

use cargo_metadata::semver;
use miette::{Diagnostic, MietteSpanContents, SourceCode, SourceSpan};
use thiserror::Error;

use crate::{
    format::{
        CriteriaName, ForeignCriteriaName, ImportName, PackageName, StoreVersion, VetVersion,
    },
    network::PayloadEncoding,
    serialization::spanned::Spanned,
};

#[derive(Eq, PartialEq)]
struct SourceFileInner {
    name: String,
    source: String,
}

#[derive(Clone, Eq, PartialEq)]
pub struct SourceFile {
    inner: Arc<SourceFileInner>,
}

impl SourceFile {
    pub fn new_empty(name: &str) -> Self {
        Self::new(name, String::new())
    }
    pub fn new(name: &str, source: String) -> Self {
        SourceFile {
            inner: Arc::new(SourceFileInner {
                name: name.to_owned(),
                source,
            }),
        }
    }
    pub fn name(&self) -> &str {
        &self.inner.name
    }
    pub fn source(&self) -> &str {
        &self.inner.source
    }
}

impl SourceCode for SourceFile {
    fn read_span<'a>(
        &'a self,
        span: &SourceSpan,
        context_lines_before: usize,
        context_lines_after: usize,
    ) -> Result<Box<dyn miette::SpanContents<'a> + 'a>, miette::MietteError> {
        let contents = self
            .source()
            .read_span(span, context_lines_before, context_lines_after)?;
        Ok(Box::new(MietteSpanContents::new_named(
            self.name().to_owned(),
            contents.data(),
            *contents.span(),
            contents.line(),
            contents.column(),
            contents.line_count(),
        )))
    }
}

impl Debug for SourceFile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SourceFile")
            .field("name", &self.name())
            .field("source", &self.source())
            .finish()
    }
}

//////////////////////////////////////////////////////////
// VersionParseError
//////////////////////////////////////////////////////////

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum VersionParseError {
    #[error(transparent)]
    Semver(#[from] semver::Error),
    #[error("unrecognized revision type, expected 'git:' prefix")]
    UnknownRevision,
    #[error("unrecognized git hash, expected 40 hex digits")]
    InvalidGitHash,
}

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StoreVersionParseError {
    #[error("error parsing version component: {0}")]
    ParseInt(#[from] ParseIntError),
    #[error("missing '.' separator")]
    MissingSeparator,
}

///////////////////////////////////////////////////////////
// MetadataAcquireError
///////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
pub enum MetadataAcquireError {
    #[error("`cargo metadata` exited with an error:\n{stderr}")]
    #[diagnostic(help("You may need to run `cargo generate-lockfile` to create a Cargo.lock"))]
    MetadataError {
        /// Stderr returned by the `cargo metadata` command
        stderr: String,
    },
    #[error(transparent)]
    Other(cargo_metadata::Error),
}

impl From<cargo_metadata::Error> for MetadataAcquireError {
    fn from(value: cargo_metadata::Error) -> Self {
        match value {
            // Wrap normal errors to provide extra help information.
            cargo_metadata::Error::CargoMetadata { stderr } => {
                MetadataAcquireError::MetadataError { stderr }
            }
            // Other errors couldn't be caused by that problem, so are
            // unchanged.
            other => MetadataAcquireError::Other(other),
        }
    }
}

///////////////////////////////////////////////////////////
// AuditAsErrors
///////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[error("There are some issues with your policy.audit-as-crates-io entries")]
#[diagnostic()]
pub struct AuditAsErrors {
    #[related]
    pub errors: Vec<AuditAsError>,
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum AuditAsError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    NeedsAuditAs(NeedsAuditAsErrors),
    #[error(transparent)]
    #[diagnostic(transparent)]
    ShouldntBeAuditAs(ShouldntBeAuditAsErrors),
    #[error(transparent)]
    #[diagnostic(transparent)]
    UnusedAuditAs(UnusedAuditAsErrors),
}

#[derive(Debug, Error, Diagnostic)]
#[diagnostic(help("Add a `policy.*.audit-as-crates-io` entry for them"))]
pub struct NeedsAuditAsErrors {
    pub errors: Vec<VersionedPackageError>,
}

impl Display for NeedsAuditAsErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Some non-crates.io-fetched packages match published crates.io versions")?;
        for e in &self.errors {
            f.write_fmt(format_args!("\n  {e}"))?
        }
        Ok(())
    }
}

#[derive(Debug, Error, Diagnostic)]
#[diagnostic(help("Remove the audit-as-crates-io entries or make them `false`"))]
pub struct ShouldntBeAuditAsErrors {
    pub errors: Vec<VersionedPackageError>,
}

impl Display for ShouldntBeAuditAsErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("some audit-as-crates-io packages don't match published crates.io versions")?;
        for e in &self.errors {
            f.write_fmt(format_args!("\n  {e}"))?
        }
        Ok(())
    }
}

#[derive(Debug, Error, Diagnostic)]
#[diagnostic(help("Remove the audit-as-crates-io entries"))]
pub struct UnusedAuditAsErrors {
    pub errors: Vec<PackageError>,
}

impl Display for UnusedAuditAsErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("some audit-as-crates-io policies don't match first-party crates")?;
        for e in &self.errors {
            f.write_fmt(format_args!("\n  {e}"))?
        }
        Ok(())
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
#[error("{package}{}", .version.as_ref().map(|v| format!(":{v}")).unwrap_or_default())]
pub struct PackageError {
    pub package: PackageName,
    pub version: Option<VetVersion>,
}

#[derive(Debug, Error, PartialEq, Eq)]
#[error("{package}:{version}")]
pub struct VersionedPackageError {
    pub package: PackageName,
    pub version: VetVersion,
}

///////////////////////////////////////////////////////////
// CratePolicyErrors
///////////////////////////////////////////////////////////
#[derive(Debug, Error, Diagnostic, PartialEq, Eq)]
#[error("There are some issues with your third-party policy entries")]
#[diagnostic()]
pub struct CratePolicyErrors {
    #[related]
    pub errors: Vec<CratePolicyError>,
}

#[derive(Debug, Error, Diagnostic, PartialEq, Eq)]
#[non_exhaustive]
pub enum CratePolicyError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    DependencyCriteriaNeedsVersion(DependencyCriteriaNeedsPolicyVersionErrors),
    #[error(transparent)]
    #[diagnostic(transparent)]
    UnusedVersion(UnusedPolicyVersionErrors),
    #[error(transparent)]
    #[diagnostic(transparent)]
    ThirdPartyNeedsVersion(ThirdPartyNeedsPolicyVersionErrors),
}

#[derive(Debug, Error, Diagnostic, PartialEq, Eq)]
#[diagnostic(help(
    "Specifing `dependency-criteria` requires explicit policies for each version of \
     a crate. Add a `policy.\"<crate>:<version>\"` entry for them."
))]
pub struct DependencyCriteriaNeedsPolicyVersionErrors {
    pub errors: Vec<VersionedPackageError>,
}

impl Display for DependencyCriteriaNeedsPolicyVersionErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("some crates have policies that are missing an associated version")?;
        for e in &self.errors {
            f.write_fmt(format_args!("\n  {e}"))?
        }
        Ok(())
    }
}

#[derive(Debug, Error, Diagnostic, PartialEq, Eq)]
#[diagnostic(help("Remove the `policy` entries"))]
pub struct UnusedPolicyVersionErrors {
    pub errors: Vec<PackageError>,
}

impl Display for UnusedPolicyVersionErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("some versioned policy entries don't correspond to crates being used")?;
        for e in &self.errors {
            f.write_fmt(format_args!("\n  {e}"))?
        }
        Ok(())
    }
}

#[derive(Debug, Error, Diagnostic, PartialEq, Eq)]
#[diagnostic(help(
    "Crates with a third-party version must use versioned policy entries. Replace the \
    `policy.<crate>` entry with `policy.\"<crate>:<version>\"` entries as desired."
))]
pub struct ThirdPartyNeedsPolicyVersionErrors {
    pub errors: Vec<VersionedPackageError>,
}

impl Display for ThirdPartyNeedsPolicyVersionErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("some crates have unversioned policies that must be versioned")?;
        for e in &self.errors {
            f.write_fmt(format_args!("\n  {e}"))?
        }
        Ok(())
    }
}

///////////////////////////////////////////////////////////
// CertifyError
///////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum CertifyError {
    #[error("no criteria chosen, aborting")]
    NoCriteriaChosen,
    #[error("couldn't guess what version of {0} to certify, please specify")]
    CouldntGuessVersion(PackageName),
    #[error("couldn't guess what package to certify, please specify")]
    CouldntGuessPackage,
    #[error("couldn't find uncommented certify statement")]
    CouldntFindCertifyStatement,
    #[error("'{0}' isn't one of your foreign packages")]
    #[diagnostic(help("use --force to ignore this error"))]
    NotAPackage(PackageName),
    #[error("'{0}' has not published any relevant version of '{1}'")]
    #[diagnostic(help("please specify a user who has published a version of '{1}'"))]
    NotAPublisher(String, PackageName),
    #[error("end date of {0} is too far in the future")]
    #[diagnostic(help("wildcard audit end dates may be at most 1 year in the future"))]
    BadWildcardEndDate(chrono::NaiveDate),
    #[error("couldn't build an audit graph to determine audit collapse validity")]
    #[diagnostic(help("use --no-collapse to disable audit collapsing"))]
    BadAuditGraph,
    #[error(transparent)]
    IoError(#[from] std::io::Error),
    #[error(transparent)]
    EditError(#[from] EditError),
    #[error(transparent)]
    UserInfoError(#[from] UserInfoError),
    #[error(transparent)]
    FetchAuditError(#[from] FetchAuditError),
    #[error(transparent)]
    GetPublishersError(#[from] CrateInfoError),
    #[error(transparent)]
    CacheAcquire(#[from] CacheAcquireError),
}

///////////////////////////////////////////////////////////
// EditError
///////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum EditError {
    #[error("Failed to launch editor")]
    CouldntLaunch(#[source] std::io::Error),
    #[error("Failed to open result of editor")]
    CouldntOpen(#[source] std::io::Error),
    #[error("Failed to read result of editor")]
    CouldntRead(#[source] std::io::Error),
}

///////////////////////////////////////////////////////////
// InitErrors
///////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[error("Failed to initialize the cargo-vet store (supply-chain)")]
#[non_exhaustive]
pub enum InitError {
    StoreCreate(#[source] StoreCreateError),
    StoreCommit(#[source] StoreCommitError),
}

///////////////////////////////////////////////////////////
// StoreErrors
///////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
#[error("Couldn't create the store (supply-chain)")]
pub enum StoreCreateError {
    CouldntCreate(#[source] std::io::Error),
    CouldntAcquire(
        #[from]
        #[source]
        FlockError,
    ),
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum StoreAcquireError {
    #[error("Couldn't acquire the store's (supply-chain's) lock")]
    CouldntLock(
        #[from]
        #[source]
        FlockError,
    ),
    #[error("The supply-chain store was created with an incompatible version of cargo-vet ({0})")]
    #[help("Run cargo vet without --locked to update the store to this version")]
    OutdatedStore(StoreVersion),
    #[error("The supply-chain store was created with a newer version of cargo-vet ({0})")]
    #[help("Update to the latest version using `cargo install cargo-vet`")]
    NewerStore(StoreVersion),
    #[error(transparent)]
    #[diagnostic(transparent)]
    LoadToml(#[from] LoadTomlError),
    #[error("Couldn't acquire the store")]
    IoError(
        #[from]
        #[source]
        std::io::Error,
    ),
    #[error(transparent)]
    #[diagnostic(transparent)]
    Validate(#[from] StoreValidateErrors),
    #[error(transparent)]
    #[diagnostic(transparent)]
    FetchAuditError(#[from] Box<FetchAuditError>),
    #[error(transparent)]
    #[diagnostic(transparent)]
    GetPublishersError(#[from] Box<CrateInfoError>),
    #[diagnostic(transparent)]
    #[error(transparent)]
    CriteriaChange(#[from] CriteriaChangeErrors),
    #[diagnostic(transparent)]
    #[error(transparent)]
    CacheAcquire(#[from] Box<CacheAcquireError>),
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
#[error("Failed to commit store")]
pub enum StoreCommitError {
    IoError(
        #[from]
        #[source]
        std::io::Error,
    ),
    StoreToml(
        #[from]
        #[source]
        StoreTomlError,
    ),
}

#[derive(Debug, Error, Diagnostic)]
#[error("Some of your imported audits changed their criteria descriptions")]
#[diagnostic()]
pub struct CriteriaChangeErrors {
    #[related]
    pub errors: Vec<CriteriaChangeError>,
}
#[derive(Debug, Error, Diagnostic)]
#[error("{import_name}'s '{criteria_name}' criteria changed:\n\n{unified_diff}")]
#[diagnostic(help("Run `cargo vet regenerate imports` to accept this new definition"))]
pub struct CriteriaChangeError {
    pub import_name: ImportName,
    pub criteria_name: ForeignCriteriaName,
    pub unified_diff: String,
}

////////////////////////////////////////////////////////////
// StoreValidateErrors
////////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[error("Your cargo-vet store (supply-chain) has consistency errors")]
pub struct StoreValidateErrors {
    #[related]
    pub errors: Vec<StoreValidateError>,
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum StoreValidateError {
    #[diagnostic(transparent)]
    #[error(transparent)]
    InvalidCriteria(InvalidCriteriaError),
    #[diagnostic(transparent)]
    #[error(transparent)]
    BadFormat(BadFormatError),
    #[diagnostic(transparent)]
    #[error(transparent)]
    BadWildcardEndDate(BadWildcardEndDateError),
    #[error("imports.lock is out-of-date with respect to configuration")]
    #[diagnostic(help("run `cargo vet` without --locked to update imports"))]
    ImportsLockOutdated,
}

#[derive(Debug, Error, Diagnostic)]
#[error("'{invalid}' is not a valid criteria name")]
#[diagnostic(help("the possible criteria are {:?}", valid_names))]
pub struct InvalidCriteriaError {
    #[source_code]
    pub source_code: SourceFile,
    #[label]
    pub span: SourceSpan,
    pub invalid: String,
    pub valid_names: Arc<Vec<String>>,
}

#[derive(Debug, Error, Diagnostic)]
#[error("A file in the store is not correctly formatted:\n\n{unified_diff}")]
#[diagnostic(help("run `cargo vet fmt` to reformat files in the store"))]
pub struct BadFormatError {
    pub unified_diff: String,
}

#[derive(Debug, Error, Diagnostic)]
#[error("'{date}' is more than a year in the future")]
#[diagnostic(help("wildcard audits must end at most a year in the future ({max})"))]
pub struct BadWildcardEndDateError {
    #[source_code]
    pub source_code: SourceFile,
    #[label]
    pub span: SourceSpan,
    pub date: chrono::NaiveDate,
    pub max: chrono::NaiveDate,
}

//////////////////////////////////////////////////////////
// CacheErrors
/////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum CacheAcquireError {
    #[error("Couldn't acquire cache")]
    IoError(
        #[from]
        #[source]
        std::io::Error,
    ),
    #[error("Failed to create cache root dir: {}", target.display())]
    Root {
        target: PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Failed to create cache src dir: {}", target.display())]
    Src {
        target: PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Failed to create cache empty dir: {}", target.display())]
    Empty {
        target: PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Failed to create cache package dir: {}", target.display())]
    Cache {
        target: PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Couldn't acquire the cache's lock")]
    CouldntLock(
        #[from]
        #[source]
        FlockError,
    ),
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
#[error("Failed to commit cache")]
pub enum CacheCommitError {
    IoError(
        #[from]
        #[source]
        std::io::Error,
    ),
    StoreToml(
        #[from]
        #[source]
        StoreTomlError,
    ),
    StoreJson(
        #[from]
        #[source]
        StoreJsonError,
    ),
}

//////////////////////////////////////////////////////////
/// CommandError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum CommandError {
    #[error("Command failed")]
    CommandFailed(#[source] std::io::Error),
    #[error("Bad status {0}")]
    BadStatus(i32),
    #[error("Wasn't UTF-8")]
    BadOutput(#[source] FromUtf8Error),
}

//////////////////////////////////////////////////////////
// FetchAndDiffError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum FetchAndDiffError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    Diff(#[from] DiffError),
    #[error(transparent)]
    #[diagnostic(transparent)]
    Fetch(#[from] FetchError),
}

//////////////////////////////////////////////////////////
// DiffError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum DiffError {
    #[error("Failed to diff package")]
    CommandError(
        #[from]
        #[source]
        CommandError,
    ),
    #[error("Diff command produced an unexpected path")]
    UnexpectedPath(#[source] StripPrefixError),
    #[error("Diff command produced invalid output")]
    InvalidOutput,
}

//////////////////////////////////////////////////////////
// UserInfoError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum UserInfoError {
    #[error("Failed to get user.name")]
    UserCommandFailed(#[source] CommandError),
    #[error("Failed to get user.email")]
    EmailCommandFailed(#[source] CommandError),
}

//////////////////////////////////////////////////////////
// FetchError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum FetchError {
    #[error("Invalid URL for package: {url}")]
    InvalidUrl {
        url: String,
        #[source]
        error: url::ParseError,
    },
    #[error("Running as --frozen but needed to fetch {package}:{version}")]
    Frozen {
        package: PackageName,
        version: semver::Version,
    },
    #[error("Failed to unpack .crate at {}", src.display())]
    Unpack {
        src: PathBuf,
        #[source]
        error: UnpackError,
    },
    #[error("failed to open cached .crate at {}", target.display())]
    OpenCached {
        target: std::path::PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Failed to unpack checkout at {}", src.display())]
    UnpackCheckout {
        src: PathBuf,
        #[source]
        error: UnpackCheckoutError,
    },
    #[error("Cannot get source for unknown git commit {git_rev} of {package}")]
    #[help("Only revisions actively used in the dependency graph can be located")]
    UnknownGitRevision {
        package: PackageName,
        git_rev: String,
    },
    #[error(transparent)]
    #[diagnostic(transparent)]
    Download(#[from] DownloadError),
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum UnpackError {
    #[error("Failed to iterate archive")]
    ArchiveIterate(#[source] std::io::Error),
    #[error("Failed to read archive entry")]
    ArchiveEntry(#[source] std::io::Error),
    #[error("Invalid archive, {} wasn't under {}", entry_path.display(), prefix.to_string_lossy())]
    InvalidPaths {
        entry_path: PathBuf,
        prefix: OsString,
    },
    #[error("Failed to unpack archive entry {}", entry_path.display())]
    Unpack {
        entry_path: PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Failed to finalize unpack to {}", target.display())]
    LockCreate {
        target: std::path::PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error(transparent)]
    IoError(#[from] std::io::Error),
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum UnpackCheckoutError {
    #[error("Failed to run 'cargo package --list'")]
    CommandError(
        #[from]
        #[source]
        CommandError,
    ),
    #[error("Failed to create directory {path}")]
    CreateDirError {
        path: std::path::PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Failed to copy file contents for {target}")]
    CopyError {
        target: std::path::PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("Failed to finalize checkout unpack")]
    LockCreate(#[source] std::io::Error),
}

//////////////////////////////////////////////////////////
// FetchAuditError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum FetchAuditError {
    // FIXME: would have to explicitly import URL for this error
    #[error("invalid URL for foreign import {import_name} @ {import_url}")]
    InvalidUrl {
        import_name: ImportName,
        import_url: String,
        #[source]
        error: url::ParseError,
    },
    #[error("{import_name}'s '{criteria_name}' criteria is missing a description")]
    MissingCriteriaDescription {
        import_name: ImportName,
        criteria_name: ForeignCriteriaName,
    },
    #[error("{import_name}'s '{criteria_name}' criteria description URI is invalid: '{url}'")]
    InvalidCriteriaDescriptionUrl {
        import_name: ImportName,
        criteria_name: ForeignCriteriaName,
        url: String,
        #[source]
        error: url::ParseError,
    },
    #[error("error when aggregating multiple sources for {import_name}")]
    #[diagnostic(help("all sources for mapped custom criteria must have identical descriptions"))]
    Aggregate {
        import_name: ImportName,
        #[related]
        errors: Vec<FetchAuditAggregateError>,
    },
    #[diagnostic(transparent)]
    #[error(transparent)]
    Download(#[from] DownloadError),
    #[diagnostic(transparent)]
    #[error(transparent)]
    Toml(#[from] LoadTomlError),
    #[diagnostic(transparent)]
    #[error(transparent)]
    Json(#[from] LoadJsonError),
}

#[derive(Debug, Error, Diagnostic)]
#[error("criteria description mismatch for {criteria_name}\n{first}\n{second}")]
#[diagnostic(help("{criteria_name} is mapped to the local criteria {mapped_to:?}"))]
pub struct FetchAuditAggregateError {
    pub criteria_name: CriteriaName,
    pub mapped_to: Vec<Spanned<CriteriaName>>,
    pub first: AggregateCriteriaDescription,
    pub second: AggregateCriteriaDescription,
}

//////////////////////////////////////////////////////////
// CrateInfoError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum CrateInfoError {
    #[diagnostic(transparent)]
    #[error(transparent)]
    Download(#[from] DownloadError),
    #[diagnostic(transparent)]
    #[error(transparent)]
    Json(#[from] LoadJsonError),
    #[error("Cannot fetch crate information, '{name}' does not exist.")]
    DoesNotExist { name: PackageName },
}

//////////////////////////////////////////////////////////
// FetchRegistryError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum FetchRegistryError {
    #[error("Encountered an error fetching the cargo-vet registry.")]
    Download(#[from] DownloadError),
    #[error("Import suggestions are disabled due to an incompatible registry. Consider upgrading to the most recent release of cargo-vet.")]
    Toml(#[from] LoadTomlError),
    #[error("Error when fetching crate information. Registry suggestions may be incomplete.")]
    CrateInfo(#[from] CrateInfoError),
}

//////////////////////////////////////////////////////////
// DownloadError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum DownloadError {
    #[error("failed to start download of {url}")]
    FailedToStartDownload {
        url: Box<reqwest::Url>,
        #[source]
        error: reqwest::Error,
    },
    #[error("failed to create file for download to {}", target.display())]
    FailedToCreateDownload {
        target: std::path::PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("failed to read download from {url}")]
    FailedToReadDownload {
        url: Box<reqwest::Url>,
        #[source]
        error: reqwest::Error,
    },
    #[error("failed to write download to {}", target.display())]
    FailedToWriteDownload {
        target: std::path::PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("failed to rename download to final location {}", target.display())]
    FailedToFinalizeDownload {
        target: std::path::PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("download wasn't valid utf8: {url}")]
    InvalidText {
        url: Box<reqwest::Url>,
        #[source]
        error: FromUtf8Error,
    },
    #[error("download encoding ({encoding}) error")]
    InvalidEncoding {
        encoding: PayloadEncoding,
        #[source]
        error: std::io::Error,
    },
}

//////////////////////////////////////////////////////////
// SuggestError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum SuggestError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    CacheAcquire(#[from] CacheAcquireError),
    #[error(transparent)]
    #[diagnostic(transparent)]
    FetchAudit(#[from] FetchAuditError),
}

//////////////////////////////////////////////////////////
// FlockError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum FlockError {
    #[error("couldn't acquire file lock")]
    IoError(
        #[from]
        #[source]
        std::io::Error,
    ),
}

//////////////////////////////////////////////////////////
// AggregateErrors
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[error("there were errors aggregating source audit files")]
#[diagnostic()]
pub struct AggregateErrors {
    #[related]
    pub errors: Vec<AggregateError>,
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum AggregateError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    CriteriaDescriptionMismatch(AggregateCriteriaDescriptionMismatchError),
    #[error(transparent)]
    #[diagnostic(transparent)]
    ImpliesMismatch(AggregateImpliesMismatchError),
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
#[error("criteria description mismatch for {criteria_name}\n{first}\n{second}")]
pub struct AggregateCriteriaDescriptionMismatchError {
    pub criteria_name: CriteriaName,
    pub first: AggregateCriteriaDescription,
    pub second: AggregateCriteriaDescription,
}

#[derive(Debug)]
pub struct AggregateCriteriaDescription {
    pub source: String,
    pub description: Option<String>,
    pub description_url: Option<String>,
}

impl Display for AggregateCriteriaDescription {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if let Some(description) = &self.description {
            write!(f, "{}:\n{}", self.source, description)
        } else if let Some(description_url) = &self.description_url {
            write!(f, "{}:\n(URL) {}", self.source, description_url)
        } else {
            write!(f, "{}:\n(no description)", self.source)
        }
    }
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
#[error("implied criteria mismatch for {criteria_name}\n{first}\n{second}")]
pub struct AggregateImpliesMismatchError {
    pub criteria_name: CriteriaName,
    pub first: AggregateCriteriaImplies,
    pub second: AggregateCriteriaImplies,
}

#[derive(Debug)]
pub struct AggregateCriteriaImplies {
    pub source: String,
    pub implies: Vec<CriteriaName>,
}

impl Display for AggregateCriteriaImplies {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}:", self.source)?;
        for implied in &self.implies {
            write!(f, "\n - {implied}")?;
        }
        Ok(())
    }
}

//////////////////////////////////////////////////////////
// TomlError/JsonError
//////////////////////////////////////////////////////////

#[derive(Debug, Error, Diagnostic)]
#[error("Failed to parse toml file: {}", error.message())]
pub struct TomlParseError {
    #[source_code]
    pub source_code: SourceFile,
    #[label("here")]
    pub span: SourceSpan,
    pub error: toml::de::Error,
}

#[derive(Debug, Error, Diagnostic)]
#[error("Failed to parse json file")]
pub struct JsonParseError {
    // #[source_code]
    // input: SourceFile,
    // #[label("here")]
    // span: SourceOffset,
    #[source]
    pub error: serde_json::Error,
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum LoadTomlError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    TomlParse(#[from] TomlParseError),

    #[error("TOML wasn't valid utf8")]
    InvalidText {
        #[source]
        #[from]
        error: FromUtf8Error,
    },

    #[error("couldn't load toml")]
    IoError(
        #[from]
        #[source]
        std::io::Error,
    ),
}

#[derive(Debug, Error, Diagnostic)]
#[non_exhaustive]
pub enum LoadJsonError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    JsonParse(#[from] JsonParseError),
    #[error("couldn't load json")]
    IoError(
        #[from]
        #[source]
        std::io::Error,
    ),
}

pub type StoreJsonError = serde_json::Error;

pub type StoreTomlError = toml_edit::ser::Error;