pkgsrc 0.10.0

Rust interface to pkgsrc packages and infrastructure
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
/*
 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*!
 * pkgsrc `distinfo` file parsing and processing.
 *
 * Most packages have a `distinfo` file that describes all of the source
 * distribution files (known in pkgsrc nomenclature as `distfiles`) used by the
 * package, as well as any pkgsrc patches that are applied to the unpacked
 * source code.
 *
 * Each `distinfo` file primarily contains checksums for each file, to ensure
 * integrity of both downloaded distfiles as well as the applied patches.  For
 * additional integrity, distfiles usually contain two hashes from different
 * digest algorithms.  They also usually include the size of the file.  Patch
 * files usually just have a single hash.
 *
 * The first line is usually a `$NetBSD$` RCS Id, and the second line is
 * usually blank.  Thus an example `distinfo` file and how to parse it looks
 * something like this:
 *
 * ```
 * use pkgsrc::distinfo::Distinfo;
 * use std::ffi::OsString;
 *
 * let input = r#"
 *     $NetBSD: distinfo,v 1.80 2024/05/27 23:27:10 riastradh Exp $
 *
 *     BLAKE2s (pkgin-23.8.1.tar.gz) = eb0f008ba9801a3c0a35de3e2b2503edd554c3cb17235b347bb8274a18794eb7
 *     SHA512 (pkgin-23.8.1.tar.gz) = 2561d9e4b28a9a77c3c798612ec489dd67dd9a93c61344937095b0683fa89d8432a9ab8e600d0e2995d954888ac2e75a407bab08aa1e8198e375c99d2999f233
 *     Size (pkgin-23.8.1.tar.gz) = 267029 bytes
 *     SHA1 (patch-configure.ac) = 53f56351fb602d9fdce2c1ed266d65919a369086
 *     "#;
 * let distinfo = Distinfo::from_bytes(&input.as_bytes());
 * assert_eq!(distinfo.rcsid(), Some(&OsString::from("$NetBSD: distinfo,v 1.80 2024/05/27 23:27:10 riastradh Exp $")));
 * ```
 *
 * As `distinfo` files can contain usernames and filenames that are not UTF-8
 * clean (for example ISO-8859), `from_bytes()` is the method used to parse
 * input, and the rcsid and filename portions are parsed as [`OsString`].  The
 * remaining sections must be UTF-8 clean and are regular [`String`]s.
 */

use crate::digest::{Digest, DigestError};
use indexmap::IndexMap;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io;
use std::io::Write;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use thiserror::Error;

/**
 * [`Checksum`] contains the [`Digest`] type and the [`String`] hash the digest
 * algorithm calculated for an associated [`Entry`].
 */
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Checksum {
    /**
     * The [`Digest`] type used for this entry.
     */
    pub digest: Digest,
    /**
     * A [`String`] result of the digest hash applied to the associated file.
     */
    pub hash: String,
}

impl Checksum {
    /**
     * Create a new empty [`Checksum`] entry using the specified [`Digest`].
     */
    pub fn new(digest: Digest, hash: String) -> Checksum {
        Checksum { digest, hash }
    }
}

/**
 * Type of this [`Entry`], either [`Distfile`] (the default) or [`Patchfile`].
 *
 * [`Distfile`]: EntryType::Distfile
 * [`Patchfile`]: EntryType::Patchfile
 */
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EntryType {
    /**
     * A source distribution file.
     */
    #[default]
    Distfile,
    /**
     * A pkgsrc patch file.
     */
    Patchfile,
}

impl<P: AsRef<Path>> From<P> for EntryType {
    fn from(path: P) -> Self {
        if Entry::is_patch_filename(&path) {
            EntryType::Patchfile
        } else {
            EntryType::Distfile
        }
    }
}

/**
 * [`Entry`] contains the information stored about each unique file listed in
 * the distinfo file.
 */
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Entry {
    /**
     * Path relative to a certain directory (usually `DISTDIR`) where this
     * entry is stored.  This may contain a directory portion, for example if
     * the package uses DIST_SUBDIR.  This is the string that will be stored
     * in the resulting `distinfo` file.
     */
    pub filename: PathBuf,
    /**
     * Full path to filename.  This is not used in the `distinfo` file but is
     * stored here for processing purposes.
     */
    pub filepath: PathBuf,
    /**
     * File size.  This field is not currently used for patch files, as they
     * are distributed alongside the distinfo file and are not downloaded
     * separately, thus a single hash check is sufficient.
     */
    pub size: Option<u64>,
    /**
     * List of checksums, one [`Checksum`] entry per Digest type.  These are in
     * order of appearance in the `distinfo` file.
     */
    pub checksums: Vec<Checksum>,
    /**
     * Whether this entry is a distfile or a patchfile.
     */
    pub filetype: EntryType,
}

