nix_compat/
path_info.rs

1use crate::{narinfo::SignatureRef, nixhash, store_path::StorePathRef};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeSet;
4
5/// Represents information about a Store Path that Nix provides inside the build
6/// if the exportReferencesGraph feature is used.
7/// This is not to be confused with the format Nix uses in its `nix path-info` command.
8/// It includes some more fields, like `registrationTime`, `signatures` and `ultimate`,
9/// does not include the `closureSize` and encodes `narHash` as SRI.
10#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
11pub struct ExportedPathInfo<'a> {
12    #[serde(rename = "closureSize")]
13    pub closure_size: u64,
14
15    #[serde(
16        rename = "narHash",
17        serialize_with = "nixhash::serde::to_nix_nixbase32",
18        deserialize_with = "nixhash::serde::from_nix_nixbase32_or_sri"
19    )]
20    pub nar_sha256: [u8; 32],
21
22    #[serde(rename = "narSize")]
23    pub nar_size: u64,
24
25    #[serde(borrow)]
26    pub path: StorePathRef<'a>,
27
28    #[serde(borrow)]
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub deriver: Option<StorePathRef<'a>>,
31
32    /// The list of other Store Paths this Store Path refers to.
33    /// StorePathRef does Ord by the nixbase32-encoded string repr, so this is correct.
34    pub references: BTreeSet<StorePathRef<'a>>,
35    // more recent versions of Nix also have a `valid: true` field here, Nix 2.3 doesn't,
36    // and nothing seems to use it.
37    #[serde(default, skip_serializing_if = "Vec::is_empty")]
38    pub signatures: Vec<SignatureRef<'a>>,
39}
40
41/// ExportedPathInfo are ordered by their `path` field.
42impl Ord for ExportedPathInfo<'_> {
43    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
44        self.path.cmp(&other.path)
45    }
46}
47
48impl PartialOrd for ExportedPathInfo<'_> {
49    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
50        Some(self.cmp(other))
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use hex_literal::hex;
57
58    use super::*;
59
60    /// Ensure we can create the same JSON as the exportReferencesGraph feature
61    #[test]
62    fn serialize_deserialize() {
63        // JSON extracted from a build of
64        // stdenv.mkDerivation { name = "hello"; __structuredAttrs = true; exportReferencesGraph.blub = [ pkgs.hello ]; nativeBuildInputs = [pkgs.jq]; buildCommand = "jq -rc .blub $NIX_ATTRS_JSON_FILE > $out"; }
65        let pathinfos_str_json = r#"[{"closureSize":1828984,"narHash":"sha256:11vm2x1ajhzsrzw7lsyss51mmr3b6yll9wdjn51bh7liwkpc8ila","narSize":1828984,"path":"/nix/store/7n0mbqydcipkpbxm24fab066lxk68aqk-libunistring-1.1","references":["/nix/store/7n0mbqydcipkpbxm24fab066lxk68aqk-libunistring-1.1"]},{"closureSize":32696176,"narHash":"sha256:0alzbhjxdcsmr1pk7z0bdh46r2xpq3xs3k9y82bi4bx5pklcvw5x","narSize":226560,"path":"/nix/store/dbghhbq1x39yxgkv3vkgfwbxrmw9nfzi-hello-2.12.1","references":["/nix/store/dbghhbq1x39yxgkv3vkgfwbxrmw9nfzi-hello-2.12.1","/nix/store/ddwyrxif62r8n6xclvskjyy6szdhvj60-glibc-2.39-5"]},{"closureSize":32469616,"narHash":"sha256:1zw5p05fh0k836ybfxkskv8apcv2m3pm2wa6y90wqn5w5kjyj13c","narSize":30119936,"path":"/nix/store/ddwyrxif62r8n6xclvskjyy6szdhvj60-glibc-2.39-5","references":["/nix/store/ddwyrxif62r8n6xclvskjyy6szdhvj60-glibc-2.39-5","/nix/store/rxganm4ibf31qngal3j3psp20mak37yy-xgcc-13.2.0-libgcc","/nix/store/s32cldbh9pfzd9z82izi12mdlrw0yf8q-libidn2-2.3.7"]},{"closureSize":159560,"narHash":"sha256:10q8iyvfmpfck3yiisnj1j8vp6lq3km17r26sr95zpdf9mgmk69s","narSize":159560,"path":"/nix/store/rxganm4ibf31qngal3j3psp20mak37yy-xgcc-13.2.0-libgcc","references":[]},{"closureSize":2190120,"narHash":"sha256:1cv997nzxbd91jhmzwnhxa1ahlzp5ffli8m4a5npcq8zg0vb1kwg","narSize":361136,"path":"/nix/store/s32cldbh9pfzd9z82izi12mdlrw0yf8q-libidn2-2.3.7","references":["/nix/store/7n0mbqydcipkpbxm24fab066lxk68aqk-libunistring-1.1","/nix/store/s32cldbh9pfzd9z82izi12mdlrw0yf8q-libidn2-2.3.7"]}]"#;
66
67        // We ensure it roundtrips (to check the sorting is correct)
68        let deserialized: BTreeSet<ExportedPathInfo> =
69            serde_json::from_str(pathinfos_str_json).expect("must serialize");
70
71        let serialized_again = serde_json::to_string(&deserialized).expect("must deserialize");
72        assert_eq!(pathinfos_str_json, serialized_again);
73
74        // Also compare one specific item to be populated as expected.
75        assert_eq!(
76            &ExportedPathInfo {
77                closure_size: 1828984,
78                nar_sha256: hex!(
79                    "8a46c4eee4911eb842b1b2f144a9376be45a43d1da6b7af8cffa43a942177587"
80                ),
81                nar_size: 1828984,
82                path: StorePathRef::from_bytes(
83                    b"7n0mbqydcipkpbxm24fab066lxk68aqk-libunistring-1.1"
84                )
85                .expect("must parse"),
86                deriver: None,
87                references: BTreeSet::from_iter([StorePathRef::from_bytes(
88                    b"7n0mbqydcipkpbxm24fab066lxk68aqk-libunistring-1.1"
89                )
90                .unwrap()]),
91                signatures: vec![],
92            },
93            deserialized.first().unwrap()
94        );
95    }
96
97    /// Ensure we can parse output from `nix path-info --json``
98    #[test]
99    fn serialize_deserialize_from_path_info() {
100        // JSON extracted from
101        // nix path-info /nix/store/z6r3bn5l51679pwkvh9nalp6c317z34m-libcxx-16.0.6-dev --json --closure-size
102        let pathinfos_str_json = r#"[{"closureSize":10756176,"deriver":"/nix/store/vs9976cyyxpykvdnlv7x85fpp3shn6ij-libcxx-16.0.6.drv","narHash":"sha256-E73Nt0NAKGxCnsyBFDUaCAbA+wiF5qjq1O9J7WrnT0E=","narSize":7020664,"path":"/nix/store/z6r3bn5l51679pwkvh9nalp6c317z34m-libcxx-16.0.6-dev","references":["/nix/store/lzzd5jgybnpfj86xkcpnd54xgwc4m457-libcxx-16.0.6"],"registrationTime":1730048276,"signatures":["cache.nixos.org-1:cTdhK6hnpPwtMXFX43CYb7v+CbpAusVI/MORZ3v5aHvpBYNg1MfBHVVeoexMBpNtHA8uFAn0aEsJaLXYIDhJDg=="],"valid":true}]"#;
103
104        let deserialized: BTreeSet<ExportedPathInfo> =
105            serde_json::from_str(pathinfos_str_json).expect("must serialize");
106
107        assert_eq!(
108            &ExportedPathInfo {
109                closure_size: 10756176,
110                nar_sha256: hex!(
111                    "13bdcdb74340286c429ecc8114351a0806c0fb0885e6a8ead4ef49ed6ae74f41"
112                ),
113                nar_size: 7020664,
114                path: StorePathRef::from_bytes(
115                    b"z6r3bn5l51679pwkvh9nalp6c317z34m-libcxx-16.0.6-dev"
116                )
117                .expect("must parse"),
118                deriver: Some(
119                    StorePathRef::from_bytes(
120                        b"vs9976cyyxpykvdnlv7x85fpp3shn6ij-libcxx-16.0.6.drv"
121                    )
122                    .expect("must parse")
123                ),
124                references: BTreeSet::from_iter([StorePathRef::from_bytes(
125                    b"lzzd5jgybnpfj86xkcpnd54xgwc4m457-libcxx-16.0.6"
126                )
127                .unwrap()]),
128                signatures: vec![SignatureRef::parse("cache.nixos.org-1:cTdhK6hnpPwtMXFX43CYb7v+CbpAusVI/MORZ3v5aHvpBYNg1MfBHVVeoexMBpNtHA8uFAn0aEsJaLXYIDhJDg==").expect("must parse")],
129            },
130            deserialized.first().unwrap()
131        );
132    }
133}