nix-bindings 0.2347.3

Rust binding for Nix, the build tool
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
//! Nix flake support.
//!
//! Types:
//!
//! - [`FlakeSettings`]: global flake configuration; pass to
//!   [`EvalStateBuilder::with_flake_settings`](crate::EvalStateBuilder::with_flake_settings).
//! - [`FetchersSettings`]: fetcher configuration required by
//!   [`FlakeReference::parse`] and [`LockedFlake::lock`].
//! - [`FlakeReferenceParseFlags`]: optional flags controlling how a flake
//!   reference string is parsed.
//! - [`LockFlags`]: controls locking behaviour (check, virtual,
//!   write-as-needed, input overrides).
//! - [`FlakeReference`]: an unresolved reference to a flake; produced by
//!   [`FlakeReference::parse`].
//! - [`LockedFlake`]: a fully locked flake; produced by [`LockedFlake::lock`].
//!   Call [`LockedFlake::output_attrs`] to obtain the flake's output attribute
//!   set.

use std::{ffi::CString, ptr::NonNull, sync::Arc};

use crate::{Context, Error, EvalState, Result, Value, check_err, sys};

/// Configuration for the Nix flake subsystem.
///
/// This enables flake evaluation features in the Nix evaluator (such as
/// `builtins.getFlake`). Obtain a `FlakeSettings` and pass it to
/// [`EvalStateBuilder::with_flake_settings`](crate::EvalStateBuilder::with_flake_settings)
/// before building the [`EvalState`].
///
/// # Example
///
/// ```no_run
/// use std::sync::Arc;
///
/// use nix_bindings::{Context, EvalStateBuilder, Store, flake::FlakeSettings};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///   let ctx = Arc::new(Context::new()?);
///   let store = Arc::new(Store::open(&ctx, None)?);
///   let flake_settings = FlakeSettings::new(&ctx)?;
///   let state = EvalStateBuilder::new(&store)?
///     .with_flake_settings(&flake_settings)?
///     .build()?;
///
///   Ok(())
/// }
/// ```
pub struct FlakeSettings {
  pub(crate) inner: NonNull<sys::nix_flake_settings>,
  _context:         Arc<Context>,
}

impl FlakeSettings {
  /// Create a new set of flake settings with default values.
  ///
  /// # Errors
  ///
  /// Returns an error if the underlying allocation fails.
  pub fn new(context: &Arc<Context>) -> Result<Self> {
    // SAFETY: context is valid
    let ptr = unsafe { sys::nix_flake_settings_new(context.as_ptr()) };

    let inner = NonNull::new(ptr).ok_or(Error::NullPointer)?;

    Ok(FlakeSettings {
      inner,
      _context: Arc::clone(context),
    })
  }

  /// Get the raw flake settings pointer.
  pub(crate) unsafe fn as_ptr(&self) -> *mut sys::nix_flake_settings {
    self.inner.as_ptr()
  }
}

impl Drop for FlakeSettings {
  fn drop(&mut self) {
    // SAFETY: We own the settings and they are valid until drop
    unsafe {
      sys::nix_flake_settings_free(self.inner.as_ptr());
    }
  }
}

// SAFETY: `FlakeSettings` owns its `nix_flake_settings*` and uses the
// `Arc<Context>` purely for lifetime extension. The settings object
// holds plain configuration values with no thread affinity. `Sync` is
// NOT implemented: every method that consults the settings goes through
// `Context`'s racy error buffer.
unsafe impl Send for FlakeSettings {}

/// Fetcher configuration.
///
/// This is required by [`FlakeReference::parse`] and [`LockedFlake::lock`].
/// Create one with [`FetchersSettings::new`] and keep it alive for the
/// duration of any flake operations that need it.
pub struct FetchersSettings {
  inner:    NonNull<sys::nix_fetchers_settings>,
  _context: Arc<Context>,
}

impl FetchersSettings {
  /// Create new fetcher settings with default values.
  ///
  /// # Errors
  ///
  /// Returns an error if the underlying allocation fails.
  pub fn new(context: &Arc<Context>) -> Result<Self> {
    // SAFETY: context is valid
    let ptr = unsafe { sys::nix_fetchers_settings_new(context.as_ptr()) };
    let inner = NonNull::new(ptr).ok_or(Error::NullPointer)?;
    Ok(FetchersSettings {
      inner,
      _context: Arc::clone(context),
    })
  }