impl Entry {
    /**
     * Returns true if the path is a valid patch filename for inclusion in a
     * distinfo.  Returns false for backup/temporary files (.orig, .rej, ~),
     * local patches (patch-local-*), and files that don't match the patch
     * naming pattern.
     *
     * Must handle quirks such as "patch-2.7.6.tar.xz" which is a distfile not
     * a patch.  This is obviously not exhaustive.
     */
    pub fn is_patch_filename<P: AsRef<Path>>(path: P) -> bool {
        let Some(p) = path.as_ref().file_name() else {
            return false;
        };
        let s = p.to_string_lossy();
        if s.starts_with("patch-local-")
            || s.ends_with(".orig")
            || s.ends_with(".rej")
            || s.ends_with("~")
        {
            return false;
        }
        if s.contains(".tar.") {
            return false;
        }
        s.starts_with("patch-")
            || (s.starts_with("emul-") && s.contains("-patch-"))
    }

    /**
     * Create a new [`Entry`].
     */
    pub fn new<P1, P2>(
        filename: P1,
        filepath: P2,
        checksums: Vec<Checksum>,
        size: Option<u64>,
    ) -> Entry
    where
        P1: AsRef<Path>,
        P2: AsRef<Path>,
    {
        let filetype = EntryType::from(filename.as_ref());
        Entry {
            filename: filename.as_ref().to_path_buf(),
            filepath: filepath.as_ref().to_path_buf(),
            checksums,
            size,
            filetype,
        }
    }
    /**
     * Pass the full path to a file to check as a [`PathBuf`] and verify that
     * it matches the size stored in the [`Distinfo`].
     *
     * Returns the size if [`Ok`], otherwise return a [`DistinfoError`].
     */
    pub fn verify_size<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Result<u64, DistinfoError> {
        if let Some(size) = self.size {
            let f = File::open(path)?;
            let fsize = f.metadata()?.len();
            if fsize != size {
                return Err(DistinfoError::Size(
                    self.filename.clone(),
                    size,
                    fsize,
                ));
            } else {
                return Ok(size);
            }
        }
        Err(DistinfoError::MissingSize(path.as_ref().to_path_buf()))
    }

    /**
     * Internal function to check a specific hash.
     */
    fn verify_checksum_internal<P: AsRef<Path>>(
        &self,
        path: P,
        digest: Digest,
    ) -> Result<Digest, DistinfoError> {
        for c in &self.checksums {
            if digest != c.digest {
                continue;
            }
            let mut f = File::open(path)?;
            let hash = match self.filetype {
                EntryType::Distfile => c.digest.hash_file(&mut f)?,
                EntryType::Patchfile => c.digest.hash_patch(&mut f)?,
            };
            if hash != c.hash {
                return Err(DistinfoError::Checksum(
                    self.filename.clone(),
                    c.digest,
                    c.hash.clone(),
                    hash,
                ));
            } else {
                return Ok(digest);
            }
        }
        Err(DistinfoError::MissingChecksum(
            path.as_ref().to_path_buf(),
            digest,
        ))
    }

    /**
     * Pass the full path to a file to check as a [`PathBuf`] and verify that
     * it matches a specific [`Digest`] checksum stored in the [`Distinfo`].
     *
     * Return the [`Digest`] if [`Ok`], otherwise return a [`DistinfoError`].
     *
     * To verify all stored checksums use use [`verify_checksums`].
     *
     * [`verify_checksums`]: Distinfo::verify_checksums
     */
    pub fn verify_checksum<P: AsRef<Path>>(
        &self,
        path: P,
        digest: Digest,
    ) -> Result<Digest, DistinfoError> {
        self.verify_checksum_internal(path, digest)
    }

    /**
     * Pass the full path to a file to check as a [`PathBuf`] and verify that
     * it matches all of the checksums stored in the [`Distinfo`].  Returns a
     * [`Vec`] of [`Result`]s containing the [`Digest`] if [`Ok`], otherwise
     * return a [`DistinfoError`].
     */
    pub fn verify_checksums<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Vec<Result<Digest, DistinfoError>> {
        let mut results = vec![];
        for c in &self.checksums {
            results
                .push(self.verify_checksum_internal(path.as_ref(), c.digest));
        }
        results
    }

