Skip to main content

bitbucket_cli/api/
webhooks.rs

1use anyhow::Result;
2
3use super::BitbucketClient;
4use crate::models::{CreateWebhookRequest, Paginated, Webhook};
5
6/// Percent-encode a string for use as a single URL path segment.
7///
8/// Bitbucket identifiers such as webhook UIDs (a UUID wrapped in braces,
9/// e.g. `{1a2b-...}`) and permission selectors (`{uuid}`, account IDs with
10/// `:`) contain characters that are not valid raw path characters, so
11/// everything outside the RFC 3986 "unreserved" set is percent-encoded.
12pub(crate) fn encode_path_segment(segment: &str) -> String {
13    let mut encoded = String::with_capacity(segment.len());
14    for byte in segment.bytes() {
15        match byte {
16            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
17                encoded.push(byte as char);
18            }
19            _ => encoded.push_str(&format!("%{:02X}", byte)),
20        }
21    }
22    encoded
23}
24
25impl BitbucketClient {
26    /// List webhook subscriptions on a repository
27    pub async fn list_webhooks(
28        &self,
29        workspace: &str,
30        repo_slug: &str,
31        pagelen: Option<u32>,
32    ) -> Result<Paginated<Webhook>> {
33        let path = format!("/repositories/{}/{}/hooks", workspace, repo_slug);
34
35        match pagelen {
36            Some(len) => {
37                self.get_with_query(&path, &[("pagelen", len.to_string().as_str())])
38                    .await
39            }
40            None => self.get(&path).await,
41        }
42    }
43
44    /// Create a webhook subscription on a repository
45    pub async fn create_webhook(
46        &self,
47        workspace: &str,
48        repo_slug: &str,
49        request: &CreateWebhookRequest,
50    ) -> Result<Webhook> {
51        let path = format!("/repositories/{}/{}/hooks", workspace, repo_slug);
52        self.post(&path, request).await
53    }
54
55    /// Get a single webhook subscription by its UID (the brace-wrapped UUID)
56    pub async fn get_webhook(
57        &self,
58        workspace: &str,
59        repo_slug: &str,
60        uid: &str,
61    ) -> Result<Webhook> {
62        let path = format!(
63            "/repositories/{}/{}/hooks/{}",
64            workspace,
65            repo_slug,
66            encode_path_segment(uid)
67        );
68        self.get(&path).await
69    }
70
71    /// Replace a webhook subscription.
72    ///
73    /// Bitbucket's PUT replaces the entire subscription, so `request` must
74    /// carry the full desired state (see [`CreateWebhookRequest`]).
75    pub async fn update_webhook(
76        &self,
77        workspace: &str,
78        repo_slug: &str,
79        uid: &str,
80        request: &CreateWebhookRequest,
81    ) -> Result<Webhook> {
82        let path = format!(
83            "/repositories/{}/{}/hooks/{}",
84            workspace,
85            repo_slug,
86            encode_path_segment(uid)
87        );
88        self.put(&path, request).await
89    }
90
91    /// Delete a webhook subscription
92    pub async fn delete_webhook(&self, workspace: &str, repo_slug: &str, uid: &str) -> Result<()> {
93        let path = format!(
94            "/repositories/{}/{}/hooks/{}",
95            workspace,
96            repo_slug,
97            encode_path_segment(uid)
98        );
99        self.delete(&path).await
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::encode_path_segment;
106
107    #[test]
108    fn encode_path_segment_passes_unreserved_through() {
109        assert_eq!(
110            encode_path_segment("abc-XYZ_0.9~"),
111            "abc-XYZ_0.9~".to_string()
112        );
113    }
114
115    #[test]
116    fn encode_path_segment_encodes_webhook_uid_braces() {
117        assert_eq!(
118            encode_path_segment("{d3a1e9b0-1234-5678-9abc-def012345678}"),
119            "%7Bd3a1e9b0-1234-5678-9abc-def012345678%7D"
120        );
121    }
122
123    #[test]
124    fn encode_path_segment_encodes_reserved_ascii() {
125        assert_eq!(encode_path_segment("a/b:c d"), "a%2Fb%3Ac%20d");
126    }
127
128    #[test]
129    fn encode_path_segment_encodes_utf8_bytes() {
130        assert_eq!(encode_path_segment("é"), "%C3%A9");
131    }
132}