  pub(crate) unsafe fn as_ptr(&self) -> *mut sys::nix_fetchers_settings {
    self.inner.as_ptr()
  }
}

impl Drop for FetchersSettings {
  fn drop(&mut self) {
    // SAFETY: We own the settings and they are valid until drop
    unsafe {
      sys::nix_fetchers_settings_free(self.inner.as_ptr());
    }
  }
}

// SAFETY: `FetchersSettings` is an opaque pointer to plain configuration
// values, kept alive by `Arc<Context>`. The C object has no thread
// affinity. `Sync` is NOT implemented for the same reason as
// `FlakeSettings`: any call into it routes through `Context`'s racy
// error buffer.
unsafe impl Send for FetchersSettings {}

/// Flags that control how a flake reference string is parsed.
///
/// Create one with [`FlakeReferenceParseFlags::new`] then optionally call
/// [`set_base_directory`](Self::set_base_directory) before passing it to
/// [`FlakeReference::parse`].
pub struct FlakeReferenceParseFlags {
  inner:    NonNull<sys::nix_flake_reference_parse_flags>,
  _context: Arc<Context>,
}

impl FlakeReferenceParseFlags {
  /// Create new parse flags with default values.
  ///
  /// # Errors
  ///
  /// Returns an error if the underlying allocation fails.
  pub fn new(
    context: &Arc<Context>,
    flake_settings: &FlakeSettings,
  ) -> Result<Self> {
    // SAFETY: context and flake_settings are valid
    let ptr = unsafe {
      sys::nix_flake_reference_parse_flags_new(
        context.as_ptr(),
        flake_settings.as_ptr(),
      )
    };
    let inner = NonNull::new(ptr).ok_or(Error::NullPointer)?;
    Ok(FlakeReferenceParseFlags {
      inner,
      _context: Arc::clone(context),
    })
  }

  /// Set the base directory used when resolving relative flake references.
  ///
  /// # Errors
  ///
  /// Returns an error if the C API call fails.
  pub fn set_base_directory(self, dir: &str) -> Result<Self> {
    let bytes = dir.as_bytes();
    // SAFETY: context, flags, and dir bytes are valid
    unsafe {
      check_err(
        self._context.as_ptr(),
        sys::nix_flake_reference_parse_flags_set_base_directory(
          self._context.as_ptr(),
          self.inner.as_ptr(),
          bytes.as_ptr().cast(),
          bytes.len(),
        ),
      )?;
    }
    Ok(self)
  }

  pub(crate) unsafe fn as_ptr(
    &self,
  ) -> *mut sys::nix_flake_reference_parse_flags {
    self.inner.as_ptr()
  }
}

impl Drop for FlakeReferenceParseFlags {
  fn drop(&mut self) {
    // SAFETY: We own the flags and they are valid until drop
    unsafe {
      sys::nix_flake_reference_parse_flags_free(self.inner.as_ptr());
    }
  }
}

// SAFETY: `FlakeReferenceParseFlags` is a small flags struct kept alive
// by `Arc<Context>` plus `Arc<FlakeSettings>`. Both Arcs are themselves
// `Send` for our types (see their notes). The C object has no thread
// affinity. `Sync` is NOT implemented: `set_base_directory` mutates
// state through `Context`'s racy error buffer.
unsafe impl Send for FlakeReferenceParseFlags {}

/// Lock-file update strategy for [`LockFlags::set_mode`].
///
/// The three modes are mutually exclusive at the C-API level. Picking one
/// writes into the underlying `nix_flake_lock_flags` slot, so chaining
/// modes is meaningless. Exposing them as an enum makes that obvious at
/// the call site.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockMode {
  /// Require the lock file to be up-to-date; fail if it needs updating.
  Check,
  /// Update the lock file in memory only; do not write it to disk.
  Virtual,
  /// Update and write the lock file to disk if it needs updating.
  WriteAsNeeded,
}

