snix_glue/
snix_io.rs

1//! This module implements a wrapper around snix-eval's [EvalIO] type,
2//! adding functionality which is required by snix-cli:
3//!
4//! 1. Handling the C++ Nix `__corepkgs__`-hack for nixpkgs bootstrapping.
5//!
6//! All uses of [EvalIO] in snix-cli must make use of this wrapper,
7//! otherwise nixpkgs bootstrapping will not work.
8
9use snix_eval::{EvalIO, FileType};
10use std::ffi::{OsStr, OsString};
11use std::io::{self, Cursor};
12use std::path::{Path, PathBuf};
13
14// TODO: Merge this together with SnixStoreIO?
15pub struct SnixIO<T> {
16    // Actual underlying [EvalIO] implementation.
17    actual: T,
18}
19
20impl<T> SnixIO<T> {
21    pub fn new(actual: T) -> Self {
22        Self { actual }
23    }
24}
25
26impl<T> EvalIO for SnixIO<T>
27where
28    T: AsRef<dyn EvalIO>,
29{
30    fn store_dir(&self) -> Option<String> {
31        self.actual.as_ref().store_dir()
32    }
33
34    fn import_path(&self, path: &Path) -> io::Result<PathBuf> {
35        self.actual.as_ref().import_path(path)
36    }
37
38    fn path_exists(&self, path: &Path) -> io::Result<bool> {
39        if path.starts_with("/__corepkgs__") {
40            return Ok(true);
41        }
42
43        self.actual.as_ref().path_exists(path)
44    }
45
46    fn open(&self, path: &Path) -> io::Result<Box<dyn io::Read>> {
47        // Bundled version of corepkgs/fetchurl.nix. The counterpart
48        // of this happens in [crate::configure_nix_path], where the `nix_path`
49        // of the evaluation has `nix=/__corepkgs__` added to it.
50        //
51        // This workaround is similar to what cppnix does for passing
52        // the path through.
53        //
54        // TODO: this comparison is bad we should use the sane path library.
55        if path.starts_with("/__corepkgs__/fetchurl.nix") {
56            return Ok(Box::new(Cursor::new(include_bytes!("fetchurl.nix"))));
57        }
58
59        self.actual.as_ref().open(path)
60    }
61
62    fn file_type(&self, path: &Path) -> io::Result<FileType> {
63        self.actual.as_ref().file_type(path)
64    }
65
66    fn read_dir(&self, path: &Path) -> io::Result<Vec<(bytes::Bytes, FileType)>> {
67        self.actual.as_ref().read_dir(path)
68    }
69
70    fn get_env(&self, key: &OsStr) -> Option<OsString> {
71        self.actual.as_ref().get_env(key)
72    }
73}