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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//! RubyGems source: full version history and per-platform `.gem` artifacts.
//!
//! Version entries come from `/api/v1/versions/{name}.json`, which carries the
//! per-platform `sha` and (when the registry reports it) `size`. Artifact URLs
//! are the declared `gem_uri` or derived from the name/version/platform. The
//! version-detail endpoint (`/api/v2/rubygems/{name}/versions/{version}.json`)
//! is consulted only when the list omits a digest or size, and a HEAD supplies
//! a size only when both omit it. (RubyGems has no working
//! `/api/v1/gems/{name}-{version}.json` endpoint; that path returns 404.)
use std::collections::BTreeMap;
use std::sync::Arc;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use serde_json::{Map, Value, json};
use crate::release::http::RegistryHttp;
use crate::release::source::{
ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, VersionInfo,
};
use crate::release::versioning::{VersionScheme, compare, normalize_version};
pub const API_BASE: &str = "https://rubygems.org/api/v1";
pub const VERSION_DETAIL_BASE: &str = "https://rubygems.org/api/v2/rubygems";
pub const GEMS_BASE: &str = "https://rubygems.org/gems";
pub struct GemSource {
http: Arc<dyn RegistryHttp>,
}
impl GemSource {
pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
Self { http }
}
async fn version_entries(&self, name: &str) -> Result<Vec<Value>> {
let url = format!("{API_BASE}/versions/{name}.json");
let payload = self.http.get_json(&url).await?;
payload
.as_array()
.cloned()
.ok_or_else(|| anyhow!("rubygems versions payload is not an array for {name}"))
}
async fn version_detail(&self, name: &str, raw: &str) -> Result<Value> {
let url = format!("{VERSION_DETAIL_BASE}/{name}/versions/{raw}.json");
self.http.get_json(&url).await
}
}
#[async_trait]
impl ReleaseSource for GemSource {
fn name(&self) -> &'static str {
"gem"
}
fn capabilities(&self) -> SourceCapabilities {
SourceCapabilities {
versions: true,
artifacts: true,
statuses: true,
project_meta: true,
}
}
async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
let entries = self.version_entries(&project.name).await?;
Ok(version_infos(&entries))
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
let entries = self.version_entries(&project.name).await?;
let matching = matching_entries(&entries, &version.raw);
if matching.is_empty() {
return Ok(Vec::new());
}
let mut detail: Option<Value> = None;
let mut by_url = BTreeMap::new();
for entry in matching {
let platform = text_field(entry, "platform").unwrap_or("ruby");
let url = text_field(entry, "gem_uri")
.map(str::to_owned)
.unwrap_or_else(|| gem_url(&project.name, &version.raw, platform));
let mut sha256 = text_field(entry, "sha").map(str::to_owned);
let mut size = entry
.get("size")
.and_then(Value::as_u64)
.filter(|size| *size > 0);
if sha256.is_none() || size.is_none() {
if detail.is_none() {
// Advisory enrichment: a failed detail leaves the field unset.
detail = self.version_detail(&project.name, &version.raw).await.ok();
}
if let Some(detail) = &detail {
let detail_platform = text_field(detail, "platform").unwrap_or("ruby");
if platform == detail_platform {
if sha256.is_none() {
sha256 = text_field(detail, "sha").map(str::to_owned);
}
if size.is_none() {
size = detail
.get("size")
.and_then(Value::as_u64)
.filter(|size| *size > 0);
}
}
}
}
if size.is_none() {
size = Some(self.http.head_size(&url).await?);
}
let file_name = url.rsplit('/').next().unwrap_or(&url).to_owned();
by_url.insert(
url.clone(),
ArtifactInfo {
file_name,
url,
sha256,
size,
mime_type: Some("application/gzip".to_owned()),
},
);
}
Ok(by_url.into_values().collect())
}
async fn statuses(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
let entries = self.version_entries(&project.name).await?;
let matching = matching_entries(&entries, &version.raw);
if matching.is_empty() || !matching.iter().all(|entry| truthy(entry.get("yanked"))) {
return Ok(Vec::new());
}
Ok(vec![StatusInfo {
status: "yanked".to_owned(),
kind: Some("registry".to_owned()),
reason: first_text(&matching, "yanked_reason"),
}])
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
let url = format!("{API_BASE}/gems/{}.json", project.name);
let payload = self.http.get_json(&url).await?;
let mut meta = Map::new();
insert_text(
&mut meta,
"name",
Some(text_field(&payload, "name").unwrap_or(project.name.as_str())),
);
insert_text(&mut meta, "description", text_field(&payload, "info"));
insert_text(&mut meta, "homepage", text_field(&payload, "homepage_uri"));
insert_text(
&mut meta,
"repository",
text_field(&payload, "source_code_uri"),
);
let license = payload
.get("licenses")
.and_then(Value::as_array)
.map(|licenses| {
licenses
.iter()
.filter_map(Value::as_str)
.filter(|license| !license.is_empty())
.collect::<Vec<_>>()
.join(", ")
})
.filter(|license| !license.is_empty());
insert_text(&mut meta, "license", license.as_deref());
// A native gem platform (`x86_64-linux`) names a runtime target.
// Pure-Ruby (`ruby`) and JVM (`java`) gems carry no OS/arch fact.
if let Some(target) = platform_target(text_field(&payload, "platform")) {
meta.insert("target".to_owned(), target);
}
Ok(Value::Object(meta))
}
}
fn platform_target(platform: Option<&str>) -> Option<Value> {
let (arch, os) = platform?.trim().rsplit_once('-')?;
let os = match os {
"linux" => "linux",
"darwin" | "macos" => "macos",
"mingw" | "mswin" | "windows" => "windows",
_ => return None,
};
if arch.is_empty() || arch == "ruby" || arch == "java" {
return None;
}
Some(json!({"os": os, "architectures": [arch]}))
}
fn matching_entries<'a>(entries: &'a [Value], raw: &str) -> Vec<&'a Value> {
entries
.iter()
.filter(|entry| text_field(entry, "number") == Some(raw))
.collect()
}
fn version_infos(entries: &[Value]) -> Vec<VersionInfo> {
let mut groups: BTreeMap<&str, Vec<&Value>> = BTreeMap::new();
for entry in entries {
if let Some(number) = text_field(entry, "number") {
groups.entry(number).or_default().push(entry);
}
}
let mut versions = groups
.into_iter()
.map(|(raw, entries)| {
let yanked = entries.iter().all(|entry| truthy(entry.get("yanked")));
VersionInfo {
raw: raw.to_owned(),
version: normalize_version(raw).unwrap_or_else(|| raw.to_owned()),
deprecated: yanked,
reason: if yanked {
first_text(&entries, "yanked_reason")
} else {
String::new()
},
}
})
.collect::<Vec<_>>();
versions.sort_by(|left, right| {
compare(VersionScheme::RubyGems, &left.raw, &right.raw)
.then_with(|| left.raw.cmp(&right.raw))
});
versions
}
fn gem_url(name: &str, raw: &str, platform: &str) -> String {
if platform.is_empty() || platform == "ruby" {
format!("{GEMS_BASE}/{name}-{raw}.gem")
} else {
format!("{GEMS_BASE}/{name}-{raw}-{platform}.gem")
}
}
fn first_text(entries: &[&Value], key: &str) -> String {
entries
.iter()
.find_map(|entry| text_field(entry, key))
.unwrap_or_default()
.to_owned()
}
fn truthy(value: Option<&Value>) -> bool {
match value {
Some(Value::Bool(value)) => *value,
Some(Value::String(value)) => !value.is_empty(),
Some(Value::Number(number)) => number.as_f64().is_some_and(|value| value != 0.0),
Some(Value::Array(values)) => !values.is_empty(),
Some(Value::Object(values)) => !values.is_empty(),
Some(Value::Null) | None => false,
}
}
fn text_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
value
.get(key)
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
}
fn insert_text(meta: &mut Map<String, Value>, key: &str, value: Option<&str>) {
if let Some(value) = value.filter(|value| !value.is_empty()) {
meta.insert(key.to_owned(), Value::String(value.to_owned()));
}
}