1use super::{repl_spec, script_spec, Machine, ReplMachine, ScriptMachine};
41use crate::prelude::*;
42use miette::{bail, miette, IntoDiagnostic, WrapErr};
43use std::path::{Path, PathBuf};
44use std::process::Command;
45
46const STORE: &str = "/nix/store";
47
48#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct Pin {
52 pub address: Box<str>,
55 pub path: PathBuf,
58}
59
60#[must_use]
63pub fn is_address(s: &str) -> bool {
64 let Some((hash, name)) = s.split_once('-') else {
65 return false;
66 };
67 hash.len() == 32
69 && hash
70 .bytes()
71 .all(|b| b.is_ascii_digit() || (b.is_ascii_lowercase() && !b"eotu".contains(&b)))
72 && !name.is_empty()
73 && !name.contains('/')
74}
75
76fn nix(args: &[&str]) -> Result<String> {
77 let out = Command::new("nix")
78 .args(["--extra-experimental-features", "nix-command flakes"])
79 .args(args)
80 .output()
81 .into_diagnostic()
82 .wrap_err("failed to run `nix` (pinning a machine needs Nix)")?;
83 if !out.status.success() {
84 bail!(
85 "nix {}: {}",
86 args.join(" "),
87 String::from_utf8_lossy(&out.stderr).trim()
88 );
89 }
90 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
91}
92
93fn name_of(path: &Path) -> Result<&str> {
94 path.file_name()
95 .and_then(|n| n.to_str())
96 .ok_or_else(|| miette!("{} is not a store path", path.display()))
97}
98
99fn cache_dir() -> PathBuf {
100 if let Some(dir) = std::env::var_os("QUILT_PIN_CACHE") {
101 return dir.into();
102 }
103 let base = std::env::var_os("XDG_CACHE_HOME").map_or_else(
104 || PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache"),
105 PathBuf::from,
106 );
107 base.join("quilt").join("pins")
108}
109
110fn rewritten<'j>(json: &'j str, original: &str) -> Option<&'j str> {
115 let key = format!("\"{original}\"");
116 let rest = json[json.find(&key)? + key.len()..].trim_start();
117 let rest = rest.strip_prefix(':')?.trim_start().strip_prefix('"')?;
118 rest.split('"').next()
119}
120
121fn content_address(original: &Path) -> Result<Box<str>> {
123 let entry = cache_dir().join(name_of(original)?);
124 if let Ok(cached) = std::fs::read_to_string(&entry) {
125 if is_address(cached.trim()) {
126 return Ok(cached.trim().into());
127 }
128 }
129 let path = original.to_string_lossy();
130 let json = nix(&["store", "make-content-addressed", "--json", &path])?;
131 let address = rewritten(&json, &path)
132 .and_then(|p| Path::new(p).file_name()?.to_str())
133 .filter(|a| is_address(a))
134 .ok_or_else(|| miette!("nix rewrote nothing for {path}: {json}"))?;
135 if std::fs::create_dir_all(cache_dir()).is_ok() {
137 let _ = std::fs::write(&entry, format!("{address}\n"));
138 }
139 Ok(address.into())
140}
141
142impl Pin {
143 fn runnable(address: Box<str>, original: PathBuf) -> Pin {
145 let path = if cfg!(target_os = "macos") {
146 original
147 } else {
148 Path::new(STORE).join(&*address)
149 };
150 Pin { address, path }
151 }
152
153 pub fn of_store_path(original: &Path) -> Result<Pin> {
158 let address = content_address(original)?;
159 Ok(Pin::runnable(address, original.to_path_buf()))
160 }
161
162 pub fn build(recipe: &str) -> Result<Pin> {
172 let out = nix(&["build", recipe, "--no-link", "--print-out-paths"])?;
173 let mut paths = out.lines();
174 let (Some(original), None) = (paths.next(), paths.next()) else {
175 bail!("{recipe} builds to {} paths, not one", out.lines().count());
176 };
177 Pin::of_store_path(Path::new(original))
178 }
179
180 pub fn check(address: &str, recipe: Option<&str>) -> Result<Pin> {
190 if !is_address(address) {
191 bail!("{address:?} is not a Nix content address");
192 }
193 if let Some(recipe) = recipe {
194 let pin = Pin::build(recipe)?;
195 if &*pin.address != address {
196 bail!("{recipe} builds to {}, not {address}", pin.address);
197 }
198 return Ok(pin);
199 }
200 for entry in std::fs::read_dir(cache_dir())
202 .into_iter()
203 .flatten()
204 .flatten()
205 {
206 let original = Path::new(STORE).join(entry.file_name());
207 let cached = std::fs::read_to_string(entry.path()).unwrap_or_default();
208 if cached.trim() == address && original.exists() {
209 return Ok(Pin::runnable(address.into(), original));
210 }
211 }
212 let rewritten = Path::new(STORE).join(address);
213 if !cfg!(target_os = "macos") && rewritten.exists() {
214 return Ok(Pin {
217 address: address.into(),
218 path: rewritten,
219 });
220 }
221 bail!("no machine with address {address} is realized here; pass the recipe that builds it")
222 }
223
224 fn program(&self, program: &str) -> Result<Box<str>> {
227 let pinned = self.path.join("bin").join(program);
228 if !pinned.exists() {
229 bail!(
230 "the machine pinned at {} has no bin/{program}",
231 self.address
232 );
233 }
234 Ok(pinned.to_string_lossy().into())
235 }
236}
237
238pub fn qspawn_pinned(lang: &str, pin: &Pin) -> Result<Box<dyn Machine>> {
247 if let Some(mut spec) = repl_spec(lang) {
248 spec.program = pin.program(&spec.program)?;
249 spec.clear_env = true;
250 spec.identity = Some(pin.address.clone());
251 return Ok(Box::new(ReplMachine::spawn(lang, spec)?));
252 }
253 if let Some(mut spec) = script_spec(lang) {
254 spec.program = pin.program(&spec.program)?;
255 spec.clear_env = true;
256 spec.identity = Some(pin.address.clone());
257 return Ok(Box::new(ScriptMachine::new(lang, spec)));
258 }
259 bail!("no subprocess machine is registered for {lang:?}, so there is nothing to pin")
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265 use crate::lang::InnerKind;
266 use crate::qterm::qleaf;
267
268 #[test]
269 fn an_address_is_a_store_paths_name() {
270 assert!(is_address(
271 "7r699cypjyibyji6c8l9yada8wbpv20a-python3-3.14.10"
272 ));
273 assert!(!is_address("Python 3.14.10"));
274 assert!(!is_address("7r699cypjyibyji6c8l9yada8wbpv20a"));
275 assert!(!is_address("7r699cypjyibyji6c8l9yada8wbpv20e-python3"));
277 assert!(!is_address(
278 "/nix/store/7r699cypjyibyji6c8l9yada8wbpv20a-python3"
279 ));
280 }
281
282 #[test]
283 fn the_rewrite_is_read_from_nixs_json() {
284 let json = r#"{"rewrites":{"/nix/store/aaa-x":"/nix/store/bbb-x"}}"#;
285 assert_eq!(
286 rewritten(json, "/nix/store/aaa-x"),
287 Some("/nix/store/bbb-x")
288 );
289 assert_eq!(rewritten(json, "/nix/store/ccc-x"), None);
290 }
291
292 #[test]
293 fn an_unknown_address_is_refused_before_anything_runs() {
294 let e = Pin::check("00000000000000000000000000000000-nothing", None).unwrap_err();
295 assert!(e.to_string().contains("recipe"), "{e}");
296 assert!(Pin::check("python3", None).is_err());
297 }
298
299 #[test]
302 #[ignore = "builds nixpkgs#python3 with Nix, which needs the network"]
303 fn a_pinned_python_answers_and_says_which_it_is() {
304 let pin = Pin::build("nixpkgs#python3").unwrap();
305 assert!(is_address(&pin.address));
306 assert_eq!(Pin::check(&pin.address, None).unwrap(), pin);
309 assert!(Pin::check(&pin.address, Some("nixpkgs#bash")).is_err());
310
311 let mut m = qspawn_pinned("py", &pin).unwrap();
312 assert_eq!(m.identity(), Some(&*pin.address));
313 m.feed(InnerKind::Item, &qleaf("code", "x = 20")).unwrap();
314 let answer = m.eval(&qleaf("code", "x + 22")).unwrap();
315 assert_eq!(answer.value.as_deref(), Some("42"));
316 let path = m
318 .eval(&qleaf("code", "__import__('os').environ.get('PATH')"))
319 .unwrap();
320 assert_eq!(path.value.as_deref(), Some("None"));
321 let exe = m
323 .eval(&qleaf("code", "__import__('sys').executable"))
324 .unwrap();
325 assert!(exe.value.unwrap().contains(STORE));
326 }
327}