libnixstore 0.4.0

Rust friendly bindings to nixos nix-store library
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
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(
    nonstandard_style,
    rust_2018_idioms,
    rustdoc::broken_intra_doc_links,
    rustdoc::private_intra_doc_links
)]
#![forbid(non_ascii_idents)]

#[cxx::bridge(namespace = "libnixstore")]
mod ffi {
    struct InternalPathInfo {
        drv: String,
        narhash: String,
        time: i64,
        size: usize,
        refs: Vec<String>,
        sigs: Vec<String>,
        ca: String,
    }

    struct InternalTuple {
        lhs: String,
        rhs: String,
    }

    struct InternalDrv {
        outputs: Vec<InternalTuple>,
        input_drvs: Vec<String>,
        input_srcs: Vec<String>,
        platform: String,
        builder: String,
        args: Vec<String>,
        env: Vec<InternalTuple>,
    }

    unsafe extern "C++" {
        include!("libnixstore/include/nix.h");

        // bindings that are also available in the perl bindings
        fn init();
        fn set_verbosity(level: i32);
        fn is_valid_path(path: &str) -> Result<bool>;
        fn query_references(path: &str) -> Result<Vec<String>>;
        fn query_path_hash(path: &str) -> Result<String>;
        fn query_deriver(path: &str) -> Result<String>;
        fn query_path_info(path: &str, base32: bool) -> Result<InternalPathInfo>;
        fn query_raw_realisation(output_id: &str) -> Result<String>;
        fn query_path_from_hash_part(hash_part: &str) -> Result<String>;
        fn compute_fs_closure(
            flip_direction: bool,
            include_outputs: bool,
            paths: Vec<&str>,
        ) -> Result<Vec<String>>;
        fn topo_sort_paths(paths: Vec<&str>) -> Result<Vec<String>>;
        fn follow_links_to_store_path(path: &str) -> Result<String>;
        fn export_paths(fd: i32, paths: Vec<&str>) -> Result<()>;
        fn import_paths(fd: i32, dont_check_signs: bool) -> Result<()>;
        fn hash_path(algo: &str, base32: bool, path: &str) -> Result<String>;
        fn hash_file(algo: &str, base32: bool, path: &str) -> Result<String>;
        fn hash_string(algo: &str, base32: bool, s: &str) -> Result<String>;
        fn convert_hash(algo: &str, s: &str, to_base_32: bool) -> Result<String>;
        fn sign_string(secret_key: &str, msg: &str) -> Result<String>;
        fn check_signature(public_key: &str, sig: &str, msg: &str) -> Result<bool>;
        fn add_to_store(src_path: &str, recursive: i32, algo: &str) -> Result<String>;
        fn make_fixed_output_path(
            recursive: bool,
            algo: &str,
            hash: &str,
            name: &str,
        ) -> Result<String>;
        fn derivation_from_path(drv_path: &str) -> Result<InternalDrv>;
        fn add_temp_root(store_path: &str) -> Result<()>;
        fn get_bin_dir() -> String;
        fn get_store_dir() -> String;

        // additional but useful for harmonia
        fn get_build_log(derivation_path: &str) -> Result<String>;
        fn get_nar_list(store_path: &str) -> Result<String>;
        fn dump_path(
            store_part: &str,
            callback: unsafe extern "C" fn(data: &[u8], user_data: usize) -> bool,
            user_data: usize,
        );
    }
}

fn string_to_opt(v: String) -> Option<String> {
    if v.is_empty() {
        None
    } else {
        Some(v)
    }
}

pub struct PathInfo {
    /// The deriver of this path, if one exists.
    pub drv: Option<String>,
    /// The result of executing `nix-store --dump` on this path and hashing its output.  This string
    /// can be either a hexidecimal or base32 string, depending on the arguments passed to
    /// `query_path_info()`.
    pub narhash: String,
    /// The time at which this store path was registered.
    pub time: i64,
    /// The size of the nar archive which would be produced by applying `nix-store --dump` to this
    /// path.
    pub size: usize,
    /// The store paths referenced by this path.
    pub refs: Vec<String>,
    /// The signatures on this store path; "note: not necessarily verified".
    pub sigs: Vec<String>,
    /// Indicates if this store-path is input-addressed (`None`) or content-addressed (`Some`).  The
    /// `String` value contains the content hash as well as "some other bits of data"; see
    /// `path-info.hh` for details.
    pub ca: Option<String>,
}

pub struct Drv {
    /// The mapping from output names to to realised outpaths, or `None` for outputs which are not
    /// realised in this store.
    pub outputs: std::collections::HashMap<String, Option<String>>,
    /// The paths of this derivation's input derivations.
    pub input_drvs: Vec<String>,
    /// The paths of this derivation's input sources; these are files which enter the nix store as a
    /// result of `nix-store --add` or a `./path` reference.
    pub input_srcs: Vec<String>,
    /// The `system` field of the derivation.
    pub platform: String,
    /// The `builder` field of the derivation, which is executed in order to realise the
    /// derivation's outputs.
    pub builder: String,
    /// The arguments passed to `builder`.
    pub args: Vec<String>,
    /// The environment with which the `builder` is executed.
    pub env: std::collections::HashMap<String, String>,
}

