use super::{repl_spec, script_spec, Machine, ReplMachine, ScriptMachine};
use crate::prelude::*;
use miette::{bail, miette, IntoDiagnostic, WrapErr};
use std::path::{Path, PathBuf};
use std::process::Command;
const STORE: &str = "/nix/store";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Pin {
pub address: Box<str>,
pub path: PathBuf,
}
#[must_use]
pub fn is_address(s: &str) -> bool {
let Some((hash, name)) = s.split_once('-') else {
return false;
};
hash.len() == 32
&& hash
.bytes()
.all(|b| b.is_ascii_digit() || (b.is_ascii_lowercase() && !b"eotu".contains(&b)))
&& !name.is_empty()
&& !name.contains('/')
}
fn nix(args: &[&str]) -> Result<String> {
let out = Command::new("nix")
.args(["--extra-experimental-features", "nix-command flakes"])
.args(args)
.output()
.into_diagnostic()
.wrap_err("failed to run `nix` (pinning a machine needs Nix)")?;
if !out.status.success() {
bail!(
"nix {}: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
fn name_of(path: &Path) -> Result<&str> {
path.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| miette!("{} is not a store path", path.display()))
}
fn cache_dir() -> PathBuf {
if let Some(dir) = std::env::var_os("QUILT_PIN_CACHE") {
return dir.into();
}
let base = std::env::var_os("XDG_CACHE_HOME").map_or_else(
|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache"),
PathBuf::from,
);
base.join("quilt").join("pins")
}
fn rewritten<'j>(json: &'j str, original: &str) -> Option<&'j str> {
let key = format!("\"{original}\"");
let rest = json[json.find(&key)? + key.len()..].trim_start();
let rest = rest.strip_prefix(':')?.trim_start().strip_prefix('"')?;
rest.split('"').next()
}
fn content_address(original: &Path) -> Result<Box<str>> {
let entry = cache_dir().join(name_of(original)?);
if let Ok(cached) = std::fs::read_to_string(&entry) {
if is_address(cached.trim()) {
return Ok(cached.trim().into());
}
}
let path = original.to_string_lossy();
let json = nix(&["store", "make-content-addressed", "--json", &path])?;
let address = rewritten(&json, &path)
.and_then(|p| Path::new(p).file_name()?.to_str())
.filter(|a| is_address(a))
.ok_or_else(|| miette!("nix rewrote nothing for {path}: {json}"))?;
if std::fs::create_dir_all(cache_dir()).is_ok() {
let _ = std::fs::write(&entry, format!("{address}\n"));
}
Ok(address.into())
}
impl Pin {
fn runnable(address: Box<str>, original: PathBuf) -> Pin {
let path = if cfg!(target_os = "macos") {
original
} else {
Path::new(STORE).join(&*address)
};
Pin { address, path }
}
pub fn of_store_path(original: &Path) -> Result<Pin> {
let address = content_address(original)?;
Ok(Pin::runnable(address, original.to_path_buf()))
}
pub fn build(recipe: &str) -> Result<Pin> {
let out = nix(&["build", recipe, "--no-link", "--print-out-paths"])?;
let mut paths = out.lines();
let (Some(original), None) = (paths.next(), paths.next()) else {
bail!("{recipe} builds to {} paths, not one", out.lines().count());
};
Pin::of_store_path(Path::new(original))
}
pub fn check(address: &str, recipe: Option<&str>) -> Result<Pin> {
if !is_address(address) {
bail!("{address:?} is not a Nix content address");
}
if let Some(recipe) = recipe {
let pin = Pin::build(recipe)?;
if &*pin.address != address {
bail!("{recipe} builds to {}, not {address}", pin.address);
}
return Ok(pin);
}
for entry in std::fs::read_dir(cache_dir())
.into_iter()
.flatten()
.flatten()
{
let original = Path::new(STORE).join(entry.file_name());
let cached = std::fs::read_to_string(entry.path()).unwrap_or_default();
if cached.trim() == address && original.exists() {
return Ok(Pin::runnable(address.into(), original));
}
}
let rewritten = Path::new(STORE).join(address);
if !cfg!(target_os = "macos") && rewritten.exists() {
return Ok(Pin {
address: address.into(),
path: rewritten,
});
}
bail!("no machine with address {address} is realized here; pass the recipe that builds it")
}
fn program(&self, program: &str) -> Result<Box<str>> {
let pinned = self.path.join("bin").join(program);
if !pinned.exists() {
bail!(
"the machine pinned at {} has no bin/{program}",
self.address
);
}
Ok(pinned.to_string_lossy().into())
}
}
pub fn qspawn_pinned(lang: &str, pin: &Pin) -> Result<Box<dyn Machine>> {
if let Some(mut spec) = repl_spec(lang) {
spec.program = pin.program(&spec.program)?;
spec.clear_env = true;
spec.identity = Some(pin.address.clone());
return Ok(Box::new(ReplMachine::spawn(lang, spec)?));
}
if let Some(mut spec) = script_spec(lang) {
spec.program = pin.program(&spec.program)?;
spec.clear_env = true;
spec.identity = Some(pin.address.clone());
return Ok(Box::new(ScriptMachine::new(lang, spec)));
}
bail!("no subprocess machine is registered for {lang:?}, so there is nothing to pin")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lang::InnerKind;
use crate::qterm::qleaf;
#[test]
fn an_address_is_a_store_paths_name() {
assert!(is_address(
"7r699cypjyibyji6c8l9yada8wbpv20a-python3-3.14.10"
));
assert!(!is_address("Python 3.14.10"));
assert!(!is_address("7r699cypjyibyji6c8l9yada8wbpv20a"));
assert!(!is_address("7r699cypjyibyji6c8l9yada8wbpv20e-python3"));
assert!(!is_address(
"/nix/store/7r699cypjyibyji6c8l9yada8wbpv20a-python3"
));
}
#[test]
fn the_rewrite_is_read_from_nixs_json() {
let json = r#"{"rewrites":{"/nix/store/aaa-x":"/nix/store/bbb-x"}}"#;
assert_eq!(
rewritten(json, "/nix/store/aaa-x"),
Some("/nix/store/bbb-x")
);
assert_eq!(rewritten(json, "/nix/store/ccc-x"), None);
}
#[test]
fn an_unknown_address_is_refused_before_anything_runs() {
let e = Pin::check("00000000000000000000000000000000-nothing", None).unwrap_err();
assert!(e.to_string().contains("recipe"), "{e}");
assert!(Pin::check("python3", None).is_err());
}
#[test]
#[ignore = "builds nixpkgs#python3 with Nix, which needs the network"]
fn a_pinned_python_answers_and_says_which_it_is() {
let pin = Pin::build("nixpkgs#python3").unwrap();
assert!(is_address(&pin.address));
assert_eq!(Pin::check(&pin.address, None).unwrap(), pin);
assert!(Pin::check(&pin.address, Some("nixpkgs#bash")).is_err());
let mut m = qspawn_pinned("py", &pin).unwrap();
assert_eq!(m.identity(), Some(&*pin.address));
m.feed(InnerKind::Item, &qleaf("code", "x = 20")).unwrap();
let answer = m.eval(&qleaf("code", "x + 22")).unwrap();
assert_eq!(answer.value.as_deref(), Some("42"));
let path = m
.eval(&qleaf("code", "__import__('os').environ.get('PATH')"))
.unwrap();
assert_eq!(path.value.as_deref(), Some("None"));
let exe = m
.eval(&qleaf("code", "__import__('sys').executable"))
.unwrap();
assert!(exe.value.unwrap().contains(STORE));
}
}