1use std::fmt::Write as _;
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use anyhow::{Context as _, Result, anyhow, bail};
27use serde::{Deserialize, Serialize};
28
29use crate::agent::{self, Invocation, SeatState};
30use crate::ask;
31use crate::config::AgentSpec;
32use crate::git;
33use crate::land;
34use crate::notices::{Link, Notice, Notices};
35use crate::proc::Quiet as _;
36use crate::run::{self, RunState, RunStatus};
37use crate::verdict;
38
39const DECISION_TIMEOUT: Duration = Duration::from_secs(600);
46
47pub fn should_release_bump(status: RunStatus) -> bool {
63 status == RunStatus::Merged
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "lowercase")]
69pub enum BumpLevel {
70 Major,
72 Minor,
74 Patch,
76}
77
78impl BumpLevel {
79 pub fn as_str(self) -> &'static str {
81 match self {
82 Self::Major => "major",
83 Self::Minor => "minor",
84 Self::Patch => "patch",
85 }
86 }
87
88 fn severity(self) -> u8 {
93 match self {
94 Self::Patch => 0,
95 Self::Minor => 1,
96 Self::Major => 2,
97 }
98 }
99}
100
101#[derive(Debug, Clone, Deserialize)]
108pub struct BumpDecision {
109 pub level: BumpLevel,
111 pub reason: String,
114}
115
116pub fn parse_decision(text: &str) -> Result<BumpDecision> {
120 let decision: BumpDecision = verdict::extract_json(text)?;
121 if decision.reason.trim().is_empty() {
122 bail!("the bump decision carried no reason");
123 }
124 Ok(decision)
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
130pub struct Version {
131 pub major: u64,
133 pub minor: u64,
135 pub patch: u64,
137}
138
139impl Version {
140 pub fn parse(s: &str) -> Result<Self> {
145 let s = s.trim();
146 let mut parts = s.splitn(3, '.');
147 let major = parts
148 .next()
149 .with_context(|| format!("`{s}` has no major component"))?;
150 let minor = parts
151 .next()
152 .with_context(|| format!("`{s}` has no minor component"))?;
153 let patch = parts
154 .next()
155 .with_context(|| format!("`{s}` has no patch component"))?;
156 let patch_digits: String = patch.chars().take_while(char::is_ascii_digit).collect();
157 Ok(Self {
158 major: major
159 .trim()
160 .parse()
161 .with_context(|| format!("`{major}` is not a number"))?,
162 minor: minor
163 .trim()
164 .parse()
165 .with_context(|| format!("`{minor}` is not a number"))?,
166 patch: patch_digits
167 .parse()
168 .with_context(|| format!("`{patch}` has no numeric patch component"))?,
169 })
170 }
171
172 #[must_use]
175 pub fn bump(self, level: BumpLevel) -> Self {
176 match level {
177 BumpLevel::Major => Self {
178 major: self.major + 1,
179 minor: 0,
180 patch: 0,
181 },
182 BumpLevel::Minor => Self {
183 major: self.major,
184 minor: self.minor + 1,
185 patch: 0,
186 },
187 BumpLevel::Patch => Self {
188 major: self.major,
189 minor: self.minor,
190 patch: self.patch + 1,
191 },
192 }
193 }
194}
195
196impl std::fmt::Display for Version {
197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
199 }
200}
201
202pub fn is_release_only(files: &[String]) -> bool {
211 !files.is_empty() && files.iter().all(|f| f == "Cargo.toml" || f == "Cargo.lock")
212}
213
214fn rewrite_table_version(toml: &str, table: &str, new_version: &str) -> Result<String> {
225 let mut out = String::with_capacity(toml.len() + 8);
226 let mut in_table = false;
227 let mut done = false;
228 for line in toml.split_inclusive('\n') {
229 let trimmed = line.trim();
230 if trimmed.starts_with('[') {
231 in_table = trimmed == table;
232 }
233 if !done && in_table && trimmed.split('=').next().map(str::trim) == Some("version") {
234 let newline = if line.ends_with("\r\n") { "\r\n" } else { "\n" };
235 let _ = write!(out, "version = \"{new_version}\"{newline}");
236 done = true;
237 continue;
238 }
239 out.push_str(line);
240 }
241 if !done {
242 bail!("no `version` field found under `{table}`");
243 }
244 Ok(out)
245}
246
247fn strip_trailing_comment(s: &str) -> &str {
253 let mut in_string = false;
254 let mut quote = '"';
255 for (i, c) in s.char_indices() {
256 if in_string {
257 if c == quote {
258 in_string = false;
259 }
260 } else if c == '"' || c == '\'' {
261 in_string = true;
262 quote = c;
263 } else if c == '#' {
264 return s[..i].trim_end();
265 }
266 }
267 s
268}
269
270fn unquote_key(key: &str) -> &str {
276 for quote in ['"', '\''] {
277 if let Some(inner) = key.strip_prefix(quote).and_then(|k| k.strip_suffix(quote)) {
278 return inner;
279 }
280 }
281 key
282}
283
284fn extract_workspace_dependencies_fragment(toml: &str) -> String {
296 let mut fragment = String::new();
297 let mut capturing = false;
298 for line in toml.split_inclusive('\n') {
299 let header = strip_trailing_comment(line.trim());
300 if header.starts_with('[') {
301 if header == "[workspace.dependencies]" {
302 capturing = true;
303 fragment.push_str("[dependencies]\n");
304 } else if let Some(name) = header
305 .strip_prefix("[workspace.dependencies.")
306 .and_then(|rest| rest.strip_suffix(']'))
307 {
308 capturing = true;
309 let _ = writeln!(fragment, "[dependencies.{name}]");
310 } else {
311 capturing = false;
312 }
313 continue;
314 }
315 if capturing {
316 fragment.push_str(line);
317 }
318 }
319 fragment
320}
321
322fn internal_pin_names(toml: &str) -> Result<Vec<String>> {
340 let fragment = extract_workspace_dependencies_fragment(toml);
341 if fragment.trim().is_empty() {
342 return Ok(Vec::new());
343 }
344 let value: toml::Value =
345 toml::from_str(&fragment).context("failed to parse `[workspace.dependencies]` as TOML")?;
346 let mut names: Vec<String> = value
347 .get("dependencies")
348 .and_then(|d| d.as_table())
349 .into_iter()
350 .flatten()
351 .filter(|(_, dep)| {
352 dep.as_table()
353 .is_some_and(|t| t.contains_key("path") && t.contains_key("version"))
354 })
355 .map(|(name, _)| name.clone())
356 .collect();
357 names.sort();
358 Ok(names)
359}
360
361fn rewrite_quoted_field(line: &str, key: &str, new_value: &str) -> Option<String> {
371 let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
372 let mut search_from = 0;
373 while let Some(rel) = line[search_from..].find(key) {
374 let key_start = search_from + rel;
375 let before_ok = key_start == 0 || !is_ident(line[..key_start].chars().next_back().unwrap());
376 let eq_pos = key_start
377 + key.len()
378 + (line[key_start + key.len()..].len()
379 - line[key_start + key.len()..].trim_start().len());
380 if before_ok && line[eq_pos..].starts_with('=') {
381 let after_eq = &line[eq_pos + 1..];
382 let ws_len = after_eq.len() - after_eq.trim_start().len();
383 let quote_pos = eq_pos + 1 + ws_len;
384 if let Some(quote_char) = line[quote_pos..]
385 .chars()
386 .next()
387 .filter(|c| *c == '"' || *c == '\'')
388 {
389 let value_begin = quote_pos + quote_char.len_utf8();
390 if let Some(end_rel) = line[value_begin..].find(quote_char) {
391 let value_end = value_begin + end_rel;
392 let mut out = String::with_capacity(line.len());
393 out.push_str(&line[..value_begin]);
394 out.push_str(new_value);
395 out.push_str(&line[value_end..]);
396 return Some(out);
397 }
398 }
399 }
400 search_from = key_start + key.len();
401 }
402 None
403}
404
405fn rewrite_workspace_dependency_pins(
420 toml: &str,
421 names: &[String],
422 new_version: &str,
423) -> Result<String> {
424 if names.is_empty() {
425 return Ok(toml.to_owned());
426 }
427 let mut out = String::with_capacity(toml.len() + names.len() * 8);
428 let mut in_flat_table = false;
429 let mut in_named_table: Option<String> = None;
430 let mut rewritten: std::collections::HashSet<String> = std::collections::HashSet::new();
431
432 for line in toml.split_inclusive('\n') {
433 let trimmed = line.trim();
434 if trimmed.starts_with('[') {
435 let header = strip_trailing_comment(trimmed);
436 in_flat_table = header == "[workspace.dependencies]";
437 in_named_table = header
438 .strip_prefix("[workspace.dependencies.")
439 .and_then(|rest| rest.strip_suffix(']'))
440 .map(str::to_owned);
441 out.push_str(line);
442 continue;
443 }
444
445 let key = trimmed.split('=').next().map(str::trim).map(unquote_key);
446
447 if in_flat_table {
448 if let Some(name) = key.and_then(|k| names.iter().find(|n| n.as_str() == k)) {
450 if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
451 rewritten.insert(name.clone());
452 out.push_str(&rewritten_line);
453 continue;
454 }
455 } else if let Some(name) = key.and_then(|k| {
456 k.strip_suffix(".version")
457 .and_then(|prefix| names.iter().find(|n| n.as_str() == prefix))
458 }) {
459 if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
464 rewritten.insert(name.clone());
465 out.push_str(&rewritten_line);
466 continue;
467 }
468 }
469 } else if let Some(table_name) = &in_named_table {
470 if key == Some("version") && names.iter().any(|n| n == table_name) {
471 if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
472 rewritten.insert(table_name.clone());
473 out.push_str(&rewritten_line);
474 continue;
475 }
476 }
477 }
478
479 out.push_str(line);
480 }
481
482 for name in names {
483 if !rewritten.contains(name) {
484 bail!(
485 "could not rewrite the `[workspace.dependencies]` version pin \
486 for `{name}` - its `version` field was not found in a shape \
487 this rewrite understands"
488 );
489 }
490 }
491 Ok(out)
492}
493
494fn verify_pins_rewritten(toml: &str, names: &[String], new_version: &str) -> Result<()> {
502 let fragment = extract_workspace_dependencies_fragment(toml);
503 let value: toml::Value = toml::from_str(&fragment)
504 .context("rewritten `[workspace.dependencies]` failed to parse")?;
505 let deps = value.get("dependencies").and_then(|d| d.as_table());
506 for name in names {
507 let actual = deps
508 .and_then(|d| d.get(name))
509 .and_then(|dep| dep.as_table())
510 .and_then(|t| t.get("version"))
511 .and_then(|v| v.as_str());
512 if actual != Some(new_version) {
513 bail!(
514 "the `[workspace.dependencies]` version pin for `{name}` did \
515 not end up at `{new_version}` after the rewrite"
516 );
517 }
518 }
519 Ok(())
520}
521
522pub fn rewrite_cargo_version(toml: &str, new_version: &str) -> Result<String> {
544 let rewritten = rewrite_table_version(toml, "[package]", new_version)
545 .or_else(|_| rewrite_table_version(toml, "[workspace.package]", new_version))
546 .context("no `version` field found under `[package]` or `[workspace.package]`")?;
547
548 let pin_names = internal_pin_names(&rewritten)?;
549 if pin_names.is_empty() {
550 return Ok(rewritten);
551 }
552
553 let rewritten = rewrite_workspace_dependency_pins(&rewritten, &pin_names, new_version)?;
554 verify_pins_rewritten(&rewritten, &pin_names, new_version)?;
555 Ok(rewritten)
556}
557
558fn version_in_table(toml: &str, table: &str) -> Option<String> {
560 let mut in_table = false;
561 for line in toml.lines() {
562 let trimmed = line.trim();
563 if trimmed.starts_with('[') {
564 in_table = trimmed == table;
565 continue;
566 }
567 if !in_table {
568 continue;
569 }
570 let mut parts = trimmed.splitn(2, '=');
571 let key = parts.next().map(str::trim);
572 let Some(value) = parts.next() else {
573 continue;
574 };
575 if key == Some("version") {
576 return Some(value.trim().trim_matches('"').to_owned());
577 }
578 }
579 None
580}
581
582fn current_version(toml: &str) -> Result<String> {
587 version_in_table(toml, "[package]")
588 .or_else(|| version_in_table(toml, "[workspace.package]"))
589 .context("no `version` field found under `[package]` or `[workspace.package]`")
590}
591
592pub fn decision_prompt(
602 subject: &str,
603 instruction: &str,
604 diffstat: &str,
605 files: &[String],
606 current_version: &str,
607) -> String {
608 let mut s = format!(
609 "A pull request just merged into the base branch. Decide which digit \
610 of this project's `major.minor.patch` version this change earns, so \
611 a release bump can be opened for exactly it.\n\n\
612 Current version: {current_version}\n\n\
613 # Merge subject\n\n{subject}\n\n\
614 # The task that produced it\n\n{instruction}\n\n\
615 # Files changed ({} total)\n\n",
616 files.len()
617 );
618 const MAX_FILES: usize = 50;
619 for f in files.iter().take(MAX_FILES) {
620 let _ = writeln!(s, "- {f}");
621 }
622 if files.len() > MAX_FILES {
623 let _ = writeln!(s, "- ... and {} more", files.len() - MAX_FILES);
624 }
625 let _ = write!(s, "\n# Diffstat\n\n```\n{}\n```\n", diffstat.trim());
626
627 s.push_str(
628 "\n# How to decide\n\n\
629 This project is below version `1.0.0`. At that stage **`minor` is \
630 the digit that carries a breaking change** - do not spend `major` \
631 below `1.0.0`.\n\n\
632 A change is breaking, and earns `minor`, when it changes any of: \
633 the public API reachable from `src/lib.rs`, a CLI subcommand or \
634 flag, an HTTP API route or response shape, a configuration key, or \
635 the on-disk shape of persisted state.\n\n\
636 A user-visible new capability that breaks none of the above also \
637 earns `minor`.\n\n\
638 A fix, an internal refactor, or a dependency update earns `patch`.\n\n\
639 **When it is not obvious which digit applies, choose the larger \
640 one.** An oversized bump costs nothing; a breaking change shipped as \
641 `patch` breaks every downstream update that pins a range.\n\n\
642 # Output\n\n\
643 Reply with exactly one fenced JSON object and nothing that matters \
644 outside it:\n\n\
645 ```json\n\
646 {\"level\": \"major\" | \"minor\" | \"patch\", \"reason\": \"one line\"}\n\
647 ```\n",
648 );
649 let _ = write!(
651 s,
652 "\n{}\n\nThe `reason` goes into a GitHub pull request body, so write it \
653 in English.\n",
654 crate::prompt::GITHUB_ENGLISH_HEADING
655 );
656 s
657}
658
659#[derive(Debug, Clone, Serialize, Deserialize)]
675pub struct PendingBump {
676 pub target_version: String,
678 pub level: BumpLevel,
681 pub branch: String,
684 pub pr_url: String,
687}
688
689pub fn marker_path(home: &Path, repo: &Path) -> PathBuf {
693 let key = repo.to_string_lossy();
694 home.join("bump")
695 .join(format!("{:016x}.json", crate::rng::fnv1a(&key)))
696}
697
698pub fn read_marker(path: &Path) -> Option<PendingBump> {
702 let body = std::fs::read_to_string(path).ok()?;
703 serde_json::from_str(&body).ok()
704}
705
706pub fn write_marker(path: &Path, marker: &PendingBump) -> Result<()> {
710 if let Some(parent) = path.parent() {
711 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
712 }
713 let body = serde_json::to_string_pretty(marker).context("serialize pending bump")?;
714 let tmp = path.with_extension("json.tmp");
715 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
716 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
717 Ok(())
718}
719
720pub fn clear_marker(path: &Path) {
723 let _ = std::fs::remove_file(path);
724}
725
726#[derive(Debug, Clone, PartialEq, Eq)]
730pub enum Coalesce {
731 Proceed,
734 Skip {
736 target_version: String,
738 },
739}
740
741pub fn coalesce(pending: Option<&PendingBump>, current_version: &str) -> Result<Coalesce> {
743 let Some(pending) = pending else {
744 return Ok(Coalesce::Proceed);
745 };
746 let current = Version::parse(current_version)?;
747 let target = Version::parse(&pending.target_version)?;
748 if current >= target {
749 return Ok(Coalesce::Proceed);
750 }
751 Ok(Coalesce::Skip {
752 target_version: pending.target_version.clone(),
753 })
754}
755
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub enum PendingAction {
759 AlreadyCovered,
762 Escalate,
765}
766
767pub fn pending_action(pending_level: BumpLevel, decision_level: BumpLevel) -> PendingAction {
776 if decision_level.severity() > pending_level.severity() {
777 PendingAction::Escalate
778 } else {
779 PendingAction::AlreadyCovered
780 }
781}
782
783fn parse_pr_state(json: &str) -> Result<bool> {
785 #[derive(Deserialize)]
786 struct State {
787 state: String,
788 }
789 let parsed: State =
790 serde_json::from_str(json).context("parse `gh pr view --json state` output")?;
791 Ok(parsed.state.eq_ignore_ascii_case("OPEN"))
792}
793
794async fn pr_is_open(repo: &Path, pr_url: &str) -> Result<bool> {
807 let out = tokio::process::Command::new("gh")
808 .args(["pr", "view", pr_url, "--json", "state"])
809 .current_dir(repo)
810 .quiet()
811 .stdin(std::process::Stdio::null())
812 .output()
813 .await
814 .context("spawn gh pr view")?;
815 if !out.status.success() {
816 bail!(
817 "gh pr view {pr_url}: {}",
818 String::from_utf8_lossy(&out.stderr).trim()
819 );
820 }
821 parse_pr_state(&String::from_utf8_lossy(&out.stdout))
822}
823
824const LOCK_STALE_AFTER: Duration = Duration::from_secs(30 * 60);
832
833struct MarkerLock {
845 path: PathBuf,
846}
847
848impl MarkerLock {
849 fn acquire(marker: &Path) -> Result<Option<Self>> {
853 let path = marker.with_extension("lock");
854 if let Some(parent) = path.parent() {
855 std::fs::create_dir_all(parent)
856 .with_context(|| format!("create {}", parent.display()))?;
857 }
858 if Self::try_create(&path)? {
859 return Ok(Some(Self { path }));
860 }
861 if Self::is_stale(&path) {
862 let _ = std::fs::remove_file(&path);
863 if Self::try_create(&path)? {
864 return Ok(Some(Self { path }));
865 }
866 }
867 Ok(None)
868 }
869
870 fn try_create(path: &Path) -> Result<bool> {
871 match std::fs::OpenOptions::new()
872 .write(true)
873 .create_new(true)
874 .open(path)
875 {
876 Ok(_) => Ok(true),
877 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
878 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
879 }
880 }
881
882 fn is_stale(path: &Path) -> bool {
883 std::fs::metadata(path)
884 .and_then(|m| m.modified())
885 .ok()
886 .and_then(|m| m.elapsed().ok())
887 .is_some_and(|age| age >= LOCK_STALE_AFTER)
888 }
889}
890
891impl Drop for MarkerLock {
892 fn drop(&mut self) {
893 let _ = std::fs::remove_file(&self.path);
894 }
895}
896
897const LOCK_POLL: Duration = Duration::from_secs(5);
899
900const LOCK_WAIT_CEILING: Duration = Duration::from_secs(25 * 60);
913
914async fn wait_for_marker_lock(marker: &Path) -> Result<Option<MarkerLock>> {
917 wait_for_marker_lock_with(marker, LOCK_POLL, LOCK_WAIT_CEILING).await
918}
919
920async fn wait_for_marker_lock_with(
924 marker: &Path,
925 poll: Duration,
926 ceiling: Duration,
927) -> Result<Option<MarkerLock>> {
928 let mut waited = Duration::ZERO;
929 loop {
930 if let Some(lock) = MarkerLock::acquire(marker)? {
931 return Ok(Some(lock));
932 }
933 if waited >= ceiling {
934 return Ok(None);
935 }
936 tokio::time::sleep(poll).await;
937 waited += poll;
938 }
939}
940
941fn level_between(from: Version, to: Version) -> Option<BumpLevel> {
949 if to.major != from.major {
950 Some(BumpLevel::Major)
951 } else if to.minor != from.minor {
952 Some(BumpLevel::Minor)
953 } else if to.patch != from.patch {
954 Some(BumpLevel::Patch)
955 } else {
956 None
957 }
958}
959
960fn parse_open_release_pr(json: &str) -> Result<Option<(String, String)>> {
963 #[derive(Deserialize)]
964 struct Pr {
965 url: String,
966 #[serde(rename = "headRefName")]
967 head_ref_name: String,
968 }
969 let list: Vec<Pr> =
970 serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
971 Ok(list
972 .into_iter()
973 .find(|p| p.head_ref_name.starts_with("chore/release-v"))
974 .map(|p| (p.head_ref_name, p.url)))
975}
976
977async fn find_open_release_pr(repo: &Path) -> Result<Option<(String, String)>> {
992 let out = tokio::process::Command::new("gh")
993 .args(["pr", "list", "--state", "open", "--json", "url,headRefName"])
994 .current_dir(repo)
995 .quiet()
996 .stdin(std::process::Stdio::null())
997 .output()
998 .await
999 .context("spawn gh pr list")?;
1000 if !out.status.success() {
1001 bail!(
1002 "gh pr list: {}",
1003 String::from_utf8_lossy(&out.stderr).trim()
1004 );
1005 }
1006 parse_open_release_pr(&String::from_utf8_lossy(&out.stdout))
1007}
1008
1009pub async fn after_merge(state: &mut RunState, pr_url: &str) -> Result<()> {
1029 after_merge_at(state, pr_url, None, None).await
1030}
1031
1032#[derive(Debug, Default)]
1034struct Progress {
1035 version: Option<String>,
1037 pending_pr: Option<String>,
1039}
1040
1041fn notice_for_failure(progress: &Progress, err: &anyhow::Error) -> (Option<String>, String) {
1047 let chain = format!("{err:#}");
1048 let first = chain.lines().next().unwrap_or_default().trim();
1049 (progress.version.clone(), first.to_owned())
1050}
1051
1052async fn base_has_cargo_toml(repo: &Path, remote: &str, base: &str) -> Result<bool> {
1058 let out = git::git(
1059 repo,
1060 &[
1061 "ls-tree",
1062 "--name-only",
1063 &format!("{remote}/{base}"),
1064 "--",
1065 "Cargo.toml",
1066 ],
1067 )
1068 .await
1069 .context("look for Cargo.toml on the base branch")?;
1070 Ok(!out.trim().is_empty())
1071}
1072
1073async fn after_merge_at(
1077 state: &mut RunState,
1078 pr_url: &str,
1079 home: Option<&Path>,
1080 store: Option<&Notices>,
1081) -> Result<()> {
1082 let mut progress = Progress::default();
1083 let result = after_merge_inner(state, pr_url, home, &mut progress).await;
1084 if let Err(e) = &result {
1085 let (version, reason) = notice_for_failure(&progress, e);
1086 let pending = progress.pending_pr.as_deref();
1087 let store = store.cloned().unwrap_or_else(Notices::open);
1088 report_problem_in(
1089 state,
1090 &store,
1091 pending,
1092 version.as_deref(),
1093 &reason,
1094 pending.is_some(),
1095 )
1096 .await;
1097 }
1098 result
1099}
1100
1101async fn after_merge_inner(
1102 state: &mut RunState,
1103 pr_url: &str,
1104 home: Option<&Path>,
1105 progress: &mut Progress,
1106) -> Result<()> {
1107 if !state.config.merge.release_bump {
1108 return Ok(());
1109 }
1110 let Some(winner) = state.winner().cloned() else {
1111 return Ok(());
1112 };
1113 let repo = state.repo.clone();
1114 let base = state.base_branch.clone();
1115 let remote = state.config.merge.remote.clone();
1116
1117 let files = git::changed_files(&winner.worktree, &base, &winner.branch)
1118 .await
1119 .unwrap_or_default();
1120 if is_release_only(&files) {
1121 state.event(
1122 "bump",
1123 "the merged change touches only the release manifest; not treating it as a trigger",
1124 );
1125 return Ok(());
1126 }
1127
1128 git::fetch(&repo, &remote, &base).await.ok();
1131 if !base_has_cargo_toml(&repo, &remote, &base).await? {
1132 state.event(
1133 "bump",
1134 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping",
1135 );
1136 return Ok(());
1137 }
1138
1139 let marker = marker_path(&home.map_or_else(run::home, Path::to_path_buf), &repo);
1140 let Some(_lock) = wait_for_marker_lock(&marker).await? else {
1147 state.event(
1148 "bump",
1149 "another release bump decision held the lock past the wait ceiling; skipping this round",
1150 );
1151 return Ok(());
1152 };
1153
1154 git::fetch(&repo, &remote, &base).await.ok();
1155 let cargo_toml = git::git(&repo, &["show", &format!("{remote}/{base}:Cargo.toml")])
1156 .await
1157 .context("read Cargo.toml from the base branch")?;
1158 let base_version = current_version(&cargo_toml)?;
1159
1160 let mut pending = read_marker(&marker);
1161 if let Some(p) = &pending {
1162 match coalesce(Some(p), &base_version)? {
1163 Coalesce::Proceed => {
1164 clear_marker(&marker);
1167 pending = None;
1168 }
1169 Coalesce::Skip { target_version } => {
1170 if !pr_is_open(&repo, &p.pr_url).await.unwrap_or(true) {
1171 state.event(
1172 "bump",
1173 format!(
1174 "the pending release bump to v{target_version} ({}) is no longer \
1175 open; treating it as abandoned",
1176 p.pr_url
1177 ),
1178 );
1179 clear_marker(&marker);
1180 pending = None;
1181 }
1182 }
1187 }
1188 }
1189
1190 if pending.is_none() {
1191 if let Ok(Some((branch, url))) = find_open_release_pr(&repo).await
1196 && let Some(target) = branch
1197 .strip_prefix("chore/release-v")
1198 .and_then(|v| Version::parse(v).ok())
1199 {
1200 let base_parsed = Version::parse(&base_version)?;
1201 if target > base_parsed
1202 && let Some(level) = level_between(base_parsed, target)
1203 {
1204 let adopted = PendingBump {
1205 target_version: target.to_string(),
1206 level,
1207 branch,
1208 pr_url: url,
1209 };
1210 let _ = write_marker(&marker, &adopted);
1213 pending = Some(adopted);
1214 }
1215 }
1216 }
1217
1218 progress.pending_pr = pending.as_ref().map(|p| p.pr_url.clone());
1219 let title = pr_title(&repo, pr_url).await.unwrap_or_default();
1220 let subject = land::merge_subject(
1221 crate::graph::landing_title(state, &title),
1222 &crate::graph::landing_subject_source(state),
1223 );
1224 let stat = git::diff_stat(&winner.worktree, &base, &winner.branch)
1225 .await
1226 .unwrap_or_default();
1227 let prompt = decision_prompt(&subject, &state.instruction, &stat, &files, &base_version);
1228
1229 let spec: AgentSpec = agent::pick(
1235 &state.config.agents,
1236 crate::config::primary(state.config.roles.chatter.as_ref()),
1237 &agent::installed,
1238 )
1239 .context("choose an agent for the release-bump decision")?;
1240 let mut seat = SeatState::new("bump", &spec.id, state.seed);
1241 let artifacts = agent::artifacts_dir(&state.dir());
1242 let out = agent::invoke(
1243 &spec,
1244 &mut seat,
1245 &Invocation {
1246 cwd: &repo,
1247 prompt: &prompt,
1248 timeout: DECISION_TIMEOUT,
1249 allow_write: false,
1252 sessions: false,
1253 artifacts: &artifacts,
1254 stem: "bump-decision",
1255 run: &state.id,
1256 node: "bump",
1257 cache_dir: state.config.cache_dir().as_deref(),
1258 attachments: &[],
1259 writable: &[],
1260 },
1261 )
1262 .await
1263 .context("ask an agent how big the merged change was")?;
1264 if !out.usable() {
1265 bail!(
1266 "the release-bump decision produced nothing usable (exit {:?}, timed out: {})",
1267 out.exit_code,
1268 out.timed_out
1269 );
1270 }
1271 let decision = parse_decision(&out.text).context("parse the release-bump decision")?;
1272
1273 if let Some(p) = pending {
1274 return match pending_action(p.level, decision.level) {
1275 PendingAction::AlreadyCovered => {
1276 state.event(
1277 "bump",
1278 format!(
1279 "a release bump to v{} ({}) already covers at least a {} change; not \
1280 opening another",
1281 p.target_version,
1282 p.pr_url,
1283 decision.level.as_str()
1284 ),
1285 );
1286 Ok(())
1287 }
1288 PendingAction::Escalate => {
1289 progress.version = Some(
1290 Version::parse(&base_version)?
1291 .bump(decision.level)
1292 .to_string(),
1293 );
1294 escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
1295 }
1296 };
1297 }
1298
1299 let next = Version::parse(&base_version)?
1300 .bump(decision.level)
1301 .to_string();
1302 progress.version = Some(next.clone());
1303 let branch = format!("chore/release-v{next}");
1304 let worktree = state.dir().join("bump");
1305 let (shared, branch_ref, next_ref, decision_ref) = (&*state, &branch, &next, &decision);
1306 let (pr_url_opened, outcome) =
1307 release_attempt(
1308 &repo,
1309 &remote,
1310 &base,
1311 &worktree,
1312 &branch,
1313 |head| {
1314 let repo = repo.clone();
1315 async move { gh_open_pr_for_head(&repo, &head).await }
1316 },
1317 |wt| async move {
1318 open_bump_pr(shared, &wt, branch_ref, next_ref, decision_ref, pr_url).await
1319 },
1320 )
1321 .await?;
1322 let (automerge_warning, merged_detail) = match outcome {
1323 AutomergeOutcome::Enabled => (None, None),
1324 AutomergeOutcome::MergedDirectly { detail } => (None, Some(detail)),
1325 AutomergeOutcome::Failed { reason } => (Some(reason), None),
1326 };
1327
1328 let marker_write = write_marker(
1337 &marker,
1338 &PendingBump {
1339 target_version: next.clone(),
1340 level: decision.level,
1341 branch,
1342 pr_url: pr_url_opened.clone(),
1343 },
1344 );
1345 state.event(
1346 "bump",
1347 format!(
1348 "opened a {} release bump to v{next} ({}): {pr_url_opened}",
1349 decision.level.as_str(),
1350 decision.reason
1351 ),
1352 );
1353 if let Err(e) = marker_write {
1354 state.event(
1355 "bump",
1356 format!(
1357 "could not record the pending release bump marker for v{next}: {e:#}; a later \
1358 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
1359 the forge either"
1360 ),
1361 );
1362 }
1363 state.release_bump = Some(run::ReleaseBump {
1364 pr_url: Some(pr_url_opened.clone()),
1365 version: Some(next.clone()),
1366 automerge_enabled: automerge_warning.is_none() && merged_detail.is_none(),
1367 merged_directly: merged_detail.is_some(),
1368 ..run::ReleaseBump::default()
1369 });
1370 if let Some(detail) = merged_detail {
1371 clear_marker(&marker);
1374 state.event("bump", format!("merged v{next} directly: {detail}"));
1375 }
1376 if let Some(warning) = automerge_warning {
1377 state.event(
1378 "bump",
1379 format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
1380 );
1381 report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
1382 }
1383 Ok(())
1384}
1385
1386pub const NOTICE_NODE: &str = "release-bump";
1391
1392fn automerge_hint(reason: &str) -> &'static str {
1399 let r = reason.to_lowercase();
1400 if is_clean_status_refusal(reason) {
1401 "merge the release pull request by hand; CI is already green"
1402 } else if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
1403 "merge the release pull request by hand, and enable branch protection with required \
1404 status checks on the base branch so automerge can work next time"
1405 } else {
1406 "merge the release pull request by hand"
1407 }
1408}
1409
1410fn automerge_failure_comment(reason: &str) -> String {
1412 format!(
1413 "magi could not enable automerge on this pull request: {reason}\n\n\
1414 Action required: {}. Until then the release does not happen.",
1415 automerge_hint(reason)
1416 )
1417}
1418
1419#[cfg(test)]
1427fn surface_problem(
1428 state: &mut RunState,
1429 store: &Notices,
1430 pr_url: Option<&str>,
1431 version: Option<&str>,
1432 reason: &str,
1433) -> Result<(Notice, Option<String>)> {
1434 surface_problem_in(state, store, pr_url, version, reason, false)
1435}
1436
1437fn surface_problem_in(
1441 state: &mut RunState,
1442 store: &Notices,
1443 pr_url: Option<&str>,
1444 version: Option<&str>,
1445 reason: &str,
1446 pending: bool,
1447) -> Result<(Notice, Option<String>)> {
1448 let action = if let (true, Some(url)) = (pending, pr_url) {
1449 let ja = crate::lang::is_japanese(&state.config.graph.language);
1450 let first = reason.lines().next().filter(|l| !l.is_empty());
1451 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1452 if ja {
1453 let target = version.map(|v| format!(" v{v}")).unwrap_or_default();
1454 format!(
1455 "既存のリリース PR {url} を{target}へ更新できませんでした{cause}。PR を手で更新してください"
1456 )
1457 } else {
1458 let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1459 format!(
1460 "the pending release pull request {url} could not be updated{target}{cause}; update it by hand"
1461 )
1462 }
1463 } else if pr_url.is_some() {
1464 automerge_hint(reason).to_owned()
1465 } else {
1466 let ja = crate::lang::is_japanese(&state.config.graph.language);
1467 let first = reason.lines().next().filter(|l| !l.is_empty());
1468 if ja {
1469 let target = version.map(|v| format!(" (v{v})")).unwrap_or_default();
1470 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1471 format!(
1472 "リリースバンプ{target}は実行されませんでした{cause}。リリース PR を手で開いてください"
1473 )
1474 } else {
1475 let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1476 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1477 format!(
1478 "the release bump{target} did not run{cause}; open the release pull request by hand"
1479 )
1480 }
1481 };
1482 let record = state.release_bump.get_or_insert_with(Default::default);
1483 record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
1484 record.version = version.map(str::to_owned).or(record.version.take());
1485 record.automerge_enabled = false;
1486 record.problem = Some(reason.to_owned());
1487 record.action_required = Some(action.clone());
1488
1489 let mut notice = Notice::error(
1490 &format!("release-bump:{}", state.id),
1491 format!(
1492 "Run {} merged, but its release step failed: {action}.",
1493 state.id
1494 ),
1495 );
1496 notice = match pr_url {
1497 Some(url) => notice.link(Link::Url {
1498 url: url.to_owned(),
1499 }),
1500 None => notice.link(Link::Run {
1501 id: state.id.clone(),
1502 }),
1503 };
1504 let notice = store
1505 .raise(notice)
1506 .context("raise the release-bump notification")?;
1507 state.event("bump", format!("needs attention: {action}"));
1508 let comment = pr_url
1509 .filter(|_| !pending)
1510 .map(|_| automerge_failure_comment(reason));
1511 Ok((notice, comment))
1512}
1513
1514pub async fn report_problem(
1519 state: &mut RunState,
1520 pr_url: Option<&str>,
1521 version: Option<&str>,
1522 reason: &str,
1523) {
1524 report_problem_in(state, &Notices::open(), pr_url, version, reason, false).await;
1525}
1526
1527async fn report_problem_in(
1529 state: &mut RunState,
1530 store: &Notices,
1531 pr_url: Option<&str>,
1532 version: Option<&str>,
1533 reason: &str,
1534 pending: bool,
1535) {
1536 match surface_problem_in(state, store, pr_url, version, reason, pending) {
1537 Ok((notice, comment)) => {
1538 if let (Some(url), Some(body)) = (pr_url, comment)
1539 && let Err(e) = gh_pr_comment(
1540 &state.repo,
1541 url,
1542 &crate::scrub::scrub(&body, &crate::scrub::Identity::current()),
1543 )
1544 .await
1545 {
1546 state.event("bump", format!("could not comment on {url}: {e:#}"));
1547 }
1548 let summary = match pr_url {
1551 Some(url) if pending => format!("Release PR could not be updated: {url}"),
1552 Some(url) => format!("Release PR needs a human: {url}"),
1553 None if crate::lang::is_japanese(&state.config.graph.language) => {
1554 "リリースバンプが実行されませんでした".to_owned()
1555 }
1556 None => "Release bump did not run".to_owned(),
1557 };
1558 let q = ask::Question::new(
1559 state.id.clone(),
1560 NOTICE_NODE.to_owned(),
1561 "bump".to_owned(),
1562 summary,
1563 notice.message.clone(),
1564 Vec::new(),
1565 );
1566 if let Err(e) = ask::notify(&state.config.notify, &q).await {
1567 tracing::warn!(
1568 "could not notify about the release bump of {}: {e:#}",
1569 state.id
1570 );
1571 }
1572 }
1573 Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
1574 }
1575}
1576
1577pub(crate) async fn gh_pr_comment(cwd: &Path, pr_url: &str, body: &str) -> Result<()> {
1578 let out = tokio::process::Command::new("gh")
1579 .args(["pr", "comment", pr_url, "--body", body])
1580 .current_dir(cwd)
1581 .quiet()
1582 .stdin(std::process::Stdio::null())
1583 .output()
1584 .await
1585 .context("spawn gh pr comment")?;
1586 if out.status.success() {
1587 Ok(())
1588 } else {
1589 bail!(
1590 "gh pr comment: {}",
1591 String::from_utf8_lossy(&out.stderr).trim()
1592 )
1593 }
1594}
1595
1596async fn escalate_pending(
1605 state: &mut RunState,
1606 repo: &Path,
1607 remote: &str,
1608 pending: &PendingBump,
1609 decision: &BumpDecision,
1610 base_version: &str,
1611 marker: &Path,
1612) -> Result<()> {
1613 let next = Version::parse(base_version)?
1614 .bump(decision.level)
1615 .to_string();
1616 let worktree = state.dir().join("bump");
1617 git::worktree_remove(repo, &worktree).await.ok();
1618 let checked_out = git::git_raw(
1619 repo,
1620 &[
1621 "worktree",
1622 "add",
1623 "--force",
1624 &worktree.to_string_lossy(),
1625 &pending.branch,
1626 ],
1627 )
1628 .await?;
1629 if !checked_out.ok() {
1630 bail!(
1631 "checking out the pending release branch {} failed: {}",
1632 pending.branch,
1633 checked_out.stderr
1634 );
1635 }
1636
1637 let pushed: Result<()> = async {
1642 let cargo_toml_path = worktree.join("Cargo.toml");
1643 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1644 .await
1645 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1646 let rewritten = rewrite_cargo_version(&toml, &next)?;
1647 tokio::fs::write(&cargo_toml_path, rewritten)
1648 .await
1649 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1650 sync_lockfile(&worktree, state.config.cache_dir().as_deref()).await?;
1651 let committed = git::commit_all(
1652 &worktree,
1653 &format!(
1654 "chore: release v{next} (supersedes v{})",
1655 pending.target_version
1656 ),
1657 )
1658 .await
1659 .context("commit the escalated version bump")?;
1660 if !committed {
1661 bail!("escalating the version bump left nothing to commit");
1662 }
1663 let pushed = git::push(&worktree, remote, &pending.branch).await?;
1664 if !pushed.ok() {
1665 bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
1666 }
1667 Ok(())
1668 }
1669 .await;
1670 if let Err(e) = pushed {
1671 git::worktree_remove(repo, &worktree).await.ok();
1672 return Err(e);
1673 }
1674
1675 let title_warning = match gh_pr_edit_title(
1679 &worktree,
1680 &pending.pr_url,
1681 &crate::scrub::scrub(
1682 &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
1683 &crate::scrub::Identity::current(),
1684 ),
1685 )
1686 .await
1687 {
1688 Ok(()) => None,
1689 Err(e) => Some(e.to_string()),
1690 };
1691 git::worktree_remove(repo, &worktree).await.ok();
1692
1693 let marker_write = write_marker(
1694 marker,
1695 &PendingBump {
1696 target_version: next.clone(),
1697 level: decision.level,
1698 branch: pending.branch.clone(),
1699 pr_url: pending.pr_url.clone(),
1700 },
1701 );
1702 state.event(
1703 "bump",
1704 format!(
1705 "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
1706 pending.target_version,
1707 decision.level.as_str(),
1708 decision.reason,
1709 pending.pr_url
1710 ),
1711 );
1712 if let Err(e) = marker_write {
1713 state.event(
1714 "bump",
1715 format!(
1716 "could not update the pending release bump marker to v{next}: {e:#}; a later \
1717 merge may misjudge whether it is already covered"
1718 ),
1719 );
1720 }
1721 if let Some(warning) = title_warning {
1722 state.event(
1723 "bump",
1724 format!(
1725 "pushed v{next} to {} but could not update its title: {warning}; the squashed \
1726 subject may still read the superseded version",
1727 pending.pr_url
1728 ),
1729 );
1730 }
1731 Ok(())
1732}
1733
1734async fn gh_open_pr_for_head(repo: &Path, branch: &str) -> Result<bool> {
1737 let out = tokio::process::Command::new("gh")
1738 .args([
1739 "pr", "list", "--head", branch, "--state", "open", "--json", "url",
1740 ])
1741 .current_dir(repo)
1742 .quiet()
1743 .stdin(std::process::Stdio::null())
1744 .output()
1745 .await
1746 .context("spawn gh pr list")?;
1747 if !out.status.success() {
1748 bail!(
1749 "gh pr list --head {branch}: {}",
1750 String::from_utf8_lossy(&out.stderr).trim()
1751 );
1752 }
1753 let prs: Vec<serde_json::Value> = serde_json::from_slice(&out.stdout)
1754 .with_context(|| format!("parse the pull requests headed by {branch}"))?;
1755 Ok(!prs.is_empty())
1756}
1757
1758async fn release_attempt<T, F, Fut, P, PFut>(
1767 repo: &Path,
1768 remote: &str,
1769 base: &str,
1770 worktree: &Path,
1771 branch: &str,
1772 open_pr: P,
1773 fill: F,
1774) -> Result<T>
1775where
1776 F: FnOnce(PathBuf) -> Fut,
1777 Fut: std::future::Future<Output = Result<T>>,
1778 P: Fn(String) -> PFut,
1779 PFut: std::future::Future<Output = Result<bool>>,
1780{
1781 let start = format!("{remote}/{base}");
1782 git::worktree_remove(repo, worktree).await.ok();
1783 let mut retried = false;
1784 if git::branch_exists(repo, branch).await? {
1785 reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await?;
1786 retried = true;
1787 }
1788 loop {
1789 if let Err(e) = git::git(repo, &["branch", branch, &start]).await {
1794 let e = e.context("create the release branch");
1795 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1796 return Err(e);
1797 }
1798 if retried {
1800 return Err(anyhow!(
1801 "{e:#}; left {branch} in place: it is not one this attempt created"
1802 ));
1803 }
1804 retried = true;
1805 if let Err(r) = reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await {
1806 return Err(anyhow!("{r:#} (after: {e:#})"));
1807 }
1808 continue;
1809 }
1810 if let Some(parent) = worktree.parent() {
1811 tokio::fs::create_dir_all(parent).await.ok();
1812 }
1813 let path = worktree.to_string_lossy();
1814 if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
1815 let e = e.context("create the release-bump worktree");
1816 return Err(discard_attempt(repo, remote, worktree, branch, e).await);
1817 }
1818 break;
1819 }
1820 match fill(worktree.to_path_buf()).await {
1821 Ok(v) => {
1822 git::worktree_remove(repo, worktree).await.ok();
1825 Ok(v)
1826 }
1827 Err(e) => Err(discard_attempt(repo, remote, worktree, branch, e).await),
1828 }
1829}
1830
1831async fn discard_attempt(
1833 repo: &Path,
1834 remote: &str,
1835 worktree: &Path,
1836 branch: &str,
1837 cause: anyhow::Error,
1838) -> anyhow::Error {
1839 git::worktree_remove(repo, worktree).await.ok();
1840 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1841 return cause;
1842 }
1843 let note = match git::remote_has_branch(repo, remote, branch).await {
1846 Ok(false) => match git::branch_delete(repo, branch).await {
1847 Ok(true) => return cause,
1848 _ => format!("could not delete the local branch {branch}"),
1849 },
1850 Ok(true) => format!("left {branch} in place: it was pushed to {remote}"),
1851 Err(e) => format!(
1852 "left {branch} in place: could not tell whether it was pushed to {remote} ({e:#})"
1853 ),
1854 };
1855 anyhow!("{cause:#}; {note}")
1856}
1857
1858async fn reclaim_stale_branch<P, PFut>(
1863 repo: &Path,
1864 remote: &str,
1865 start: &str,
1866 branch: &str,
1867 open_pr: &P,
1868) -> Result<()>
1869where
1870 P: Fn(String) -> PFut,
1871 PFut: std::future::Future<Output = Result<bool>>,
1872{
1873 match git::remote_has_branch(repo, remote, branch).await {
1874 Ok(false) => {}
1875 Ok(true) => bail!("the branch {branch} already exists and is on {remote}; left alone"),
1876 Err(e) => bail!(
1877 "the branch {branch} already exists and could not check whether {remote} has it ({e:#}); left alone"
1878 ),
1879 }
1880 match open_pr(branch.to_string()).await {
1881 Ok(false) => {}
1882 Ok(true) => {
1883 bail!("the branch {branch} already exists and has an open pull request; left alone")
1884 }
1885 Err(e) => bail!(
1886 "the branch {branch} already exists and could not check for an open pull request \
1887 ({e:#}); left alone"
1888 ),
1889 }
1890 match git::commits_ahead(repo, start, branch).await {
1891 Ok(0) => {}
1892 Ok(n) => bail!(
1893 "the branch {branch} already exists with {n} commit(s) not in {start}; left alone"
1894 ),
1895 Err(e) => bail!(
1896 "the branch {branch} already exists and could not compare it with {start} ({e:#}); \
1897 left alone"
1898 ),
1899 }
1900 if let Some(held) = git::worktree_holding(repo, branch).await? {
1901 let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
1902 (Ok(a), Ok(b)) => a == b,
1903 _ => a == b,
1904 };
1905 if same(&held, repo) {
1906 bail!(
1907 "the branch {branch} already exists and is checked out in the main checkout; left alone"
1908 );
1909 }
1910 git::worktree_remove(repo, &held).await.ok();
1911 }
1912 if !git::branch_delete(repo, branch).await? {
1913 bail!("the branch {branch} already exists and could not be deleted; left alone");
1914 }
1915 Ok(())
1916}
1917
1918async fn open_bump_pr(
1924 state: &RunState,
1925 worktree: &Path,
1926 branch: &str,
1927 next_version: &str,
1928 decision: &BumpDecision,
1929 source_pr_url: &str,
1930) -> Result<(String, AutomergeOutcome)> {
1931 let cargo_toml_path = worktree.join("Cargo.toml");
1932 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1933 .await
1934 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1935 let rewritten = rewrite_cargo_version(&toml, next_version)?;
1936 tokio::fs::write(&cargo_toml_path, rewritten)
1937 .await
1938 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1939
1940 sync_lockfile(worktree, state.config.cache_dir().as_deref()).await?;
1941
1942 let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
1943 .await
1944 .context("commit the version bump")?;
1945 if !committed {
1946 bail!("the version bump left nothing to commit");
1947 }
1948
1949 let remote = state.config.merge.remote.clone();
1950 let pushed = git::push(worktree, &remote, branch).await?;
1951 if !pushed.ok() {
1952 bail!("pushing {branch} failed: {}", pushed.stderr);
1953 }
1954
1955 let (title, body) = release_pr(
1956 decision.level.as_str(),
1957 &decision.reason,
1958 next_version,
1959 &state.id,
1960 source_pr_url,
1961 );
1962 let who = crate::scrub::Identity::current();
1963 let (title, body) = (
1964 crate::scrub::scrub(&title, &who),
1965 crate::scrub::scrub(&body, &who),
1966 );
1967 let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
1968 let outcome = match gh_enable_automerge(worktree, &url).await {
1969 Ok(()) => AutomergeOutcome::Enabled,
1970 Err(e) => {
1971 let reason = e.to_string();
1972 if is_clean_status_refusal(&reason) {
1973 gh_merge_directly(worktree, &url, &title, reason).await
1974 } else {
1975 AutomergeOutcome::Failed { reason }
1976 }
1977 }
1978 };
1979 Ok((url, outcome))
1980}
1981
1982#[derive(Debug, Clone, PartialEq, Eq)]
1984enum AutomergeOutcome {
1985 Enabled,
1987 MergedDirectly { detail: String },
1989 Failed { reason: String },
1991}
1992
1993fn is_clean_status_refusal(reason: &str) -> bool {
1999 let r = reason.to_lowercase();
2000 r.contains("is in clean status") && r.contains("enablepullrequestautomerge")
2001}
2002
2003fn bump_merge_argv(pr_url: &str, subject: &str) -> Vec<String> {
2006 [
2007 "pr",
2008 "merge",
2009 pr_url,
2010 "--squash",
2011 "--delete-branch",
2012 "--subject",
2013 subject,
2014 ]
2015 .map(str::to_owned)
2016 .to_vec()
2017}
2018
2019fn resolve_direct_merge(
2023 refusal: &str,
2024 argv: &[String],
2025 merge_ok: bool,
2026 stderr: &str,
2027 after: Option<land::PrLifecycle>,
2028) -> AutomergeOutcome {
2029 if merge_ok {
2030 return AutomergeOutcome::MergedDirectly {
2031 detail: format!("automerge was refused ({refusal}); gh {}", argv.join(" ")),
2032 };
2033 }
2034 match land::merged_after_all(argv, stderr, after) {
2035 Some(m) => AutomergeOutcome::MergedDirectly { detail: m.detail },
2036 None => AutomergeOutcome::Failed {
2037 reason: format!("{refusal}; merging directly failed too: {}", stderr.trim()),
2038 },
2039 }
2040}
2041
2042async fn gh_merge_directly(
2046 cwd: &Path,
2047 pr_url: &str,
2048 subject: &str,
2049 refusal: String,
2050) -> AutomergeOutcome {
2051 let argv = bump_merge_argv(pr_url, subject);
2052 let out = match tokio::process::Command::new("gh")
2053 .args(&argv)
2054 .current_dir(cwd)
2055 .quiet()
2056 .stdin(std::process::Stdio::null())
2057 .output()
2058 .await
2059 {
2060 Ok(o) => o,
2061 Err(e) => {
2062 return AutomergeOutcome::Failed {
2063 reason: format!("{refusal}; could not spawn gh to merge directly: {e}"),
2064 };
2065 }
2066 };
2067 let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
2068 let after = if out.status.success() {
2071 None
2072 } else {
2073 land::lifecycle(cwd, pr_url).await.ok()
2074 };
2075 resolve_direct_merge(&refusal, &argv, out.status.success(), &stderr, after)
2076}
2077
2078async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
2086 let mut cmd = tokio::process::Command::new("cargo");
2087 cmd.arg("build").current_dir(worktree).quiet();
2088 if let Some(dir) = cache_dir {
2089 cmd.env("CARGO_TARGET_DIR", dir);
2090 }
2091 let out = cmd
2092 .stdin(std::process::Stdio::null())
2093 .output()
2094 .await
2095 .context("spawn cargo build")?;
2096 if !out.status.success() {
2097 bail!(
2098 "cargo build failed while syncing Cargo.lock: {}",
2099 String::from_utf8_lossy(&out.stderr).trim()
2100 );
2101 }
2102 Ok(())
2103}
2104
2105fn release_pr(
2110 level: &str,
2111 reason: &str,
2112 next_version: &str,
2113 run_id: &str,
2114 source_pr_url: &str,
2115) -> (String, String) {
2116 let title = format!("chore: release v{next_version} ({level} bump)");
2117 let body = format!(
2118 "## Background\n\n\
2119 A change that was just merged is a `{level}` change, so the crate needs a new \
2120 release: {reason}\n\n\
2121 Triggered by magi run `{run_id}`, which landed {source}.\n\n\
2122 ## Change\n\n\
2123 Raises the package version to `v{next_version}` in `Cargo.toml`, with \
2124 `Cargo.lock` following it. Nothing else changes.\n\n\
2125 ## Risk\n\n\
2126 Version-bump-only, so there is nothing here for a reviewer to find. Merging \
2127 it starts the release pipeline (auto-tag, then the release workflow).",
2128 source = source_pr_url,
2129 );
2130 (title, body)
2131}
2132
2133async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
2135 let out = tokio::process::Command::new("gh")
2136 .args(["pr", "view", pr_url, "--json", "title"])
2137 .current_dir(repo)
2138 .quiet()
2139 .stdin(std::process::Stdio::null())
2140 .output()
2141 .await
2142 .context("spawn gh pr view")?;
2143 if !out.status.success() {
2144 bail!(
2145 "gh pr view {pr_url}: {}",
2146 String::from_utf8_lossy(&out.stderr).trim()
2147 );
2148 }
2149 #[derive(Deserialize)]
2150 struct Title {
2151 title: String,
2152 }
2153 let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
2154 .context("parse `gh pr view --json title` output")?;
2155 Ok(parsed.title)
2156}
2157
2158async fn gh_pr_create(
2159 cwd: &Path,
2160 base: &str,
2161 head: &str,
2162 title: &str,
2163 body: &str,
2164) -> Result<String> {
2165 let out = tokio::process::Command::new("gh")
2166 .args([
2167 "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
2168 ])
2169 .current_dir(cwd)
2170 .quiet()
2171 .stdin(std::process::Stdio::null())
2172 .output()
2173 .await
2174 .context("spawn gh pr create")?;
2175 if out.status.success() {
2176 Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
2177 } else {
2178 bail!(
2179 "gh pr create: {}",
2180 String::from_utf8_lossy(&out.stderr).trim()
2181 )
2182 }
2183}
2184
2185async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
2189 let out = tokio::process::Command::new("gh")
2190 .args([
2191 "pr",
2192 "merge",
2193 pr_url,
2194 "--auto",
2195 "--squash",
2196 "--delete-branch",
2197 ])
2198 .current_dir(cwd)
2199 .quiet()
2200 .stdin(std::process::Stdio::null())
2201 .output()
2202 .await
2203 .context("spawn gh pr merge --auto")?;
2204 if out.status.success() {
2205 Ok(())
2206 } else {
2207 bail!(
2208 "gh pr merge --auto: {}",
2209 String::from_utf8_lossy(&out.stderr).trim()
2210 )
2211 }
2212}
2213
2214async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
2218 let out = tokio::process::Command::new("gh")
2219 .args(["pr", "edit", pr_url, "--title", title])
2220 .current_dir(cwd)
2221 .quiet()
2222 .stdin(std::process::Stdio::null())
2223 .output()
2224 .await
2225 .context("spawn gh pr edit")?;
2226 if out.status.success() {
2227 Ok(())
2228 } else {
2229 bail!(
2230 "gh pr edit --title: {}",
2231 String::from_utf8_lossy(&out.stderr).trim()
2232 )
2233 }
2234}
2235
2236#[cfg(test)]
2237mod tests {
2238 use super::*;
2239 use crate::notices::Severity;
2240
2241 #[test]
2242 fn github_facing_bump_text_is_english() {
2243 let (title, body) =
2244 release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
2245 assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
2246 assert_eq!(title, "chore: release v0.37.0 (minor bump)");
2247 assert!(
2248 body.contains("## Background") && body.contains("## Change"),
2249 "{body}"
2250 );
2251 let p = decision_prompt("s", "i", "d", &[], "0.36.5");
2252 assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
2253 }
2254 use crate::config::Config;
2255 use crate::land::PrLifecycle;
2256
2257 #[tokio::test]
2263 async fn a_disabled_config_does_nothing() {
2264 let config = Config {
2265 merge: crate::config::Merge {
2266 release_bump: false,
2267 ..crate::config::Merge::default()
2268 },
2269 ..Config::default()
2270 };
2271 let mut state = RunState::new(
2272 PathBuf::from("/no/such/repo"),
2273 "main".to_owned(),
2274 "0000000000000000000000000000000000000000".to_owned(),
2275 "irrelevant".to_owned(),
2276 config,
2277 );
2278 after_merge(&mut state, "https://example.invalid/pull/1")
2279 .await
2280 .expect("a disabled config must return Ok without touching anything");
2281 assert!(
2282 state.events.is_empty(),
2283 "nothing should happen at all, not even a logged event"
2284 );
2285 }
2286
2287 async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
2289 let dir = tempfile::tempdir().unwrap();
2290 let origin = dir.path().join("origin.git");
2291 let repo = dir.path().join("repo");
2292 let o = origin.to_string_lossy().into_owned();
2293 git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
2294 .await
2295 .unwrap();
2296 tokio::fs::create_dir_all(&repo).await.unwrap();
2297 git::git(&repo, &["init", "-b", "main"]).await.unwrap();
2298 git::git(&repo, &["config", "user.name", "test"])
2299 .await
2300 .unwrap();
2301 git::git(&repo, &["config", "user.email", "test@example.com"])
2302 .await
2303 .unwrap();
2304 for (name, body) in files {
2305 tokio::fs::write(repo.join(name), body).await.unwrap();
2306 }
2307 git::git(&repo, &["add", "-A"]).await.unwrap();
2308 git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
2309 git::git(&repo, &["remote", "add", "origin", &o])
2310 .await
2311 .unwrap();
2312 git::git(&repo, &["push", "origin", "main"]).await.unwrap();
2313 (dir, repo)
2314 }
2315
2316 async fn no_pr(_: String) -> Result<bool> {
2317 Ok(false)
2318 }
2319
2320 async fn with_branch(ahead: bool) -> (tempfile::TempDir, PathBuf) {
2323 let (d, repo) = origin_with(&[("f", "x\n")]).await;
2324 git::git(&repo, &["branch", "b"]).await.unwrap();
2325 if ahead {
2326 git::git(&repo, &["checkout", "-q", "b"]).await.unwrap();
2327 git::git(&repo, &["commit", "--allow-empty", "-m", "wip"])
2328 .await
2329 .unwrap();
2330 git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
2331 }
2332 (d, repo)
2333 }
2334
2335 async fn attempt(repo: &Path, open_pr: bool, fail_after_push: Option<bool>) -> Result<()> {
2336 let wt = repo.parent().unwrap().join("bump");
2337 release_attempt(
2338 repo,
2339 "origin",
2340 "main",
2341 &wt,
2342 "b",
2343 |_| async move { Ok(open_pr) },
2344 |w| async move {
2345 if fail_after_push == Some(true) {
2346 git::push(&w, "origin", "b").await?;
2347 }
2348 if fail_after_push.is_some() {
2349 bail!("cargo build failed");
2350 }
2351 Ok(())
2352 },
2353 )
2354 .await
2355 }
2356
2357 #[tokio::test]
2358 async fn a_stale_ancestor_branch_is_deleted_and_the_attempt_proceeds() {
2359 let (_d, repo) = with_branch(false).await;
2360 attempt(&repo, false, None).await.unwrap();
2361 assert!(git::branch_exists(&repo, "b").await.unwrap());
2363 }
2364
2365 #[tokio::test]
2366 async fn a_stale_branch_holding_a_leftover_worktree_is_reclaimed() {
2367 let (_d, repo) = with_branch(false).await;
2368 let old = repo.parent().unwrap().join("old");
2369 git::git(&repo, &["worktree", "add", &old.to_string_lossy(), "b"])
2370 .await
2371 .unwrap();
2372 attempt(&repo, false, None).await.unwrap();
2373 assert!(!old.exists());
2374 }
2375
2376 #[tokio::test]
2377 async fn a_stale_branch_with_an_unmerged_commit_is_kept_with_a_reason() {
2378 let (_d, repo) = with_branch(true).await;
2379 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2380 assert!(e.contains("`b`") || e.contains("branch b"), "{e}");
2381 assert!(e.contains("1 commit(s) not in origin/main"), "{e}");
2382 assert!(git::branch_exists(&repo, "b").await.unwrap());
2383 }
2384
2385 #[tokio::test]
2386 async fn a_stale_branch_on_the_remote_is_kept() {
2387 let (_d, repo) = with_branch(false).await;
2388 git::git(&repo, &["push", "origin", "b"]).await.unwrap();
2389 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2390 assert!(e.contains("branch b") && e.contains("is on origin"), "{e}");
2391 assert!(git::branch_exists(&repo, "b").await.unwrap());
2392 }
2393
2394 #[tokio::test]
2395 async fn a_stale_branch_with_an_open_pull_request_is_kept() {
2396 let (_d, repo) = with_branch(false).await;
2397 let e = attempt(&repo, true, None).await.unwrap_err().to_string();
2398 assert!(e.contains("open pull request"), "{e}");
2399 assert!(git::branch_exists(&repo, "b").await.unwrap());
2400 }
2401
2402 #[tokio::test]
2403 async fn an_unanswerable_pull_request_check_keeps_the_branch() {
2404 let (_d, repo) = with_branch(false).await;
2405 let wt = repo.parent().unwrap().join("bump");
2406 let e = release_attempt(
2407 &repo,
2408 "origin",
2409 "main",
2410 &wt,
2411 "b",
2412 |_| async { bail!("offline") },
2413 |_| async { Ok(()) },
2414 )
2415 .await
2416 .unwrap_err()
2417 .to_string();
2418 assert!(
2419 e.contains("could not check for an open pull request"),
2420 "{e}"
2421 );
2422 assert!(git::branch_exists(&repo, "b").await.unwrap());
2423 }
2424
2425 #[tokio::test]
2426 async fn a_failed_attempt_removes_its_own_worktree_and_branch() {
2427 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2428 let wt = repo.parent().unwrap().join("bump");
2429 let e = attempt(&repo, false, Some(false)).await.unwrap_err();
2430 assert!(format!("{e:#}").contains("cargo build failed"));
2431 assert!(!wt.exists());
2432 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2433 }
2434
2435 #[tokio::test]
2436 async fn a_pushed_branch_survives_a_failed_attempt_and_the_reason_says_so() {
2437 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2438 let e = attempt(&repo, false, Some(true)).await.unwrap_err();
2439 let e = format!("{e:#}");
2440 assert!(
2441 e.contains("cargo build failed") && e.contains("pushed to origin"),
2442 "{e}"
2443 );
2444 assert!(git::branch_exists(&repo, "b").await.unwrap());
2445 }
2446
2447 #[tokio::test]
2448 async fn a_branch_left_by_a_half_done_worktree_add_is_removed() {
2449 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2452 let blocker = repo.parent().unwrap().join("blocker");
2453 tokio::fs::write(&blocker, "file").await.unwrap();
2454 let wt = blocker.join("bump");
2455 let r = release_attempt(
2456 &repo,
2457 "origin",
2458 "main",
2459 &wt,
2460 "b",
2461 |_| async { bail!("offline") },
2462 |_| async { Ok(()) },
2463 )
2464 .await;
2465 assert!(r.is_err());
2466 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2467 }
2468
2469 #[tokio::test]
2470 async fn the_retry_is_taken_at_most_once() {
2471 let (_d, repo) = with_branch(false).await;
2474 let blocker = repo.parent().unwrap().join("blocker");
2475 tokio::fs::write(&blocker, "file").await.unwrap();
2476 let wt = blocker.join("bump");
2477 let r = release_attempt(&repo, "origin", "main", &wt, "b", no_pr, |_| async {
2478 Ok(())
2479 })
2480 .await;
2481 assert!(r.is_err());
2482 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2483 }
2484
2485 #[tokio::test]
2486 async fn base_has_cargo_toml_tells_rust_from_non_rust() {
2487 let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
2488 assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
2489 let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
2490 assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
2491 assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
2493 }
2494
2495 #[tokio::test]
2496 async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
2497 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2498 let home = tempfile::tempdir().unwrap();
2499 let mut state = RunState::new(
2500 repo.clone(),
2501 "main".to_owned(),
2502 "0000000000000000000000000000000000000000".to_owned(),
2503 "task".to_owned(),
2504 Config::default(),
2505 );
2506 state.candidates.push(crate::run::Candidate {
2507 index: 0,
2508 label: 'A',
2509 agent: "x".to_owned(),
2510 branch: "main".to_owned(),
2511 worktree: repo.clone(),
2512 summary: String::new(),
2513 stat: String::new(),
2514 files: 1,
2515 commits: 1,
2516 empty: false,
2517 failed: None,
2518 verified_noop: None,
2519 duration_ms: 0,
2520 folded: false,
2521 });
2522 state.tally = Some(
2523 serde_json::from_value(serde_json::json!({
2524 "first_choice": {}, "borda": {}, "winner": "A",
2525 "unanimous_initial": true, "deliberated": false,
2526 "changed_votes": 0, "unanimous_final": true,
2527 }))
2528 .unwrap(),
2529 );
2530 after_merge_at(
2531 &mut state,
2532 "https://example.invalid/pull/1",
2533 Some(home.path()),
2534 None,
2535 )
2536 .await
2537 .expect("a non-Rust repository is not an error");
2538 let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
2539 assert_eq!(bumps.len(), 1, "{:?}", state.events);
2540 assert_eq!(
2541 bumps[0].message,
2542 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
2543 );
2544 assert!(
2545 std::fs::read_dir(home.path()).unwrap().next().is_none(),
2546 "no marker and no lock may be created"
2547 );
2548 }
2549
2550 fn winner_state(repo: &Path, base: &str) -> RunState {
2551 let mut state = RunState::new(
2552 repo.to_path_buf(),
2553 base.to_owned(),
2554 "0000000000000000000000000000000000000000".to_owned(),
2555 "task".to_owned(),
2556 Config::default(),
2557 );
2558 state.candidates.push(crate::run::Candidate {
2559 index: 0,
2560 label: 'A',
2561 agent: "x".to_owned(),
2562 branch: "main".to_owned(),
2563 worktree: repo.to_path_buf(),
2564 summary: String::new(),
2565 stat: String::new(),
2566 files: 1,
2567 commits: 1,
2568 empty: false,
2569 failed: None,
2570 verified_noop: None,
2571 duration_ms: 0,
2572 folded: false,
2573 });
2574 state.tally = Some(
2575 serde_json::from_value(serde_json::json!({
2576 "first_choice": {}, "borda": {}, "winner": "A",
2577 "unanimous_initial": true, "deliberated": false,
2578 "changed_votes": 0, "unanimous_final": true,
2579 }))
2580 .unwrap(),
2581 );
2582 state
2583 }
2584
2585 #[tokio::test]
2586 async fn a_real_failure_without_a_pr_raises_one_notice_and_a_retry_folds_into_it() {
2587 let (_d, repo) =
2588 origin_with(&[("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n")]).await;
2589 let home = tempfile::tempdir().unwrap();
2590 let store = Notices::at(home.path().join("notifications"));
2591 let mut state = winner_state(&repo, "nope");
2593 let url = "https://example.invalid/pull/1";
2594 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2595 .await
2596 .expect_err("an unresolvable base is a failure");
2597 let listed = store.list();
2598 assert_eq!(listed.len(), 1, "{listed:?}");
2599 assert!(
2600 listed[0].message.contains("did not run"),
2601 "{}",
2602 listed[0].message
2603 );
2604 assert!(
2605 listed[0].message.contains("Cargo.toml"),
2606 "{}",
2607 listed[0].message
2608 );
2609 assert!(state.events.iter().any(|e| e.node == "bump"));
2610 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2611 .await
2612 .expect_err("still failing");
2613 let listed = store.list();
2614 assert_eq!(listed.len(), 1, "{listed:?}");
2615 assert_eq!(listed[0].count, 2);
2616 }
2617
2618 #[tokio::test]
2619 async fn not_eligible_cases_raise_no_notice() {
2620 let home = tempfile::tempdir().unwrap();
2621 let store = Notices::at(home.path().join("notifications"));
2622 let url = "https://example.invalid/pull/1";
2623 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2625 let mut state = winner_state(&repo, "main");
2626 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2627 .await
2628 .unwrap();
2629 let mut state = winner_state(&repo, "nope");
2631 state.config.merge.release_bump = false;
2632 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2633 .await
2634 .unwrap();
2635 let mut state = winner_state(&repo, "nope");
2637 state.tally = None;
2638 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2639 .await
2640 .unwrap();
2641 assert!(store.list().is_empty(), "{:?}", store.list());
2642 }
2643
2644 #[test]
2645 fn the_no_pr_notice_follows_the_configured_language() {
2646 let dir = tempfile::tempdir().unwrap();
2647 let store = Notices::at(dir.path().join("notifications"));
2648 let mut state = merged_state();
2649 state.config.graph.language = "ja".to_owned();
2650 let (n, _) = surface_problem(&mut state, &store, None, Some("0.2.0"), "boom").unwrap();
2651 assert!(n.message.contains("実行されませんでした"), "{}", n.message);
2652 assert!(n.message.contains("boom") && n.message.contains("v0.2.0"));
2653 }
2654
2655 #[test]
2656 fn a_failed_escalation_points_at_the_pending_pr_without_commenting() {
2657 let dir = tempfile::tempdir().unwrap();
2658 let store = Notices::at(dir.path().join("notifications"));
2659 let mut state = merged_state();
2660 let url = "https://example.invalid/pull/9";
2661 let (n, comment) = surface_problem_in(
2662 &mut state,
2663 &store,
2664 Some(url),
2665 Some("0.3.0"),
2666 "push failed",
2667 true,
2668 )
2669 .unwrap();
2670 assert!(comment.is_none());
2671 assert!(
2672 n.message.contains(url) && n.message.contains("v0.3.0"),
2673 "{}",
2674 n.message
2675 );
2676 assert!(!n.message.contains("open the release pull request by hand"));
2677 assert!(matches!(n.link, Some(Link::Url { .. })));
2678 }
2679
2680 #[test]
2681 fn a_failure_notice_names_the_pending_pr_and_the_first_line_of_the_cause() {
2682 let err = anyhow!("outer context").context("cargo build failed\nsecond line");
2683 let with_pr = Progress {
2684 version: Some("0.2.0".into()),
2685 pending_pr: Some("https://example.invalid/pull/9".into()),
2686 };
2687 let (v, reason) = notice_for_failure(&with_pr, &err);
2688 assert_eq!(v.as_deref(), Some("0.2.0"));
2689 assert_eq!(reason, "cargo build failed");
2690 let (v, reason) = notice_for_failure(&Progress::default(), &err);
2691 assert_eq!(v, None);
2692 assert_eq!(reason, "cargo build failed");
2693 }
2694
2695 const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
2696 required protected branch rules (enablePullRequestAutoMerge)";
2697
2698 fn merged_state() -> RunState {
2699 run::set_home(std::env::temp_dir().join("magi-report-test-home"));
2702 let mut s = RunState::new(
2703 PathBuf::from("/no/such/repo"),
2704 "main".to_owned(),
2705 "0000000000000000000000000000000000000000".to_owned(),
2706 "task".to_owned(),
2707 Config::default(),
2708 );
2709 s.status = RunStatus::Merged;
2710 s
2711 }
2712
2713 #[test]
2714 fn the_known_automerge_refusal_names_branch_protection() {
2715 assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
2716 let other = automerge_hint("gh: network unreachable");
2717 assert!(!other.contains("branch protection"), "{other}");
2718 let body = automerge_failure_comment(NO_RULES);
2719 assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
2720 assert!(body.contains("Action required"), "{body}");
2721 }
2722
2723 const CLEAN: &str = "gh pr merge --auto: GraphQL: Pull request Pull request is in clean \
2724 status (enablePullRequestAutoMerge)";
2725
2726 #[test]
2727 fn clean_status_refusal_is_matched_narrowly() {
2728 assert!(is_clean_status_refusal(CLEAN));
2729 assert!(!is_clean_status_refusal(NO_RULES));
2730 assert!(!is_clean_status_refusal("gh: network unreachable"));
2731 assert!(!is_clean_status_refusal("Pull request is in clean status"));
2732 assert!(automerge_hint(CLEAN).contains("already green"));
2733 }
2734
2735 #[test]
2736 fn the_direct_merge_argv_matches_the_land_flags() {
2737 let a = bump_merge_argv("https://github.com/o/r/pull/9", "chore: release v1.0.0");
2738 let l = land::merge_argv(9, "chore: release v1.0.0");
2739 assert_eq!(a[..2], l[..2]);
2740 assert_eq!(a[3..], l[3..]);
2741 assert_eq!(a[2], "https://github.com/o/r/pull/9");
2742 }
2743
2744 #[test]
2745 fn a_direct_merge_is_judged_by_the_forge_not_the_exit_code() {
2746 let argv = bump_merge_argv("u", "t");
2747 let merged = |o: &AutomergeOutcome| matches!(o, AutomergeOutcome::MergedDirectly { .. });
2748 assert!(merged(&resolve_direct_merge(CLEAN, &argv, true, "", None)));
2749 let detached = "not on any branch";
2750 assert!(merged(&resolve_direct_merge(
2751 CLEAN,
2752 &argv,
2753 false,
2754 detached,
2755 Some(PrLifecycle::Merged)
2756 )));
2757 for after in [Some(PrLifecycle::Open), None] {
2758 let o = resolve_direct_merge(CLEAN, &argv, false, "boom", after);
2759 match o {
2760 AutomergeOutcome::Failed { reason } => {
2761 assert!(
2762 reason.contains("clean status") && reason.contains("boom"),
2763 "{reason}"
2764 )
2765 }
2766 other => panic!("expected Failed, got {other:?}"),
2767 }
2768 }
2769 }
2770
2771 #[test]
2772 fn a_directly_merged_bump_is_not_reported_as_pending_or_failed() {
2773 let mut state = merged_state();
2774 state.release_bump = Some(run::ReleaseBump {
2775 pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2776 version: Some("1.0.0".to_owned()),
2777 merged_directly: true,
2778 ..run::ReleaseBump::default()
2779 });
2780 assert!(!state.needs_attention());
2781 let text = crate::report::run(&state);
2782 assert!(text.contains("merged directly"), "{text}");
2783 assert!(!text.contains("FAILED"), "{text}");
2784 }
2785
2786 #[test]
2787 fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
2788 let dir = tempfile::tempdir().unwrap();
2789 let store = Notices::at(dir.path().join("notifications"));
2790 let questions = ask::Questions::at(dir.path().join("questions"));
2791 let mut state = merged_state();
2792 let url = "https://github.com/o/r/pull/35";
2793
2794 let (n, comment) =
2795 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2796
2797 let comment = comment.expect("a PR was opened, so it gets a comment");
2799 assert!(comment.contains("branch protection"), "{comment}");
2800
2801 assert_eq!(state.status, RunStatus::Merged);
2803 assert!(state.needs_attention());
2804 let text = crate::report::run(&state);
2805 assert!(text.contains("release bump"), "{text}");
2806 assert!(text.contains("FAILED"), "{text}");
2807 assert!(text.contains(url), "{text}");
2808 assert!(text.contains("action required"), "{text}");
2809 assert!(crate::report::line(&state).contains("release needs a human"));
2810
2811 assert_eq!(n.severity, Severity::Error);
2813 assert_eq!(
2814 n.link,
2815 Some(Link::Url {
2816 url: url.to_owned()
2817 })
2818 );
2819 assert_eq!(store.list().len(), 1);
2820 assert!(questions.open_for(&state.id).is_empty());
2821
2822 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2824 let listed = store.list();
2825 assert_eq!(listed.len(), 1);
2826 assert_eq!(listed[0].count, 2);
2827 }
2828
2829 #[test]
2830 fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
2831 let dir = tempfile::tempdir().unwrap();
2832 let store = Notices::at(dir.path().join("notifications"));
2833 let mut state = merged_state();
2834 let (n, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
2835 assert!(comment.is_none());
2836 assert!(matches!(n.link, Some(Link::Run { .. })));
2837 assert!(state.needs_attention());
2838 }
2839
2840 #[test]
2841 fn version_parses_and_bumps_each_digit() {
2842 let v = Version::parse("0.4.0").unwrap();
2843 assert_eq!(
2844 v,
2845 Version {
2846 major: 0,
2847 minor: 4,
2848 patch: 0
2849 }
2850 );
2851
2852 assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
2853 assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
2854 assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
2855 }
2856
2857 #[test]
2858 fn version_tolerates_a_prerelease_suffix_on_patch() {
2859 let v = Version::parse("1.2.3-rc1").unwrap();
2860 assert_eq!(
2861 v,
2862 Version {
2863 major: 1,
2864 minor: 2,
2865 patch: 3
2866 }
2867 );
2868 }
2869
2870 #[test]
2871 fn version_rejects_garbage() {
2872 assert!(Version::parse("not-a-version").is_err());
2873 assert!(Version::parse("1.2").is_err());
2874 }
2875
2876 #[test]
2877 fn decision_parses_each_level() {
2878 for (json, level) in [
2879 (
2880 r#"{"level":"major","reason":"drops a config key"}"#,
2881 BumpLevel::Major,
2882 ),
2883 (
2884 r#"{"level":"minor","reason":"adds a new flag"}"#,
2885 BumpLevel::Minor,
2886 ),
2887 (
2888 r#"{"level":"patch","reason":"fixes a race"}"#,
2889 BumpLevel::Patch,
2890 ),
2891 ] {
2892 let decision = parse_decision(json).unwrap();
2893 assert_eq!(decision.level, level);
2894 assert!(!decision.reason.is_empty());
2895 }
2896 }
2897
2898 #[test]
2899 fn decision_wrapped_in_a_fence_and_prose_still_parses() {
2900 let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
2901 let decision = parse_decision(text).unwrap();
2902 assert_eq!(decision.level, BumpLevel::Minor);
2903 assert_eq!(decision.reason, "new HTTP route");
2904 }
2905
2906 #[test]
2907 fn a_broken_reply_is_an_error_not_a_default() {
2908 assert!(parse_decision("I decline to answer.").is_err());
2909 assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
2910 assert!(
2911 parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
2912 "an empty reason must not pass either"
2913 );
2914 assert!(
2915 parse_decision(r#"{"level":"patch"}"#).is_err(),
2916 "a reply with no reason at all must not pass"
2917 );
2918 }
2919
2920 #[test]
2921 fn prompt_states_the_zero_x_rule_and_the_tie_break() {
2922 let prompt = decision_prompt(
2923 "feat: add a phone endpoint",
2924 "add POST /api/widgets",
2925 "1 file changed, 10 insertions(+)",
2926 &["src/web.rs".to_owned()],
2927 "0.8.0",
2928 );
2929 assert!(prompt.contains("0.8.0"), "the current version is stated");
2930 assert!(
2931 prompt.contains("below `1.0.0`")
2932 && prompt.contains("`minor` is the digit that carries a breaking change"),
2933 "the 0.x rule must be explicit: {prompt}"
2934 );
2935 assert!(
2936 prompt.contains("choose the larger"),
2937 "the tie-break toward the bigger digit must be explicit: {prompt}"
2938 );
2939 }
2940
2941 #[test]
2942 fn release_only_diffs_are_recognised() {
2943 assert!(is_release_only(&["Cargo.toml".to_owned()]));
2944 assert!(is_release_only(&[
2945 "Cargo.toml".to_owned(),
2946 "Cargo.lock".to_owned()
2947 ]));
2948 assert!(!is_release_only(&[]));
2949 assert!(!is_release_only(&[
2950 "Cargo.toml".to_owned(),
2951 "src/main.rs".to_owned()
2952 ]));
2953 }
2954
2955 #[test]
2956 fn cargo_version_rewrite_touches_only_the_package_table() {
2957 let toml = "\
2958[package]\n\
2959# a comment mentioning version on purpose\n\
2960name = \"magi-cli\"\n\
2961version = \"0.8.0\"\n\
2962edition = \"2024\"\n\
2963\n\
2964[dependencies]\n\
2965foo = { version = \"1.2.3\" }\n";
2966 let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
2967 assert!(out.contains("version = \"0.9.0\""));
2968 assert!(
2969 out.contains("foo = { version = \"1.2.3\" }"),
2970 "a dependency's own version pin must survive: {out}"
2971 );
2972 assert!(
2973 out.contains("# a comment mentioning version on purpose"),
2974 "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
2975 );
2976 assert_eq!(
2977 out.lines().count(),
2978 toml.lines().count(),
2979 "the rewrite replaces one line, it does not add or remove any"
2980 );
2981 }
2982
2983 #[test]
2984 fn cargo_version_rewrite_fails_without_a_package_table() {
2985 let toml = "[dependencies]\nfoo = \"1\"\n";
2986 assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
2987 }
2988
2989 #[test]
2995 fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
2996 let toml = "\
2997[workspace]\n\
2998members = [\"crates/a\", \"crates/b\"]\n\
2999\n\
3000[workspace.package]\n\
3001version = \"0.45.18\"\n\
3002edition = \"2024\"\n\
3003\n\
3004[workspace.dependencies]\n\
3005foo = { version = \"1.2.3\" }\n";
3006 let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
3007 assert!(out.contains("version = \"0.45.19\""));
3008 assert!(
3009 out.contains("foo = { version = \"1.2.3\" }"),
3010 "a workspace dependency's own version pin must survive: {out}"
3011 );
3012 assert_eq!(
3013 out.lines().count(),
3014 toml.lines().count(),
3015 "the rewrite replaces one line, it does not add or remove any"
3016 );
3017 }
3018
3019 #[test]
3023 fn cargo_version_rewrite_bumps_an_internal_workspace_dependency_pin() {
3024 let toml = "\
3025[workspace]\n\
3026members = [\"crates/kanade-shared\"]\n\
3027\n\
3028[workspace.package]\n\
3029version = \"0.48.2\"\n\
3030\n\
3031[workspace.dependencies]\n\
3032kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n";
3033 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3034 assert!(out.contains("[workspace.package]\nversion = \"0.48.3\"\n"));
3035 assert!(
3036 out.contains(
3037 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3038 ),
3039 "the internal pin must move with the workspace version: {out}"
3040 );
3041 }
3042
3043 #[test]
3045 fn cargo_version_rewrite_bumps_an_internal_pin_with_version_before_path() {
3046 let toml = "\
3047[workspace.package]\n\
3048version = \"1.0.0\"\n\
3049\n\
3050[workspace.dependencies]\n\
3051inner = { version = \"1.0.0\", path = \"crates/inner\" }\n";
3052 let out = rewrite_cargo_version(toml, "1.0.1").unwrap();
3053 assert!(out.contains("inner = { version = \"1.0.1\", path = \"crates/inner\" }"));
3054 }
3055
3056 #[test]
3059 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_table_form() {
3060 let toml = "\
3061[workspace.package]\n\
3062version = \"2.3.0\"\n\
3063\n\
3064[workspace.dependencies.inner]\n\
3065path = \"crates/inner\"\n\
3066version = \"2.3.0\"\n";
3067 let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
3068 assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
3069 assert!(out.contains(
3070 "[workspace.dependencies.inner]\npath = \"crates/inner\"\nversion = \"2.4.0\"\n"
3071 ));
3072 }
3073
3074 #[test]
3079 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_key_form() {
3080 let toml = "\
3081[workspace.package]\n\
3082version = \"2.3.0\"\n\
3083\n\
3084[workspace.dependencies]\n\
3085inner.path = \"crates/inner\"\n\
3086inner.version = \"2.3.0\"\n";
3087 let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
3088 assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
3089 assert!(out.contains("inner.path = \"crates/inner\"\ninner.version = \"2.4.0\"\n"));
3090 }
3091
3092 #[test]
3095 fn cargo_version_rewrite_leaves_a_path_only_workspace_dependency_untouched() {
3096 let toml = "\
3097[workspace.package]\n\
3098version = \"0.1.0\"\n\
3099\n\
3100[workspace.dependencies]\n\
3101internal-only = { path = \"crates/internal-only\" }\n";
3102 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3103 assert!(out.contains("internal-only = { path = \"crates/internal-only\" }"));
3104 }
3105
3106 #[test]
3110 fn cargo_version_rewrite_leaves_an_external_dependency_untouched() {
3111 let toml = "\
3112[workspace.package]\n\
3113version = \"0.1.0\"\n\
3114\n\
3115[workspace.dependencies]\n\
3116serde = { version = \"1\", features = [\"derive\"] }\n\
3117inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3118 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3119 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3120 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3121 }
3122
3123 #[test]
3127 fn cargo_version_rewrite_without_workspace_dependencies_table_still_bumps_package() {
3128 let toml = "[workspace.package]\nversion = \"0.9.0\"\nedition = \"2024\"\n";
3129 let out = rewrite_cargo_version(toml, "0.10.0").unwrap();
3130 assert_eq!(
3131 out,
3132 "[workspace.package]\nversion = \"0.10.0\"\nedition = \"2024\"\n"
3133 );
3134 }
3135
3136 #[test]
3139 fn cargo_version_rewrite_handles_a_kanade_shaped_workspace_dependencies_table() {
3140 let toml = "\
3141[workspace.package]\n\
3142version = \"0.48.2\"\n\
3143\n\
3144[workspace.dependencies]\n\
3145anyhow = { version = \"1\" }\n\
3146serde = { version = \"1\", features = [\"derive\"] }\n\
3147kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n\
3148kanade-core = { path = \"crates/kanade-core\", version = \"0.48.2\" }\n\
3149kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }\n";
3150 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3151 assert!(out.contains("anyhow = { version = \"1\" }"));
3152 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3153 assert!(
3154 out.contains(
3155 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3156 )
3157 );
3158 assert!(
3159 out.contains("kanade-core = { path = \"crates/kanade-core\", version = \"0.48.3\" }")
3160 );
3161 assert!(out.contains("kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }"));
3162 }
3163
3164 #[test]
3168 fn cargo_version_rewrite_bails_on_an_unrepresentable_inline_table() {
3169 let toml = "\
3170[workspace.package]\n\
3171version = \"0.1.0\"\n\
3172\n\
3173[workspace.dependencies]\n\
3174inner = { path = \"crates/inner\",\n\
3175 version = \"0.1.0\" }\n";
3176 assert!(rewrite_cargo_version(toml, "0.2.0").is_err());
3177 }
3178
3179 #[test]
3182 fn cargo_version_rewrite_recognises_a_commented_workspace_dependencies_header() {
3183 let toml = "\
3184[workspace.package]\n\
3185version = \"0.1.0\"\n\
3186\n\
3187[workspace.dependencies] # internal pins\n\
3188inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3189 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3190 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3191 }
3192
3193 #[test]
3196 fn cargo_version_rewrite_bumps_a_quoted_dependency_key() {
3197 let toml = "\
3198[workspace.package]\n\
3199version = \"0.1.0\"\n\
3200\n\
3201[workspace.dependencies]\n\
3202\"inner\" = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3203 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3204 assert!(out.contains("\"inner\" = { path = \"crates/inner\", version = \"0.2.0\" }"));
3205 }
3206
3207 #[test]
3211 fn cargo_version_rewrite_bumps_a_literal_string_version_pin() {
3212 let toml = "\
3213[workspace.package]\n\
3214version = \"0.1.0\"\n\
3215\n\
3216[workspace.dependencies]\n\
3217inner = { path = 'crates/inner', version = '0.1.0' }\n";
3218 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3219 assert!(out.contains("inner = { path = 'crates/inner', version = '0.2.0' }"));
3220 }
3221
3222 #[test]
3228 fn cargo_version_rewrite_does_not_require_the_whole_file_to_parse() {
3229 let toml = "\
3230[workspace.package]\n\
3231version = \"0.1.0\"\n\
3232\n\
3233[workspace.dependencies]\n\
3234inner = { path = \"crates/inner\", version = \"0.1.0\" }\n\
3235\n\
3236[workspace.package]\n\
3237edition = \"2024\"\n";
3238 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3239 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3240 assert!(
3241 toml::from_str::<toml::Value>(toml).is_err(),
3242 "the fixture itself must be invalid as a whole file, or this test proves nothing"
3243 );
3244 }
3245
3246 #[test]
3247 fn current_version_prefers_the_package_table_when_both_exist() {
3248 let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
3249 assert_eq!(current_version(toml).unwrap(), "0.8.0");
3250 }
3251
3252 #[test]
3255 fn current_version_falls_back_to_workspace_package_without_a_package_table() {
3256 let toml = "\
3257[workspace]\n\
3258members = [\"crates/a\", \"crates/b\"]\n\
3259\n\
3260[workspace.package]\n\
3261version = \"0.45.18\"\n";
3262 assert_eq!(current_version(toml).unwrap(), "0.45.18");
3263 }
3264
3265 #[test]
3266 fn coalesce_proceeds_with_nothing_pending() {
3267 assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
3268 }
3269
3270 fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
3273 PendingBump {
3274 target_version: target_version.to_owned(),
3275 level,
3276 branch: format!("chore/release-v{target_version}"),
3277 pr_url: "https://example.invalid/pull/9".to_owned(),
3278 }
3279 }
3280
3281 #[test]
3282 fn coalesce_skips_while_the_pending_target_is_still_ahead() {
3283 let pending = test_pending("0.9.0", BumpLevel::Minor);
3284 assert_eq!(
3285 coalesce(Some(&pending), "0.8.0").unwrap(),
3286 Coalesce::Skip {
3287 target_version: "0.9.0".to_owned()
3288 }
3289 );
3290 }
3291
3292 #[test]
3293 fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
3294 let pending = test_pending("0.9.0", BumpLevel::Minor);
3295 assert_eq!(
3297 coalesce(Some(&pending), "0.9.0").unwrap(),
3298 Coalesce::Proceed
3299 );
3300 assert_eq!(
3302 coalesce(Some(&pending), "1.0.0").unwrap(),
3303 Coalesce::Proceed
3304 );
3305 }
3306
3307 #[test]
3308 fn pending_action_escalates_only_for_a_more_severe_decision() {
3309 assert_eq!(
3310 pending_action(BumpLevel::Patch, BumpLevel::Patch),
3311 PendingAction::AlreadyCovered
3312 );
3313 assert_eq!(
3314 pending_action(BumpLevel::Patch, BumpLevel::Minor),
3315 PendingAction::Escalate
3316 );
3317 assert_eq!(
3318 pending_action(BumpLevel::Patch, BumpLevel::Major),
3319 PendingAction::Escalate
3320 );
3321 assert_eq!(
3322 pending_action(BumpLevel::Minor, BumpLevel::Patch),
3323 PendingAction::AlreadyCovered
3324 );
3325 assert_eq!(
3326 pending_action(BumpLevel::Major, BumpLevel::Minor),
3327 PendingAction::AlreadyCovered
3328 );
3329 assert_eq!(
3330 pending_action(BumpLevel::Major, BumpLevel::Major),
3331 PendingAction::AlreadyCovered
3332 );
3333 }
3334
3335 #[test]
3336 fn pr_state_parsing_reads_open_and_not_open() {
3337 assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
3338 assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
3339 assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
3340 }
3341
3342 #[test]
3343 fn a_lock_is_exclusive_until_dropped() {
3344 let dir = tempfile::tempdir().unwrap();
3345 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3346 let first = MarkerLock::acquire(&marker)
3347 .unwrap()
3348 .expect("first attempt takes the lock");
3349 assert!(
3350 MarkerLock::acquire(&marker).unwrap().is_none(),
3351 "a second attempt must be refused while the first holds it"
3352 );
3353 drop(first);
3354 assert!(
3355 MarkerLock::acquire(&marker).unwrap().is_some(),
3356 "dropping the guard releases the lock for the next attempt"
3357 );
3358 }
3359
3360 #[test]
3361 fn a_stale_lock_is_reclaimed() {
3362 let dir = tempfile::tempdir().unwrap();
3363 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3364 let lock_path = marker.with_extension("lock");
3365 std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
3366 std::fs::write(&lock_path, b"").unwrap();
3367 let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
3368 std::fs::OpenOptions::new()
3369 .write(true)
3370 .open(&lock_path)
3371 .unwrap()
3372 .set_modified(old)
3373 .unwrap();
3374 assert!(
3375 MarkerLock::acquire(&marker).unwrap().is_some(),
3376 "a lock older than the stale window must be reclaimed rather than block forever"
3377 );
3378 }
3379
3380 #[tokio::test]
3381 async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
3382 let dir = tempfile::tempdir().unwrap();
3383 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3384 let held = MarkerLock::acquire(&marker)
3385 .unwrap()
3386 .expect("seed the contention");
3387 let releaser = tokio::spawn(async move {
3388 tokio::time::sleep(Duration::from_millis(20)).await;
3389 drop(held);
3390 });
3391 let waited =
3392 wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
3393 .await
3394 .unwrap();
3395 assert!(
3396 waited.is_some(),
3397 "a merge landing behind another's still-running decision must not be dropped - it \
3398 must wait for that decision to finish and then judge against what it left behind"
3399 );
3400 releaser.await.unwrap();
3401 }
3402
3403 #[tokio::test]
3404 async fn a_lock_held_past_the_ceiling_gives_up() {
3405 let dir = tempfile::tempdir().unwrap();
3406 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3407 let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
3408 let waited =
3409 wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
3410 .await
3411 .unwrap();
3412 assert!(
3413 waited.is_none(),
3414 "a lock genuinely held past the ceiling must eventually give up rather than wait \
3415 forever"
3416 );
3417 }
3418
3419 #[test]
3420 fn level_between_reads_off_the_differing_digit() {
3421 assert_eq!(
3422 level_between(
3423 Version::parse("0.8.0").unwrap(),
3424 Version::parse("1.0.0").unwrap()
3425 ),
3426 Some(BumpLevel::Major)
3427 );
3428 assert_eq!(
3429 level_between(
3430 Version::parse("0.8.0").unwrap(),
3431 Version::parse("0.9.0").unwrap()
3432 ),
3433 Some(BumpLevel::Minor)
3434 );
3435 assert_eq!(
3436 level_between(
3437 Version::parse("0.8.0").unwrap(),
3438 Version::parse("0.8.1").unwrap()
3439 ),
3440 Some(BumpLevel::Patch)
3441 );
3442 assert_eq!(
3443 level_between(
3444 Version::parse("0.8.0").unwrap(),
3445 Version::parse("0.8.0").unwrap()
3446 ),
3447 None
3448 );
3449 }
3450
3451 #[test]
3452 fn open_release_pr_is_found_among_unrelated_pull_requests() {
3453 let json = r#"[
3454 {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
3455 {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
3456 ]"#;
3457 let found = parse_open_release_pr(json).unwrap();
3458 assert_eq!(
3459 found,
3460 Some((
3461 "chore/release-v0.9.0".to_owned(),
3462 "https://example.invalid/pull/2".to_owned()
3463 ))
3464 );
3465 }
3466
3467 #[test]
3468 fn no_open_release_pr_reads_as_none_not_an_error() {
3469 let json =
3470 r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
3471 assert_eq!(parse_open_release_pr(json).unwrap(), None);
3472 assert_eq!(parse_open_release_pr("[]").unwrap(), None);
3473 }
3474
3475 #[test]
3476 fn marker_round_trips_through_disk() {
3477 let dir = tempfile::tempdir().unwrap();
3478 let path = marker_path(dir.path(), Path::new("/repos/magi"));
3479 assert!(read_marker(&path).is_none());
3480
3481 let marker = test_pending("0.9.0", BumpLevel::Patch);
3482 write_marker(&path, &marker).unwrap();
3483 let read_back = read_marker(&path).unwrap();
3484 assert_eq!(read_back.target_version, "0.9.0");
3485 assert_eq!(read_back.level, BumpLevel::Patch);
3486 assert_eq!(read_back.pr_url, marker.pr_url);
3487
3488 clear_marker(&path);
3489 assert!(read_marker(&path).is_none());
3490 }
3491
3492 #[test]
3493 fn different_repos_get_different_marker_files() {
3494 let dir = tempfile::tempdir().unwrap();
3495 let a = marker_path(dir.path(), Path::new("/repos/a"));
3496 let b = marker_path(dir.path(), Path::new("/repos/b"));
3497 assert_ne!(a, b);
3498 }
3499
3500 #[test]
3504 fn a_bump_pull_requests_own_merge_does_not_retrigger() {
3505 let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
3506 assert!(
3507 is_release_only(&files),
3508 "the bump pull request's own diff must read as release-only"
3509 );
3510 }
3511
3512 #[test]
3513 fn should_release_bump_reads_only_a_merged_status() {
3514 assert!(should_release_bump(RunStatus::Merged));
3515 for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
3516 assert!(!should_release_bump(other));
3517 }
3518 }
3519
3520 #[test]
3524 fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
3525 let pr = land::PrState {
3526 url: "https://github.com/o/r/pull/1".to_owned(),
3527 number: 1,
3528 state: PrLifecycle::Merged,
3529 checks: land::Checks::Green,
3530 failing: Vec::new(),
3531 review_comments: Vec::new(),
3532 blocking: land::Blocking::No,
3533 };
3534 assert_eq!(
3535 land::decide(&pr, 0, 4, Duration::ZERO),
3536 land::Step::Done { merged: true }
3537 );
3538 assert!(should_release_bump(RunStatus::Merged));
3539 }
3540
3541 #[test]
3546 fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
3547 let pr = land::PrState {
3548 url: "https://github.com/o/r/pull/2".to_owned(),
3549 number: 2,
3550 state: PrLifecycle::Open,
3551 checks: land::Checks::Green,
3552 failing: Vec::new(),
3553 review_comments: Vec::new(),
3554 blocking: land::Blocking::No,
3555 };
3556 assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
3557 assert!(should_release_bump(RunStatus::Merged));
3560 }
3561
3562 #[test]
3565 fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
3566 let argv = land::merge_argv(3, "feat: something");
3567 let outcome = land::merged_after_all(
3568 &argv,
3569 "could not determine current branch: not on any branch",
3570 Some(PrLifecycle::Merged),
3571 );
3572 assert!(outcome.is_some(), "the forge's confirmation must win");
3573 assert!(should_release_bump(RunStatus::Merged));
3574
3575 assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
3578 assert!(land::merged_after_all(&argv, "network error", None).is_none());
3579 }
3580
3581 #[test]
3583 fn a_close_or_a_give_up_does_not_trigger_a_bump() {
3584 let pr = land::PrState {
3585 url: "https://github.com/o/r/pull/4".to_owned(),
3586 number: 4,
3587 state: PrLifecycle::Closed,
3588 checks: land::Checks::Green,
3589 failing: Vec::new(),
3590 review_comments: Vec::new(),
3591 blocking: land::Blocking::No,
3592 };
3593 assert_eq!(
3594 land::decide(&pr, 0, 4, Duration::ZERO),
3595 land::Step::Done { merged: false }
3596 );
3597 assert!(!should_release_bump(RunStatus::Blocked));
3598 }
3599}