1use std::borrow::Cow;2use std::cell::RefCell;3use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void};4use std::fmt;5use std::ptr::null_mut;6use std::sync::LazyLock;7use std::{collections::HashMap, path::PathBuf};89use anyhow::{Context, anyhow, bail};10use serde::Serialize;11use serde::de::DeserializeOwned;1213pub use anyhow::Result;14use tracing::instrument;1516use self::logging::nix_logging_cxx;17use self::nix_cxx::set_fetcher_setting;18use self::nix_raw::{19 alloc_value, c_context, c_context_create, err_code, err_info_msg, eval_state_build,20 eval_state_builder_new, expr_eval_from_string, fetchers_settings, fetchers_settings_free,21 fetchers_settings_new, flake_lock, flake_lock_flags, flake_lock_flags_free,22 flake_lock_flags_new, flake_reference_parse_flags, flake_reference_parse_flags_free,23 flake_reference_parse_flags_new, flake_reference_parse_flags_set_base_directory,24 flake_settings, flake_settings_free, flake_settings_new, get_string, init_bool, init_int,25 init_string, locked_flake_free, locked_flake_get_output_attrs, set_err_msg, setting_set,26 state_free, value_decref, value_incref,27};282930pub mod logging;31#[doc(hidden)]32pub mod macros;33pub mod util;3435#[allow(36 non_upper_case_globals,37 non_camel_case_types,38 non_snake_case,39 dead_code40)]41mod nix_raw {42 include!(concat!(env!("OUT_DIR"), "/bindings.rs"));43}44#[cxx::bridge]45pub mod nix_cxx {46 unsafe extern "C++" {47 type nix_fetchers_settings;48 include!("nix-eval/src/lib.hh");4950 unsafe fn set_fetcher_setting(51 settings: *mut nix_fetchers_settings,52 setting: *const c_char,53 value: *const c_char,54 );55 }56}5758#[derive(Debug, PartialEq, Eq)]59pub enum NixType {60 Thunk,61 Int,62 Float,63 Bool,64 String,65 Path,66 Null,67 Attrs,68 List,69 Function,70 External,71}72impl NixType {73 fn from_int(c: c_uint) -> Self {74 match c {75 0 => Self::Thunk,76 1 => Self::Int,77 2 => Self::Float,78 3 => Self::Bool,79 4 => Self::String,80 5 => Self::Path,81 6 => Self::Null,82 7 => Self::Attrs,83 8 => Self::List,84 9 => Self::Function,85 10 => Self::External,86 _ => unreachable!("unknown nix type: {c}"),87 }88 }89}9091enum FunctorKind {92 Function,93 Functor,94}9596#[derive(Debug)]97#[repr(i32)]98pub enum NixErrorKind {99 Unknown = 1,100 Overflow = 2,101 Key = 3,102 Generic = 4,103}104impl NixErrorKind {105 fn from_int(v: c_int) -> Option<Self> {106 Some(match v {107 0 => return None,108 -1 => Self::Unknown,109 -2 => Self::Overflow,110 -3 => Self::Key,111 -4 => Self::Generic,112 _ => {113 debug_assert!(false, "unexpected nix error kind: {v}");114 Self::Unknown115 }116 })117 }118}119120pub fn gc_register_my_thread() {121 assert_eq!(unsafe { nix_raw::GC_thread_is_registered() }, 0);122123 let mut sb = nix_raw::GC_stack_base {124 mem_base: null_mut(),125 };126 let r = unsafe { nix_raw::GC_get_stack_base(&mut sb) };127 if r as u32 != nix_raw::GC_SUCCESS {128 panic!("failed to get thread stack base");129 }130 unsafe { nix_raw::GC_register_my_thread(&sb) };131}132pub fn gc_unregister_my_thread() {133 assert_eq!(unsafe { nix_raw::GC_thread_is_registered() }, 1);134135 unsafe { nix_raw::GC_unregister_my_thread() };136}137138pub struct ThreadRegisterGuard {}139impl ThreadRegisterGuard {140 #[allow(clippy::new_without_default)]141 pub fn new() -> Self {142 gc_register_my_thread();143 Self {}144 }145}146impl Drop for ThreadRegisterGuard {147 fn drop(&mut self) {148 gc_unregister_my_thread();149 }150}151152pub struct NixContext(*mut c_context);153impl NixContext {154 pub fn set_err(&mut self, err: NixErrorKind, msg: &CStr) {155 unsafe { set_err_msg(self.0, err as c_int, msg.as_ptr()) };156 }157 pub fn new() -> Self {158 let ctx = unsafe { c_context_create() };159 Self(ctx)160 }161 fn error_kind(&self) -> Option<NixErrorKind> {162 let code = unsafe { err_code(self.0) };163 NixErrorKind::from_int(code)164 }165 fn error<'t>(&self) -> Option<Cow<'t, str>> {166 if let NixErrorKind::Generic = self.error_kind()? {167 let mut err_out = String::new();168 unsafe {169 err_info_msg(170 null_mut(),171 self.0,172 Some(copy_nix_str),173 (&raw mut err_out).cast(),174 )175 };176 return Some(Cow::Owned(err_out));177 };178179 180 181 let str = unsafe { nix_raw::err_msg(null_mut(), self.0, null_mut()) };182 Some(unsafe { CStr::from_ptr(str) }.to_string_lossy())183 }184 fn clean_err(&mut self) {185 unsafe {186 nix_raw::clear_err(self.0);187 }188 }189190 fn bail_if_error(&self) -> Result<()> {191 if let Some(err) = self.error() {192 bail!("{err}");193 };194 Ok(())195 }196197 fn run_in_context<T>(&mut self, f: impl FnOnce(*mut c_context) -> T) -> Result<T> {198 self.clean_err();199 let o = f(self.0);200 self.bail_if_error()?;201 self.clean_err();202 Ok(o)203 }204}205206impl Default for NixContext {207 fn default() -> Self {208 Self::new()209 }210}211impl Drop for NixContext {212 fn drop(&mut self) {213 unsafe {214 nix_raw::c_context_free(self.0);215 }216 }217}218struct GlobalState {219 220 #[allow(dead_code)]221 store: Store,222 state: EvalState,223}224impl GlobalState {225 fn new() -> Result<Self> {226 let mut ctx = NixContext::new();227 let store = ctx228 .run_in_context(|c| unsafe { nix_raw::store_open(c, c"auto".as_ptr(), null_mut()) })229 .map(Store)?;230231 let builder = ctx.run_in_context(|c| unsafe { eval_state_builder_new(c, store.0) })?;232 ctx.run_in_context(|c| {233 unsafe { nix_raw::eval_state_builder_load(c, builder) }234 235 })?;236 ctx.run_in_context(|c| {237 unsafe {238 nix_raw::eval_state_builder_set_eval_setting(239 c,240 builder,241 c"lazy-trees".as_ptr(),242 c"true".as_ptr(),243 )244 }245 246 })?;247 ctx.run_in_context(|c| {248 unsafe {249 nix_raw::eval_state_builder_set_eval_setting(250 c,251 builder,252 c"lazy-locks".as_ptr(),253 c"true".as_ptr(),254 )255 }256 257 })?;258 let state = ctx259 .run_in_context(|c| unsafe { eval_state_build(c, builder) })260 .map(EvalState)?;261262 Ok(Self { store, state })263 }264}265266struct ThreadState {267 ctx: NixContext,268}269impl ThreadState {270 fn new() -> Result<Self> {271 let ctx = NixContext::new();272273 Ok(Self { ctx })274 }275}276277static GLOBAL_STATE: LazyLock<GlobalState> =278 LazyLock::new(|| GlobalState::new().expect("global state init shouldn't fail"));279280thread_local! {281 static THREAD_STATE: RefCell<ThreadState> = RefCell::new(ThreadState::new().expect("thread state init shouldn't fail"));282}283fn with_default_context<T>(284 f: impl FnOnce(*mut c_context, *mut nix_raw::EvalState) -> T,285) -> Result<T> {286 let global = &GLOBAL_STATE.state;287 let (ctx, state) = THREAD_STATE.with_borrow_mut(|w| (w.ctx.0, global.0));288 let mut ctx = NixContext(ctx);289 let v = ctx.run_in_context(|c| f(c, state));290 291 std::mem::forget(ctx);292 v293}294295pub fn set_setting(s: &CStr, v: &CStr) -> Result<()> {296 with_default_context(|c, _| unsafe { setting_set(c, s.as_ptr(), v.as_ptr()) }).map(|_| ())297}298299pub struct FetchSettings(*mut fetchers_settings);300impl FetchSettings {301 pub fn new() -> Self {302 Self::try_new().expect("allocation should not fail")303 }304 fn try_new() -> Result<Self> {305 with_default_context(|c, _| unsafe { fetchers_settings_new(c) }).map(Self)306 }307 pub fn set(&mut self, setting: &CStr, value: &CStr) {308 unsafe {309 set_fetcher_setting(self.0.cast(), setting.as_ptr(), value.as_ptr());310 };311 }312}313unsafe impl Send for FetchSettings {}314unsafe impl Sync for FetchSettings {}315316impl Default for FetchSettings {317 fn default() -> Self {318 Self::new()319 }320}321322impl Drop for FetchSettings {323 fn drop(&mut self) {324 unsafe { fetchers_settings_free(self.0) };325 }326}327pub struct FlakeSettings(*mut flake_settings);328impl FlakeSettings {329 pub fn new() -> Result<Self> {330 with_default_context(|c, _| unsafe { flake_settings_new(c) }).map(Self)331 }332}333unsafe impl Send for FlakeSettings {}334unsafe impl Sync for FlakeSettings {}335impl Drop for FlakeSettings {336 fn drop(&mut self) {337 unsafe {338 flake_settings_free(self.0);339 }340 }341}342343pub struct FlakeReferenceParseFlags(*mut flake_reference_parse_flags);344impl FlakeReferenceParseFlags {345 pub fn new(settings: &FlakeSettings) -> Result<Self> {346 with_default_context(|c, _| unsafe { flake_reference_parse_flags_new(c, settings.0) })347 .map(Self)348 }349 pub fn set_base_dir(&mut self, dir: &str) -> Result<()> {350 with_default_context(|c, _| {351 unsafe {352 flake_reference_parse_flags_set_base_directory(353 c,354 self.0,355 dir.as_ptr().cast(),356 dir.len(),357 )358 };359 })360 }361}362impl Drop for FlakeReferenceParseFlags {363 fn drop(&mut self) {364 unsafe {365 flake_reference_parse_flags_free(self.0);366 }367 }368}369pub struct FlakeLockFlags(*mut flake_lock_flags);370impl FlakeLockFlags {371 pub fn new(settings: &FlakeSettings) -> Result<Self> {372 let o = with_default_context(|c, _| unsafe { flake_lock_flags_new(c, settings.0) })373 .map(Self)?;374 375376 Ok(o)377 }378}379impl Drop for FlakeLockFlags {380 fn drop(&mut self) {381 unsafe {382 flake_lock_flags_free(self.0);383 }384 }385}386387unsafe extern "C" fn copy_nix_str(start: *const c_char, n: c_uint, user_data: *mut c_void) {388 let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };389 let s = std::str::from_utf8(s).expect("c string has invalid utf-8");390 unsafe { *user_data.cast::<String>() = s.to_owned() };391}392393struct Store(*mut nix_raw::Store);394unsafe impl Send for Store {}395unsafe impl Sync for Store {}396397struct EvalState(*mut nix_raw::EvalState);398unsafe impl Send for EvalState {}399unsafe impl Sync for EvalState {}400401impl Drop for EvalState {402 fn drop(&mut self) {403 unsafe {404 state_free(self.0);405 }406 }407}408409pub struct FlakeReference(*mut nix_raw::flake_reference);410impl FlakeReference {411 #[instrument(name = "new-flake-reference", skip(flake, parse, fetch))]412 pub fn new(413 s: &str,414 flake: &FlakeSettings,415 parse: &FlakeReferenceParseFlags,416 fetch: &FetchSettings,417 ) -> Result<(Self, String)> {418 let mut out = null_mut();419 let mut fragment = String::new();420 421 with_default_context(|c, _| unsafe {422 nix_raw::flake_reference_and_fragment_from_string(423 c,424 fetch.0,425 flake.0,426 parse.0,427 s.as_ptr().cast(),428 s.len(),429 &mut out,430 Some(copy_nix_str),431 (&raw mut fragment).cast(),432 )433 })?;434 assert!(!out.is_null());435436 Ok((Self(out), fragment))437 }438 #[instrument(name = "lock-flake", skip(self, fetch, flake, lock))]439 pub fn lock(440 &mut self,441 fetch: &FetchSettings,442 flake: &FlakeSettings,443 lock: &FlakeLockFlags,444 ) -> Result<LockedFlake> {445 with_default_context(|c, es| unsafe { flake_lock(c, fetch.0, flake.0, es, lock.0, self.0) })446 .map(LockedFlake)447 }448}449unsafe impl Send for FlakeReference {}450unsafe impl Sync for FlakeReference {}451452pub struct LockedFlake(*mut nix_raw::locked_flake);453impl LockedFlake {454 pub fn get_attrs(&self, settings: &mut FlakeSettings) -> Result<Value> {455 with_default_context(|c, es| unsafe {456 locked_flake_get_output_attrs(c, settings.0, es, self.0)457 })458 .map(Value)459 }460}461unsafe impl Send for LockedFlake {}462unsafe impl Sync for LockedFlake {}463impl Drop for LockedFlake {464 fn drop(&mut self) {465 unsafe {466 locked_flake_free(self.0);467 };468 }469}470471type FieldName = [u8; 32];472fn init_field_name(v: &str) -> FieldName {473 let mut f = [0; 32];474 assert!(v.len() < 32, "max field name is 31 char");475 assert!(476 v.bytes().all(|v| v != 0),477 "nul bytes are unsupported in field name"478 );479 f[0..v.len()].copy_from_slice(v.as_bytes());480 f481}482483pub struct RealisedString(*mut nix_raw::realised_string);484impl fmt::Debug for RealisedString {485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {486 self.as_str().fmt(f)487 }488}489490impl RealisedString {491 pub fn as_str(&self) -> &str {492 let len = unsafe { nix_raw::realised_string_get_buffer_size(self.0) };493 let data: *const u8 = unsafe { nix_raw::realised_string_get_buffer_start(self.0) }.cast();494 let data = unsafe { std::slice::from_raw_parts(data, len) };495 std::str::from_utf8(data).expect("non-utf8 strings not supported")496 }497 pub fn path_count(&self) -> usize {498 unsafe { nix_raw::realised_string_get_store_path_count(self.0) }499 }500 pub fn path(&self, i: usize) -> String {501 assert!(i < self.path_count());502 let path = unsafe { nix_raw::realised_string_get_store_path(self.0, i) };503 let mut err_out = String::new();504 unsafe { nix_raw::store_path_name(path, Some(copy_nix_str), (&raw mut err_out).cast()) };505 err_out506 }507}508509unsafe impl Send for RealisedString {}510impl Drop for RealisedString {511 fn drop(&mut self) {512 unsafe { nix_raw::realised_string_free(self.0) }513 }514}515516pub struct Value(*mut nix_raw::value);517518unsafe impl Send for Value {}519unsafe impl Sync for Value {}520521pub trait AsFieldName {522 fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T>;523 fn to_field_name(&self) -> Result<String>;524}525impl AsFieldName for Value {526 fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {527 let f = self.to_string()?;528 v(init_field_name(&f))529 }530 fn to_field_name(&self) -> Result<String> {531 self.to_string()532 }533}534impl<E> AsFieldName for E535where536 E: AsRef<str>,537{538 fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {539 let f = self.as_ref();540 v(init_field_name(f))541 }542 fn to_field_name(&self) -> Result<String> {543 Ok(self.as_ref().to_owned())544 }545}546547struct AttrsBuilder(*mut nix_raw::BindingsBuilder);548impl AttrsBuilder {549 fn new(capacity: usize) -> Self {550 with_default_context(|c, es| unsafe { nix_raw::make_bindings_builder(c, es, capacity) })551 .map(Self)552 .expect("alloc should not fail")553 }554 fn insert(&mut self, k: &impl AsFieldName, v: Value) {555 k.as_field_name(|name| {556 with_default_context(|c, _| unsafe {557 nix_raw::bindings_builder_insert(c, self.0, name.as_ptr().cast(), v.0)558 })559 })560 .expect("builder insert shouldn't fail");561 }562}563impl Drop for AttrsBuilder {564 fn drop(&mut self) {565 unsafe { nix_raw::bindings_builder_free(self.0) };566 }567}568569impl Value {570 pub fn new_attrs(v: HashMap<&str, Value>) -> Self {571 let out = Self::new_uninit();572 let mut b = AttrsBuilder::new(v.len());573 for (k, v) in v {574 b.insert(&k, v);575 }576 with_default_context(|c, _| unsafe { nix_raw::make_attrs(c, out.0, b.0) })577 .expect("attrs initialization should not fail");578 out579 }580 fn new_list<T: Into<Self>>(v: Vec<T>) -> Self {581 todo!()582 }583 fn new_uninit() -> Self {584 let out = with_default_context(|c, es| unsafe { alloc_value(c, es) })585 .expect("value allocation should not fail");586 Self(out)587 }588 pub fn new_str(v: &str) -> Self {589 let s = CString::new(v).expect("string should not contain NULs");590 let out = Self::new_uninit();591 592 with_default_context(|c, _| unsafe { init_string(c, out.0, s.as_ptr()) })593 .expect("string initialization should not fail");594 out595 }596 pub fn new_int(i: i64) -> Self {597 let out = Self::new_uninit();598 with_default_context(|c, _| unsafe { init_int(c, out.0, i) })599 .expect("int initialization should not fail");600 out601 }602 pub fn new_bool(v: bool) -> Self {603 let out = Self::new_uninit();604 with_default_context(|c, _| unsafe { init_bool(c, out.0, v) })605 .expect("bool initialization should not fail");606 out607 }608 609 610 611 612 613 pub fn type_of(&self) -> NixType {614 let ty = with_default_context(|c, _| unsafe { nix_raw::get_type(c, self.0) })615 .expect("get_type should not fail");616 NixType::from_int(ty)617 }618 fn builtin_to_string(&self) -> Result<Self> {619 let builtin = Self::eval("builtins.toString")?;620 builtin.call(self.clone())621 }622 pub fn to_string(&self) -> Result<String> {623 let mut str_out = String::new();624 with_default_context(|c, _| unsafe {625 get_string(c, self.0, Some(copy_nix_str), (&raw mut str_out).cast())626 })?;627628 Ok(str_out)629 }630 pub fn to_realised_string(&self) -> Result<RealisedString> {631 with_default_context(|c, es| unsafe { nix_raw::string_realise(c, es, self.0, false) })632 .map(RealisedString)633634 635 636 637 638 639 640 641 }642643 pub fn has_field(&self, field: &str) -> Result<bool> {644 let f = init_field_name(field);645 with_default_context(|c, es| unsafe {646 nix_raw::has_attr_byname(c, self.0, es, f.as_ptr().cast())647 })648 }649 650 651 652 pub fn list_fields(&self) -> Result<Vec<String>> {653 if !matches!(self.type_of(), NixType::Attrs) {654 bail!("invalid type: expected attrs");655 }656657 let len = with_default_context(|c, _| unsafe { nix_raw::get_attrs_size(c, self.0) })?;658 let mut out = Vec::with_capacity(len as usize);659660 for i in 0..len {661 let name = with_default_context(|c, es| unsafe {662 nix_raw::get_attr_name_byidx(c, self.0, es, i)663 })?;664 let c = unsafe { CStr::from_ptr(name) };665 out.push(c.to_str().expect("nix field names are utf-8").to_owned());666 }667 Ok(out)668 }669 pub fn get_elem(&self, v: usize) -> Result<Self> {670 if !matches!(self.type_of(), NixType::List) {671 bail!("invalid type: expected list");672 }673 let len =674 with_default_context(|c, _| unsafe { nix_raw::get_list_size(c, self.0) })? as usize;675 if v >= len {676 bail!("oob list get: {v} >= {len}");677 }678679 with_default_context(|c, es| unsafe { nix_raw::get_list_byidx(c, self.0, es, v as u32) })680 .map(Self)681 }682 pub fn attrs_update(self, other: Value) -> Result<Self> {683 let a_fields = self.list_fields()?;684 let b_fields = other.list_fields()?;685 match (a_fields.len(), b_fields.len()) {686 (_, 0) => return Ok(self),687 (0, _) => return Ok(other),688 _ => {}689 }690 let mut out = HashMap::new();691 for f in a_fields.iter() {692 if b_fields.contains(f) {693 break;694 }695 out.insert(f.as_str(), self.get_field(f)?);696 }697 if out.is_empty() {698 699 return Ok(other);700 }701 for f in b_fields.iter() {702 out.insert(f.as_str(), other.get_field(f)?);703 }704 Ok(Self::new_attrs(out))705 }706 pub fn get_field(&self, name: impl AsFieldName) -> Result<Self> {707 if !matches!(self.type_of(), NixType::Attrs) {708 bail!("invalid type: expected attrs");709 }710711 name.as_field_name(|name| {712 with_default_context(|c, es| unsafe {713 nix_raw::get_attr_byname(c, self.0, es, name.as_ptr().cast())714 })715 .map(Self)716 })717 .with_context(|| format!("getting field {:?}", name.to_field_name()))718 }719 pub fn call(&self, v: Value) -> Result<Self> {720 let kind = self721 .functor_kind()722 .ok_or_else(|| anyhow!("can only call function or functor"))?;723724 let function = match kind {725 FunctorKind::Function => self.clone(),726 FunctorKind::Functor => {727 let f = self.get_field("__functor")?;728 assert_eq!(729 f.type_of(),730 NixType::Function,731 "invalid functor encountered"732 );733 f734 }735 };736737 let out = Value::new_uninit();738 with_default_context(|c, es| unsafe {739 nix_raw::value_call(c, es, function.0, v.0, out.0)740 })?;741742 Ok(out)743 }744 pub fn eval(v: &str) -> Result<Self> {745 let s = CString::new(v).expect("expression shouldn't have internal NULs");746 let out = Self::new_uninit();747 with_default_context(|c, es| unsafe {748 expr_eval_from_string(c, es, s.as_ptr(), c"/homeless-shelter".as_ptr(), out.0)749 })?;750 Ok(out)751 }752 pub async fn build(&self, output: &str) -> Result<PathBuf> {753 if !self.is_derivation() {754 bail!("expected derivation to build")755 }756 let output_name = self.get_field("outputName")?.to_string()?;757 let v = if output_name != output {758 let out = self.get_field(output)?;759 if !out.is_derivation() {760 bail!("unknown output: {output}");761 }762 out763 } else {764 self.clone()765 };766 767 let drv_path =768 tokio::task::spawn_blocking(move || v.builtin_to_string()?.to_realised_string())769 .await770 .expect("spawn should not fail")?;771 Ok(PathBuf::from(drv_path.as_str()))772 }773 pub fn as_json<T: DeserializeOwned>(&self) -> Result<T> {774 let to_json = Self::eval("builtins.toJSON")?;775 let s = to_json.call(self.clone())?.to_string()?;776 Ok(serde_json::from_str(&s)?)777 }778 pub fn serialized<T: Serialize>(v: &T) -> Result<Self> {779 Self::eval(&nixlike::serialize(v)?)780 }781782 783 784 785 786 787788 fn is_derivation(&self) -> bool {789 if !matches!(self.type_of(), NixType::Attrs) {790 return false;791 }792 let Some(ty) = self.get_field("type").ok() else {793 return false;794 };795 matches!(ty.to_string().as_deref(), Ok("derivation"))796 }797 fn functor_kind(&self) -> Option<FunctorKind> {798 match self.type_of() {799 NixType::Attrs => self800 .has_field("__functor")801 .expect("has_field shouldn't fail for attrs")802 .then_some(FunctorKind::Functor),803 NixType::Function => Some(FunctorKind::Function),804 _ => None,805 }806 }807 pub fn is_function(&self) -> bool {808 self.functor_kind().is_some()809 }810}811812impl From<String> for Value {813 fn from(value: String) -> Self {814 Value::new_str(&value)815 }816}817impl From<bool> for Value {818 fn from(value: bool) -> Self {819 Value::new_bool(value)820 }821}822impl From<&str> for Value {823 fn from(value: &str) -> Self {824 Value::new_str(value)825 }826}827impl<T> From<Vec<T>> for Value828where829 T: Into<Value>,830{831 fn from(value: Vec<T>) -> Self {832 Value::new_list(value)833 }834}835836impl Clone for Value {837 fn clone(&self) -> Self {838 with_default_context(|c, _| unsafe { value_incref(c, self.0) })839 .expect("value incref should not fail");840 Self(self.0)841 }842}843impl Drop for Value {844 fn drop(&mut self) {845 with_default_context(|c, _| unsafe { value_decref(c, self.0) })846 .expect("value drop should not fail");847 }848}849850pub fn init_libraries() {851 unsafe { nix_raw::GC_allow_register_threads() };852 unsafe {853 nix_raw::GC_init();854 };855856 let mut ctx = NixContext::new();857 ctx.run_in_context(|c| unsafe { nix_raw::libutil_init(c) })858 .expect("util init should not fail");859 ctx.run_in_context(|c| unsafe { nix_raw::libstore_init(c) })860 .expect("store init should not fail");861 ctx.run_in_context(|c| unsafe { nix_raw::libexpr_init(c) })862 .expect("expr init should not fail");863864 nix_logging_cxx::apply_tracing_logger();865}866867#[test_log::test]868fn test_native() -> Result<()> {869 init_libraries();870871 let mut fetch_settings = FetchSettings::new();872 fetch_settings.set(c"warn-dirty", c"false");873874 let manifest = format!("{}/../../", env!("CARGO_MANIFEST_DIR"));875 let (mut r, _) = FlakeReference::new(&manifest, &fetch_settings)?;876 let locked = r.lock(&fetch_settings)?;877 let attrs = locked.get_attrs(&mut FlakeSettings::new()?)?;878879 let builtins = Value::eval("builtins")?;880 assert_eq!(builtins.type_of(), NixType::Attrs);881882 assert_eq!(attrs.type_of(), NixType::Attrs);883 let test_data = nix_go!(attrs.testData);884885 let test_string: String = nix_go_json!(test_data.testString);886 assert_eq!(test_string, "hello");887888 Ok(())889}