1use bindgen::{2 RustEdition,3 callbacks::{ItemInfo, ParseCallbacks},4};5use std::path::PathBuf;67#[derive(Debug)]8struct StripPrefix;9impl ParseCallbacks for StripPrefix {10 fn item_name(&self, name: ItemInfo<'_>) -> Option<String> {11 name.name.strip_prefix("nix_").map(ToOwned::to_owned)12 }13}1415fn main() {16 17 for lib in &[18 "nix-util",19 "nix-util-c",20 "nix-store",21 "nix-store-c",22 "nix-expr",23 "nix-flake",24 "nix-fetchers",25 "bdw-gc",26 ] {27 if let Ok(library) = pkg_config::probe_library(lib) {28 for lib_path in library.libs {29 println!("cargo:rustc-link-lib={lib_path}");30 }31 for search_path in library.link_paths {32 println!("cargo:rustc-link-search=native={}", search_path.display());33 }34 }35 }3637 cxx_build::bridge("src/logging.rs")38 .file("src/logging.cc")39 .std("c++23")40 .compile("nix-eval-logging");41 cxx_build::bridge("src/lib.rs")42 .file("src/lib.cc")43 .std("c++23")44 .compile("nix-eval");4546 println!("cargo:rerun-if-changed=src/lib.cc");47 println!("cargo:rerun-if-changed=src/lib.hh");48 println!("cargo:rerun-if-changed=src/logging.cc");49 println!("cargo:rerun-if-changed=src/logging.hh");5051 52 let mut libnix = bindgen::builder()53 .rust_edition(RustEdition::Edition2024)54 .header_contents(55 "nix.h",56 "57 #define GC_THREADS58 #include <gc/gc.h>59 #include <nix_api_expr.h>60 #include <nix_api_store.h>61 #include <nix_api_flake.h>62 #include <nix_api_fetchers.h>63 #include <nix_api_util.h>64 #include <nix_api_value.h>65 ",66 )67 .parse_callbacks(Box::new(StripPrefix));6869 for header in pkg_config::probe_library("nix-expr-c")70 .expect("nix-expr-c")71 .include_paths72 .into_iter()73 .chain(74 pkg_config::probe_library("nix-store-c")75 .expect("nix-store-c")76 .include_paths77 .into_iter(),78 )79 .chain(80 pkg_config::probe_library("nix-flake-c")81 .expect("nix-flake-c")82 .include_paths83 .into_iter(),84 )85 .chain(86 pkg_config::probe_library("nix-fetchers-c")87 .expect("nix-fetchers-c")88 .include_paths89 .into_iter(),90 )91 .chain(92 pkg_config::probe_library("bdw-gc")93 .expect("bdw-gc")94 .include_paths95 .into_iter(),96 ) {97 libnix = libnix.clang_arg(format!("-I{}", header.to_str().expect("path is utf-8")));98 }99100 let mut out = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo"));101 out.push("bindings.rs");102 libnix103 .generate()104 .expect("generate bindings")105 .write_to_file(out)106 .expect("write bindings");107}