#![forbid(unsafe_code)]
#![warn(missing_docs)]
pub const VERSION: &str = "0.0.1";
pub const VALIDATE_PATH: &str = "/api/v1/validate";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub base_url: String,
pub token: Option<String>,
}
impl Config {
pub fn new(base_url: impl Into<String>) -> Result<Self, Error> {
let base_url = base_url.into();
let trimmed = base_url.trim_end_matches('/');
if trimmed.is_empty() {
return Err(Error::MissingBaseUrl);
}
Ok(Self { base_url: trimmed.to_owned(), token: None })
}
#[must_use]
pub fn with_token(mut self, token: impl Into<String>) -> Self {
self.token = Some(token.into());
self
}
#[must_use]
pub fn validate_url(&self) -> String {
format!("{}{}", self.base_url, VALIDATE_PATH)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
MissingBaseUrl,
MissingLicenseKey,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MissingBaseUrl => write!(f, "SunLicense: base_url must not be empty"),
Self::MissingLicenseKey => write!(f, "SunLicense: license_key must not be empty"),
}
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trims_trailing_slashes() {
let c = Config::new("https://example.test///").unwrap();
assert_eq!(c.base_url, "https://example.test");
assert_eq!(c.validate_url(), "https://example.test/api/v1/validate");
}
#[test]
fn rejects_empty_base_url() {
assert_eq!(Config::new("").unwrap_err(), Error::MissingBaseUrl);
assert_eq!(Config::new("///").unwrap_err(), Error::MissingBaseUrl);
}
#[test]
fn sets_token() {
let c = Config::new("https://example.test").unwrap().with_token("t");
assert_eq!(c.token.as_deref(), Some("t"));
}
}