use super::{ConfigError, SymbolServerErrorKind};
use std::path::{Path, PathBuf};
const MICROSOFT_SYMBOL_SERVER: &str = "https://msdl.microsoft.com/download/symbols";
const DEFAULT_CACHE_RELATIVE_PATH: &str = "pdb-bindgen/cache";
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CachePolicy {
location: CacheLocation,
}
impl CachePolicy {
pub(super) const fn out_dir() -> Self {
Self {
location: CacheLocation::OutDir,
}
}
pub(super) fn set_directory(&mut self, path: PathBuf) {
self.location = CacheLocation::Directory(path);
}
pub(super) fn reset_out_dir(&mut self) {
self.location = CacheLocation::OutDir;
}
#[must_use]
pub const fn is_out_dir_relative(&self) -> bool {
matches!(&self.location, CacheLocation::OutDir)
}
#[must_use]
pub fn out_dir_relative_path(&self) -> Option<&Path> {
match &self.location {
CacheLocation::OutDir => Some(Path::new(DEFAULT_CACHE_RELATIVE_PATH)),
CacheLocation::Directory(_) => None,
}
}
#[must_use]
pub fn directory(&self) -> Option<&Path> {
match &self.location {
CacheLocation::OutDir => None,
CacheLocation::Directory(path) => Some(path),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum CacheLocation {
OutDir,
Directory(PathBuf),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SymbolServer {
source: SymbolServerSource,
}
impl SymbolServer {
pub(super) const fn microsoft() -> Self {
Self {
source: SymbolServerSource::Microsoft,
}
}
pub(super) fn set_custom(&mut self, url: String) {
self.source = SymbolServerSource::Custom(url);
}
pub(super) fn reset_microsoft(&mut self) {
self.source = SymbolServerSource::Microsoft;
}
pub(super) fn disable(&mut self) {
self.source = SymbolServerSource::Disabled;
}
#[must_use]
pub fn url(&self) -> Option<&str> {
match &self.source {
SymbolServerSource::Microsoft => Some(MICROSOFT_SYMBOL_SERVER),
SymbolServerSource::Custom(url) => Some(url),
SymbolServerSource::Disabled => None,
}
}
#[must_use]
pub const fn is_microsoft(&self) -> bool {
matches!(&self.source, SymbolServerSource::Microsoft)
}
#[must_use]
pub const fn is_disabled(&self) -> bool {
matches!(&self.source, SymbolServerSource::Disabled)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum SymbolServerSource {
Microsoft,
Custom(String),
Disabled,
}
pub(super) fn validate_symbol_server(url: &str) -> Result<(), ConfigError> {
let remainder = if let Some(remainder) = url.strip_prefix("https://") {
remainder
} else if let Some(remainder) = url.strip_prefix("http://") {
remainder
} else {
return Err(ConfigError::InvalidSymbolServer {
url: url.to_owned(),
reason: SymbolServerErrorKind::Scheme,
});
};
if remainder.is_empty() || remainder.starts_with('/') {
return Err(ConfigError::InvalidSymbolServer {
url: url.to_owned(),
reason: SymbolServerErrorKind::MissingAuthority,
});
}
if url
.chars()
.any(|character| character.is_ascii_whitespace() || character.is_control())
|| url.contains(['?', '#'])
{
return Err(ConfigError::InvalidSymbolServer {
url: url.to_owned(),
reason: SymbolServerErrorKind::InvalidCharacter,
});
}
Ok(())
}