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
//! Go module proxy source: full tagged history, module archives, and
//! retraction signals.
//!
//! Module paths and versions are case-escaped for the proxy URL: every
//! uppercase letter becomes `!` plus its lowercase form (`github.com/Acme` →
//! `github.com/!acme`). Pseudo-versions (timestamp/commit snapshots) are
//! skipped by default because they are not releases; callers opt in with
//! [`GolangSource::include_pseudo_versions`].
//!
//! The proxy exposes `@v/{version}.zip` and `@v/{version}.mod` but no size or
//! digest. `go.sum` hashes are not SHA-256 of these files, so artifacts
//! report `sha256: None`. Retraction is read from the version's `.info`
//! document when the proxy reports it.
use std::collections::BTreeSet;
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::{Map, Value, json};
use crate::release::artifact::go_escape;
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 PROXY_BASE: &str = "https://proxy.golang.org";
pub struct GolangSource {
http: Arc<dyn RegistryHttp>,
include_pseudo_versions: bool,
}
impl GolangSource {
pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
Self {
http,
include_pseudo_versions: false,
}
}
/// Include pseudo-versions in [`ReleaseSource::versions`]. Off by default.
pub fn include_pseudo_versions(mut self, include: bool) -> Self {
self.include_pseudo_versions = include;
self
}
fn base_url(module: &str) -> String {
format!("{PROXY_BASE}/{}", go_escape(module))
}
async fn raw_versions(&self, module: &str) -> Result<Vec<String>> {
let url = format!("{}/@v/list", Self::base_url(module));
let text = self.http.get_text(&url).await?;
let mut seen = BTreeSet::new();
let mut versions = text
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.filter(|version| self.include_pseudo_versions || !is_pseudo_version(version))
.filter(|version| seen.insert((*version).to_owned()))
.map(str::to_owned)
.collect::<Vec<_>>();
versions.sort_by(|left, right| {
compare(VersionScheme::Go, left, right).then_with(|| left.cmp(right))
});
Ok(versions)
}
fn leaf_name(module: &str) -> &str {
module.rsplit('/').next().unwrap_or(module)
}
}
#[async_trait]
impl ReleaseSource for GolangSource {
fn name(&self) -> &'static str {
"golang"
}
fn capabilities(&self) -> SourceCapabilities {
SourceCapabilities {
versions: true,
artifacts: true,
statuses: true,
project_meta: true,
}
}
async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
Ok(self
.raw_versions(&project.name)
.await?
.into_iter()
.map(|raw| VersionInfo {
version: normalize_version(&raw).unwrap_or_else(|| raw.clone()),
raw,
deprecated: false,
reason: String::new(),
})
.collect())
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
let base = Self::base_url(&project.name);
let escaped = go_escape(&version.raw);
let leaf = Self::leaf_name(&project.name);
// The proxy reports no size and no digest; sizes are left unset rather
// than spending a HEAD request per file.
Ok(vec![
ArtifactInfo {
file_name: format!("{leaf}-{}.zip", version.raw),
url: format!("{base}/@v/{escaped}.zip"),
sha256: None,
size: None,
mime_type: Some("application/zip".to_owned()),
},
ArtifactInfo {
file_name: format!("{leaf}-{}.mod", version.raw),
url: format!("{base}/@v/{escaped}.mod"),
sha256: None,
size: None,
mime_type: Some("text/plain".to_owned()),
},
])
}
async fn statuses(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
let base = Self::base_url(&project.name);
let escaped = go_escape(&version.raw);
let payload = self
.http
.get_json(&format!("{base}/@v/{escaped}.info"))
.await?;
let Some(reason) = retraction(&payload) else {
return Ok(Vec::new());
};
Ok(vec![StatusInfo {
status: "retracted".to_owned(),
kind: Some("registry".to_owned()),
reason,
}])
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
let versions = self.raw_versions(&project.name).await?;
let base = Self::base_url(&project.name);
let latest = match self.http.get_json(&format!("{base}/@latest")).await {
Ok(payload) => text_field(&payload, "Version").map(str::to_owned),
Err(_) => None,
}
.or_else(|| versions.last().cloned());
let mut meta = Map::new();
meta.insert("module".to_owned(), Value::String(project.name.clone()));
meta.insert("versions".to_owned(), json!(versions));
if let Some(latest) = latest {
meta.insert("latest".to_owned(), Value::String(latest));
}
Ok(Value::Object(meta))
}
}
/// Go pseudo-version: a semver prerelease containing a 14-digit UTC
/// timestamp and a commit hash, for example
/// `v0.0.0-20240101120000-abcdef123456`.
pub fn is_pseudo_version(version: &str) -> bool {
let core = version.split('+').next().unwrap_or(version);
let Some((_, prerelease)) = core.split_once('-') else {
return false;
};
let timestamp = prerelease
.split(['-', '.'])
.any(|token| token.len() == 14 && token.bytes().all(|byte| byte.is_ascii_digit()));
let commit = prerelease.rsplit('-').next().unwrap_or("");
timestamp && commit.len() >= 12 && commit.bytes().all(|byte| byte.is_ascii_hexdigit())
}
/// Retraction reason when the `.info` document carries a retraction signal.
fn retraction(payload: &Value) -> Option<String> {
let flag = payload
.get("Retracted")
.or_else(|| payload.get("retracted"))?;
let retracted = match flag {
Value::Bool(value) => *value,
Value::String(value) => !value.is_empty(),
Value::Number(number) => number.as_f64().is_some_and(|value| value != 0.0),
_ => false,
};
if !retracted {
return None;
}
let reason = [
"RetractReason",
"retractReason",
"retracted_reason",
"reason",
"message",
]
.iter()
.find_map(|key| text_field(payload, key));
Some(reason.map(str::to_owned).unwrap_or_else(|| match flag {
Value::String(value) => value.clone(),
_ => String::new(),
}))
}
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())
}