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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//! NuGet source: full registration history, listing state, and deprecations.
//!
//! Versions come from the semver2 registration index. Pages are either
//! inlined in the index or referenced by `@id` and fetched on demand; both
//! shapes are handled. The `registration5-gz-semver2` resource is
//! gzip-compressed on the wire and the shared [`RegistryHttp`] client
//! negotiates and decompresses it, so this module sees plain JSON.
//!
//! The registration document carries no SHA-256 for the `.nupkg`, so
//! artifacts report `sha256: None`; a digest is never invented from another
//! hash. `packageSize` is used when the entry reports it, and no HEAD request
//! is issued just to fill the field.
use std::collections::BTreeSet;
use std::sync::Arc;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use serde_json::{Map, Value};
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 REGISTRATION_BASE: &str = "https://api.nuget.org/v3/registration5-gz-semver2";
pub struct NugetSource {
http: Arc<dyn RegistryHttp>,
}
impl NugetSource {
pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
Self { http }
}
async fn registration_entries(&self, id: &str) -> Result<Vec<Value>> {
let url = format!("{REGISTRATION_BASE}/{}/index.json", id.to_ascii_lowercase());
let index = self.http.get_json(&url).await?;
let pages = index
.get("items")
.and_then(Value::as_array)
.ok_or_else(|| anyhow!("nuget registration index missing items for {id}"))?;
let mut entries = Vec::new();
for page in pages {
if let Some(items) = page.get("items").and_then(Value::as_array) {
entries.extend(items.iter().cloned());
continue;
}
let Some(page_url) = text_field(page, "@id") else {
continue;
};
let payload = self.http.get_json(page_url).await?;
if let Some(items) = payload.get("items").and_then(Value::as_array) {
entries.extend(items.iter().cloned());
}
}
Ok(entries)
}
}
#[async_trait]
impl ReleaseSource for NugetSource {
fn name(&self) -> &'static str {
"nuget"
}
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.registration_entries(&project.name).await?;
Ok(version_infos(&entries))
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
let entries = self.registration_entries(&project.name).await?;
let Some(entry) = entry_for(&entries, &version.raw) else {
return Ok(Vec::new());
};
let Some(url) = package_content(entry) else {
return Ok(Vec::new());
};
let file_name = url
.split(['?', '#'])
.next()
.unwrap_or(url)
.rsplit('/')
.next()
.filter(|name| !name.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| {
format!(
"{}.{}.nupkg",
project.name.to_ascii_lowercase(),
version.raw.to_ascii_lowercase()
)
});
Ok(vec![ArtifactInfo {
file_name,
url: url.to_owned(),
sha256: None,
size: package_size(entry),
mime_type: Some("application/zip".to_owned()),
}])
}
async fn statuses(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
let entries = self.registration_entries(&project.name).await?;
let Some(entry) = entry_for(&entries, &version.raw) else {
return Ok(Vec::new());
};
let catalog = catalog(entry);
let mut signals = Vec::new();
if !listed(catalog) {
signals.push(StatusInfo {
status: "deprecated".to_owned(),
kind: Some("registry".to_owned()),
reason: "unlisted".to_owned(),
});
}
if let Some(deprecation) = catalog.get("deprecation").filter(|value| value.is_object()) {
signals.push(StatusInfo {
status: "deprecated".to_owned(),
kind: Some(deprecation_kind(deprecation).to_owned()),
reason: deprecation_reason(deprecation),
});
}
Ok(signals)
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
let entries = self.registration_entries(&project.name).await?;
let newest = entries
.iter()
.filter_map(|entry| version_of(entry).map(|version| (version, entry)))
.max_by(|(left, _), (right, _)| {
compare(VersionScheme::Nuget, left, right).then_with(|| left.cmp(right))
});
let catalog = newest
.map(|(_, entry)| catalog(entry))
.unwrap_or(&Value::Null);
let mut meta = Map::new();
let name = text_field(catalog, "id").unwrap_or(project.name.as_str());
insert_text(&mut meta, "name", name);
if let Some((version, _)) = newest {
insert_text(&mut meta, "latest", version);
}
insert_text(
&mut meta,
"description",
text_field(catalog, "description")
.or_else(|| text_field(catalog, "summary"))
.unwrap_or_default(),
);
if let Some(project_url) = text_field(catalog, "projectUrl") {
insert_text(&mut meta, "homepage", project_url);
insert_text(&mut meta, "project_url", project_url);
}
insert_text(
&mut meta,
"license",
text_field(catalog, "licenseExpression")
.or_else(|| text_field(catalog, "licenseUrl"))
.unwrap_or_default(),
);
insert_text(
&mut meta,
"repository",
repository_url(catalog).unwrap_or_default(),
);
Ok(Value::Object(meta))
}
}
fn catalog(entry: &Value) -> &Value {
entry
.get("catalogEntry")
.filter(|value| value.is_object())
.unwrap_or(entry)
}
fn version_of(entry: &Value) -> Option<&str> {
text_field(catalog(entry), "version").or_else(|| text_field(entry, "version"))
}
fn entry_for<'a>(entries: &'a [Value], raw: &str) -> Option<&'a Value> {
entries
.iter()
.find(|entry| version_of(entry).is_some_and(|version| version.eq_ignore_ascii_case(raw)))
}
fn package_content(entry: &Value) -> Option<&str> {
text_field(catalog(entry), "packageContent").or_else(|| text_field(entry, "packageContent"))
}
fn package_size(entry: &Value) -> Option<u64> {
let catalog = catalog(entry);
["packageSize", "size"]
.iter()
.find_map(|key| {
catalog
.get(*key)
.or_else(|| entry.get(*key))
.and_then(number_u64)
})
.filter(|size| *size > 0)
}
fn number_u64(value: &Value) -> Option<u64> {
match value {
Value::Number(number) => number.as_u64(),
Value::String(text) => text.parse().ok(),
_ => None,
}
}
fn listed(catalog: &Value) -> bool {
catalog
.get("listed")
.and_then(Value::as_bool)
.unwrap_or(true)
}
fn deprecation_kind(deprecation: &Value) -> &'static str {
let critical = deprecation
.get("reasons")
.and_then(Value::as_array)
.is_some_and(|reasons| {
reasons
.iter()
.filter_map(Value::as_str)
.any(|reason| reason.eq_ignore_ascii_case("CriticalBugs"))
});
if critical { "broken" } else { "registry" }
}
fn deprecation_reason(deprecation: &Value) -> String {
if let Some(message) = text_field(deprecation, "message") {
return message.to_owned();
}
deprecation
.get("reasons")
.and_then(Value::as_array)
.map(|reasons| {
reasons
.iter()
.filter_map(Value::as_str)
.collect::<Vec<_>>()
.join(", ")
})
.unwrap_or_default()
}
fn repository_url(catalog: &Value) -> Option<&str> {
match catalog.get("repository") {
Some(Value::String(url)) if !url.is_empty() => Some(url),
Some(Value::Object(object)) => object
.get("url")
.and_then(Value::as_str)
.filter(|url| !url.is_empty()),
_ => text_field(catalog, "repositoryUrl").or_else(|| text_field(catalog, "repository_url")),
}
}
fn version_infos(entries: &[Value]) -> Vec<VersionInfo> {
let mut seen = BTreeSet::new();
let mut versions = entries
.iter()
.filter_map(|entry| {
let raw = version_of(entry)?;
if !seen.insert(raw.to_ascii_lowercase()) {
return None;
}
let catalog = catalog(entry);
let deprecation = catalog.get("deprecation").filter(|value| value.is_object());
let unlisted = !listed(catalog);
let deprecated = deprecation.is_some() || unlisted;
let reason = match deprecation {
Some(deprecation) => deprecation_reason(deprecation),
None if unlisted => "unlisted".to_owned(),
None => String::new(),
};
Some(VersionInfo {
raw: raw.to_owned(),
version: normalize_version(raw).unwrap_or_else(|| raw.to_owned()),
deprecated,
reason,
})
})
.collect::<Vec<_>>();
versions.sort_by(|left, right| {
compare(VersionScheme::Nuget, &left.raw, &right.raw).then_with(|| left.raw.cmp(&right.raw))
});
versions
}
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: &str) {
if !value.is_empty() {
meta.insert(key.to_owned(), Value::String(value.to_owned()));
}
}