    /**
     * Convert [`Entry`] into a byte representation suitable for writing to
     * a `distinfo` file.  The contents will be ordered as expected.
     */
    pub fn as_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        for c in &self.checksums {
            let _ = writeln!(
                bytes,
                "{} ({}) = {}",
                c.digest,
                self.filename.display(),
                c.hash,
            );
        }
        if let Some(size) = self.size {
            let _ = writeln!(
                bytes,
                "Size ({}) = {} bytes",
                self.filename.display(),
                size,
            );
        }
        bytes
    }
}

/**
 * Parse a single `distinfo` line into a valid line type.  This is an
 * intermediate format, as it doesn't serve any useful function to the user,
 * but is helpful for internally constructing an eventual [`Distinfo`].
 */
#[derive(Debug, Eq, PartialEq)]
enum Line {
    RcsId(OsString),
    Size(PathBuf, u64),
    Checksum(Digest, PathBuf, String),
    None,
}

/**
 * [`Distinfo`] contains the contents of a `distinfo` file.
 *
 * The primary interface for populating a [`Distinfo`] from an existing
 * `distinfo` file is using the [`from_bytes`] function.  There is no error
 * handling.  Any input that is unrecognised or not in the correct format is
 * simply ignored.
 *
 * To create a new `distinfo` file, use [`new`] and set the fields manually.
 *
 * [`from_bytes`]: Distinfo::from_bytes
 * [`new`]: Distinfo::new
 */
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Distinfo {
    /**
     * An optional `$NetBSD: ... $` RCS Id.  As the username portion may
     * contain e.g. ISO-8859 characters it is stored as an [`OsString`].
     */
    rcsid: Option<OsString>,
    /**
     * An [`IndexMap`] of [`Entry`] entries for all source distfiles used by
     * the package, keyed by [`PathBuf`].  These should store both checksums
     * and size information.
     */
    distfiles: IndexMap<PathBuf, Entry>,
    /**
     * An [`IndexMap`] of [`Entry`] entries for any pkgsrc patches applied to
     * the extracted source code, keyed by [`PathBuf`].  These currently do
     * not contain size information.
     */
    patchfiles: IndexMap<PathBuf, Entry>,
}

/**
 * Possible errors returned by various [`Distinfo`] operations.
 */
