bitbucket_cli/api/
downloads.rs1use std::path::PathBuf;
2
3use anyhow::{Context, Result};
4use reqwest::multipart::{Form, Part};
5
6use super::BitbucketClient;
7use crate::models::Download;
8
9impl BitbucketClient {
10 pub async fn upload_downloads(
14 &self,
15 workspace: &str,
16 repo_slug: &str,
17 files: &[(String, PathBuf)],
18 ) -> Result<()> {
19 let mut form = Form::new();
20
21 for (upload_name, path) in files {
22 let bytes = std::fs::read(path)
26 .with_context(|| format!("Failed to read file '{}'", path.display()))?;
27 let part = Part::bytes(bytes).file_name(upload_name.clone());
28 form = form.part("files", part);
30 }
31
32 let path = format!("/repositories/{}/{}/downloads", workspace, repo_slug);
33 self.post_multipart(&path, form).await
34 }
35
36 pub async fn list_downloads(&self, workspace: &str, repo_slug: &str) -> Result<Vec<Download>> {
39 let path = format!("/repositories/{}/{}/downloads", workspace, repo_slug);
40 self.get_all_pages::<Download>(&path).await
41 }
42
43 pub async fn delete_download(
45 &self,
46 workspace: &str,
47 repo_slug: &str,
48 filename: &str,
49 ) -> Result<()> {
50 let path = format!(
51 "/repositories/{}/{}/downloads/{}",
52 workspace,
53 repo_slug,
54 urlencode_segment(filename)
55 );
56 self.delete(&path).await
57 }
58}
59
60pub fn download_url(workspace: &str, repo_slug: &str, name: &str) -> String {
65 format!(
66 "https://bitbucket.org/{}/{}/downloads/{}",
67 workspace,
68 repo_slug,
69 urlencode_segment(name)
70 )
71}
72
73fn urlencode_segment(s: &str) -> String {
76 let mut out = String::with_capacity(s.len());
77 for b in s.bytes() {
78 match b {
79 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
80 out.push(b as char)
81 }
82 _ => out.push_str(&format!("%{:02X}", b)),
83 }
84 }
85 out
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91
92 #[test]
93 fn download_url_is_browser_facing_host() {
94 assert_eq!(
95 download_url("acme", "widgets", "shot.png"),
96 "https://bitbucket.org/acme/widgets/downloads/shot.png"
97 );
98 }
99
100 #[test]
101 fn download_url_encodes_spaces_and_specials() {
102 assert_eq!(
103 download_url("acme", "widgets", "my shot (1).png"),
104 "https://bitbucket.org/acme/widgets/downloads/my%20shot%20%281%29.png"
105 );
106 }
107
108 #[test]
109 fn urlencode_leaves_safe_chars_untouched() {
110 assert_eq!(urlencode_segment("a-b_c.d~1.png"), "a-b_c.d~1.png");
111 }
112}