Skip to main content

bitbucket_cli/api/
source.rs

1use anyhow::Result;
2
3use super::BitbucketClient;
4use crate::api::util::urlencode_segment;
5use crate::models::{FileHistoryEntry, Paginated, SourceEntry};
6
7impl BitbucketClient {
8    /// List the entries of a directory at `path` (empty string for the
9    /// repository root) as of `git_ref` (branch, tag, or commit hash).
10    pub async fn list_source(
11        &self,
12        workspace: &str,
13        repo_slug: &str,
14        git_ref: &str,
15        path: &str,
16        page: Option<u32>,
17        pagelen: Option<u32>,
18    ) -> Result<Paginated<SourceEntry>> {
19        let endpoint = source_path(workspace, repo_slug, git_ref, path);
20
21        let mut params = Vec::new();
22        if let Some(p) = page {
23            params.push(("page", p.to_string()));
24        }
25        if let Some(len) = pagelen {
26            params.push(("pagelen", len.to_string()));
27        }
28
29        let param_refs: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
30        self.get_with_query(&endpoint, &param_refs).await
31    }
32
33    /// Fetch the raw contents of the file at `path` as of `git_ref`.
34    ///
35    /// This is the same endpoint as [`Self::list_source`]; pointed at a file
36    /// instead of a directory, it returns the file body verbatim.
37    pub async fn get_file_raw(
38        &self,
39        workspace: &str,
40        repo_slug: &str,
41        git_ref: &str,
42        path: &str,
43    ) -> Result<String> {
44        let endpoint = source_path(workspace, repo_slug, git_ref, path);
45        self.get_text(&endpoint, None).await
46    }
47
48    /// List the commits that touched the file at `path`, starting from
49    /// `git_ref`, newest first.
50    pub async fn get_file_history(
51        &self,
52        workspace: &str,
53        repo_slug: &str,
54        git_ref: &str,
55        path: &str,
56        pagelen: Option<u32>,
57    ) -> Result<Paginated<FileHistoryEntry>> {
58        let endpoint = format!(
59            "/repositories/{}/{}/filehistory/{}/{}",
60            workspace,
61            repo_slug,
62            urlencode_segment(git_ref),
63            urlencode_path(path)
64        );
65
66        let mut params = Vec::new();
67        if let Some(len) = pagelen {
68            params.push(("pagelen", len.to_string()));
69        }
70
71        let param_refs: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
72        self.get_with_query(&endpoint, &param_refs).await
73    }
74}
75
76/// Build the `src/{ref}/{path}` endpoint path. An empty `path` targets the
77/// repository root; the trailing slash tells Bitbucket to return a directory
78/// listing rather than a ref redirect.
79fn source_path(workspace: &str, repo_slug: &str, git_ref: &str, path: &str) -> String {
80    let base = format!(
81        "/repositories/{}/{}/src/{}",
82        workspace,
83        repo_slug,
84        urlencode_segment(git_ref)
85    );
86
87    if path.is_empty() {
88        format!("{}/", base)
89    } else {
90        format!("{}/{}", base, urlencode_path(path))
91    }
92}
93
94/// Percent-encode a repository file path: each component is encoded as a
95/// path segment while the `/` separators are preserved.
96fn urlencode_path(path: &str) -> String {
97    path.split('/')
98        .map(urlencode_segment)
99        .collect::<Vec<_>>()
100        .join("/")
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn urlencode_path_preserves_separators() {
109        assert_eq!(urlencode_path("src/api/mod.rs"), "src/api/mod.rs");
110    }
111
112    #[test]
113    fn urlencode_path_encodes_specials_within_segments() {
114        assert_eq!(
115            urlencode_path("docs/release notes/v1 (draft).md"),
116            "docs/release%20notes/v1%20%28draft%29.md"
117        );
118    }
119
120    #[test]
121    fn source_path_uses_trailing_slash_for_root() {
122        assert_eq!(
123            source_path("acme", "widgets", "main", ""),
124            "/repositories/acme/widgets/src/main/"
125        );
126    }
127
128    #[test]
129    fn source_path_appends_encoded_file_path() {
130        assert_eq!(
131            source_path("acme", "widgets", "feature/x", "src/lib.rs"),
132            "/repositories/acme/widgets/src/feature%2Fx/src/lib.rs"
133        );
134    }
135}