puffin_build/library/build/
sources.rs

1use std::io;
2use std::path::{Path, PathBuf};
3use std::process::Command;
4
5use serde::{Deserialize, Serialize};
6
7use crate::utils::git;
8use crate::{Error, Result};
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11#[serde(untagged)]
12pub enum Sources {
13    Git {
14        #[serde(flatten)]
15        tree: git::Tree,
16        version: String,
17    },
18    Url {
19        url: String,
20        hash: Option<String>,
21        version: String,
22    },
23}
24
25impl Sources {
26    pub fn download(&self, dest_dir: impl AsRef<Path>) -> Result<PathBuf> {
27        std::fs::create_dir_all(&dest_dir).map_err(|e| Error::SourcesDownloadFailed {
28            sources: self.clone(),
29            reason: e,
30        })?;
31
32        match self {
33            Sources::Git { tree, .. } => git::archive(tree.clone()).to_dir(dest_dir),
34            Sources::Url { url, hash, .. } => download_url(url, hash.as_deref(), dest_dir.as_ref()),
35        }
36        .map_err(|e| Error::SourcesDownloadFailed {
37            sources: self.clone(),
38            reason: e,
39        })
40    }
41
42    pub fn version(&self) -> String {
43        match self {
44            Sources::Git { version, .. } | Sources::Url { version, .. } => version.clone(),
45        }
46    }
47}
48
49impl AsRef<Sources> for Sources {
50    fn as_ref(&self) -> &Sources {
51        self
52    }
53}
54
55/// Download an archive from `url` into `dest_dir` and return the path of the archive.
56///
57/// If `hash` is provided (hex-encoded SHA-256, optionally prefixed by `sha256:`), the download is
58/// verified against it. The archive itself is extracted by the builder (CMake `ExternalProject`).
59fn download_url(url: &str, hash: Option<&str>, dest_dir: &Path) -> io::Result<PathBuf> {
60    let file_name = url
61        .rsplit('/')
62        .next()
63        .filter(|name| !name.is_empty())
64        .ok_or_else(|| io::Error::other(format!("cannot infer a file name from url: {url}")))?;
65    let archive_file = dest_dir.join(file_name);
66
67    let status = Command::new("curl")
68        .args([
69            "--fail",
70            "--silent",
71            "--show-error",
72            "--location",
73            "--retry",
74            "3",
75        ])
76        .arg("--output")
77        .arg(&archive_file)
78        .arg(url)
79        .status()?;
80
81    if !status.success() {
82        return Err(io::Error::other(format!("failed to download: url={url}")));
83    }
84
85    if let Some(expected) = hash {
86        let expected = expected.strip_prefix("sha256:").unwrap_or(expected);
87        let actual = sha256::try_digest(&archive_file)?;
88
89        if !actual.eq_ignore_ascii_case(expected) {
90            return Err(io::Error::other(format!(
91                "hash mismatch for {url}: expected sha256={expected}, got sha256={actual}"
92            )));
93        }
94    }
95
96    Ok(archive_file)
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    const HELLO_SHA256: &str = "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";
104
105    #[test]
106    fn sha256_matches_known_digest() {
107        let dir = tempfile::tempdir().unwrap();
108        let file = dir.path().join("hello.txt");
109        std::fs::write(&file, "hello\n").unwrap();
110
111        assert_eq!(sha256::try_digest(&file).unwrap(), HELLO_SHA256);
112    }
113
114    #[test]
115    fn download_verifies_hash() {
116        let dir = tempfile::tempdir().unwrap();
117        let src = dir.path().join("hello.txt");
118        std::fs::write(&src, "hello\n").unwrap();
119        let url = format!("file://{}", src.display());
120
121        let dest = tempfile::tempdir().unwrap();
122        let ok = download_url(&url, Some(&format!("sha256:{HELLO_SHA256}")), dest.path());
123        assert!(ok.is_ok(), "{ok:?}");
124
125        let bad = download_url(&url, Some(&"0".repeat(64)), dest.path());
126        assert!(bad.unwrap_err().to_string().contains("hash mismatch"));
127    }
128}