#[derive(Debug, Error)]
pub enum DistinfoError {
    /// Transparent [`io::Error`] error.
    #[error(transparent)]
    Io(#[from] io::Error),
    /// Transparent [`Digest`] error.
    #[error(transparent)]
    Digest(#[from] DigestError),
    /// File was not found as a valid entry in the current [`Distinfo`] struct.
    #[error("File not found")]
    NotFound,
    /// Checksum mismatch, expected vs actual.
    #[error("Checksum {1} mismatch for {0}: expected {2}, actual {3}")]
    Checksum(PathBuf, Digest, String, String),
    /// No checksum found for the requested Digest
    #[error("Missing {1} checksum entry for {0}")]
    MissingChecksum(PathBuf, Digest),
    /// Size mismatch, expected vs actual.
    #[error("Size mismatch for {0}: expected {1}, actual {2}")]
    Size(PathBuf, u64, u64),
    /// No checksum found for the requested Digest
    #[error("Missing size entry for {0}")]
    MissingSize(PathBuf),
}

impl Distinfo {
    /**
     * Return a new empty [`Distinfo`].
     */
    pub fn new() -> Self {
        Self::default()
    }

    /**
     * Return an [`Option`] containing either a valid `$NetBSD: ...` RCS Id
     * line, or None if one was not found.
     */
    pub fn rcsid(&self) -> Option<&OsString> {
        self.rcsid.as_ref()
    }

    /**
     * Set the rcsid value.
     */
    pub fn set_rcsid(&mut self, rcsid: impl Into<OsString>) {
        self.rcsid = Some(rcsid.into());
    }
    /**
     * Return a matching distfile [`Entry`] if found, otherwise [`None`].
     */
    pub fn distfile<P: AsRef<Path>>(&self, path: P) -> Option<&Entry> {
        self.distfiles.get(path.as_ref())
    }

    /**
     * Return a matching patchfile [`Entry`] if found, otherwise [`None`].
     */
    pub fn patchfile<P: AsRef<Path>>(&self, path: P) -> Option<&Entry> {
        self.patchfiles.get(path.as_ref())
    }

    /**
     * Return a [`Vec`] of references to distfile entries, if any.
     */
    pub fn distfiles(&self) -> Vec<&Entry> {
        self.distfiles.values().collect()
    }

    /**
     * Return a [`Vec`] of references to patchfile entries, if any.
     */
    pub fn patchfiles(&self) -> Vec<&Entry> {
        self.patchfiles.values().collect()
    }

    /**
     * Calculate size of a [`PathBuf`].
     */
    pub fn calculate_size<P: AsRef<Path>>(
        path: P,
    ) -> Result<u64, DistinfoError> {
        let file = File::open(path)?;
        Ok(file.metadata()?.len())
    }

    /**
     * Calculate [`Digest`] hash for a [`Path`].  The hash will differ depending on the
     * [`EntryType`] of the supplied path.
     */
    pub fn calculate_checksum<P: AsRef<Path>>(
        path: P,
        digest: Digest,
    ) -> Result<String, DistinfoError> {
        let filetype = EntryType::from(path.as_ref());
        let mut f = File::open(path)?;
        match filetype {
            EntryType::Distfile => Ok(digest.hash_file(&mut f)?),
            EntryType::Patchfile => Ok(digest.hash_patch(&mut f)?),
        }
    }

    /**
     * Insert a populated [`Entry`] into the [`Distinfo`].
     */
    pub fn insert(&mut self, entry: Entry) -> bool {
        let map = match entry.filetype {
            EntryType::Distfile => &mut self.distfiles,
            EntryType::Patchfile => &mut self.patchfiles,
        };
        map.insert(entry.filename.clone(), entry).is_none()
    }

    /**
     * Find an [`Entry`] in the current [`Distinfo`] given a [`Path`].
     * [`Distinfo`] distfile entries may include a directory component
     * (`DIST_SUBDIR`) so applications can't simply look up by filename.
     *
     * This function iterates over the [`Path`] in reverse, adding any leading
     * components until an entry is found, or returns
     * [`DistinfoError::NotFound`].
     */
    pub fn find_entry<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Result<&Entry, DistinfoError> {
        let filetype = EntryType::from(path.as_ref());
        let mut file = PathBuf::new();
        for component in path.as_ref().iter().rev() {
            if file.parent().is_none() {
                file = PathBuf::from(component);
            } else {
                file = PathBuf::from(component).join(file);
            }
            match filetype {
                EntryType::Distfile => {
                    if let Some(entry) = self.distfile(&file) {
                        return Ok(entry);
                    }
                }
                EntryType::Patchfile => {
                    if let Some(entry) = self.patchfile(&file) {
                        return Ok(entry);
                    }
                }
            }
        }
        Err(DistinfoError::NotFound)
    }

    /**
     * Internal functions to update or insert entries in the current
     * [`Distinfo`], given a [`Path`] and its value data.
     */
    fn update_size<P: AsRef<Path>>(&mut self, path: P, size: u64) {
        let filetype = EntryType::from(path.as_ref());
        let map = match filetype {
            EntryType::Distfile => &mut self.distfiles,
            EntryType::Patchfile => &mut self.patchfiles,
        };
        match map.get_mut(path.as_ref()) {
            Some(entry) => entry.size = Some(size),
            None => {
                map.insert(
                    path.as_ref().to_path_buf(),
                    Entry {
                        filename: path.as_ref().to_path_buf(),
                        size: Some(size),
                        filetype,
                        ..Default::default()
                    },
                );
            }
        };
    }
    fn update_checksum<P: AsRef<Path>>(
        &mut self,
        path: P,
        digest: Digest,
        hash: String,
    ) {
        let filetype = EntryType::from(path.as_ref());
        let map = match filetype {
            EntryType::Distfile => &mut self.distfiles,
            EntryType::Patchfile => &mut self.patchfiles,
        };
        match map.get_mut(path.as_ref()) {
            Some(entry) => entry.checksums.push(Checksum { digest, hash }),
            None => {
                let v: Vec<Checksum> = vec![Checksum { digest, hash }];
                map.insert(
                    path.as_ref().to_path_buf(),
                    Entry {
                        filename: path.as_ref().to_path_buf(),
                        checksums: v,
                        filetype,
                        ..Default::default()
                    },
                );
            }
        };
    }

    /**
     * Pass the full path to a file to check as a [`PathBuf`] and verify that
     * it matches the size stored in the [`Distinfo`].
     *
     * Returns the size if [`Ok`], otherwise return a [`DistinfoError`].
     */
    pub fn verify_size<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Result<u64, DistinfoError> {
        let entry = self.find_entry(path.as_ref())?;
        entry.verify_size(path)
    }

    /**
     * Pass the full path to a file to check as a [`PathBuf`] and verify that
     * it matches a specific [`Digest`] checksum stored in the [`Distinfo`].
     *
     * Return the [`Digest`] if [`Ok`], otherwise return a [`DistinfoError`].
     *
     * To verify all stored checksums use use [`verify_checksums`].
     *
     * [`verify_checksums`]: Distinfo::verify_checksums
     */
    pub fn verify_checksum<P: AsRef<Path>>(
        &self,
        path: P,
        digest: Digest,
    ) -> Result<Digest, DistinfoError> {
        let entry = self.find_entry(path.as_ref())?;
        entry.verify_checksum_internal(path, digest)
    }

    /**
     * Pass the full path to a file to check as a [`PathBuf`] and verify that
     * it matches all of the checksums stored in the [`Distinfo`].  Returns a
     * [`Vec`] of [`Result`]s containing the [`Digest`] if [`Ok`], otherwise
     * return a [`DistinfoError`].
     */
    pub fn verify_checksums<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Vec<Result<Digest, DistinfoError>> {
        let entry = match self.find_entry(path.as_ref()) {
            Ok(entry) => entry,
            Err(e) => return vec![Err(e)],
        };
        let mut results = vec![];
        for c in &entry.checksums {
            results
                .push(entry.verify_checksum_internal(path.as_ref(), c.digest));
        }
        results
    }

    /**
     * Read a [`Vec`] of [`u8`] bytes and parse for [`Distinfo`] entries.  If
     * nothing is found then an empty [`Distinfo`] is returned.
     */
    pub fn from_bytes(bytes: &[u8]) -> Distinfo {
        let mut distinfo = Distinfo::new();
        for line in bytes.split(|c| *c == b'\n') {
            match Line::from_bytes(line) {
                /*
                 * We shouldn't encounter multiple RcsId entries, but if we do
                 * then last match wins.
                 */
                Line::RcsId(s) => distinfo.rcsid = Some(s),
                Line::Size(p, v) => {
                    distinfo.update_size(&p, v);
                }
                Line::Checksum(d, p, s) => {
                    distinfo.update_checksum(&p, d, s);
                }
                Line::None => {}
            }
        }
        distinfo
    }

    /**
     * Convert [`Distinfo`] into a byte representation suitable for writing to
     * a `distinfo` file.  The contents will be ordered as expected.
     */
    pub fn as_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        if let Some(s) = self.rcsid() {
            bytes.extend_from_slice(s.as_bytes());
        } else {
            bytes.extend_from_slice("$NetBSD$".as_bytes());
        }
        bytes.extend_from_slice("\n\n".as_bytes());

        for q in self.distfiles.values() {
            for c in &q.checksums {
                let _ = writeln!(
                    bytes,
                    "{} ({}) = {}",
                    c.digest,
                    q.filename.display(),
                    c.hash,
                );
            }
            if let Some(size) = q.size {
                let _ = writeln!(
                    bytes,
                    "Size ({}) = {} bytes",
                    q.filename.display(),
                    size,
                );
            }
        }

        for q in self.patchfiles.values() {
            for c in &q.checksums {
                let _ = writeln!(
                    bytes,
                    "{} ({}) = {}",
                    c.digest,
                    q.filename.display(),
                    c.hash,
                );
            }
        }

        bytes
    }
}

impl Line {
    fn from_bytes(bytes: &[u8]) -> Line {
        /*
         * Despite expecting a single line, handle embedded newlines anyway
         * to simplify things.  First valid (i.e. not None) match wins.
         */
        for line in bytes.split(|c| *c == b'\n') {
            let mut start = 0;
            /*
             * Skip leading whitespace.  Technically this isn't supported, but
             * be liberal in what you accept...
             */
            for ch in line.iter() {
                if !(*ch as char).is_whitespace() {
                    break;
                }
                start += 1;
            }

            let line = &line[start..];

            /* Skip comments and empty lines */
            if line.starts_with(b"#") || line.is_empty() {
                continue;
            }

            /*
             * Match NetBSD RCS Id.  Only match an expanded "$NetBSD: ..."
             * string, there's no point matching an unexpanded "$NetBSD$".
             */
            if line.starts_with(b"$NetBSD: ") {
                return Line::RcsId(OsString::from_vec((*line).to_vec()));
            }

            /*
             * The remaining types are matched the same, even though they in
             * format, because the important parts are in the same place:
             *
             *   DIGEST (FILENAME) = HASH
             *   Size (FILENAME) = BYTES bytes
             *
             * We just ignore the trailing "bytes" of "Size" lines.
             *
             * If we see anything we don't like then Line::None is
             * immediately returned.
             */
            let mut field = 0;
            let mut action = String::new();
            let mut path = PathBuf::new();
            let mut value = String::new();
            for s in line.split(|c| (*c as char).is_whitespace()) {
                /* Skip extra whitespace */
                if s.is_empty() {
                    continue;
                }
                if field == 0 {
                    action = match String::from_utf8(s.to_vec()) {
                        Ok(s) => s,
                        Err(_) => return Line::None,
                    };
                }
                /* Record path from "(filename)" */
                if field == 1 {
                    if s[0] == b'(' && s[s.len() - 1] == b')' {
                        path.push(OsStr::from_bytes(&s[1..s.len() - 1]));
                    } else {
                        return Line::None;
                    }
                }
                /* Record size or hash */
                if field == 3 {
                    value = match String::from_utf8(s.to_vec()) {
                        Ok(s) => s,
                        Err(_) => return Line::None,
                    }
                }
                field += 1;
            }
            /*
             * Valid actions are "Size", or a valid Digest type.  Anything
             * else is unmatched.
             */
            if action == "Size" {
                match u64::from_str(&value) {
                    Ok(n) => return Line::Size(path, n),
                    Err(_) => return Line::None,
                };
            } else {
                match Digest::from_str(&action) {
                    Ok(d) => return Line::Checksum(d, path, value),
                    Err(_) => return Line::None,
                }
            }
        }
        Line::None
    }
}

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

