nix_bindings_store/derivation/
mod.rs

1#![cfg(nix_at_least = "2.33.0pre")]
2
3use nix_bindings_store_sys as raw;
4#[cfg(nix_at_least = "2.33")]
5use nix_bindings_util::{
6    check_call,
7    context::Context,
8    result_string_init,
9    string_return::{callback_get_result_string, callback_get_result_string_data},
10};
11use std::ptr::NonNull;
12
13/// A Nix derivation
14///
15/// **Requires Nix 2.33 or later.**
16pub struct Derivation {
17    pub(crate) inner: NonNull<raw::derivation>,
18}
19
20impl Derivation {
21    pub(crate) fn new_raw(inner: NonNull<raw::derivation>) -> Self {
22        Derivation { inner }
23    }
24
25    /// Convert the derivation to JSON (which is encoded to a string).
26    ///
27    /// **Requires Nix 2.33 or later.**
28    ///
29    /// The JSON format follows the [Nix derivation JSON schema](https://nix.dev/manual/nix/latest/protocols/json/derivation.html).
30    /// Note that this format is experimental as of writing.
31    #[cfg(nix_at_least = "2.33")]
32    pub fn to_json_string(&self) -> anyhow::Result<String> {
33        let mut ctx = Context::new();
34
35        unsafe {
36            let mut r = result_string_init!();
37            check_call!(raw::derivation_to_json(
38                &mut ctx,
39                self.inner.as_ptr(),
40                Some(callback_get_result_string),
41                callback_get_result_string_data(&mut r)
42            ))?;
43            r
44        }
45    }
46
47    /// This is a low level function that you shouldn't have to call unless you are developing the Nix bindings.
48    ///
49    /// Construct a new `Derivation` by first cloning the C derivation.
50    ///
51    /// # Safety
52    ///
53    /// This does not take ownership of the C derivation, so it should be a borrowed pointer, or you should free it.
54    pub unsafe fn new_raw_clone(inner: NonNull<raw::derivation>) -> Self {
55        Self::new_raw(
56            NonNull::new(raw::derivation_clone(inner.as_ptr()))
57                .or_else(|| panic!("nix_derivation_clone returned a null pointer"))
58                .unwrap(),
59        )
60    }
61
62    /// This is a low level function that you shouldn't have to call unless you are developing the Nix bindings.
63    ///
64    /// Get a pointer to the underlying Nix C API derivation.
65    ///
66    /// # Safety
67    ///
68    /// This function is unsafe because it returns a raw pointer. The caller must ensure that the pointer is not used beyond the lifetime of this `Derivation`.
69    pub unsafe fn as_ptr(&self) -> *mut raw::derivation {
70        self.inner.as_ptr()
71    }
72}
73
74impl Clone for Derivation {
75    fn clone(&self) -> Self {
76        unsafe { Self::new_raw_clone(self.inner) }
77    }
78}
79
80impl Drop for Derivation {
81    fn drop(&mut self) {
82        unsafe {
83            raw::derivation_free(self.inner.as_ptr());
84        }
85    }
86}
87
88#[cfg(feature = "harmonia")]
89mod harmonia;
90
91#[cfg(test)]
92mod tests {}