1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! Bitbucket Cloud tags, downloads, and repository metadata.
//!
//! Bitbucket has no release objects, so versions come from tags. Downloads are
//! repository-scoped rather than version-scoped; assets are matched to a
//! version by file name. The downloads listing supplies size and URL but never
//! a digest, so `sha256` stays `None` and the download fallback in
//! `release::artifact` hashes the bytes.
use std::sync::Arc;
use anyhow::{Result, anyhow, bail};
use async_trait::async_trait;
use serde_json::{Map, Value};
use super::github::{
GitHttp, RepoRef, check_status, dedupe_artifacts, get_response, normalize_tag, repo_ref,
};
use crate::release::source::{
ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason,
VersionInfo,
};
pub const BITBUCKET_API: &str = "https://api.bitbucket.org/2.0";
const PAGE_LEN: usize = 100;
const MAX_PAGES: usize = 100;
fn tag_date(tag: &Value) -> String {
tag.pointer("/target/date")
.and_then(Value::as_str)
.unwrap_or("")
.to_owned()
}
fn download_url(download: &Value) -> Option<&str> {
download
.pointer("/links/self/href")
.and_then(Value::as_str)
.filter(|url| !url.is_empty())
}
fn names_version(file_name: &str, version: &VersionInfo) -> bool {
let file_name = file_name.to_ascii_lowercase();
[version.raw.as_str(), version.version.as_str()]
.into_iter()
.filter(|candidate| !candidate.is_empty())
.any(|candidate| file_name.contains(&candidate.to_ascii_lowercase()))
}
/// Bitbucket Cloud source adapter.
pub struct BitbucketSource {
http: Arc<dyn GitHttp>,
}
impl BitbucketSource {
pub fn new(http: Arc<dyn GitHttp>) -> Self {
Self { http }
}
fn repo_url(repo: &RepoRef, suffix: &str) -> String {
format!("{BITBUCKET_API}/repositories/{}{suffix}", repo.path)
}
/// Follow body-level `next` links until exhausted.
async fn pages(&self, start: &str) -> Result<Vec<Value>> {
let mut values = Vec::new();
let mut next = Some(start.to_owned());
let mut pages = 0usize;
while let Some(url) = next {
pages += 1;
if pages > MAX_PAGES {
bail!("bitbucket: pagination exceeded {MAX_PAGES} pages");
}
let response = get_response(self.http.as_ref(), &url, &[]).await?;
check_status(&response, &url, "bitbucket")?;
let body = response.body;
let page = body
.get("values")
.and_then(Value::as_array)
.ok_or_else(|| anyhow!("bitbucket: missing values array from {url}"))?;
values.extend(page.iter().cloned());
next = body.get("next").and_then(Value::as_str).map(str::to_owned);
}
Ok(values)
}
}
#[async_trait]
impl ReleaseSource for BitbucketSource {
fn name(&self) -> &'static str {
"bitbucket"
}
fn capabilities(&self) -> SourceCapabilities {
SourceCapabilities {
versions: true,
artifacts: true,
statuses: false,
project_meta: true,
}
}
async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
let repo = repo_ref(project, "bitbucket", false)?;
let tags = self
.pages(&Self::repo_url(
&repo,
&format!("/refs/tags?pagelen={PAGE_LEN}"),
))
.await?;
let mut dated: Vec<(String, String)> = tags
.iter()
.filter_map(|tag| {
let name = tag.get("name").and_then(Value::as_str)?;
Some((tag_date(tag), name.to_owned()))
})
.collect();
dated.sort_by(|left, right| right.0.cmp(&left.0));
let mut versions = Vec::new();
let mut seen = std::collections::HashSet::new();
for (_, raw) in dated {
let Some(version) = normalize_tag(&raw) else {
continue;
};
if seen.insert(version.clone()) {
versions.push(VersionInfo {
raw,
version,
deprecated: false,
reason: String::new(),
});
}
}
Ok(versions)
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
let repo = repo_ref(project, "bitbucket", false)?;
let downloads = self
.pages(&Self::repo_url(
&repo,
&format!("/downloads?pagelen={PAGE_LEN}"),
))
.await?;
// ponytail: downloads are repository-scoped, so a version is matched by
// substring in the file name. Upgrade to per-version metadata if
// Bitbucket ever exposes it.
let artifacts = downloads
.iter()
.filter_map(|download| {
let name = download.get("name").and_then(Value::as_str)?;
if !names_version(name, version) {
return None;
}
let url = download_url(download)?;
Some(ArtifactInfo {
file_name: name.to_owned(),
url: url.to_owned(),
sha256: None,
size: download.get("size").and_then(Value::as_u64),
mime_type: None,
})
})
.collect();
Ok(dedupe_artifacts(artifacts))
}
async fn statuses(
&self,
_project: &ProjectRef,
_version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
Err(anyhow!(
"{:?}: bitbucket exposes no release status signals",
UnsupportedReason::NoStatuses
))
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
let repo = repo_ref(project, "bitbucket", false)?;
let url = Self::repo_url(&repo, "");
let response = get_response(self.http.as_ref(), &url, &[]).await?;
let meta = require_object(response, &url)?;
let mut out = Map::new();
if let Some(value) = meta
.pointer("/links/html/href")
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
{
out.insert("repository".to_owned(), Value::String(value.to_owned()));
}
if let Some(value) = meta
.pointer("/links/website/href")
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
{
out.insert("homepage".to_owned(), Value::String(value.to_owned()));
}
// Bitbucket Cloud exposes no license field.
if let Some(value) = meta
.get("description")
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
{
out.insert("description".to_owned(), Value::String(value.to_owned()));
}
Ok(Value::Object(out))
}
}
fn require_object(response: super::github::GitResponse, url: &str) -> Result<Value> {
check_status(&response, url, "bitbucket")?;
if !response.body.is_object() {
bail!("bitbucket: expected a repository object from {url}");
}
Ok(response.body)
}