    /*
     * Test RcsId parsing, with and without additional whitespace and comments.
     */
    #[test]
    fn test_line_rcsid() {
        let rcsid = "$NetBSD: distinfo,v 1.1 1970/01/01 01:01:01 ken Exp $";
        let exp = Line::RcsId(rcsid.into());

        assert_eq!(Line::from_bytes(rcsid.as_bytes()), exp);
        assert_eq!(Line::from_bytes(format!("     {rcsid}").as_bytes()), exp);
        assert_eq!(Line::from_bytes(format!("\n\n {rcsid}").as_bytes()), exp);
        assert_eq!(Line::from_bytes(format!(" {rcsid}\n\n").as_bytes()), exp);

        /* Commented entry should return None */
        let entry = Line::from_bytes(format!("#{rcsid}").as_bytes());
        assert_eq!(entry, Line::None);
    }

    #[test]
    fn test_line_size() {
        /*
         * Regular entry
         */
        let i = "Size    (foo-1.2.3.tar.gz)    =    321     bytes";
        let o = Line::from_bytes(i.as_bytes());
        assert_eq!(o, Line::Size(PathBuf::from("foo-1.2.3.tar.gz"), 321));

        /*
         * Entry with extra whitespace is accepted, but in reality is likely
         * to be rejected by other tools.
         */
        let i = "Size    (foo-1.2.3.tar.gz)    =    321     bytes";
        let o = Line::from_bytes(i.as_bytes());
        assert_eq!(o, Line::Size(PathBuf::from("foo-1.2.3.tar.gz"), 321));

        /*
         * Invalid as it's missing "bytes", but accepted anyway.
         */
        let i = "Size (foo-1.2.3.tar.gz) = 123";
        let o = Line::from_bytes(i.as_bytes());
        assert_eq!(o, Line::Size(PathBuf::from("foo-1.2.3.tar.gz"), 123));

        /*
         * Check for u64 overflow
         */
        let i = "Size (a.tar.gz) = 18446744073709551615";
        let o = Line::from_bytes(i.as_bytes());
        assert_eq!(
            o,
            Line::Size(PathBuf::from("a.tar.gz"), 18446744073709551615)
        );
        let i = "Size (a.tar.gz) = 18446744073709551616";
        let o = Line::from_bytes(i.as_bytes());
        assert_eq!(o, Line::None);
    }