/// Nix's `libstore` offers two options for representing the
/// hash-part of store paths.
pub enum Radix {
    /// Ordinary hexadecimal, using the 16-character alphabet [0-9a-f]
    Base16,

    /// The encoding used for filenames directly beneath /nix/store, using a 32-character alphabet
    Base32,
}

impl Default for Radix {
    /// Defaults to base-32 since that is almost always what you want.
    fn default() -> Self {
        Self::Base32
    }
}

#[inline]
/// Perform any necessary effectful operation to make the store up and running.
pub fn init() {
    ffi::init();
}

#[inline]
/// Set the loglevel.
pub fn set_verbosity(level: i32) {
    ffi::set_verbosity(level);
}

#[inline]
#[must_use]
/// Check whether a path is valid.
pub fn is_valid_path(path: &str) -> bool {
    ffi::is_valid_path(path).unwrap_or(false)
}

#[inline]
/// Return references of a valid path. It is permitted to omit the name part of the store path.
pub fn query_references(path: &str) -> Result<Vec<String>, cxx::Exception> {
    ffi::query_references(path)
}

#[inline]
/// Return narhash of a valid path. It is permitted to omit the name part of the store path.
pub fn query_path_hash(path: &str) -> Result<String, cxx::Exception> {
    ffi::query_path_hash(path)
}

#[inline]
#[must_use]
/// Return deriver of a valid path. It is permitted to omit the name part of the store path.
pub fn query_deriver(path: &str) -> Option<String> {
    match ffi::query_deriver(path) {
        Ok(v) => string_to_opt(v),
        Err(_) => None,
    }
}

#[inline]
/// Query information about a valid path. It is permitted to omit the name part of the store path.
/// The `radix` field affects only the `narHash` field of the result.
pub fn query_path_info(path: &str, radix: Radix) -> Result<PathInfo, cxx::Exception> {
    let res = ffi::query_path_info(path, matches!(radix, Radix::Base32))?;
    Ok(PathInfo {
        drv: string_to_opt(res.drv),
        narhash: res.narhash,
        time: res.time,
        size: res.size,
        refs: res.refs,
        sigs: res.sigs,
        ca: string_to_opt(res.ca),
    })
}

#[inline]
#[must_use]
/// Query the information about a realisation
pub fn query_raw_realisation(output_id: &str) -> Option<String> {
    match ffi::query_raw_realisation(output_id) {
        Ok(v) => string_to_opt(v),
        Err(_) => None,
    }
}

#[inline]
#[must_use]
/// Query the full store path given the hash part of a valid store path, or empty if the path
/// doesn't exist.
pub fn query_path_from_hash_part(hash_part: &str) -> Option<String> {
    match ffi::query_path_from_hash_part(hash_part) {
        Ok(v) => string_to_opt(v),
        Err(_) => None,
    }
}

#[inline]
/// Returns all store paths in the file system closure of `storePath`
///
/// That is, all paths than can be directly or indirectly reached from it. If `flip_direction` is
/// true, the set of paths that can reach `storePath` is returned; that is, the closures under the
/// `referrers` relation instead of the `references` relation is returned.  If `include_outputs` is
/// `true` then closure will additionally include all outputs of every derivation in the closure.
pub fn compute_fs_closure(
    flip_direction: bool,
    include_outputs: bool,
    paths: Vec<&str>,
) -> Result<Vec<String>, cxx::Exception> {
    ffi::compute_fs_closure(flip_direction, include_outputs, paths)
}

#[inline]
/// Sort a set of paths topologically under the references relation. If `p` refers to `q`, then `p`
/// precedes `q` in this list.
pub fn topo_sort_paths(paths: Vec<&str>) -> Result<Vec<String>, cxx::Exception> {
    ffi::topo_sort_paths(paths)
}

#[inline]
/// Follow symlinks until we end up with a path in the Nix store. Will transform the results to
/// store paths.
pub fn follow_links_to_store_path(path: &str) -> Result<String, cxx::Exception> {
    ffi::follow_links_to_store_path(path)
}

#[inline]
/// Export multiple paths in the format expected by `nix-store --import`.
pub fn export_paths(fd: i32, paths: Vec<&str>) -> Result<(), cxx::Exception> {
    ffi::export_paths(fd, paths)
}

#[inline]
/// Import a sequence of NAR dumps created by `export_paths()` into the Nix store. Optionally, the
/// contents of the NARs are preloaded into the specified FS accessor to speed up subsequent
/// access.
pub fn import_paths(fd: i32, dont_check_signs: bool) -> Result<(), cxx::Exception> {
    ffi::import_paths(fd, dont_check_signs)
}

