Skip to main content

snix_build_glue/
fetchurl_derivation.rs

1//! Code translating from a `builtin:derivation` [UnverifiedDerivation] to a [Fetch].
2use crate::fetchers::Fetch;
3use nix_compat::derivation::{OutputHash, OutputHashMode, UnverifiedDerivation};
4use tracing::instrument;
5
6/// Parses a [UnverifiedDerivation] to a [Fetch] if using the `builtin:fetchurl` command and otherwise valid
7///
8/// If it doesn't use `builtin:fetchurl` as `command`, `Ok(None)` is returned.
9/// If it uses `builtin:fetchurl`, but is otherwise invalid, an [Error] is returned.
10/// Otherwise returns the synthesized [Fetch].
11#[instrument]
12pub fn fetchurl_derivation_to_fetch(drv: &UnverifiedDerivation) -> Result<Option<Fetch>, Error> {
13    if drv.command() != "builtin:fetchurl" {
14        return Ok(None);
15    }
16    if !drv.arguments().is_empty() {
17        return Err(Error::ArgumentsInvalid);
18    }
19    if drv.system() != "builtin" {
20        return Err(Error::SystemInvalid);
21    }
22
23    // ensure this is a fixed-output derivation
24    let Some(output_hash) = drv.outputs().as_fixed_output_hash() else {
25        return Err(Error::NoFOD);
26    };
27
28    // parse `url` from the environment
29    let url = std::str::from_utf8(drv.environment().get("url").ok_or(Error::URLMissing)?)
30        .or(Err(Error::URLInvalid))?
31        .parse()
32        .or(Err(Error::URLInvalid))?;
33
34    Ok(Some(match output_hash {
35        OutputHash {
36            mode: OutputHashMode::Flat,
37            hash,
38        } => Fetch::URL {
39            url,
40            exp_hash: Some(hash.to_owned()),
41        },
42        OutputHash {
43            mode: OutputHashMode::Recursive,
44            hash,
45        } if drv.environment().get("executable").map(|b| b.as_slice()) == Some(b"1") => {
46            Fetch::Executable {
47                url,
48                hash: hash.to_owned(),
49            }
50        }
51        OutputHash {
52            mode: OutputHashMode::Recursive,
53            hash,
54        } => Fetch::NAR {
55            url,
56            hash: hash.to_owned(),
57        },
58    }))
59}
60
61#[derive(Debug, thiserror::Error)]
62pub enum Error {
63    #[error("invalid arguments")]
64    ArgumentsInvalid,
65    #[error("Invalid system")]
66    SystemInvalid,
67    #[error("Derivation is not fixed-output")]
68    NoFOD,
69    #[error("Missing URL")]
70    URLMissing,
71    #[error("Invalid URL")]
72    URLInvalid,
73}