    #[test]
    fn test_line_digest() {
        let i = "BLAKE2s (pkgin-23.8.1.tar.gz) = ojnk";
        let o = Line::from_bytes(i.as_bytes());
        assert_eq!(
            o,
            Line::Checksum(
                Digest::BLAKE2s,
                PathBuf::from("pkgin-23.8.1.tar.gz"),
                "ojnk".to_string()
            )
        );
    }

    #[test]
    fn test_line_none() {
        let o = Line::from_bytes(String::new().as_bytes());
        assert_eq!(o, Line::None);
        let o = Line::from_bytes("\n  \n\n".to_string().as_bytes());
        assert_eq!(o, Line::None);
        let o = Line::from_bytes("#  \n\n".to_string().as_bytes());
        assert_eq!(o, Line::None);
    }

    #[test]
    fn test_distinfo() {
        let i = r#"
            $NetBSD: distinfo,v 1.80 2024/05/27 23:27:10 riastradh Exp $

            BLAKE2s (pkgin-23.8.1.tar.gz) = eb0f008ba9801a3c0a35de3e2b2503edd554c3cb17235b347bb8274a18794eb7
            SHA512 (pkgin-23.8.1.tar.gz) = 2561d9e4b28a9a77c3c798612ec489dd67dd9a93c61344937095b0683fa89d8432a9ab8e600d0e2995d954888ac2e75a407bab08aa1e8198e375c99d2999f233
            Size (pkgin-23.8.1.tar.gz) = 267029 bytes
            SHA1 (patch-configure.ac) = 53f56351fb602d9fdce2c1ed266d65919a369086
        "#;
        let di = Distinfo::from_bytes(i.as_bytes());
        assert_eq!(
            di.rcsid(),
            Some(&OsString::from(
                "$NetBSD: distinfo,v 1.80 2024/05/27 23:27:10 riastradh Exp $"
            ))
        );
        let f = di.distfile("pkgin-23.8.1.tar.gz");
        assert!(f.is_some());
        let p = di.patchfile("patch-configure.ac");
        assert!(p.is_some());
        assert_eq!(None, di.distfile("foo-23.8.1.tar.gz"));
        assert_eq!(None, di.patchfile("patch-Makefile"));
    }

