Skip to main content

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
14const COREPKGS_FETCHURL: &str = "/__corepkgs__/fetchurl.nix";
15
16// TODO: Merge this together with SnixStoreIO?
17pub struct SnixIO<T> {
18    // Actual underlying [EvalIO] implementation.
19    actual: T,
20}
21
22impl<T> SnixIO<T> {
23    pub fn new(actual: T) -> Self {
24        Self { actual }
25    }
26}
27
28impl<T> EvalIO for SnixIO<T>
29where
30    T: AsRef<dyn EvalIO>,
31{
32    fn store_dir(&self) -> Option<String> {
33        self.actual.as_ref().store_dir()
34    }
35
36    fn import_path(&self, path: &Path) -> io::Result<PathBuf> {
37        self.actual.as_ref().import_path(path)
38    }
39
40    fn path_exists(&self, path: &Path) -> io::Result<bool> {
41        if path.starts_with("/__corepkgs__") {
42            return Ok(true);
43        }
44
45        self.actual.as_ref().path_exists(path)
46    }
47
48    fn open(&self, path: &Path) -> io::Result<Box<dyn io::Read>> {
49        // Bundled version of corepkgs/fetchurl.nix. The counterpart
50        // of this happens in [crate::configure_nix_path], where the `nix_path`
51        // of the evaluation has `nix=/__corepkgs__` added to it.
52        //
53        // This workaround is similar to what cppnix does for passing
54        // the path through.
55        if path == COREPKGS_FETCHURL {
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        if path == COREPKGS_FETCHURL {
64            return Ok(FileType::Regular);
65        }
66
67        self.actual.as_ref().file_type(path)
68    }
69
70    fn read_dir(&self, path: &Path) -> io::Result<Vec<(bytes::Bytes, FileType)>> {
71        self.actual.as_ref().read_dir(path)
72    }
73
74    fn get_env(&self, key: &OsStr) -> Option<OsString> {
75        self.actual.as_ref().get_env(key)
76    }
77}