#[inline]
/// Compute the hash of the given path. The hash is defined as (essentially)
/// `hashString(ht, dumpPath(path))`.
pub fn hash_path(algo: &str, radix: Radix, path: &str) -> Result<String, cxx::Exception> {
    ffi::hash_path(algo, matches!(radix, Radix::Base32), path)
}

#[inline]
/// Compute the hash of the given file.
pub fn hash_file(algo: &str, radix: Radix, path: &str) -> Result<String, cxx::Exception> {
    ffi::hash_file(algo, matches!(radix, Radix::Base32), path)
}

#[inline]
/// Compute the hash of the given string.
pub fn hash_string(algo: &str, radix: Radix, s: &str) -> Result<String, cxx::Exception> {
    ffi::hash_string(algo, matches!(radix, Radix::Base32), s)
}

#[inline]
/// Parse the hash from a string representation in the format `[<type>:]<base16|base32|base64>` or
/// `<type>-<base64>` to a string representation of the hash, in `base-16`, `base-32`. The result
/// is not prefixed by the hash type.
pub fn convert_hash(algo: &str, s: &str, to_radix: Radix) -> Result<String, cxx::Exception> {
    ffi::convert_hash(algo, s, matches!(to_radix, Radix::Base32))
}

#[inline]
/// Return a detached signature of the given string.
pub fn sign_string(secret_key: &str, msg: &str) -> Result<String, cxx::Exception> {
    ffi::sign_string(secret_key, msg)
}

#[inline]
/// Verify that `sig` is a valid signature for `msg`, using the signer's `public_key`.
pub fn check_signature(public_key: &str, sig: &str, msg: &str) -> Result<bool, cxx::Exception> {
    ffi::check_signature(public_key, sig, msg)
}

#[inline]
/// This is the preparatory part of `addToStore()`;
///
/// It computes the store path to which `src_path` is to be copied. Returns the store path.
pub fn add_to_store(src_path: &str, recursive: i32, algo: &str) -> Result<String, cxx::Exception> {
    ffi::add_to_store(src_path, recursive, algo)
}

#[inline]
pub fn make_fixed_output_path(
    recursive: bool,
    algo: &str,
    hash: &str,
    name: &str,
) -> Result<String, cxx::Exception> {
    ffi::make_fixed_output_path(recursive, algo, hash, name)
}

#[inline]
/// Read a derivation, after ensuring its existence through `ensurePath()`.
pub fn derivation_from_path(drv_path: &str) -> Result<Drv, cxx::Exception> {
    let res = ffi::derivation_from_path(drv_path)?;
    let mut outputs = std::collections::HashMap::new();
    for out in res.outputs {
        outputs.insert(out.lhs, string_to_opt(out.rhs));
    }

    let mut env = std::collections::HashMap::new();
    for v in res.env {
        env.insert(v.lhs, v.rhs);
    }

    Ok(Drv {
        outputs,
        input_drvs: res.input_drvs,
        input_srcs: res.input_srcs,
        platform: res.platform,
        builder: res.builder,
        args: res.args,
        env,
    })
}

#[inline]
/// Add a store path as a temporary root of the garbage collector. The root disappears as soon as
/// we exit.
pub fn add_temp_root(store_path: &str) -> Result<(), cxx::Exception> {
    ffi::add_temp_root(store_path)
}

#[inline]
#[must_use]
/// Return the path to the directory where the main programs are stored.
pub fn get_bin_dir() -> String {
    ffi::get_bin_dir()
}

#[inline]
#[must_use]
/// Returns the path to the directory where nix store sources and derived files.
pub fn get_store_dir() -> String {
    ffi::get_store_dir()
}

#[inline]
#[must_use]
/// Return the build log of the specified store path, if available, or null otherwise.
pub fn get_build_log(derivation_path: &str) -> Option<String> {
    match ffi::get_build_log(derivation_path) {
        Ok(v) => string_to_opt(v),
        Err(_) => None,
    }
}

#[inline]
/// Return a JSON representation as String of the contents of a NAR (except file contents).
pub fn get_nar_list(store_path: &str) -> Result<String, cxx::Exception> {
    ffi::get_nar_list(store_path)
}

fn dump_path_trampoline<F>(data: &[u8], userdata: usize) -> bool
where
    F: FnMut(&[u8]) -> bool,
{
    let closure = unsafe { &mut *(userdata as *mut std::ffi::c_void).cast::<F>() };
    closure(data)
}

#[inline]
/// Dump a store path in NAR format. The data is passed in chunks to callback
pub fn dump_path<F>(store_path: &str, callback: F)
where
    F: FnMut(&[u8]) -> bool,
{
    ffi::dump_path(
        store_path,
        dump_path_trampoline::<F>,
        std::ptr::addr_of!(callback).cast::<std::ffi::c_void>() as usize,
    );
}