/// Flags controlling the lock-file update strategy for [`LockedFlake::lock`].
///
/// Holds an Arc to the originating [`FlakeSettings`] so the settings cannot
/// be dropped while these flags are alive.
pub struct LockFlags {
  inner:     NonNull<sys::nix_flake_lock_flags>,
  _context:  Arc<Context>,
  _settings: Arc<FlakeSettings>,
}

impl LockFlags {
  /// Create new lock flags with default values.
  ///
  /// # Errors
  ///
  /// Returns an error if the underlying allocation fails.
  pub fn new(
    context: &Arc<Context>,
    flake_settings: &Arc<FlakeSettings>,
  ) -> Result<Self> {
    // SAFETY: context and flake_settings are valid
    let ptr = unsafe {
      sys::nix_flake_lock_flags_new(context.as_ptr(), flake_settings.as_ptr())
    };
    let inner = NonNull::new(ptr).ok_or(Error::NullPointer)?;
    Ok(LockFlags {
      inner,
      _context: Arc::clone(context),
      _settings: Arc::clone(flake_settings),
    })
  }

  /// Set the lock-file update strategy.
  ///
  /// # Errors
  ///
  /// Returns an error if the C API call fails.
  pub fn set_mode(self, mode: LockMode) -> Result<Self> {
    // SAFETY: context and flags are valid
    unsafe {
      let err = match mode {
        LockMode::Check => {
          sys::nix_flake_lock_flags_set_mode_check(
            self._context.as_ptr(),
            self.inner.as_ptr(),
          )
        },
        LockMode::Virtual => {
          sys::nix_flake_lock_flags_set_mode_virtual(
            self._context.as_ptr(),
            self.inner.as_ptr(),
          )
        },
        LockMode::WriteAsNeeded => {
          sys::nix_flake_lock_flags_set_mode_write_as_needed(
            self._context.as_ptr(),
            self.inner.as_ptr(),
          )
        },
      };
      check_err(self._context.as_ptr(), err)?;
    }
    Ok(self)
  }

  /// Override a specific input with an alternative flake reference.
  ///
  /// `input_path` identifies the input (e.g. `"nixpkgs"`).
  ///
  /// # Errors
  ///
  /// Returns an error if the C API call fails.
  pub fn add_input_override(
    self,
    input_path: &str,
    flake_ref: &FlakeReference,
  ) -> Result<Self> {
    let path_c = CString::new(input_path)?;
    // SAFETY: context, flags, path_c, and flake_ref are valid
    unsafe {
      check_err(
        self._context.as_ptr(),
        sys::nix_flake_lock_flags_add_input_override(
          self._context.as_ptr(),
          self.inner.as_ptr(),
          path_c.as_ptr(),
          flake_ref.inner.as_ptr(),
        ),
      )?;
    }
    Ok(self)
  }

  pub(crate) unsafe fn as_ptr(&self) -> *mut sys::nix_flake_lock_flags {
    self.inner.as_ptr()
  }
}

impl Drop for LockFlags {
  fn drop(&mut self) {
    // SAFETY: We own the flags and they are valid until drop
    unsafe {
      sys::nix_flake_lock_flags_free(self.inner.as_ptr());
    }
  }
}

// SAFETY: `LockFlags` is a small mode-and-overrides struct kept alive
// by `Arc<Context>` plus `Arc<FlakeSettings>`. Same move-only contract
// as `FlakeReferenceParseFlags`. `Sync` is NOT implemented:
// `set_mode` and `add_input_override` mutate through `Context`'s racy
// error buffer.
unsafe impl Send for LockFlags {}

/// Callback that collects a string returned from the Nix C API via a pointer
/// and length pair into an `Option<String>` stored in `user_data`.
unsafe extern "C" fn collect_fragment_cb(
  start: *const std::os::raw::c_char,
  n: std::os::raw::c_uint,
  user_data: *mut std::os::raw::c_void,
) {
  let result = unsafe { &mut *(user_data as *mut Option<String>) };
  if !start.is_null() {
    let bytes =
      unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
    *result = std::str::from_utf8(bytes).ok().map(|s| s.to_owned());
  }
}