    #[test]
    fn test_construct() {
        let mut di = Distinfo::new();

        let distsums: Vec<Checksum> = vec![
            Checksum::new(Digest::BLAKE2s, String::new()),
            Checksum::new(Digest::SHA512, String::new()),
        ];

        let entry =
            Entry::new("foo.tar.gz", "/distfiles/foo.tar.gz", distsums, None);

        /* First insert is created, returns true */
        assert!(di.insert(entry.clone()));

        /* Second insert is an update, returns false */
        assert!(!di.insert(entry.clone()));

        assert_eq!(di.distfiles()[0].filetype, EntryType::Distfile);
        assert_eq!(di.distfiles().len(), 1);

        let patchsums: Vec<Checksum> =
            vec![Checksum::new(Digest::SHA1, String::new())];

        di.insert(Entry::new(
            "patch-Makefile",
            "patches/patch-Makefile",
            patchsums,
            None,
        ));

        assert_eq!(di.patchfiles().len(), 1);
        assert_eq!(di.patchfiles()[0].filetype, EntryType::Patchfile);
    }

    #[test]
    fn test_is_patch_filename() {
        /* Valid patch filenames */
        assert!(Entry::is_patch_filename("patch-Makefile"));
        assert!(Entry::is_patch_filename("patch-configure.ac"));
        assert!(Entry::is_patch_filename("emul-linux-x86-patch-foo"));

        /* Junk files */
        assert!(!Entry::is_patch_filename("patch-local-foo"));
        assert!(!Entry::is_patch_filename("patch-Makefile.orig"));
        assert!(!Entry::is_patch_filename("patch-Makefile.rej"));
        assert!(!Entry::is_patch_filename("patch-Makefile~"));

        /* Distfiles (don't match patch pattern) */
        assert!(!Entry::is_patch_filename("foo-1.0.tar.gz"));
        assert!(!Entry::is_patch_filename("patch-2.7.6.tar.xz"));
        assert!(!Entry::is_patch_filename("emul-foo.tar.gz"));
    }

    #[test]
    fn test_set_rcsid() {
        let mut di = Distinfo::new();
        assert_eq!(di.rcsid(), None);

        di.set_rcsid("$NetBSD$");
        assert_eq!(di.rcsid(), Some(&OsString::from("$NetBSD$")));

        di.set_rcsid(OsString::from("$NetBSD: test $"));
        assert_eq!(di.rcsid(), Some(&OsString::from("$NetBSD: test $")));
    }

