azure-devops 0.1.0

Idiomatic Rust client for Azure DevOps REST APIs
Documentation
use crate::auth::Credentials;
use crate::client::AzureDevOps;
use crate::error::{ AzureDevOpsError, Result };
use reqwest;
use url::Url;

/// Default API version used when none is specified.
const DEFAULT_API_VERSION: &str = crate::constants::DEFAULT_API_VERSION;

/// Builder for constructing an [`AzureDevOps`] client.
///
/// # Example
///
/// ```no_run
/// use azure_devops::AzureDevOpsBuilder;
///
/// let client = AzureDevOpsBuilder::new()
///     .organization("my-company")
///     .pat("my-pat-token")
///     .build()
///     .unwrap();
/// ```
#[derive(Debug)]
pub struct AzureDevOpsBuilder {
    organization: Option<String>,
    pat: Option<String>,
    api_version: Option<String>,
}

impl Default for AzureDevOpsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl AzureDevOpsBuilder {
    /// Create a new builder with no configuration set.
    pub fn new() -> Self {
        Self {
            organization: None,
            pat: None,
            api_version: None,
        }
    }

    /// Set the Azure DevOps organization name.
    ///
    /// This is the subdomain portion of your Azure DevOps URL.
    /// For `https://dev.azure.com/my-company`, the organization is `my-company`.
    pub fn organization(mut self, org: impl Into<String>) -> Self {
        self.organization = Some(org.into());
        self
    }

    /// Set a Personal Access Token for authentication.
    pub fn pat(mut self, token: impl Into<String>) -> Self {
        self.pat = Some(token.into());
        self
    }

    /// Override the default API version.
    ///
    /// The default is `"7.1"`. You might set this to a preview version
    /// like `"7.2-preview.1"` if you need preview features.
    pub fn api_version(mut self, version: impl Into<String>) -> Self {
        self.api_version = Some(version.into());
        self
    }

    /// Build the [`AzureDevOps`] client.
    ///
    /// # Errors
    ///
    /// Returns `AzureDevOpsError::Config` if the organization is not set.
    pub fn build(self) -> Result<AzureDevOps> {
        let organization = self.organization.ok_or_else(||
            AzureDevOpsError::Config(crate::constants::msg::ORG_REQUIRED.into())
        )?;

        let api_version = self.api_version.unwrap_or_else(|| DEFAULT_API_VERSION.to_string());

        let pat = self.pat.ok_or_else(||
            AzureDevOpsError::Config(crate::constants::msg::PAT_REQUIRED.into())
        )?;

        let credentials = Credentials::from_pat(pat);

        let base_url = Url::parse(
            &format!("{}/{}/", crate::constants::AZURE_DEVOPS_URL, organization)
        )?;

        let http_client = reqwest::Client
            ::builder()
            .user_agent(format!("{}/{}", crate::constants::USER_AGENT, env!("CARGO_PKG_VERSION")))
            .build()?;

        Ok(AzureDevOps::new(http_client, base_url, credentials, api_version))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn build_succeeds_with_org_and_pat() {
        let result = AzureDevOpsBuilder::new()
            .organization("my-org")
            .pat("my-pat")
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn build_fails_without_organization() {
        let result = AzureDevOpsBuilder::new().pat("my-pat").build();
        assert!(result.is_err());
        let msg = format!("{}", result.unwrap_err());
        assert!(msg.contains("organization") || msg.contains("Organization"));
    }

    #[test]
    fn build_fails_without_pat() {
        let result = AzureDevOpsBuilder::new()
            .organization("my-org")
            .build();
        assert!(result.is_err());
        let msg = format!("{}", result.unwrap_err());
        assert!(msg.contains("PAT") || msg.contains("pat") || msg.contains("token") || msg.contains("auth"));
    }

    #[test]
    fn build_with_custom_api_version() {
        let result = AzureDevOpsBuilder::new()
            .organization("my-org")
            .pat("my-pat")
            .api_version("7.2-preview.1")
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn default_is_empty() {
        let b = AzureDevOpsBuilder::default();
        assert!(b.organization.is_none());
        assert!(b.pat.is_none());
        assert!(b.api_version.is_none());
    }

    #[test]
    fn builder_debug_contains_organization() {
        let b = AzureDevOpsBuilder::new()
            .organization("my-org")
            .pat("secret");
        let dbg = format!("{:?}", b);
        assert!(dbg.contains("my-org"));
    }
}