use std::fs;
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
pub const GUIX_SIGS_URL: &str = "https://raw.githubusercontent.com/bitcoin-core/guix.sigs/main";
pub enum Source {
Dir(PathBuf),
Http(String),
}
impl Source {
pub fn parse(s: &str) -> Source {
if s.starts_with("https://") || s.starts_with("http://") {
Source::Http(s.to_string())
} else {
Source::Dir(PathBuf::from(s))
}
}
pub fn get(&self, path: &str) -> Result<Option<Vec<u8>>> {
match self {
Source::Dir(root) => match fs::read(root.join(path)) {
Ok(d) => Ok(Some(d)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| format!("reading {path}")),
},
Source::Http(base) => {
let url = format!("{}/{}", base.trim_end_matches('/'), path);
match agent().get(&url).call() {
Ok(mut resp) => Ok(Some(
resp.body_mut()
.with_config()
.limit(16 * 1024 * 1024)
.read_to_vec()
.with_context(|| format!("downloading {url}"))?,
)),
Err(ureq::Error::StatusCode(404)) => Ok(None),
Err(e) => bail!("downloading {url}: {e}"),
}
}
}
}
pub fn describe(&self) -> String {
match self {
Source::Dir(p) => p.display().to_string(),
Source::Http(u) => u.clone(),
}
}
}
#[cfg(windows)]
fn agent() -> ureq::Agent {
use ureq::tls::{RootCerts, TlsConfig, TlsProvider};
let tls = TlsConfig::builder()
.provider(TlsProvider::NativeTls)
.root_certs(RootCerts::PlatformVerifier)
.build();
ureq::Agent::config_builder().tls_config(tls).build().into()
}
#[cfg(not(windows))]
fn agent() -> ureq::Agent {
ureq::Agent::new_with_defaults()
}