/// An unresolved flake reference.
///
/// Obtain one via [`FlakeReference::parse`], then pass it to
/// [`LockedFlake::lock`] (or [`LockFlags::add_input_override`]).
pub struct FlakeReference {
  inner:    NonNull<sys::nix_flake_reference>,
  _context: Arc<Context>,
}

impl FlakeReference {
  /// Parse a flake reference string into a [`FlakeReference`].
  ///
  /// Returns both the parsed reference and any fragment that followed a `#`
  /// in the input string. For references without a fragment the second
  /// element is an empty string.
  ///
  /// # Errors
  ///
  /// Returns an error if the C API call fails or returns a null pointer.
  pub fn parse(
    context: &Arc<Context>,
    fetch_settings: &FetchersSettings,
    flake_settings: &FlakeSettings,
    parse_flags: &FlakeReferenceParseFlags,
    s: &str,
  ) -> Result<(Self, String)> {
    let bytes = s.as_bytes();

    let mut out_ptr: *mut sys::nix_flake_reference = std::ptr::null_mut();
    let mut fragment: Option<String> = None;

    // SAFETY: all arguments are valid; we capture the fragment via callback
    let err = unsafe {
      sys::nix_flake_reference_and_fragment_from_string(
        context.as_ptr(),
        fetch_settings.as_ptr(),
        flake_settings.as_ptr(),
        parse_flags.as_ptr(),
        bytes.as_ptr().cast(),
        bytes.len(),
        &mut out_ptr as *mut *mut sys::nix_flake_reference,
        Some(collect_fragment_cb),
        &mut fragment as *mut Option<String> as *mut std::os::raw::c_void,
      )
    };

    check_err(unsafe { context.as_ptr() }, err)?;

    let inner = NonNull::new(out_ptr).ok_or(Error::NullPointer)?;

    let frag = fragment.unwrap_or_default();

    Ok((
      FlakeReference {
        inner,
        _context: Arc::clone(context),
      },
      frag,
    ))
  }
}

impl Drop for FlakeReference {
  fn drop(&mut self) {
    // SAFETY: We own the reference and it is valid until drop
    unsafe {
      sys::nix_flake_reference_free(self.inner.as_ptr());
    }
  }
}

// SAFETY: `FlakeReference` wraps a parsed but unresolved reference value
// owned outright via `nix_flake_reference*`, kept alive by
// `Arc<Context>`. Resolution happens later through `LockedFlake::lock`,
// which calls into `Context`; sending the unresolved value to another
// thread before locking is sound. `Sync` is NOT implemented because
// `lock` and `add_input_override` mutate through `Context`'s error
// buffer.
unsafe impl Send for FlakeReference {}

/// A fully locked flake.
///
/// Obtain one via [`LockedFlake::lock`], then call
/// [`output_attrs`](LockedFlake::output_attrs) to get the attribute set of
/// flake outputs.
pub struct LockedFlake {
  inner:    NonNull<sys::nix_locked_flake>,
  _context: Arc<Context>,
}

impl LockedFlake {
  /// Lock a flake, resolving and pinning all inputs.
  ///
  /// # Errors
  ///
  /// Returns an error if the C API call fails or returns a null pointer.
  pub fn lock(
    context: &Arc<Context>,
    fetch_settings: &FetchersSettings,
    flake_settings: &FlakeSettings,
    eval_state: &EvalState,
    lock_flags: &LockFlags,
    flake_ref: &FlakeReference,
  ) -> Result<Self> {
    // SAFETY: all arguments are valid
    let ptr = unsafe {
      sys::nix_flake_lock(
        context.as_ptr(),
        fetch_settings.as_ptr(),
        flake_settings.as_ptr(),
        eval_state.as_ptr(),
        lock_flags.as_ptr(),
        flake_ref.inner.as_ptr(),
      )
    };

    let inner = NonNull::new(ptr).ok_or(Error::NullPointer)?;

    Ok(LockedFlake {
      inner,
      _context: Arc::clone(context),
    })
  }

