Skip to main content

azure_devops/
builder.rs

1use crate::auth::Credentials;
2use crate::client::AzureDevOps;
3use crate::error::{ AzureDevOpsError, Result };
4use reqwest;
5use url::Url;
6
7/// Default API version used when none is specified.
8const DEFAULT_API_VERSION: &str = crate::constants::DEFAULT_API_VERSION;
9
10/// Builder for constructing an [`AzureDevOps`] client.
11///
12/// # Example
13///
14/// ```no_run
15/// use azure_devops::AzureDevOpsBuilder;
16///
17/// let client = AzureDevOpsBuilder::new()
18///     .organization("my-company")
19///     .pat("my-pat-token")
20///     .build()
21///     .unwrap();
22/// ```
23#[derive(Debug)]
24pub struct AzureDevOpsBuilder {
25    organization: Option<String>,
26    pat: Option<String>,
27    api_version: Option<String>,
28}
29
30impl Default for AzureDevOpsBuilder {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36impl AzureDevOpsBuilder {
37    /// Create a new builder with no configuration set.
38    pub fn new() -> Self {
39        Self {
40            organization: None,
41            pat: None,
42            api_version: None,
43        }
44    }
45
46    /// Set the Azure DevOps organization name.
47    ///
48    /// This is the subdomain portion of your Azure DevOps URL.
49    /// For `https://dev.azure.com/my-company`, the organization is `my-company`.
50    pub fn organization(mut self, org: impl Into<String>) -> Self {
51        self.organization = Some(org.into());
52        self
53    }
54
55    /// Set a Personal Access Token for authentication.
56    pub fn pat(mut self, token: impl Into<String>) -> Self {
57        self.pat = Some(token.into());
58        self
59    }
60
61    /// Override the default API version.
62    ///
63    /// The default is `"7.1"`. You might set this to a preview version
64    /// like `"7.2-preview.1"` if you need preview features.
65    pub fn api_version(mut self, version: impl Into<String>) -> Self {
66        self.api_version = Some(version.into());
67        self
68    }
69
70    /// Build the [`AzureDevOps`] client.
71    ///
72    /// # Errors
73    ///
74    /// Returns `AzureDevOpsError::Config` if the organization is not set.
75    pub fn build(self) -> Result<AzureDevOps> {
76        let organization = self.organization.ok_or_else(||
77            AzureDevOpsError::Config(crate::constants::msg::ORG_REQUIRED.into())
78        )?;
79
80        let api_version = self.api_version.unwrap_or_else(|| DEFAULT_API_VERSION.to_string());
81
82        let pat = self.pat.ok_or_else(||
83            AzureDevOpsError::Config(crate::constants::msg::PAT_REQUIRED.into())
84        )?;
85
86        let credentials = Credentials::from_pat(pat);
87
88        let base_url = Url::parse(
89            &format!("{}/{}/", crate::constants::AZURE_DEVOPS_URL, organization)
90        )?;
91
92        let http_client = reqwest::Client
93            ::builder()
94            .user_agent(format!("{}/{}", crate::constants::USER_AGENT, env!("CARGO_PKG_VERSION")))
95            .build()?;
96
97        Ok(AzureDevOps::new(http_client, base_url, credentials, api_version))
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn build_succeeds_with_org_and_pat() {
107        let result = AzureDevOpsBuilder::new()
108            .organization("my-org")
109            .pat("my-pat")
110            .build();
111        assert!(result.is_ok());
112    }
113
114    #[test]
115    fn build_fails_without_organization() {
116        let result = AzureDevOpsBuilder::new().pat("my-pat").build();
117        assert!(result.is_err());
118        let msg = format!("{}", result.unwrap_err());
119        assert!(msg.contains("organization") || msg.contains("Organization"));
120    }
121
122    #[test]
123    fn build_fails_without_pat() {
124        let result = AzureDevOpsBuilder::new()
125            .organization("my-org")
126            .build();
127        assert!(result.is_err());
128        let msg = format!("{}", result.unwrap_err());
129        assert!(msg.contains("PAT") || msg.contains("pat") || msg.contains("token") || msg.contains("auth"));
130    }
131
132    #[test]
133    fn build_with_custom_api_version() {
134        let result = AzureDevOpsBuilder::new()
135            .organization("my-org")
136            .pat("my-pat")
137            .api_version("7.2-preview.1")
138            .build();
139        assert!(result.is_ok());
140    }
141
142    #[test]
143    fn default_is_empty() {
144        let b = AzureDevOpsBuilder::default();
145        assert!(b.organization.is_none());
146        assert!(b.pat.is_none());
147        assert!(b.api_version.is_none());
148    }
149
150    #[test]
151    fn builder_debug_contains_organization() {
152        let b = AzureDevOpsBuilder::new()
153            .organization("my-org")
154            .pat("secret");
155        let dbg = format!("{:?}", b);
156        assert!(dbg.contains("my-org"));
157    }
158}