fetch_source/
tar.rs

1//! Support for declaring and fetching tar archives.
2
3use super::error::FetchErrorKind;
4
5/// Represents a remote tar archive to be downloaded and extracted.
6#[derive(Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)]
7pub struct Tar {
8    #[serde(rename = "tar")]
9    pub(crate) url: String,
10}
11
12impl Tar {
13    /// The upstream URL.
14    pub fn upstream(&self) -> &str {
15        &self.url
16    }
17
18    /// Download and extract the tar archive directly into `dir`.
19    pub(crate) fn fetch<P: AsRef<std::path::Path>>(
20        &self,
21        dir: P,
22    ) -> Result<std::path::PathBuf, FetchErrorKind> {
23        let dir = dir.as_ref();
24        if !dir.exists() {
25            std::fs::create_dir_all(dir)?;
26        }
27        let bytes = reqwest::blocking::get(self.url.clone())?.bytes()?;
28        let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(bytes.as_ref()));
29        // Unpack the contents of the archive directly into the provided directory
30        archive.unpack(dir)?;
31        Ok(dir.to_path_buf())
32    }
33}
34
35impl std::fmt::Display for Tar {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        write!(f, "{}", self.url)
38    }
39}