forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

release.rs969 lines, 33.9 KiBHistoryRawDownload
1//! Publishes a release when a tag run finishes with every job succeeded and the workflow at the
2//! run's commit has a `[release]` table (see docs/ci.md, Releases). The finish handler spawns
3//! [`on_run_finished`], so the runner's request is not slowed down.
4//!
5//! The run is idempotent. A release that already exists keeps its title, notes and draft state and
6//! only gets the selected artifacts; an asset with the same name is replaced.
7//!
8//! The release is made as the run's actor. A system run has no actor, and an organization never
9//! acts, so those fall back to the repo owner, then to the ghost account (`status_creator`).
10//!
11//! The outcome is written as one `[forge]` line at the end of the log of the run's last finished
12//! job, so it shows on the run's job pages with the rest of the output.
13
14use forge_ci::config::{Event, ReleaseNotes, ReleaseSpec};
15use forge_core::ci::{CiJob, CiRun, RunState};
16use forge_core::releases::{MAX_BODY_CHARS, MAX_TITLE_CHARS, Release};
17use forge_core::{Repo, User};
18use forge_git::browse::CommitInfo;
19use forge_git::history::log;
20use forge_git::pulls::{is_ancestor, range_log};
21use forge_git::repo::repo_path;
22use forge_git::tags::previous_tag;
23use tokio::io::AsyncWriteExt;
24
25use super::api::fit_to_cap;
26use super::{artifact_key, log_path, schedule, status_creator};
27use crate::release_ops::{self, CreateRelease, ReleaseError};
28use crate::render::commit_message::CommitMessage;
29use crate::state::AppState;
30
31/// Most commits listed in the notes. Older commits are left out.
32const MAX_NOTE_COMMITS: usize = 200;
33const MIB: u64 = 1024 * 1024;
34
35/// Runs after a run finished. Does nothing unless the run is a successful tag run and the workflow
36/// at its commit asks for a release for this tag. Failures are logged and written to the job log;
37/// they never fail the caller.
38pub async fn on_run_finished(state: &AppState, run: &CiRun) {
39 if run.state != RunState::Success {
40 return;
41 }
42 let Some(tag) = run.git_ref.strip_prefix("refs/tags/") else {
43 return;
44 };
45 let repo = match state.store.repo_by_id(&run.repo_id).await {
46 Ok(Some(repo)) => repo,
47 Ok(None) => return,
48 Err(e) => {
49 tracing::error!(error = %e, run_id = %run.id, "release: loading the repo failed");
50 return;
51 }
52 };
53 let Some(config) = schedule::config_at(state, &repo.id, &run.commit_oid).await else {
54 return;
55 };
56 let Some(spec) = config
57 .release
58 .as_ref()
59 .filter(|_| config.wants_release(&Event::Tag { tag }))
60 else {
61 return;
62 };
63
64 let text = publish(state, &repo, run, tag, spec).await;
65 let jobs = match state.store.jobs_for_run(&run.id).await {
66 Ok(jobs) => jobs,
67 Err(e) => {
68 tracing::error!(error = %e, run_id = %run.id, "release: listing the jobs failed");
69 return;
70 }
71 };
72 if let Some(job) = jobs.iter().max_by(|a, b| a.finished_at.cmp(&b.finished_at)) {
73 note(state, job, &text).await;
74 }
75}
76
77/// Creates or finds the release, attaches the selected artifacts, and describes the outcome.
78async fn publish(
79 state: &AppState,
80 repo: &Repo,
81 run: &CiRun,
82 tag: &str,
83 spec: &ReleaseSpec,
84) -> String {
85 let Some(actor) = actor_of(state, repo, run).await else {
86 return format!("Could not publish release {tag}: no user to publish as");
87 };
88 let release = match release_for(state, repo, run, tag, spec, &actor).await {
89 Ok(release) => release,
90 Err(reason) => return format!("Could not publish release {tag}: {reason}"),
91 };
92
93 let jobs = match state.store.jobs_for_run(&run.id).await {
94 Ok(jobs) => jobs,
95 Err(e) => {
96 tracing::error!(error = %e, run_id = %run.id, "release: listing the jobs failed");
97 return format!("Could not publish release {tag}: could not list the jobs");
98 }
99 };
100 let max_bytes = state.live().releases.max_asset_mb.saturating_mul(MIB);
101 let mut attached = 0usize;
102 let mut failed: Vec<String> = Vec::new();
103 for job in &jobs {
104 let artifacts = match state.store.list_artifacts(&job.id).await {
105 Ok(artifacts) => artifacts,
106 Err(e) => {
107 tracing::error!(error = %e, job_id = %job.id, "release: listing artifacts failed");
108 failed.push(format!("{}: could not list the artifacts", job.name));
109 continue;
110 }
111 };
112 for artifact in artifacts
113 .iter()
114 .filter(|a| spec.asset_matches(&job.name, &a.name))
115 {
116 match attach(
117 state,
118 repo,
119 &release,
120 &actor,
121 &artifact.id,
122 &artifact.name,
123 max_bytes,
124 )
125 .await
126 {
127 Ok(()) => attached += 1,
128 Err(reason) => {
129 tracing::error!(run_id = %run.id, tag, artifact = %artifact.name, %reason, "release: attaching an asset failed");
130 failed.push(format!("{}: {reason}", artifact.name));
131 }
132 }
133 }
134 }
135
136 let mut text = format!("Published release {tag} with {attached} assets.");
137 if !failed.is_empty() {
138 text.push_str(&format!(" {} failed: {}.", failed.len(), failed.join(", ")));
139 }
140 text
141}
142
143/// The person the release is made as: the run's actor, or the fallback of `status_creator`.
144async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option<User> {
145 let id = status_creator(state, repo, &run.actor_id).await?;
146 match state.store.user_by_id(&id).await {
147 Ok(user) => user,
148 Err(e) => {
149 tracing::error!(error = %e, run_id = %run.id, "release: loading the actor failed");
150 None
151 }
152 }
153}
154
155/// The existing release for `tag`, or a new one made from the spec. A release made by another run
156/// in the meantime (a `Conflict`) is read back instead.
157async fn release_for(
158 state: &AppState,
159 repo: &Repo,
160 run: &CiRun,
161 tag: &str,
162 spec: &ReleaseSpec,
163 actor: &User,
164) -> Result<Release, String> {
165 match state.store.release_by_tag(&repo.id, tag).await {
166 Ok(Some(existing)) if existing.target_oid == run.commit_oid => return Ok(existing),
167 Ok(Some(existing)) => {
168 return Ok(follow_tag(state, repo, run, tag, spec, actor, existing).await);
169 }
170 Ok(None) => {}
171 Err(e) => {
172 tracing::error!(error = %e, run_id = %run.id, "release: reading the release failed");
173 return Err("could not read the release".to_owned());
174 }
175 }
176
177 let input = CreateRelease {
178 tag: tag.to_owned(),
179 target: Some(run.commit_oid.clone()),
180 title: spec.title_for(tag).chars().take(MAX_TITLE_CHARS).collect(),
181 body: notes(state, repo, run, tag, spec).await,
182 draft: spec.draft,
183 prerelease: spec.is_prerelease(tag),
184 };
185 match release_ops::create(state, repo, actor, input).await {
186 Ok(release) => Ok(release),
187 Err(ReleaseError::Conflict(_)) => match state.store.release_by_tag(&repo.id, tag).await {
188 Ok(Some(existing)) => Ok(existing),
189 _ => Err("a release for this tag could not be made".to_owned()),
190 },
191 Err(e) => {
192 tracing::error!(error = ?e, run_id = %run.id, tag, "release: creating the release failed");
193 Err(e.message())
194 }
195 }
196}
197
198/// An existing release whose tag now names the run's commit (the tag was deleted and pushed
199/// again elsewhere) follows it: its target becomes that commit, and notes the forge wrote for the
200/// old target, unedited, are written again for the new one. Hand-written notes and the title are
201/// kept. A failure is logged and the release is used as it is.
202async fn follow_tag(
203 state: &AppState,
204 repo: &Repo,
205 run: &CiRun,
206 tag: &str,
207 spec: &ReleaseSpec,
208 actor: &User,
209 existing: Release,
210) -> Release {
211 let generated = !matches!(spec.notes, ReleaseNotes::Off)
212 && changelog(state, repo, &existing.target_oid, tag)
213 .await
214 .as_deref()
215 == Ok(existing.body.as_str());
216 let body = if generated {
217 Some(notes(state, repo, run, tag, spec).await)
218 } else {
219 None
220 };
221 match release_ops::follow_moved_tag(state, repo, actor, &existing, &run.commit_oid, body).await
222 {
223 Ok(Some(moved)) => moved,
224 Ok(None) => existing,
225 Err(e) => {
226 tracing::error!(error = ?e, run_id = %run.id, tag, "release: moving the target failed");
227 existing
228 }
229 }
230}
231
232/// Stores one artifact as an asset of `release`, replacing an asset with the same name.
233async fn attach(
234 state: &AppState,
235 repo: &Repo,
236 release: &Release,
237 actor: &User,
238 artifact_id: &str,
239 name: &str,
240 max_bytes: u64,
241) -> Result<(), String> {
242 let read = match state.blobs.read(&artifact_key(artifact_id)).await {
243 Ok(Some(read)) => read,
244 Ok(None) => return Err("the file is missing from storage".to_owned()),
245 Err(e) => {
246 tracing::error!(error = %e, artifact_id, "release: reading an artifact failed");
247 return Err("the file could not be read".to_owned());
248 }
249 };
250 release_ops::put_asset(
251 state,
252 repo,
253 release,
254 actor,
255 name,
256 None,
257 read.stream,
258 max_bytes,
259 )
260 .await
261 .map(|_| ())
262 .map_err(|e| {
263 tracing::error!(error = ?e, artifact_id, "release: storing an asset failed");
264 e.message()
265 })
266}
267
268/// The notes for a new release, or an empty string when the spec turns them off. A git failure
269/// leaves the notes empty and is logged; the release is still made.
270async fn notes(
271 state: &AppState,
272 repo: &Repo,
273 run: &CiRun,
274 tag: &str,
275 spec: &ReleaseSpec,
276) -> String {
277 if matches!(spec.notes, ReleaseNotes::Off) {
278 return String::new();
279 }
280 match changelog(state, repo, &run.commit_oid, tag).await {
281 Ok(text) => text,
282 Err(e) => {
283 tracing::error!(error = %e, run_id = %run.id, tag, "release: building the notes failed");
284 String::new()
285 }
286 }
287}
288
289/// The commit list since the previous release. The previous release is the newest other
290/// published release whose target is an ancestor of this commit. Without one, it is the closest
291/// git tag reachable from the commit. Without either, the list is capped at the newest commits.
292async fn changelog(
293 state: &AppState,
294 repo: &Repo,
295 commit: &str,
296 tag: &str,
297) -> Result<String, String> {
298 let dir = repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?;
299 let env = &state.git;
300
301 let releases = state
302 .store
303 .list_releases(&repo.id)
304 .await
305 .map_err(|e| e.to_string())?;
306 let mut previous: Option<(String, String)> = None;
307 for release in releases.iter().filter(|r| !r.draft && r.tag != tag) {
308 if is_ancestor(env, &dir, &release.target_oid, commit)
309 .await
310 .unwrap_or(false)
311 {
312 previous = Some((release.tag.clone(), release.target_oid.clone()));
313 break;
314 }
315 }
316 if previous.is_none() {
317 previous = previous_tag(env, &dir, commit)
318 .await
319 .map_err(|e| e.to_string())?;
320 }
321
322 let commits = match &previous {
323 Some((_, base)) => {
324 let mut commits = range_log(env, &dir, base, commit, MAX_NOTE_COMMITS)
325 .await
326 .map_err(|e| e.to_string())?;
327 commits.reverse();
328 commits
329 }
330 None => log(env, &dir, commit, None, 0, MAX_NOTE_COMMITS)
331 .await
332 .map_err(|e| e.to_string())?,
333 };
334 let footer = previous
335 .as_ref()
336 .map(|(name, _)| format!("Full changelog: {name}...{tag}"));
337 Ok(bullets(&commits, footer.as_deref()))
338}
339
340/// Note sections in output order. Commit kinds map to them through `section_of`.
341const SECTIONS: [&str; 7] = [
342 "Features",
343 "Fixes",
344 "Performance",
345 "Style",
346 "CI",
347 "Documentation",
348 "Other",
349];
350
351/// The index in `SECTIONS` for a commit kind. Unknown kinds go to `Other`.
352fn section_of(kind: &str) -> usize {
353 match kind {
354 "feat" => 0,
355 "fix" => 1,
356 "perf" => 2,
357 "style" | "ui" | "ux" => 3,
358 "ci" => 4,
359 "docs" => 5,
360 _ => 6,
361 }
362}
363
364/// The notes body. When at least one subject is structured, the clauses are grouped under
365/// `SECTIONS`; otherwise one `- subject (shortsha)` line per commit, newest first. Commits that
366/// would push the notes past the body limit are left out, and the footer is kept in the count.
367fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String {
368 let footer_len = footer.map_or(0, |f| f.chars().count() + 2);
369 let structured = commits
370 .iter()
371 .any(|commit| CommitMessage::parse(&commit.summary).is_some());
372 let body = if structured {
373 grouped_bullets(commits, footer_len)
374 } else {
375 flat_bullets(commits, footer_len)
376 };
377 with_footer(&body, footer)
378}
379
380/// One `- subject (shortsha)` line per commit, newest first.
381fn flat_bullets(commits: &[CommitInfo], footer_len: usize) -> String {
382 let mut body = String::new();
383 let mut used = 0usize;
384 for commit in commits {
385 let short = commit.oid.get(..7).unwrap_or(&commit.oid);
386 let line = format!("- {} ({short})\n", commit.summary);
387 let len = line.chars().count();
388 if used + len + footer_len > MAX_BODY_CHARS {
389 break;
390 }
391 used += len;
392 body.push_str(&line);
393 }
394 body
395}
396
397/// Lines grouped under `SECTIONS`, in commit order within each section. A heading costs its
398/// `### name` line and the blank line after the section, and is counted once per section.
399fn grouped_bullets(commits: &[CommitInfo], footer_len: usize) -> String {
400 let mut sections: Vec<Vec<String>> = vec![Vec::new(); SECTIONS.len()];
401 let mut used = 0usize;
402 'commits: for commit in commits {
403 let short = commit.oid.get(..7).unwrap_or(&commit.oid);
404 let clauses: Vec<(usize, String)> = match CommitMessage::parse(&commit.summary) {
405 Some(message) => message
406 .groups
407 .iter()
408 .flat_map(|group| {
409 let section = section_of(&group.kind);
410 group
411 .clauses
412 .iter()
413 .map(move |clause| (section, clause.clone()))
414 })
415 .collect(),
416 None => vec![(section_of(""), commit.summary.clone())],
417 };
418 for (section, text) in clauses {
419 let line = format!("- {text} ({short})\n");
420 let mut len = line.chars().count();
421 if sections[section].is_empty() {
422 len += SECTIONS[section].chars().count() + 6;
423 }
424 if used + len + footer_len > MAX_BODY_CHARS {
425 break 'commits;
426 }
427 used += len;
428 sections[section].push(line);
429 }
430 }
431 let mut body = String::new();
432 for (name, lines) in SECTIONS.iter().zip(&sections) {
433 if lines.is_empty() {
434 continue;
435 }
436 if !body.is_empty() {
437 body.push('\n');
438 }
439 body.push_str(&format!("### {name}\n"));
440 for line in lines {
441 body.push_str(line);
442 }
443 }
444 body
445}
446
447/// The body without trailing whitespace, then the footer after a blank line.
448fn with_footer(body: &str, footer: Option<&str>) -> String {
449 let mut body = body.trim_end().to_owned();
450 if let Some(footer) = footer {
451 if !body.is_empty() {
452 body.push_str("\n\n");
453 }
454 body.push_str(footer);
455 }
456 body
457}
458
459/// Appends one `[forge]` line to the log of `job`. Respects the log size cap. A failure is logged;
460/// the outcome is not lost, it is also in the tracing output.
461async fn note(state: &AppState, job: &CiJob, text: &str) {
462 let line = format!("[forge] {text}\n");
463 let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
464 let path = log_path(&state.config.data_dir, &job.id);
465 let current = match tokio::fs::metadata(&path).await {
466 Ok(meta) => meta.len(),
467 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
468 Err(e) => {
469 tracing::error!(error = %e, job_id = %job.id, "release: reading the job log failed");
470 return;
471 }
472 };
473 let bytes = fit_to_cap(current, cap, line.as_bytes());
474 if bytes.is_empty() {
475 return;
476 }
477 let written: std::io::Result<()> = async {
478 if let Some(parent) = path.parent() {
479 tokio::fs::create_dir_all(parent).await?;
480 }
481 let mut file = tokio::fs::OpenOptions::new()
482 .create(true)
483 .append(true)
484 .open(&path)
485 .await?;
486 file.write_all(&bytes).await?;
487 file.flush().await
488 }
489 .await;
490 if let Err(e) = written {
491 tracing::error!(error = %e, job_id = %job.id, "release: writing the job log failed");
492 return;
493 }
494 if let Err(e) = state.store.add_log_bytes(&job.id, bytes.len() as i64).await {
495 tracing::error!(error = %e, job_id = %job.id, "release: counting the job log bytes failed");
496 return;
497 }
498 state.ci_live.bump_job(&job.id);
499}
500
501#[cfg(test)]
502mod tests {
503 use forge_core::ci::{CiArtifact, JobState};
504
505 use super::*;
506 use crate::ci::schedule::CONFIG_PATH;
507 use crate::ci::schedule::tests::{Fixture, ZERO, fixture, git, land, push};
508 use crate::post_update::after_ref_update;
509
510 /// A tag release workflow with two jobs. Only `build` feeds the release, through `dist_*`.
511 const RELEASE: &str = r#"
512[on]
513push = ["main"]
514tags = ["v*"]
515
516[jobs.build]
517image = "alpine:3"
518run = "make"
519artifacts = ["dist/*"]
520
521[jobs.docs]
522image = "alpine:3"
523run = "make docs"
524artifacts = ["site/*"]
525
526[release]
527assets = ["build:dist_*"]
528title = "forge {tag}"
529"#;
530
531 /// Finishes the jobs of `run_id` in order. The job named `failing` fails; the others succeed.
532 async fn finish_all(fx: &Fixture, run_id: &str, failing: Option<&str>) {
533 loop {
534 let jobs = fx.state.store.jobs_for_run(run_id).await.expect("jobs");
535 let Some(job) = jobs.iter().find(|j| !j.state.is_terminal()) else {
536 break;
537 };
538 let fails = failing == Some(job.name.as_str());
539 let (outcome, code) = if fails {
540 (JobState::Failure, 1)
541 } else {
542 (JobState::Success, 0)
543 };
544 fx.state
545 .store
546 .finish_job(&job.id, outcome, Some(code), None)
547 .await
548 .expect("finish");
549 }
550 }
551
552 async fn run_of(fx: &Fixture, number: i64) -> CiRun {
553 fx.state
554 .store
555 .run_by_number(&fx.repo.id, number)
556 .await
557 .expect("query")
558 .expect("run")
559 }
560
561 async fn job_of(fx: &Fixture, run: &CiRun, name: &str) -> CiJob {
562 fx.state
563 .store
564 .jobs_for_run(&run.id)
565 .await
566 .expect("jobs")
567 .into_iter()
568 .find(|j| j.name == name)
569 .expect("job")
570 }
571
572 /// Stores `body` as an artifact of `job`, the way the upload handler does.
573 async fn add_artifact(fx: &Fixture, job: &CiJob, name: &str, body: &[u8]) -> CiArtifact {
574 let tmp = format!("ci/tmp/{}", ulid::Ulid::generate());
575 let mut writer = fx.state.blobs.begin(&tmp, 1 << 30).await.expect("begin");
576 writer.push(body).await.expect("push");
577 let (size, sha) = writer.finish().await.expect("finish");
578 let artifact = fx
579 .state
580 .store
581 .add_artifact(&job.id, name, size as i64, &sha)
582 .await
583 .expect("artifact");
584 fx.state
585 .blobs
586 .rename(&tmp, &artifact_key(&artifact.id))
587 .await
588 .expect("rename");
589 artifact
590 }
591
592 /// Commits an empty change with `message` and returns the commit.
593 fn commit_message(work: &std::path::Path, message: &str) -> String {
594 git(work, &["commit", "--allow-empty", "-m", message]);
595 git(work, &["rev-parse", "HEAD"])
596 }
597
598 async fn release_named(fx: &Fixture, tag: &str) -> Option<Release> {
599 fx.state
600 .store
601 .release_by_tag(&fx.repo.id, tag)
602 .await
603 .expect("query")
604 }
605
606 async fn asset_names(fx: &Fixture, release: &Release) -> Vec<(String, u64)> {
607 let mut assets: Vec<(String, u64)> = fx
608 .state
609 .store
610 .list_release_assets(&release.id)
611 .await
612 .expect("assets")
613 .into_iter()
614 .map(|a| (a.name, a.size))
615 .collect();
616 assets.sort();
617 assets
618 }
619
620 #[tokio::test]
621 async fn tag_run_publishes_release_with_matching_assets() {
622 let fx = fixture().await;
623 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
624 let run = run_of(&fx, 1).await;
625 let build = job_of(&fx, &run, "build").await;
626 let docs = job_of(&fx, &run, "docs").await;
627 add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await;
628 add_artifact(&fx, &build, "dist_SHA256SUMS", b"sums").await;
629 add_artifact(&fx, &docs, "dist_docs-only", b"x").await;
630 add_artifact(&fx, &docs, "site_index.html", b"<html>").await;
631 finish_all(&fx, &run.id, None).await;
632 let run = run_of(&fx, 1).await;
633 assert_eq!(run.state, RunState::Success);
634
635 on_run_finished(&fx.state, &run).await;
636
637 let release = release_named(&fx, "v1.0").await.expect("release made");
638 assert_eq!(release.title, "forge v1.0");
639 assert_eq!(release.target_oid, run.commit_oid);
640 assert!(!release.draft);
641 assert!(!release.prerelease);
642 assert_eq!(release.author_id, fx.owner.id);
643 assert_eq!(
644 asset_names(&fx, &release).await,
645 vec![
646 ("dist_SHA256SUMS".to_owned(), 4),
647 ("dist_forge-linux-x86_64".to_owned(), 6),
648 ],
649 "only build's dist_* artifacts are attached"
650 );
651
652 let mut log_text = String::new();
653 for job in fx.state.store.jobs_for_run(&run.id).await.expect("jobs") {
654 let path = crate::ci::log_path(&fx.state.config.data_dir, &job.id);
655 if let Ok(text) = std::fs::read_to_string(path) {
656 log_text.push_str(&text);
657 }
658 }
659 assert!(log_text.contains("[forge] Published release v1.0 with 2 assets."));
660 }
661
662 #[tokio::test]
663 async fn notes_list_commits_since_the_previous_release() {
664 let fx = fixture().await;
665 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
666 finish_all(&fx, &run_of(&fx, 1).await.id, None).await;
667 on_run_finished(&fx.state, &run_of(&fx, 1).await).await;
668
669 commit_message(&fx.work, "feat: one");
670 let oid = commit_message(&fx.work, "fix: two");
671 land(&fx, &oid, "refs/tags/v1.1");
672 after_ref_update(
673 &fx.state,
674 &fx.repo,
675 &fx.owner.id,
676 "refs/tags/v1.1",
677 ZERO,
678 &oid,
679 )
680 .await
681 .expect("post update");
682 finish_all(&fx, &run_of(&fx, 2).await.id, None).await;
683 on_run_finished(&fx.state, &run_of(&fx, 2).await).await;
684
685 let release = release_named(&fx, "v1.1").await.expect("release made");
686 let short = &oid[..7];
687 assert!(release.body.starts_with("### Features\n- one ("));
688 assert!(
689 release
690 .body
691 .contains(&format!("### Fixes\n- two ({short})"))
692 );
693 assert!(release.body.ends_with("Full changelog: v1.0...v1.1"));
694 assert!(
695 !release.body.contains("- change ("),
696 "older commits are not repeated"
697 );
698 }
699
700 #[tokio::test]
701 async fn moved_tag_moves_the_release_and_its_generated_notes() {
702 let fx = fixture().await;
703 let first = push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
704 finish_all(&fx, &run_of(&fx, 1).await.id, None).await;
705 on_run_finished(&fx.state, &run_of(&fx, 1).await).await;
706 let before = release_named(&fx, "v1.0").await.expect("release made");
707 assert_eq!(before.target_oid, first);
708
709 let oid = commit_message(&fx.work, "fix: later");
710 land(&fx, &oid, "refs/tags/v1.0");
711 after_ref_update(
712 &fx.state,
713 &fx.repo,
714 &fx.owner.id,
715 "refs/tags/v1.0",
716 &first,
717 &oid,
718 )
719 .await
720 .expect("post update");
721 finish_all(&fx, &run_of(&fx, 2).await.id, None).await;
722 on_run_finished(&fx.state, &run_of(&fx, 2).await).await;
723
724 let after = release_named(&fx, "v1.0").await.expect("release kept");
725 assert_eq!(after.id, before.id);
726 assert_eq!(after.target_oid, oid);
727 assert!(
728 after.body.contains("later"),
729 "notes follow the tag: {}",
730 after.body
731 );
732 }
733
734 #[tokio::test]
735 async fn existing_manual_release_keeps_its_fields_and_gets_assets() {
736 let fx = fixture().await;
737 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
738 let run = run_of(&fx, 1).await;
739 let manual = release_ops::create(
740 &fx.state,
741 &fx.repo,
742 &fx.owner,
743 CreateRelease {
744 tag: "v1.0".to_owned(),
745 target: None,
746 title: "Hand made".to_owned(),
747 body: "Keep me".to_owned(),
748 draft: true,
749 prerelease: true,
750 },
751 )
752 .await
753 .expect("manual release");
754 let build = job_of(&fx, &run, "build").await;
755 add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await;
756 finish_all(&fx, &run.id, None).await;
757
758 on_run_finished(&fx.state, &run_of(&fx, 1).await).await;
759
760 let release = release_named(&fx, "v1.0").await.expect("release");
761 assert_eq!(release.id, manual.id);
762 assert_eq!(release.title, "Hand made");
763 assert_eq!(release.body, "Keep me");
764 assert!(release.draft);
765 assert!(release.prerelease);
766 assert_eq!(asset_names(&fx, &release).await.len(), 1);
767 }
768
769 /// Failed runs never publish. Each scenario has its own tag, so its run is number 1, 2 and 3.
770 /// Scenario 1: `docs` fails after the jobs run in order. Scenario 2: `build` finishes green
771 /// while `docs` still runs, then `docs` fails. Scenario 3: `docs` fails fast while `build`
772 /// has not finished, so `build` is cancelled at once (the running-job path is covered in the
773 /// store tests). No release is created in any scenario.
774 #[tokio::test]
775 async fn failed_runs_create_no_release() {
776 let fx = fixture().await;
777
778 // Scenario 1.
779 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
780 let run = run_of(&fx, 1).await;
781 let build = job_of(&fx, &run, "build").await;
782 add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await;
783 finish_all(&fx, &run.id, Some("docs")).await;
784 let run = run_of(&fx, 1).await;
785 assert_eq!(run.state, RunState::Failure, "in order");
786 on_run_finished(&fx.state, &run).await;
787 assert!(release_named(&fx, "v1.0").await.is_none(), "in order");
788
789 // Scenario 2.
790 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v2.0").await;
791 let run = run_of(&fx, 2).await;
792 let build = job_of(&fx, &run, "build").await;
793 let docs = job_of(&fx, &run, "docs").await;
794 add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await;
795
796 let after_build = fx
797 .state
798 .store
799 .finish_job(&build.id, JobState::Success, Some(0), None)
800 .await
801 .expect("finish build");
802 assert_eq!(after_build.state, RunState::Running, "docs is still queued");
803 on_run_finished(&fx.state, &after_build).await;
804 assert!(release_named(&fx, "v2.0").await.is_none(), "parallel");
805
806 let after_docs = fx
807 .state
808 .store
809 .finish_job(&docs.id, JobState::Failure, Some(1), None)
810 .await
811 .expect("finish docs");
812 assert_eq!(after_docs.state, RunState::Failure, "parallel");
813 on_run_finished(&fx.state, &after_docs).await;
814 assert!(release_named(&fx, "v2.0").await.is_none(), "parallel");
815
816 // Scenario 3.
817 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v3.0").await;
818 let run = run_of(&fx, 3).await;
819 let build = job_of(&fx, &run, "build").await;
820 let docs = job_of(&fx, &run, "docs").await;
821 add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await;
822
823 let after_docs = fx
824 .state
825 .store
826 .finish_job(&docs.id, JobState::Failure, Some(1), None)
827 .await
828 .expect("finish docs");
829 assert_eq!(after_docs.state, RunState::Failure, "fail fast");
830 assert_eq!(job_of(&fx, &run, "build").await.state, JobState::Cancelled);
831 on_run_finished(&fx.state, &after_docs).await;
832 assert!(release_named(&fx, "v3.0").await.is_none(), "fail fast");
833 }
834
835 #[tokio::test]
836 async fn branch_push_run_creates_no_release() {
837 let fx = fixture().await;
838 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/heads/main").await;
839 let run = run_of(&fx, 1).await;
840 finish_all(&fx, &run.id, None).await;
841
842 on_run_finished(&fx.state, &run_of(&fx, 1).await).await;
843
844 assert!(release_named(&fx, "v1.0").await.is_none());
845 assert!(release_named(&fx, "main").await.is_none());
846 }
847
848 #[tokio::test]
849 async fn rerun_replaces_assets_by_name() {
850 let fx = fixture().await;
851 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
852 let first = run_of(&fx, 1).await;
853 let build = job_of(&fx, &first, "build").await;
854 add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"one").await;
855 finish_all(&fx, &first.id, None).await;
856 on_run_finished(&fx.state, &run_of(&fx, 1).await).await;
857
858 let second = fx
859 .state
860 .store
861 .rerun(&first.id, &fx.owner.id)
862 .await
863 .expect("rerun");
864 let build = job_of(&fx, &second, "build").await;
865 add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"second!").await;
866 finish_all(&fx, &second.id, None).await;
867 on_run_finished(&fx.state, &run_of(&fx, 2).await).await;
868
869 let release = release_named(&fx, "v1.0").await.expect("release");
870 assert_eq!(
871 asset_names(&fx, &release).await,
872 vec![("dist_forge-linux-x86_64".to_owned(), 7)]
873 );
874 }
875
876 /// No release exists for the earlier tag, so the notes start from the closest git tag.
877 #[tokio::test]
878 async fn notes_fall_back_to_the_previous_git_tag() {
879 let fx = fixture().await;
880 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
881 commit_message(&fx.work, "feat: one");
882 let oid = commit_message(&fx.work, "fix: two");
883 land(&fx, &oid, "refs/tags/v1.1");
884 after_ref_update(
885 &fx.state,
886 &fx.repo,
887 &fx.owner.id,
888 "refs/tags/v1.1",
889 ZERO,
890 &oid,
891 )
892 .await
893 .expect("post update");
894 finish_all(&fx, &run_of(&fx, 2).await.id, None).await;
895 on_run_finished(&fx.state, &run_of(&fx, 2).await).await;
896
897 let release = release_named(&fx, "v1.1").await.expect("release made");
898 assert!(release.body.starts_with("### Features\n- one ("));
899 assert!(release.body.contains("### Fixes\n- two ("));
900 assert!(release.body.ends_with("Full changelog: v1.0...v1.1"));
901 assert!(release_named(&fx, "v1.0").await.is_none());
902 }
903
904 #[test]
905 fn bullets_put_the_footer_last_and_respect_the_limit() {
906 let commit = |oid: &str, summary: &str| CommitInfo {
907 oid: oid.to_owned(),
908 parents: Vec::new(),
909 author_name: String::new(),
910 author_email: String::new(),
911 author_time: 0,
912 committer_name: String::new(),
913 committer_email: String::new(),
914 committer_time: 0,
915 summary: summary.to_owned(),
916 message: String::new(),
917 };
918 let commits = vec![
919 commit("abcdef1234567", "new"),
920 commit("1234567abcdef", "old"),
921 ];
922 assert_eq!(
923 bullets(&commits, Some("Full changelog: a...b")),
924 "- new (abcdef1)\n- old (1234567)\n\nFull changelog: a...b"
925 );
926 assert_eq!(bullets(&[], None), "");
927 }
928
929 fn info(oid: &str, summary: &str) -> CommitInfo {
930 CommitInfo {
931 oid: oid.to_owned(),
932 parents: Vec::new(),
933 author_name: String::new(),
934 author_email: String::new(),
935 author_time: 0,
936 committer_name: String::new(),
937 committer_email: String::new(),
938 committer_time: 0,
939 summary: summary.to_owned(),
940 message: String::new(),
941 }
942 }
943
944 #[test]
945 fn bullets_group_structured_commits_in_section_order() {
946 let commits = vec![
947 info("aaaaaaa1111", "🐛 fix: b; ✨ feat: a"),
948 info("bbbbbbb2222", "Update the readme"),
949 info("ccccccc3333", "✨ feat: c"),
950 ];
951 assert_eq!(
952 bullets(&commits, None),
953 "### Features\n- a (aaaaaaa)\n- c (ccccccc)\n\n### Fixes\n- b (aaaaaaa)\n\n### Other\n- Update the readme (bbbbbbb)"
954 );
955 }
956
957 #[test]
958 fn bullets_count_headings_and_footer_in_the_limit() {
959 let long = "x".repeat(1000);
960 let commits: Vec<CommitInfo> = (0..200)
961 .map(|i| info(&format!("{i:07}abcdef"), &format!("✨ feat: {long}{i}")))
962 .collect();
963 let footer = "Full changelog: a...b";
964 let body = bullets(&commits, Some(footer));
965 assert!(body.chars().count() <= MAX_BODY_CHARS);
966 assert!(body.starts_with("### Features\n- "));
967 assert!(body.ends_with(footer));
968 }
969}