sunlicense 0.0.1

Official SunLicense client for Rust — licence key management and validation for indie software developers.
Documentation
//! Official SunLicense client for Rust.
//!
//! **Early preview.** The client API is being finalised alongside SunLicense 2.0.
//! This release reserves the crate name and defines the request and response shapes;
//! the HTTP transport arrives in `1.0.0`.
//!
//! See <https://docs.sunlicense.hapangama.com> for the API documentation.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

/// The version of this client.
pub const VERSION: &str = "0.0.1";

/// Path of the licence validation endpoint, relative to your instance's base URL.
pub const VALIDATE_PATH: &str = "/api/v1/validate";

/// Configuration for a SunLicense instance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    /// Base URL of your SunLicense instance, without a trailing slash.
    pub base_url: String,
    /// API token, if your endpoint requires one.
    pub token: Option<String>,
}

impl Config {
    /// Creates a configuration, trimming any trailing slashes from `base_url`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::MissingBaseUrl`] when `base_url` is empty.
    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 })
    }

    /// Sets the API token.
    #[must_use]
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Returns the full URL of the validation endpoint.
    #[must_use]
    pub fn validate_url(&self) -> String {
        format!("{}{}", self.base_url, VALIDATE_PATH)
    }
}

/// Errors produced by this crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// The base URL was empty.
    MissingBaseUrl,
    /// The licence key was empty.
    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"));
    }
}