  /// Get the output attributes of this locked flake as a Nix value.
  ///
  /// The returned [`Value`] is tied to the lifetime of `eval_state`.
  ///
  /// # Errors
  ///
  /// Returns an error if the C API call fails.
  pub fn output_attrs<'s>(
    &self,
    flake_settings: &FlakeSettings,
    eval_state: &'s EvalState,
  ) -> Result<Value<'s>> {
    // SAFETY: all pointers are valid
    let ptr = unsafe {
      sys::nix_locked_flake_get_output_attrs(
        self._context.as_ptr(),
        flake_settings.as_ptr(),
        eval_state.as_ptr(),
        self.inner.as_ptr(),
      )
    };

    let inner = std::ptr::NonNull::new(ptr).ok_or(Error::NullPointer)?;

    Ok(Value {
      inner,
      state: eval_state,
    })
  }
}

impl Drop for LockedFlake {
  fn drop(&mut self) {
    // SAFETY: We own the locked flake and it is valid until drop
    unsafe {
      sys::nix_locked_flake_free(self.inner.as_ptr());
    }
  }
}

// SAFETY: `LockedFlake` owns its `nix_locked_flake*` and keeps the
// context alive via `Arc<Context>`. The locked-flake value is immutable
// once produced; calling `output_attrs` only reads from it but still
// routes through `Context`'s error buffer, which is why `Sync` is NOT
// implemented.
unsafe impl Send for LockedFlake {}

#[cfg(test)]
mod tests {
  use std::sync::Arc;

  use serial_test::serial;

  use super::*;
  use crate::{Context, EvalStateBuilder, Store};

  fn make_state(ctx: &Arc<Context>) -> (Arc<Store>, EvalState) {
    let store = Arc::new(Store::open(ctx, None).expect("Failed to open store"));
    let flake_settings =
      FlakeSettings::new(ctx).expect("Failed to create flake settings");
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .with_flake_settings(&flake_settings)
      .expect("Failed to apply flake settings")
      .build()
      .expect("Failed to build state");
    (store, state)
  }

  #[test]
  #[serial]
  fn test_flake_settings_new() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let _settings =
      FlakeSettings::new(&ctx).expect("Failed to create flake settings");
  }

  #[test]
  #[serial]
  fn test_flake_settings_with_eval_state() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    make_state(&ctx);
  }

  #[test]
  #[serial]
  fn test_fetchers_settings_new() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let _s =
      FetchersSettings::new(&ctx).expect("Failed to create fetcher settings");
  }

  #[test]
  #[serial]
  fn test_flake_reference_parse_flags_new() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let settings = Arc::new(
      FlakeSettings::new(&ctx).expect("Failed to create flake settings"),
    );
    let _f = FlakeReferenceParseFlags::new(&ctx, &settings)
      .expect("Failed to create parse flags");
  }

  #[test]
  #[serial]
  fn test_flake_reference_parse_flags_set_base_directory() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let settings = Arc::new(
      FlakeSettings::new(&ctx).expect("Failed to create flake settings"),
    );
    let _f = FlakeReferenceParseFlags::new(&ctx, &settings)
      .expect("Failed to create parse flags")
      .set_base_directory("/tmp")
      .expect("Failed to set base directory");
  }

  #[test]
  #[serial]
  fn test_lock_flags_new() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let settings = Arc::new(
      FlakeSettings::new(&ctx).expect("Failed to create flake settings"),
    );
    let _f =
      LockFlags::new(&ctx, &settings).expect("Failed to create lock flags");
  }

  #[test]
  #[serial]
  fn test_lock_flags_set_modes() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let settings = Arc::new(
      FlakeSettings::new(&ctx).expect("Failed to create flake settings"),
    );
    let _check = LockFlags::new(&ctx, &settings)
      .expect("create")
      .set_mode(LockMode::Check)
      .expect("set Check");
    let _virtual = LockFlags::new(&ctx, &settings)
      .expect("create")
      .set_mode(LockMode::Virtual)
      .expect("set Virtual");
    let _write = LockFlags::new(&ctx, &settings)
      .expect("create")
      .set_mode(LockMode::WriteAsNeeded)
      .expect("set WriteAsNeeded");
  }
}