use crate::tui::settings::GithubOverrides;
pub const DEFAULT_API_BASE: &str = "https://api.github.com";
pub const DEFAULT_RAW_BASE: &str = "https://raw.githubusercontent.com";
pub const DEFAULT_DOWNLOAD_BASE: &str = "https://github.com";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoSpec {
pub owner: String,
pub repo: String,
}
impl RepoSpec {
pub fn from_pkg_repository() -> Self {
let url = env!("CARGO_PKG_REPOSITORY");
let mut parts = url.trim_end_matches('/').rsplit('/');
let repo = parts.next().unwrap_or("mdbook-plotly").to_string();
let owner = parts.next().unwrap_or("TickPoints").to_string();
Self { owner, repo }
}
pub fn path(&self) -> String {
format!("{}/{}", self.owner, self.repo)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GithubHosts {
pub api: String,
pub raw: String,
pub download: String,
pub proxy: Option<String>,
}
impl Default for GithubHosts {
fn default() -> Self {
Self {
api: DEFAULT_API_BASE.to_string(),
raw: DEFAULT_RAW_BASE.to_string(),
download: DEFAULT_DOWNLOAD_BASE.to_string(),
proxy: None,
}
}
}
impl GithubHosts {
pub fn resolve(overrides: &GithubOverrides) -> Self {
Self {
api: overrides
.api
.clone()
.unwrap_or_else(|| DEFAULT_API_BASE.to_string()),
raw: overrides
.raw
.clone()
.unwrap_or_else(|| DEFAULT_RAW_BASE.to_string()),
download: overrides
.download
.clone()
.unwrap_or_else(|| DEFAULT_DOWNLOAD_BASE.to_string()),
proxy: overrides.proxy.clone(),
}
}
fn with_proxy(&self, url: String) -> String {
match &self.proxy {
Some(proxy) => format!("{proxy}{url}"),
None => url,
}
}
fn join(base: &str, path: &str) -> String {
format!(
"{}/{}",
base.trim_end_matches('/'),
path.trim_start_matches('/')
)
}
pub fn api_releases_latest(&self, repo: &RepoSpec) -> String {
self.with_proxy(Self::join(
&self.api,
&format!("repos/{}/releases/latest", repo.path()),
))
}
pub fn raw_file_url(&self, repo: &RepoSpec, tag: &str, path: &str) -> String {
self.with_proxy(Self::join(
&self.raw,
&format!(
"{}/{}/{}/{}",
repo.owner,
repo.repo,
tag,
path.trim_start_matches('/')
),
))
}
pub fn download_url(&self, browser_url: &str) -> String {
let url = if self.download != DEFAULT_DOWNLOAD_BASE
&& browser_url.starts_with(DEFAULT_DOWNLOAD_BASE)
{
format!(
"{}{}",
self.download.trim_end_matches('/'),
&browser_url[DEFAULT_DOWNLOAD_BASE.len()..]
)
} else {
browser_url.to_string()
};
self.with_proxy(url)
}
}