1use serde_json::Value;
15
16use super::context::Ctx;
17use crate::detect::Forge;
18use crate::release_state::{self, Answer, Api, ForgeCli, Registry};
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Milestone {
23 pub id: &'static str,
25 pub status: &'static str,
28 pub detail: String,
30}
31
32impl Milestone {
33 #[must_use]
35 pub fn line(&self) -> String {
36 format!("milestone {}: {} ({})", self.id, self.status, self.detail)
37 }
38}
39
40pub const FIRST_VERSION: &str = "first-version-published";
42pub const AUTOMATED_RELEASE: &str = "automated-release-proven";
44
45const fn word(answer: Answer) -> &'static str {
47 match answer {
48 Answer::Yes => "observed",
49 Answer::No => "not-observed",
50 Answer::Unknown => "unknown",
51 Answer::NotApplicable => "not-applicable",
52 }
53}
54
55fn operator_forms(
58 driver: &str,
59 package: &str,
60 forge: Option<Forge>,
61 repo: &str,
62) -> Vec<(&'static str, String)> {
63 match driver {
64 "rust" => vec![
65 (
66 "trusted-publisher",
67 format!(
68 "rk binding rust, the trusted publisher: the Trusted Publishing table on crates.io/crates/{package}/settings lists the owner, the repository, and release-plz.yml"
69 ),
70 ),
71 (
72 "bootstrap-token-revoked",
73 "rk binding rust, revoking the bootstrap token: the token is gone from crates.io/settings/tokens, and the host's cargo credentials name no crates-io token".to_owned(),
74 ),
75 (
76 "trusted-publishing-required",
77 format!(
78 "rk binding rust, the trusted publisher: on crates.io/crates/{package}/settings, require trusted publishing for all new versions reads as enabled after a reload"
79 ),
80 ),
81 ],
82 "python" => vec![
83 (
84 "trusted-publisher",
85 if forge == Some(Forge::Gitlab) {
86 format!(
87 "rk binding python, setup specifics: the publishing settings of {package} on PyPI list a GitLab publisher with the namespace and the project of {repo} and the top-level pipeline file .gitlab-ci.yml"
88 )
89 } else {
90 format!(
91 "rk binding python, setup specifics: the publishing settings of {package} on PyPI list the owner, the repository, the workflow release.yml, and the environment pypi"
92 )
93 },
94 ),
95 (
96 "bootstrap-token-revoked",
97 "rk binding python, setup specifics: the project-scoped API token is gone from the PyPI account's API tokens".to_owned(),
98 ),
99 ],
100 _ => Vec::new(),
101 }
102}
103
104#[must_use]
106pub fn observe(ctx: &Ctx) -> Vec<Milestone> {
107 let Some(driver) = ctx.driver().filter(|_| ctx.automatic_release()) else {
108 let reason = "the target selects no automated release".to_owned();
109 return vec![
110 Milestone {
111 id: FIRST_VERSION,
112 status: "not-applicable",
113 detail: reason.clone(),
114 },
115 Milestone {
116 id: AUTOMATED_RELEASE,
117 status: "not-applicable",
118 detail: reason,
119 },
120 ];
121 };
122 let registry = release_state::registry_for(driver, ctx.profile.release.registry);
123 let package = crate::release_engine::adapter::package_name(ctx.target.as_std_path(), driver);
124 let mut found = vec![first_version(registry, package.as_deref())];
125 found.push(automated_release(ctx, driver));
126 if let Some(package) = package.as_deref().filter(|_| registry.is_some()) {
130 for (id, check) in operator_forms(driver, package, ctx.forge, &ctx.repo) {
131 found.push(Milestone {
132 id,
133 status: "operator",
134 detail: check,
135 });
136 }
137 }
138 found
139}
140
141fn first_version(registry: Option<Registry>, package: Option<&str>) -> Milestone {
142 let (status, detail) = match (registry, package) {
143 (None, _) => (
144 "not-applicable",
145 "the release publishes to no registry; the release page is the distribution".to_owned(),
146 ),
147 (Some(_), None) => (
148 "unknown",
149 "the version file names no package the registry can be asked about".to_owned(),
150 ),
151 (Some(registry), Some(package)) => {
152 let answer = release_state::registry_serves(registry, package, None);
153 (
154 word(answer),
155 format!("{} answers for {package}", registry.url(package, None)),
156 )
157 }
158 };
159 Milestone {
160 id: FIRST_VERSION,
161 status,
162 detail,
163 }
164}
165
166fn automated_release(ctx: &Ctx, driver: &str) -> Milestone {
167 let milestone = |status, detail: String| Milestone {
168 id: AUTOMATED_RELEASE,
169 status,
170 detail,
171 };
172 let Some(forge) = ctx.forge else {
173 return milestone(
174 "not-applicable",
175 "the target names no forge this release reads".to_owned(),
176 );
177 };
178 if ctx.repo.is_empty() {
179 return milestone("unknown", "the target names no forge repository".to_owned());
180 }
181 let cli = ForgeCli::new(ctx.cli.clone(), ctx.target.as_std_path().to_path_buf());
182 let trunk = ctx.trunk();
183 let unknown =
184 |reason: String| milestone("unknown", format!("the forge did not answer: {reason}"));
185 let releases_path = match forge {
189 Forge::Github => format!("repos/{}/releases?per_page=1", ctx.repo),
190 Forge::Gitlab => format!(
191 "projects/{}/releases?per_page=1",
192 release_state::gitlab_project(&ctx.repo)
193 ),
194 };
195 let tag = match cli.api(&releases_path) {
196 Api::Ok(body) => body
197 .as_array()
198 .and_then(|list| list.first())
199 .and_then(|release| release["tag_name"].as_str())
200 .map(str::to_owned),
201 Api::Missing => None,
202 Api::Failed(reason) => return unknown(reason),
203 };
204 let Some(tag) = tag else {
205 return milestone("not-observed", "no release exists yet".to_owned());
206 };
207 let (commit_path, commit_pointer) = match forge {
208 Forge::Github => (format!("repos/{}/commits/{tag}", ctx.repo), "/sha"),
209 Forge::Gitlab => (
210 format!(
211 "projects/{}/repository/tags/{tag}",
212 release_state::gitlab_project(&ctx.repo)
213 ),
214 "/commit/id",
215 ),
216 };
217 let commit = match cli.api(&commit_path) {
218 Api::Ok(body) => body
219 .pointer(commit_pointer)
220 .and_then(Value::as_str)
221 .map(str::to_owned),
222 Api::Missing => None,
223 Api::Failed(reason) => return unknown(reason),
224 };
225 let Some(commit) = commit else {
226 return milestone(
227 "not-observed",
228 format!("the newest release, {tag}, names no commit the forge serves"),
229 );
230 };
231 let runs_path = match forge {
232 Forge::Github => {
233 let workflow = match driver {
234 "rust" => "release-plz.yml",
235 _ => "release.yml",
236 };
237 format!(
238 "repos/{}/actions/workflows/{workflow}/runs?branch={trunk}&head_sha={commit}&event=push&status=success&per_page=1",
239 ctx.repo
240 )
241 }
242 Forge::Gitlab => format!(
243 "projects/{}/pipelines?ref={trunk}&sha={commit}&status=success&per_page=1",
244 release_state::gitlab_project(&ctx.repo)
245 ),
246 };
247 let ran = match cli.api(&runs_path) {
248 Api::Ok(body) => body["total_count"].as_u64().map_or_else(
249 || body.as_array().is_some_and(|list| !list.is_empty()),
250 |count| count > 0,
251 ),
252 Api::Missing => false,
253 Api::Failed(reason) => return unknown(reason),
254 };
255 if ran {
256 milestone(
257 "observed",
258 format!("a publish run succeeded on {trunk} at the commit {tag} names"),
259 )
260 } else {
261 milestone(
262 "not-observed",
263 format!("the newest release, {tag}, came from no successful publish run on {trunk}"),
264 )
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::{operator_forms, word};
271 use crate::detect::Forge;
272 use crate::release_state::Answer;
273
274 #[test]
275 fn each_registry_form_carries_its_read_back_check() {
276 let rust: Vec<&str> = operator_forms("rust", "widget", Some(Forge::Github), "acme/widget")
277 .iter()
278 .map(|(id, _)| *id)
279 .collect();
280 assert_eq!(
281 rust,
282 [
283 "trusted-publisher",
284 "bootstrap-token-revoked",
285 "trusted-publishing-required"
286 ]
287 );
288 assert!(
289 operator_forms("rust", "widget", Some(Forge::Github), "acme/widget")[0]
290 .1
291 .contains("crates.io/crates/widget/settings")
292 );
293 let github = operator_forms("python", "widget", Some(Forge::Github), "acme/widget");
294 assert_eq!(github.len(), 2);
295 assert!(github[0].1.contains("release.yml"), "{}", github[0].1);
296 assert!(github[0].1.contains("environment pypi"), "{}", github[0].1);
297 let gitlab = operator_forms("python", "widget", Some(Forge::Gitlab), "acme/widget");
298 assert!(gitlab[0].1.contains("acme/widget"), "{}", gitlab[0].1);
299 assert!(gitlab[0].1.contains(".gitlab-ci.yml"), "{}", gitlab[0].1);
300 assert!(operator_forms("bash", "widget", Some(Forge::Github), "acme/widget").is_empty());
301 assert_eq!(word(Answer::Yes), "observed");
302 assert_eq!(word(Answer::No), "not-observed");
303 }
304}