    #[test]
    fn test_entry_as_bytes() {
        let entry = Entry::new(
            "foo-1.0.tar.gz",
            "/distfiles/foo-1.0.tar.gz",
            vec![
                Checksum::new(Digest::BLAKE2s, "abc123".to_string()),
                Checksum::new(Digest::SHA512, "def456".to_string()),
            ],
            Some(12345),
        );
        let bytes = entry.as_bytes();
        let s = String::from_utf8(bytes).expect("valid utf8");
        assert!(s.contains("BLAKE2s (foo-1.0.tar.gz) = abc123\n"));
        assert!(s.contains("SHA512 (foo-1.0.tar.gz) = def456\n"));
        assert!(s.contains("Size (foo-1.0.tar.gz) = 12345 bytes\n"));
    }

    #[test]
    fn test_entry_as_bytes_no_size() {
        let entry = Entry::new(
            "patch-Makefile",
            "patches/patch-Makefile",
            vec![Checksum::new(Digest::SHA1, "abc123".to_string())],
            None,
        );
        let bytes = entry.as_bytes();
        let s = String::from_utf8(bytes).expect("valid utf8");
        assert!(s.contains("SHA1 (patch-Makefile) = abc123\n"));
        assert!(!s.contains("Size"));
    }

    #[test]
    fn test_distinfo_as_bytes() {
        let input = concat!(
            "$NetBSD: distinfo,v 1.1 2024/01/01 00:00:00 user Exp $\n",
            "\n",
            "BLAKE2s (foo-1.0.tar.gz) = abc123\n",
            "SHA512 (foo-1.0.tar.gz) = def456\n",
            "Size (foo-1.0.tar.gz) = 99999 bytes\n",
            "SHA1 (patch-Makefile) = fedcba\n",
        );
        let di = Distinfo::from_bytes(input.as_bytes());
        let output = di.as_bytes();
        let s = String::from_utf8(output).expect("valid utf8");
        assert!(s.starts_with("$NetBSD: distinfo,v 1.1"));
        assert!(s.contains("BLAKE2s (foo-1.0.tar.gz) = abc123\n"));
        assert!(s.contains("SHA512 (foo-1.0.tar.gz) = def456\n"));
        assert!(s.contains("Size (foo-1.0.tar.gz) = 99999 bytes\n"));
        assert!(s.contains("SHA1 (patch-Makefile) = fedcba\n"));
    }

    #[test]
    fn test_line_malformed() {
        /* Missing parentheses around filename */
        let o = Line::from_bytes(b"SHA1 foo = abc123");
        assert_eq!(o, Line::None);

        /* Non-UTF8 action field */
        let o = Line::from_bytes(b"\xff\xfe (foo) = abc");
        assert_eq!(o, Line::None);

        /* Non-UTF8 value field */
        let o = Line::from_bytes(b"SHA1 (foo) = \xff\xfe");
        assert_eq!(o, Line::None);

        /* Unknown digest type */
        let o = Line::from_bytes(b"BOGUS (foo) = abc");
        assert_eq!(o, Line::None);
    }

    #[test]
    fn test_calculate_size() -> Result<(), DistinfoError> {
        let mut file = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        file.push("tests/data/digest.txt");
        let size = Distinfo::calculate_size(&file)?;
        assert_eq!(size, 158);
        Ok(())
    }

    #[test]
    fn test_calculate_checksum() -> Result<(), DistinfoError> {
        let mut file = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        file.push("tests/data/digest.txt");
        let hash = Distinfo::calculate_checksum(&file, Digest::BLAKE2s)?;
        assert_eq!(
            hash,
            "555e56e8177159b7d7fe96d5068dcf5335b554b917c8daaa4c893ec4f04b5303"
        );

        let mut patch = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        patch.push("tests/data/patch-Makefile");
        let hash = Distinfo::calculate_checksum(&patch, Digest::SHA1)?;
        assert_eq!(hash, "ab5ce8a374d3aca7948eecabc35386d8195e3fbf");
        Ok(())
    }

    #[test]
    fn test_distinfo_as_bytes_no_rcsid() {
        let mut di = Distinfo::new();
        di.insert(Entry::new(
            "foo-1.0.tar.gz",
            "/distfiles/foo-1.0.tar.gz",
            vec![Checksum::new(Digest::SHA1, "abc".to_string())],
            None,
        ));
        let output = di.as_bytes();
        let s = String::from_utf8(output).expect("valid utf8");
        assert!(s.starts_with("$NetBSD$\n\n"));
        assert!(s.contains("SHA1 (foo-1.0.tar.gz) = abc\n"));
    }
}