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<()> {
1018 after_merge_at(state, pr_url, None).await
1019}
1020
1021async fn base_has_cargo_toml(repo: &Path, remote: &str, base: &str) -> Result<bool> {
1027 let out = git::git(
1028 repo,
1029 &[
1030 "ls-tree",
1031 "--name-only",
1032 &format!("{remote}/{base}"),
1033 "--",
1034 "Cargo.toml",
1035 ],
1036 )
1037 .await
1038 .context("look for Cargo.toml on the base branch")?;
1039 Ok(!out.trim().is_empty())
1040}
1041
1042async fn after_merge_at(state: &mut RunState, pr_url: &str, home: Option<&Path>) -> Result<()> {
1045 if !state.config.merge.release_bump {
1046 return Ok(());
1047 }
1048 let Some(winner) = state.winner().cloned() else {
1049 return Ok(());
1050 };
1051 let repo = state.repo.clone();
1052 let base = state.base_branch.clone();
1053 let remote = state.config.merge.remote.clone();
1054
1055 let files = git::changed_files(&winner.worktree, &base, &winner.branch)
1056 .await
1057 .unwrap_or_default();
1058 if is_release_only(&files) {
1059 state.event(
1060 "bump",
1061 "the merged change touches only the release manifest; not treating it as a trigger",
1062 );
1063 return Ok(());
1064 }
1065
1066 git::fetch(&repo, &remote, &base).await.ok();
1069 if !base_has_cargo_toml(&repo, &remote, &base).await? {
1070 state.event(
1071 "bump",
1072 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping",
1073 );
1074 return Ok(());
1075 }
1076
1077 let marker = marker_path(&home.map_or_else(run::home, Path::to_path_buf), &repo);
1078 let Some(_lock) = wait_for_marker_lock(&marker).await? else {
1085 state.event(
1086 "bump",
1087 "another release bump decision held the lock past the wait ceiling; skipping this round",
1088 );
1089 return Ok(());
1090 };
1091
1092 git::fetch(&repo, &remote, &base).await.ok();
1093 let cargo_toml = git::git(&repo, &["show", &format!("{remote}/{base}:Cargo.toml")])
1094 .await
1095 .context("read Cargo.toml from the base branch")?;
1096 let base_version = current_version(&cargo_toml)?;
1097
1098 let mut pending = read_marker(&marker);
1099 if let Some(p) = &pending {
1100 match coalesce(Some(p), &base_version)? {
1101 Coalesce::Proceed => {
1102 clear_marker(&marker);
1105 pending = None;
1106 }
1107 Coalesce::Skip { target_version } => {
1108 if !pr_is_open(&repo, &p.pr_url).await.unwrap_or(true) {
1109 state.event(
1110 "bump",
1111 format!(
1112 "the pending release bump to v{target_version} ({}) is no longer \
1113 open; treating it as abandoned",
1114 p.pr_url
1115 ),
1116 );
1117 clear_marker(&marker);
1118 pending = None;
1119 }
1120 }
1125 }
1126 }
1127
1128 if pending.is_none() {
1129 if let Ok(Some((branch, url))) = find_open_release_pr(&repo).await
1134 && let Some(target) = branch
1135 .strip_prefix("chore/release-v")
1136 .and_then(|v| Version::parse(v).ok())
1137 {
1138 let base_parsed = Version::parse(&base_version)?;
1139 if target > base_parsed
1140 && let Some(level) = level_between(base_parsed, target)
1141 {
1142 let adopted = PendingBump {
1143 target_version: target.to_string(),
1144 level,
1145 branch,
1146 pr_url: url,
1147 };
1148 let _ = write_marker(&marker, &adopted);
1151 pending = Some(adopted);
1152 }
1153 }
1154 }
1155
1156 let title = pr_title(&repo, pr_url).await.unwrap_or_default();
1157 let subject = land::merge_subject(&title, &state.instruction);
1158 let stat = git::diff_stat(&winner.worktree, &base, &winner.branch)
1159 .await
1160 .unwrap_or_default();
1161 let prompt = decision_prompt(&subject, &state.instruction, &stat, &files, &base_version);
1162
1163 let spec: AgentSpec = agent::pick(
1169 &state.config.agents,
1170 state.config.roles.chatter.as_deref(),
1171 &agent::installed,
1172 )
1173 .context("choose an agent for the release-bump decision")?;
1174 let mut seat = SeatState::new("bump", &spec.id, state.seed);
1175 let artifacts = agent::artifacts_dir(&state.dir());
1176 let out = agent::invoke(
1177 &spec,
1178 &mut seat,
1179 &Invocation {
1180 cwd: &repo,
1181 prompt: &prompt,
1182 timeout: DECISION_TIMEOUT,
1183 allow_write: false,
1186 sessions: false,
1187 artifacts: &artifacts,
1188 stem: "bump-decision",
1189 run: &state.id,
1190 node: "bump",
1191 cache_dir: state.config.cache_dir().as_deref(),
1192 attachments: &[],
1193 },
1194 )
1195 .await
1196 .context("ask an agent how big the merged change was")?;
1197 if !out.usable() {
1198 bail!(
1199 "the release-bump decision produced nothing usable (exit {:?}, timed out: {})",
1200 out.exit_code,
1201 out.timed_out
1202 );
1203 }
1204 let decision = parse_decision(&out.text).context("parse the release-bump decision")?;
1205
1206 if let Some(p) = pending {
1207 return match pending_action(p.level, decision.level) {
1208 PendingAction::AlreadyCovered => {
1209 state.event(
1210 "bump",
1211 format!(
1212 "a release bump to v{} ({}) already covers at least a {} change; not \
1213 opening another",
1214 p.target_version,
1215 p.pr_url,
1216 decision.level.as_str()
1217 ),
1218 );
1219 Ok(())
1220 }
1221 PendingAction::Escalate => {
1222 escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
1223 }
1224 };
1225 }
1226
1227 let next = Version::parse(&base_version)?
1228 .bump(decision.level)
1229 .to_string();
1230 let branch = format!("chore/release-v{next}");
1231 let worktree = state.dir().join("bump");
1232 let (shared, branch_ref, next_ref, decision_ref) = (&*state, &branch, &next, &decision);
1233 let (pr_url_opened, outcome) =
1234 release_attempt(
1235 &repo,
1236 &remote,
1237 &base,
1238 &worktree,
1239 &branch,
1240 |head| {
1241 let repo = repo.clone();
1242 async move { gh_open_pr_for_head(&repo, &head).await }
1243 },
1244 |wt| async move {
1245 open_bump_pr(shared, &wt, branch_ref, next_ref, decision_ref, pr_url).await
1246 },
1247 )
1248 .await?;
1249 let (automerge_warning, merged_detail) = match outcome {
1250 AutomergeOutcome::Enabled => (None, None),
1251 AutomergeOutcome::MergedDirectly { detail } => (None, Some(detail)),
1252 AutomergeOutcome::Failed { reason } => (Some(reason), None),
1253 };
1254
1255 let marker_write = write_marker(
1264 &marker,
1265 &PendingBump {
1266 target_version: next.clone(),
1267 level: decision.level,
1268 branch,
1269 pr_url: pr_url_opened.clone(),
1270 },
1271 );
1272 state.event(
1273 "bump",
1274 format!(
1275 "opened a {} release bump to v{next} ({}): {pr_url_opened}",
1276 decision.level.as_str(),
1277 decision.reason
1278 ),
1279 );
1280 if let Err(e) = marker_write {
1281 state.event(
1282 "bump",
1283 format!(
1284 "could not record the pending release bump marker for v{next}: {e:#}; a later \
1285 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
1286 the forge either"
1287 ),
1288 );
1289 }
1290 state.release_bump = Some(run::ReleaseBump {
1291 pr_url: Some(pr_url_opened.clone()),
1292 version: Some(next.clone()),
1293 automerge_enabled: automerge_warning.is_none() && merged_detail.is_none(),
1294 merged_directly: merged_detail.is_some(),
1295 ..run::ReleaseBump::default()
1296 });
1297 if let Some(detail) = merged_detail {
1298 clear_marker(&marker);
1301 state.event("bump", format!("merged v{next} directly: {detail}"));
1302 }
1303 if let Some(warning) = automerge_warning {
1304 state.event(
1305 "bump",
1306 format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
1307 );
1308 report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
1309 }
1310 Ok(())
1311}
1312
1313pub const NOTICE_NODE: &str = "release-bump";
1318
1319fn automerge_hint(reason: &str) -> &'static str {
1326 let r = reason.to_lowercase();
1327 if is_clean_status_refusal(reason) {
1328 "merge the release pull request by hand; CI is already green"
1329 } else if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
1330 "merge the release pull request by hand, and enable branch protection with required \
1331 status checks on the base branch so automerge can work next time"
1332 } else {
1333 "merge the release pull request by hand"
1334 }
1335}
1336
1337fn automerge_failure_comment(reason: &str) -> String {
1339 format!(
1340 "magi could not enable automerge on this pull request: {reason}\n\n\
1341 Action required: {}. Until then the release does not happen.",
1342 automerge_hint(reason)
1343 )
1344}
1345
1346fn surface_problem(
1354 state: &mut RunState,
1355 store: &Notices,
1356 pr_url: Option<&str>,
1357 version: Option<&str>,
1358 reason: &str,
1359) -> Result<(Notice, Option<String>)> {
1360 let action = if pr_url.is_some() {
1361 automerge_hint(reason).to_owned()
1362 } else {
1363 "the release bump did not run; open the release pull request by hand".to_owned()
1364 };
1365 let record = state.release_bump.get_or_insert_with(Default::default);
1366 record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
1367 record.version = version.map(str::to_owned).or(record.version.take());
1368 record.automerge_enabled = false;
1369 record.problem = Some(reason.to_owned());
1370 record.action_required = Some(action.clone());
1371
1372 let mut notice = Notice::error(
1373 &format!("release-bump:{}", state.id),
1374 format!(
1375 "Run {} merged, but its release step failed: {action}.",
1376 state.id
1377 ),
1378 );
1379 notice = match pr_url {
1380 Some(url) => notice.link(Link::Url {
1381 url: url.to_owned(),
1382 }),
1383 None => notice.link(Link::Run {
1384 id: state.id.clone(),
1385 }),
1386 };
1387 let notice = store
1388 .raise(notice)
1389 .context("raise the release-bump notification")?;
1390 state.event("bump", format!("needs attention: {action}"));
1391 let comment = pr_url.map(|_| automerge_failure_comment(reason));
1392 Ok((notice, comment))
1393}
1394
1395pub async fn report_problem(
1400 state: &mut RunState,
1401 pr_url: Option<&str>,
1402 version: Option<&str>,
1403 reason: &str,
1404) {
1405 match surface_problem(state, &Notices::open(), pr_url, version, reason) {
1406 Ok((notice, comment)) => {
1407 if let (Some(url), Some(body)) = (pr_url, comment)
1408 && let Err(e) = gh_pr_comment(
1409 &state.repo,
1410 url,
1411 &crate::scrub::scrub(&body, &crate::scrub::Identity::current()),
1412 )
1413 .await
1414 {
1415 state.event("bump", format!("could not comment on {url}: {e:#}"));
1416 }
1417 let summary = match pr_url {
1420 Some(url) => format!("Release PR needs a human: {url}"),
1421 None => "Release bump did not run".to_owned(),
1422 };
1423 let q = ask::Question::new(
1424 state.id.clone(),
1425 NOTICE_NODE.to_owned(),
1426 "bump".to_owned(),
1427 summary,
1428 notice.message.clone(),
1429 Vec::new(),
1430 );
1431 if let Err(e) = ask::notify(&state.config.notify, &q).await {
1432 tracing::warn!(
1433 "could not notify about the release bump of {}: {e:#}",
1434 state.id
1435 );
1436 }
1437 }
1438 Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
1439 }
1440}
1441
1442async fn gh_pr_comment(cwd: &Path, pr_url: &str, body: &str) -> Result<()> {
1443 let out = tokio::process::Command::new("gh")
1444 .args(["pr", "comment", pr_url, "--body", body])
1445 .current_dir(cwd)
1446 .quiet()
1447 .stdin(std::process::Stdio::null())
1448 .output()
1449 .await
1450 .context("spawn gh pr comment")?;
1451 if out.status.success() {
1452 Ok(())
1453 } else {
1454 bail!(
1455 "gh pr comment: {}",
1456 String::from_utf8_lossy(&out.stderr).trim()
1457 )
1458 }
1459}
1460
1461async fn escalate_pending(
1470 state: &mut RunState,
1471 repo: &Path,
1472 remote: &str,
1473 pending: &PendingBump,
1474 decision: &BumpDecision,
1475 base_version: &str,
1476 marker: &Path,
1477) -> Result<()> {
1478 let next = Version::parse(base_version)?
1479 .bump(decision.level)
1480 .to_string();
1481 let worktree = state.dir().join("bump");
1482 git::worktree_remove(repo, &worktree).await.ok();
1483 let checked_out = git::git_raw(
1484 repo,
1485 &[
1486 "worktree",
1487 "add",
1488 "--force",
1489 &worktree.to_string_lossy(),
1490 &pending.branch,
1491 ],
1492 )
1493 .await?;
1494 if !checked_out.ok() {
1495 bail!(
1496 "checking out the pending release branch {} failed: {}",
1497 pending.branch,
1498 checked_out.stderr
1499 );
1500 }
1501
1502 let pushed: Result<()> = async {
1507 let cargo_toml_path = worktree.join("Cargo.toml");
1508 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1509 .await
1510 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1511 let rewritten = rewrite_cargo_version(&toml, &next)?;
1512 tokio::fs::write(&cargo_toml_path, rewritten)
1513 .await
1514 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1515 sync_lockfile(&worktree, state.config.cache_dir().as_deref()).await?;
1516 let committed = git::commit_all(
1517 &worktree,
1518 &format!(
1519 "chore: release v{next} (supersedes v{})",
1520 pending.target_version
1521 ),
1522 )
1523 .await
1524 .context("commit the escalated version bump")?;
1525 if !committed {
1526 bail!("escalating the version bump left nothing to commit");
1527 }
1528 let pushed = git::push(&worktree, remote, &pending.branch).await?;
1529 if !pushed.ok() {
1530 bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
1531 }
1532 Ok(())
1533 }
1534 .await;
1535 if let Err(e) = pushed {
1536 git::worktree_remove(repo, &worktree).await.ok();
1537 return Err(e);
1538 }
1539
1540 let title_warning = match gh_pr_edit_title(
1544 &worktree,
1545 &pending.pr_url,
1546 &crate::scrub::scrub(
1547 &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
1548 &crate::scrub::Identity::current(),
1549 ),
1550 )
1551 .await
1552 {
1553 Ok(()) => None,
1554 Err(e) => Some(e.to_string()),
1555 };
1556 git::worktree_remove(repo, &worktree).await.ok();
1557
1558 let marker_write = write_marker(
1559 marker,
1560 &PendingBump {
1561 target_version: next.clone(),
1562 level: decision.level,
1563 branch: pending.branch.clone(),
1564 pr_url: pending.pr_url.clone(),
1565 },
1566 );
1567 state.event(
1568 "bump",
1569 format!(
1570 "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
1571 pending.target_version,
1572 decision.level.as_str(),
1573 decision.reason,
1574 pending.pr_url
1575 ),
1576 );
1577 if let Err(e) = marker_write {
1578 state.event(
1579 "bump",
1580 format!(
1581 "could not update the pending release bump marker to v{next}: {e:#}; a later \
1582 merge may misjudge whether it is already covered"
1583 ),
1584 );
1585 }
1586 if let Some(warning) = title_warning {
1587 state.event(
1588 "bump",
1589 format!(
1590 "pushed v{next} to {} but could not update its title: {warning}; the squashed \
1591 subject may still read the superseded version",
1592 pending.pr_url
1593 ),
1594 );
1595 }
1596 Ok(())
1597}
1598
1599async fn gh_open_pr_for_head(repo: &Path, branch: &str) -> Result<bool> {
1602 let out = tokio::process::Command::new("gh")
1603 .args([
1604 "pr", "list", "--head", branch, "--state", "open", "--json", "url",
1605 ])
1606 .current_dir(repo)
1607 .quiet()
1608 .stdin(std::process::Stdio::null())
1609 .output()
1610 .await
1611 .context("spawn gh pr list")?;
1612 if !out.status.success() {
1613 bail!(
1614 "gh pr list --head {branch}: {}",
1615 String::from_utf8_lossy(&out.stderr).trim()
1616 );
1617 }
1618 let prs: Vec<serde_json::Value> = serde_json::from_slice(&out.stdout)
1619 .with_context(|| format!("parse the pull requests headed by {branch}"))?;
1620 Ok(!prs.is_empty())
1621}
1622
1623async fn release_attempt<T, F, Fut, P, PFut>(
1632 repo: &Path,
1633 remote: &str,
1634 base: &str,
1635 worktree: &Path,
1636 branch: &str,
1637 open_pr: P,
1638 fill: F,
1639) -> Result<T>
1640where
1641 F: FnOnce(PathBuf) -> Fut,
1642 Fut: std::future::Future<Output = Result<T>>,
1643 P: Fn(String) -> PFut,
1644 PFut: std::future::Future<Output = Result<bool>>,
1645{
1646 let start = format!("{remote}/{base}");
1647 git::worktree_remove(repo, worktree).await.ok();
1648 let mut retried = false;
1649 if git::branch_exists(repo, branch).await? {
1650 reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await?;
1651 retried = true;
1652 }
1653 loop {
1654 if let Err(e) = git::git(repo, &["branch", branch, &start]).await {
1659 let e = e.context("create the release branch");
1660 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1661 return Err(e);
1662 }
1663 if retried {
1665 return Err(anyhow!(
1666 "{e:#}; left {branch} in place: it is not one this attempt created"
1667 ));
1668 }
1669 retried = true;
1670 if let Err(r) = reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await {
1671 return Err(anyhow!("{r:#} (after: {e:#})"));
1672 }
1673 continue;
1674 }
1675 if let Some(parent) = worktree.parent() {
1676 tokio::fs::create_dir_all(parent).await.ok();
1677 }
1678 let path = worktree.to_string_lossy();
1679 if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
1680 let e = e.context("create the release-bump worktree");
1681 return Err(discard_attempt(repo, remote, worktree, branch, e).await);
1682 }
1683 break;
1684 }
1685 match fill(worktree.to_path_buf()).await {
1686 Ok(v) => {
1687 git::worktree_remove(repo, worktree).await.ok();
1690 Ok(v)
1691 }
1692 Err(e) => Err(discard_attempt(repo, remote, worktree, branch, e).await),
1693 }
1694}
1695
1696async fn discard_attempt(
1698 repo: &Path,
1699 remote: &str,
1700 worktree: &Path,
1701 branch: &str,
1702 cause: anyhow::Error,
1703) -> anyhow::Error {
1704 git::worktree_remove(repo, worktree).await.ok();
1705 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1706 return cause;
1707 }
1708 let note = match git::remote_has_branch(repo, remote, branch).await {
1711 Ok(false) => match git::branch_delete(repo, branch).await {
1712 Ok(true) => return cause,
1713 _ => format!("could not delete the local branch {branch}"),
1714 },
1715 Ok(true) => format!("left {branch} in place: it was pushed to {remote}"),
1716 Err(e) => format!(
1717 "left {branch} in place: could not tell whether it was pushed to {remote} ({e:#})"
1718 ),
1719 };
1720 anyhow!("{cause:#}; {note}")
1721}
1722
1723async fn reclaim_stale_branch<P, PFut>(
1728 repo: &Path,
1729 remote: &str,
1730 start: &str,
1731 branch: &str,
1732 open_pr: &P,
1733) -> Result<()>
1734where
1735 P: Fn(String) -> PFut,
1736 PFut: std::future::Future<Output = Result<bool>>,
1737{
1738 match git::remote_has_branch(repo, remote, branch).await {
1739 Ok(false) => {}
1740 Ok(true) => bail!("the branch {branch} already exists and is on {remote}; left alone"),
1741 Err(e) => bail!(
1742 "the branch {branch} already exists and could not check whether {remote} has it ({e:#}); left alone"
1743 ),
1744 }
1745 match open_pr(branch.to_string()).await {
1746 Ok(false) => {}
1747 Ok(true) => {
1748 bail!("the branch {branch} already exists and has an open pull request; left alone")
1749 }
1750 Err(e) => bail!(
1751 "the branch {branch} already exists and could not check for an open pull request \
1752 ({e:#}); left alone"
1753 ),
1754 }
1755 match git::commits_ahead(repo, start, branch).await {
1756 Ok(0) => {}
1757 Ok(n) => bail!(
1758 "the branch {branch} already exists with {n} commit(s) not in {start}; left alone"
1759 ),
1760 Err(e) => bail!(
1761 "the branch {branch} already exists and could not compare it with {start} ({e:#}); \
1762 left alone"
1763 ),
1764 }
1765 if let Some(held) = git::worktree_holding(repo, branch).await? {
1766 let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
1767 (Ok(a), Ok(b)) => a == b,
1768 _ => a == b,
1769 };
1770 if same(&held, repo) {
1771 bail!(
1772 "the branch {branch} already exists and is checked out in the main checkout; left alone"
1773 );
1774 }
1775 git::worktree_remove(repo, &held).await.ok();
1776 }
1777 if !git::branch_delete(repo, branch).await? {
1778 bail!("the branch {branch} already exists and could not be deleted; left alone");
1779 }
1780 Ok(())
1781}
1782
1783async fn open_bump_pr(
1789 state: &RunState,
1790 worktree: &Path,
1791 branch: &str,
1792 next_version: &str,
1793 decision: &BumpDecision,
1794 source_pr_url: &str,
1795) -> Result<(String, AutomergeOutcome)> {
1796 let cargo_toml_path = worktree.join("Cargo.toml");
1797 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1798 .await
1799 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1800 let rewritten = rewrite_cargo_version(&toml, next_version)?;
1801 tokio::fs::write(&cargo_toml_path, rewritten)
1802 .await
1803 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1804
1805 sync_lockfile(worktree, state.config.cache_dir().as_deref()).await?;
1806
1807 let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
1808 .await
1809 .context("commit the version bump")?;
1810 if !committed {
1811 bail!("the version bump left nothing to commit");
1812 }
1813
1814 let remote = state.config.merge.remote.clone();
1815 let pushed = git::push(worktree, &remote, branch).await?;
1816 if !pushed.ok() {
1817 bail!("pushing {branch} failed: {}", pushed.stderr);
1818 }
1819
1820 let (title, body) = release_pr(
1821 decision.level.as_str(),
1822 &decision.reason,
1823 next_version,
1824 &state.id,
1825 source_pr_url,
1826 );
1827 let who = crate::scrub::Identity::current();
1828 let (title, body) = (
1829 crate::scrub::scrub(&title, &who),
1830 crate::scrub::scrub(&body, &who),
1831 );
1832 let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
1833 let outcome = match gh_enable_automerge(worktree, &url).await {
1834 Ok(()) => AutomergeOutcome::Enabled,
1835 Err(e) => {
1836 let reason = e.to_string();
1837 if is_clean_status_refusal(&reason) {
1838 gh_merge_directly(worktree, &url, &title, reason).await
1839 } else {
1840 AutomergeOutcome::Failed { reason }
1841 }
1842 }
1843 };
1844 Ok((url, outcome))
1845}
1846
1847#[derive(Debug, Clone, PartialEq, Eq)]
1849enum AutomergeOutcome {
1850 Enabled,
1852 MergedDirectly { detail: String },
1854 Failed { reason: String },
1856}
1857
1858fn is_clean_status_refusal(reason: &str) -> bool {
1864 let r = reason.to_lowercase();
1865 r.contains("is in clean status") && r.contains("enablepullrequestautomerge")
1866}
1867
1868fn bump_merge_argv(pr_url: &str, subject: &str) -> Vec<String> {
1871 [
1872 "pr",
1873 "merge",
1874 pr_url,
1875 "--squash",
1876 "--delete-branch",
1877 "--subject",
1878 subject,
1879 ]
1880 .map(str::to_owned)
1881 .to_vec()
1882}
1883
1884fn resolve_direct_merge(
1888 refusal: &str,
1889 argv: &[String],
1890 merge_ok: bool,
1891 stderr: &str,
1892 after: Option<land::PrLifecycle>,
1893) -> AutomergeOutcome {
1894 if merge_ok {
1895 return AutomergeOutcome::MergedDirectly {
1896 detail: format!("automerge was refused ({refusal}); gh {}", argv.join(" ")),
1897 };
1898 }
1899 match land::merged_after_all(argv, stderr, after) {
1900 Some(m) => AutomergeOutcome::MergedDirectly { detail: m.detail },
1901 None => AutomergeOutcome::Failed {
1902 reason: format!("{refusal}; merging directly failed too: {}", stderr.trim()),
1903 },
1904 }
1905}
1906
1907async fn gh_merge_directly(
1911 cwd: &Path,
1912 pr_url: &str,
1913 subject: &str,
1914 refusal: String,
1915) -> AutomergeOutcome {
1916 let argv = bump_merge_argv(pr_url, subject);
1917 let out = match tokio::process::Command::new("gh")
1918 .args(&argv)
1919 .current_dir(cwd)
1920 .quiet()
1921 .stdin(std::process::Stdio::null())
1922 .output()
1923 .await
1924 {
1925 Ok(o) => o,
1926 Err(e) => {
1927 return AutomergeOutcome::Failed {
1928 reason: format!("{refusal}; could not spawn gh to merge directly: {e}"),
1929 };
1930 }
1931 };
1932 let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
1933 let after = if out.status.success() {
1936 None
1937 } else {
1938 land::lifecycle(cwd, pr_url).await.ok()
1939 };
1940 resolve_direct_merge(&refusal, &argv, out.status.success(), &stderr, after)
1941}
1942
1943async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
1951 let mut cmd = tokio::process::Command::new("cargo");
1952 cmd.arg("build").current_dir(worktree).quiet();
1953 if let Some(dir) = cache_dir {
1954 cmd.env("CARGO_TARGET_DIR", dir);
1955 }
1956 let out = cmd
1957 .stdin(std::process::Stdio::null())
1958 .output()
1959 .await
1960 .context("spawn cargo build")?;
1961 if !out.status.success() {
1962 bail!(
1963 "cargo build failed while syncing Cargo.lock: {}",
1964 String::from_utf8_lossy(&out.stderr).trim()
1965 );
1966 }
1967 Ok(())
1968}
1969
1970fn release_pr(
1975 level: &str,
1976 reason: &str,
1977 next_version: &str,
1978 run_id: &str,
1979 source_pr_url: &str,
1980) -> (String, String) {
1981 let title = format!("chore: release v{next_version} ({level} bump)");
1982 let body = format!(
1983 "## Background\n\n\
1984 A change that was just merged is a `{level}` change, so the crate needs a new \
1985 release: {reason}\n\n\
1986 Triggered by magi run `{run_id}`, which landed {source}.\n\n\
1987 ## Change\n\n\
1988 Raises the package version to `v{next_version}` in `Cargo.toml`, with \
1989 `Cargo.lock` following it. Nothing else changes.\n\n\
1990 ## Risk\n\n\
1991 Version-bump-only, so there is nothing here for a reviewer to find. Merging \
1992 it starts the release pipeline (auto-tag, then the release workflow).",
1993 source = source_pr_url,
1994 );
1995 (title, body)
1996}
1997
1998async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
2000 let out = tokio::process::Command::new("gh")
2001 .args(["pr", "view", pr_url, "--json", "title"])
2002 .current_dir(repo)
2003 .quiet()
2004 .stdin(std::process::Stdio::null())
2005 .output()
2006 .await
2007 .context("spawn gh pr view")?;
2008 if !out.status.success() {
2009 bail!(
2010 "gh pr view {pr_url}: {}",
2011 String::from_utf8_lossy(&out.stderr).trim()
2012 );
2013 }
2014 #[derive(Deserialize)]
2015 struct Title {
2016 title: String,
2017 }
2018 let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
2019 .context("parse `gh pr view --json title` output")?;
2020 Ok(parsed.title)
2021}
2022
2023async fn gh_pr_create(
2024 cwd: &Path,
2025 base: &str,
2026 head: &str,
2027 title: &str,
2028 body: &str,
2029) -> Result<String> {
2030 let out = tokio::process::Command::new("gh")
2031 .args([
2032 "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
2033 ])
2034 .current_dir(cwd)
2035 .quiet()
2036 .stdin(std::process::Stdio::null())
2037 .output()
2038 .await
2039 .context("spawn gh pr create")?;
2040 if out.status.success() {
2041 Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
2042 } else {
2043 bail!(
2044 "gh pr create: {}",
2045 String::from_utf8_lossy(&out.stderr).trim()
2046 )
2047 }
2048}
2049
2050async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
2054 let out = tokio::process::Command::new("gh")
2055 .args([
2056 "pr",
2057 "merge",
2058 pr_url,
2059 "--auto",
2060 "--squash",
2061 "--delete-branch",
2062 ])
2063 .current_dir(cwd)
2064 .quiet()
2065 .stdin(std::process::Stdio::null())
2066 .output()
2067 .await
2068 .context("spawn gh pr merge --auto")?;
2069 if out.status.success() {
2070 Ok(())
2071 } else {
2072 bail!(
2073 "gh pr merge --auto: {}",
2074 String::from_utf8_lossy(&out.stderr).trim()
2075 )
2076 }
2077}
2078
2079async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
2083 let out = tokio::process::Command::new("gh")
2084 .args(["pr", "edit", pr_url, "--title", title])
2085 .current_dir(cwd)
2086 .quiet()
2087 .stdin(std::process::Stdio::null())
2088 .output()
2089 .await
2090 .context("spawn gh pr edit")?;
2091 if out.status.success() {
2092 Ok(())
2093 } else {
2094 bail!(
2095 "gh pr edit --title: {}",
2096 String::from_utf8_lossy(&out.stderr).trim()
2097 )
2098 }
2099}
2100
2101#[cfg(test)]
2102mod tests {
2103 use super::*;
2104 use crate::notices::Severity;
2105
2106 #[test]
2107 fn github_facing_bump_text_is_english() {
2108 let (title, body) =
2109 release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
2110 assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
2111 assert_eq!(title, "chore: release v0.37.0 (minor bump)");
2112 assert!(
2113 body.contains("## Background") && body.contains("## Change"),
2114 "{body}"
2115 );
2116 let p = decision_prompt("s", "i", "d", &[], "0.36.5");
2117 assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
2118 }
2119 use crate::config::Config;
2120 use crate::land::PrLifecycle;
2121
2122 #[tokio::test]
2128 async fn a_disabled_config_does_nothing() {
2129 let config = Config {
2130 merge: crate::config::Merge {
2131 release_bump: false,
2132 ..crate::config::Merge::default()
2133 },
2134 ..Config::default()
2135 };
2136 let mut state = RunState::new(
2137 PathBuf::from("/no/such/repo"),
2138 "main".to_owned(),
2139 "0000000000000000000000000000000000000000".to_owned(),
2140 "irrelevant".to_owned(),
2141 config,
2142 );
2143 after_merge(&mut state, "https://example.invalid/pull/1")
2144 .await
2145 .expect("a disabled config must return Ok without touching anything");
2146 assert!(
2147 state.events.is_empty(),
2148 "nothing should happen at all, not even a logged event"
2149 );
2150 }
2151
2152 async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
2154 let dir = tempfile::tempdir().unwrap();
2155 let origin = dir.path().join("origin.git");
2156 let repo = dir.path().join("repo");
2157 let o = origin.to_string_lossy().into_owned();
2158 git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
2159 .await
2160 .unwrap();
2161 tokio::fs::create_dir_all(&repo).await.unwrap();
2162 git::git(&repo, &["init", "-b", "main"]).await.unwrap();
2163 git::git(&repo, &["config", "user.name", "test"])
2164 .await
2165 .unwrap();
2166 git::git(&repo, &["config", "user.email", "test@example.com"])
2167 .await
2168 .unwrap();
2169 for (name, body) in files {
2170 tokio::fs::write(repo.join(name), body).await.unwrap();
2171 }
2172 git::git(&repo, &["add", "-A"]).await.unwrap();
2173 git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
2174 git::git(&repo, &["remote", "add", "origin", &o])
2175 .await
2176 .unwrap();
2177 git::git(&repo, &["push", "origin", "main"]).await.unwrap();
2178 (dir, repo)
2179 }
2180
2181 async fn no_pr(_: String) -> Result<bool> {
2182 Ok(false)
2183 }
2184
2185 async fn with_branch(ahead: bool) -> (tempfile::TempDir, PathBuf) {
2188 let (d, repo) = origin_with(&[("f", "x\n")]).await;
2189 git::git(&repo, &["branch", "b"]).await.unwrap();
2190 if ahead {
2191 git::git(&repo, &["checkout", "-q", "b"]).await.unwrap();
2192 git::git(&repo, &["commit", "--allow-empty", "-m", "wip"])
2193 .await
2194 .unwrap();
2195 git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
2196 }
2197 (d, repo)
2198 }
2199
2200 async fn attempt(repo: &Path, open_pr: bool, fail_after_push: Option<bool>) -> Result<()> {
2201 let wt = repo.parent().unwrap().join("bump");
2202 release_attempt(
2203 repo,
2204 "origin",
2205 "main",
2206 &wt,
2207 "b",
2208 |_| async move { Ok(open_pr) },
2209 |w| async move {
2210 if fail_after_push == Some(true) {
2211 git::push(&w, "origin", "b").await?;
2212 }
2213 if fail_after_push.is_some() {
2214 bail!("cargo build failed");
2215 }
2216 Ok(())
2217 },
2218 )
2219 .await
2220 }
2221
2222 #[tokio::test]
2223 async fn a_stale_ancestor_branch_is_deleted_and_the_attempt_proceeds() {
2224 let (_d, repo) = with_branch(false).await;
2225 attempt(&repo, false, None).await.unwrap();
2226 assert!(git::branch_exists(&repo, "b").await.unwrap());
2228 }
2229
2230 #[tokio::test]
2231 async fn a_stale_branch_holding_a_leftover_worktree_is_reclaimed() {
2232 let (_d, repo) = with_branch(false).await;
2233 let old = repo.parent().unwrap().join("old");
2234 git::git(&repo, &["worktree", "add", &old.to_string_lossy(), "b"])
2235 .await
2236 .unwrap();
2237 attempt(&repo, false, None).await.unwrap();
2238 assert!(!old.exists());
2239 }
2240
2241 #[tokio::test]
2242 async fn a_stale_branch_with_an_unmerged_commit_is_kept_with_a_reason() {
2243 let (_d, repo) = with_branch(true).await;
2244 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2245 assert!(e.contains("`b`") || e.contains("branch b"), "{e}");
2246 assert!(e.contains("1 commit(s) not in origin/main"), "{e}");
2247 assert!(git::branch_exists(&repo, "b").await.unwrap());
2248 }
2249
2250 #[tokio::test]
2251 async fn a_stale_branch_on_the_remote_is_kept() {
2252 let (_d, repo) = with_branch(false).await;
2253 git::git(&repo, &["push", "origin", "b"]).await.unwrap();
2254 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2255 assert!(e.contains("branch b") && e.contains("is on origin"), "{e}");
2256 assert!(git::branch_exists(&repo, "b").await.unwrap());
2257 }
2258
2259 #[tokio::test]
2260 async fn a_stale_branch_with_an_open_pull_request_is_kept() {
2261 let (_d, repo) = with_branch(false).await;
2262 let e = attempt(&repo, true, None).await.unwrap_err().to_string();
2263 assert!(e.contains("open pull request"), "{e}");
2264 assert!(git::branch_exists(&repo, "b").await.unwrap());
2265 }
2266
2267 #[tokio::test]
2268 async fn an_unanswerable_pull_request_check_keeps_the_branch() {
2269 let (_d, repo) = with_branch(false).await;
2270 let wt = repo.parent().unwrap().join("bump");
2271 let e = release_attempt(
2272 &repo,
2273 "origin",
2274 "main",
2275 &wt,
2276 "b",
2277 |_| async { bail!("offline") },
2278 |_| async { Ok(()) },
2279 )
2280 .await
2281 .unwrap_err()
2282 .to_string();
2283 assert!(
2284 e.contains("could not check for an open pull request"),
2285 "{e}"
2286 );
2287 assert!(git::branch_exists(&repo, "b").await.unwrap());
2288 }
2289
2290 #[tokio::test]
2291 async fn a_failed_attempt_removes_its_own_worktree_and_branch() {
2292 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2293 let wt = repo.parent().unwrap().join("bump");
2294 let e = attempt(&repo, false, Some(false)).await.unwrap_err();
2295 assert!(format!("{e:#}").contains("cargo build failed"));
2296 assert!(!wt.exists());
2297 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2298 }
2299
2300 #[tokio::test]
2301 async fn a_pushed_branch_survives_a_failed_attempt_and_the_reason_says_so() {
2302 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2303 let e = attempt(&repo, false, Some(true)).await.unwrap_err();
2304 let e = format!("{e:#}");
2305 assert!(
2306 e.contains("cargo build failed") && e.contains("pushed to origin"),
2307 "{e}"
2308 );
2309 assert!(git::branch_exists(&repo, "b").await.unwrap());
2310 }
2311
2312 #[tokio::test]
2313 async fn a_branch_left_by_a_half_done_worktree_add_is_removed() {
2314 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2317 let blocker = repo.parent().unwrap().join("blocker");
2318 tokio::fs::write(&blocker, "file").await.unwrap();
2319 let wt = blocker.join("bump");
2320 let r = release_attempt(
2321 &repo,
2322 "origin",
2323 "main",
2324 &wt,
2325 "b",
2326 |_| async { bail!("offline") },
2327 |_| async { Ok(()) },
2328 )
2329 .await;
2330 assert!(r.is_err());
2331 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2332 }
2333
2334 #[tokio::test]
2335 async fn the_retry_is_taken_at_most_once() {
2336 let (_d, repo) = with_branch(false).await;
2339 let blocker = repo.parent().unwrap().join("blocker");
2340 tokio::fs::write(&blocker, "file").await.unwrap();
2341 let wt = blocker.join("bump");
2342 let r = release_attempt(&repo, "origin", "main", &wt, "b", no_pr, |_| async {
2343 Ok(())
2344 })
2345 .await;
2346 assert!(r.is_err());
2347 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2348 }
2349
2350 #[tokio::test]
2351 async fn base_has_cargo_toml_tells_rust_from_non_rust() {
2352 let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
2353 assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
2354 let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
2355 assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
2356 assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
2358 }
2359
2360 #[tokio::test]
2361 async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
2362 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2363 let home = tempfile::tempdir().unwrap();
2364 let mut state = RunState::new(
2365 repo.clone(),
2366 "main".to_owned(),
2367 "0000000000000000000000000000000000000000".to_owned(),
2368 "task".to_owned(),
2369 Config::default(),
2370 );
2371 state.candidates.push(crate::run::Candidate {
2372 index: 0,
2373 label: 'A',
2374 agent: "x".to_owned(),
2375 branch: "main".to_owned(),
2376 worktree: repo.clone(),
2377 summary: String::new(),
2378 stat: String::new(),
2379 files: 1,
2380 commits: 1,
2381 empty: false,
2382 failed: None,
2383 verified_noop: None,
2384 duration_ms: 0,
2385 folded: false,
2386 });
2387 state.tally = Some(
2388 serde_json::from_value(serde_json::json!({
2389 "first_choice": {}, "borda": {}, "winner": "A",
2390 "unanimous_initial": true, "deliberated": false,
2391 "changed_votes": 0, "unanimous_final": true,
2392 }))
2393 .unwrap(),
2394 );
2395 after_merge_at(
2396 &mut state,
2397 "https://example.invalid/pull/1",
2398 Some(home.path()),
2399 )
2400 .await
2401 .expect("a non-Rust repository is not an error");
2402 let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
2403 assert_eq!(bumps.len(), 1, "{:?}", state.events);
2404 assert_eq!(
2405 bumps[0].message,
2406 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
2407 );
2408 assert!(
2409 std::fs::read_dir(home.path()).unwrap().next().is_none(),
2410 "no marker and no lock may be created"
2411 );
2412 }
2413
2414 const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
2415 required protected branch rules (enablePullRequestAutoMerge)";
2416
2417 fn merged_state() -> RunState {
2418 run::set_home(std::env::temp_dir().join("magi-report-test-home"));
2421 let mut s = RunState::new(
2422 PathBuf::from("/no/such/repo"),
2423 "main".to_owned(),
2424 "0000000000000000000000000000000000000000".to_owned(),
2425 "task".to_owned(),
2426 Config::default(),
2427 );
2428 s.status = RunStatus::Merged;
2429 s
2430 }
2431
2432 #[test]
2433 fn the_known_automerge_refusal_names_branch_protection() {
2434 assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
2435 let other = automerge_hint("gh: network unreachable");
2436 assert!(!other.contains("branch protection"), "{other}");
2437 let body = automerge_failure_comment(NO_RULES);
2438 assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
2439 assert!(body.contains("Action required"), "{body}");
2440 }
2441
2442 const CLEAN: &str = "gh pr merge --auto: GraphQL: Pull request Pull request is in clean \
2443 status (enablePullRequestAutoMerge)";
2444
2445 #[test]
2446 fn clean_status_refusal_is_matched_narrowly() {
2447 assert!(is_clean_status_refusal(CLEAN));
2448 assert!(!is_clean_status_refusal(NO_RULES));
2449 assert!(!is_clean_status_refusal("gh: network unreachable"));
2450 assert!(!is_clean_status_refusal("Pull request is in clean status"));
2451 assert!(automerge_hint(CLEAN).contains("already green"));
2452 }
2453
2454 #[test]
2455 fn the_direct_merge_argv_matches_the_land_flags() {
2456 let a = bump_merge_argv("https://github.com/o/r/pull/9", "chore: release v1.0.0");
2457 let l = land::merge_argv(9, "chore: release v1.0.0");
2458 assert_eq!(a[..2], l[..2]);
2459 assert_eq!(a[3..], l[3..]);
2460 assert_eq!(a[2], "https://github.com/o/r/pull/9");
2461 }
2462
2463 #[test]
2464 fn a_direct_merge_is_judged_by_the_forge_not_the_exit_code() {
2465 let argv = bump_merge_argv("u", "t");
2466 let merged = |o: &AutomergeOutcome| matches!(o, AutomergeOutcome::MergedDirectly { .. });
2467 assert!(merged(&resolve_direct_merge(CLEAN, &argv, true, "", None)));
2468 let detached = "not on any branch";
2469 assert!(merged(&resolve_direct_merge(
2470 CLEAN,
2471 &argv,
2472 false,
2473 detached,
2474 Some(PrLifecycle::Merged)
2475 )));
2476 for after in [Some(PrLifecycle::Open), None] {
2477 let o = resolve_direct_merge(CLEAN, &argv, false, "boom", after);
2478 match o {
2479 AutomergeOutcome::Failed { reason } => {
2480 assert!(
2481 reason.contains("clean status") && reason.contains("boom"),
2482 "{reason}"
2483 )
2484 }
2485 other => panic!("expected Failed, got {other:?}"),
2486 }
2487 }
2488 }
2489
2490 #[test]
2491 fn a_directly_merged_bump_is_not_reported_as_pending_or_failed() {
2492 let mut state = merged_state();
2493 state.release_bump = Some(run::ReleaseBump {
2494 pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2495 version: Some("1.0.0".to_owned()),
2496 merged_directly: true,
2497 ..run::ReleaseBump::default()
2498 });
2499 assert!(!state.needs_attention());
2500 let text = crate::report::run(&state);
2501 assert!(text.contains("merged directly"), "{text}");
2502 assert!(!text.contains("FAILED"), "{text}");
2503 }
2504
2505 #[test]
2506 fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
2507 let dir = tempfile::tempdir().unwrap();
2508 let store = Notices::at(dir.path().join("notifications"));
2509 let questions = ask::Questions::at(dir.path().join("questions"));
2510 let mut state = merged_state();
2511 let url = "https://github.com/o/r/pull/35";
2512
2513 let (n, comment) =
2514 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2515
2516 let comment = comment.expect("a PR was opened, so it gets a comment");
2518 assert!(comment.contains("branch protection"), "{comment}");
2519
2520 assert_eq!(state.status, RunStatus::Merged);
2522 assert!(state.needs_attention());
2523 let text = crate::report::run(&state);
2524 assert!(text.contains("release bump"), "{text}");
2525 assert!(text.contains("FAILED"), "{text}");
2526 assert!(text.contains(url), "{text}");
2527 assert!(text.contains("action required"), "{text}");
2528 assert!(crate::report::line(&state).contains("release needs a human"));
2529
2530 assert_eq!(n.severity, Severity::Error);
2532 assert_eq!(
2533 n.link,
2534 Some(Link::Url {
2535 url: url.to_owned()
2536 })
2537 );
2538 assert_eq!(store.list().len(), 1);
2539 assert!(questions.open_for(&state.id).is_empty());
2540
2541 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2543 let listed = store.list();
2544 assert_eq!(listed.len(), 1);
2545 assert_eq!(listed[0].count, 2);
2546 }
2547
2548 #[test]
2549 fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
2550 let dir = tempfile::tempdir().unwrap();
2551 let store = Notices::at(dir.path().join("notifications"));
2552 let mut state = merged_state();
2553 let (n, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
2554 assert!(comment.is_none());
2555 assert!(matches!(n.link, Some(Link::Run { .. })));
2556 assert!(state.needs_attention());
2557 }
2558
2559 #[test]
2560 fn version_parses_and_bumps_each_digit() {
2561 let v = Version::parse("0.4.0").unwrap();
2562 assert_eq!(
2563 v,
2564 Version {
2565 major: 0,
2566 minor: 4,
2567 patch: 0
2568 }
2569 );
2570
2571 assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
2572 assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
2573 assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
2574 }
2575
2576 #[test]
2577 fn version_tolerates_a_prerelease_suffix_on_patch() {
2578 let v = Version::parse("1.2.3-rc1").unwrap();
2579 assert_eq!(
2580 v,
2581 Version {
2582 major: 1,
2583 minor: 2,
2584 patch: 3
2585 }
2586 );
2587 }
2588
2589 #[test]
2590 fn version_rejects_garbage() {
2591 assert!(Version::parse("not-a-version").is_err());
2592 assert!(Version::parse("1.2").is_err());
2593 }
2594
2595 #[test]
2596 fn decision_parses_each_level() {
2597 for (json, level) in [
2598 (
2599 r#"{"level":"major","reason":"drops a config key"}"#,
2600 BumpLevel::Major,
2601 ),
2602 (
2603 r#"{"level":"minor","reason":"adds a new flag"}"#,
2604 BumpLevel::Minor,
2605 ),
2606 (
2607 r#"{"level":"patch","reason":"fixes a race"}"#,
2608 BumpLevel::Patch,
2609 ),
2610 ] {
2611 let decision = parse_decision(json).unwrap();
2612 assert_eq!(decision.level, level);
2613 assert!(!decision.reason.is_empty());
2614 }
2615 }
2616
2617 #[test]
2618 fn decision_wrapped_in_a_fence_and_prose_still_parses() {
2619 let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
2620 let decision = parse_decision(text).unwrap();
2621 assert_eq!(decision.level, BumpLevel::Minor);
2622 assert_eq!(decision.reason, "new HTTP route");
2623 }
2624
2625 #[test]
2626 fn a_broken_reply_is_an_error_not_a_default() {
2627 assert!(parse_decision("I decline to answer.").is_err());
2628 assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
2629 assert!(
2630 parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
2631 "an empty reason must not pass either"
2632 );
2633 assert!(
2634 parse_decision(r#"{"level":"patch"}"#).is_err(),
2635 "a reply with no reason at all must not pass"
2636 );
2637 }
2638
2639 #[test]
2640 fn prompt_states_the_zero_x_rule_and_the_tie_break() {
2641 let prompt = decision_prompt(
2642 "feat: add a phone endpoint",
2643 "add POST /api/widgets",
2644 "1 file changed, 10 insertions(+)",
2645 &["src/web.rs".to_owned()],
2646 "0.8.0",
2647 );
2648 assert!(prompt.contains("0.8.0"), "the current version is stated");
2649 assert!(
2650 prompt.contains("below `1.0.0`")
2651 && prompt.contains("`minor` is the digit that carries a breaking change"),
2652 "the 0.x rule must be explicit: {prompt}"
2653 );
2654 assert!(
2655 prompt.contains("choose the larger"),
2656 "the tie-break toward the bigger digit must be explicit: {prompt}"
2657 );
2658 }
2659
2660 #[test]
2661 fn release_only_diffs_are_recognised() {
2662 assert!(is_release_only(&["Cargo.toml".to_owned()]));
2663 assert!(is_release_only(&[
2664 "Cargo.toml".to_owned(),
2665 "Cargo.lock".to_owned()
2666 ]));
2667 assert!(!is_release_only(&[]));
2668 assert!(!is_release_only(&[
2669 "Cargo.toml".to_owned(),
2670 "src/main.rs".to_owned()
2671 ]));
2672 }
2673
2674 #[test]
2675 fn cargo_version_rewrite_touches_only_the_package_table() {
2676 let toml = "\
2677[package]\n\
2678# a comment mentioning version on purpose\n\
2679name = \"magi-cli\"\n\
2680version = \"0.8.0\"\n\
2681edition = \"2024\"\n\
2682\n\
2683[dependencies]\n\
2684foo = { version = \"1.2.3\" }\n";
2685 let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
2686 assert!(out.contains("version = \"0.9.0\""));
2687 assert!(
2688 out.contains("foo = { version = \"1.2.3\" }"),
2689 "a dependency's own version pin must survive: {out}"
2690 );
2691 assert!(
2692 out.contains("# a comment mentioning version on purpose"),
2693 "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
2694 );
2695 assert_eq!(
2696 out.lines().count(),
2697 toml.lines().count(),
2698 "the rewrite replaces one line, it does not add or remove any"
2699 );
2700 }
2701
2702 #[test]
2703 fn cargo_version_rewrite_fails_without_a_package_table() {
2704 let toml = "[dependencies]\nfoo = \"1\"\n";
2705 assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
2706 }
2707
2708 #[test]
2714 fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
2715 let toml = "\
2716[workspace]\n\
2717members = [\"crates/a\", \"crates/b\"]\n\
2718\n\
2719[workspace.package]\n\
2720version = \"0.45.18\"\n\
2721edition = \"2024\"\n\
2722\n\
2723[workspace.dependencies]\n\
2724foo = { version = \"1.2.3\" }\n";
2725 let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
2726 assert!(out.contains("version = \"0.45.19\""));
2727 assert!(
2728 out.contains("foo = { version = \"1.2.3\" }"),
2729 "a workspace dependency's own version pin must survive: {out}"
2730 );
2731 assert_eq!(
2732 out.lines().count(),
2733 toml.lines().count(),
2734 "the rewrite replaces one line, it does not add or remove any"
2735 );
2736 }
2737
2738 #[test]
2742 fn cargo_version_rewrite_bumps_an_internal_workspace_dependency_pin() {
2743 let toml = "\
2744[workspace]\n\
2745members = [\"crates/kanade-shared\"]\n\
2746\n\
2747[workspace.package]\n\
2748version = \"0.48.2\"\n\
2749\n\
2750[workspace.dependencies]\n\
2751kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n";
2752 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
2753 assert!(out.contains("[workspace.package]\nversion = \"0.48.3\"\n"));
2754 assert!(
2755 out.contains(
2756 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
2757 ),
2758 "the internal pin must move with the workspace version: {out}"
2759 );
2760 }
2761
2762 #[test]
2764 fn cargo_version_rewrite_bumps_an_internal_pin_with_version_before_path() {
2765 let toml = "\
2766[workspace.package]\n\
2767version = \"1.0.0\"\n\
2768\n\
2769[workspace.dependencies]\n\
2770inner = { version = \"1.0.0\", path = \"crates/inner\" }\n";
2771 let out = rewrite_cargo_version(toml, "1.0.1").unwrap();
2772 assert!(out.contains("inner = { version = \"1.0.1\", path = \"crates/inner\" }"));
2773 }
2774
2775 #[test]
2778 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_table_form() {
2779 let toml = "\
2780[workspace.package]\n\
2781version = \"2.3.0\"\n\
2782\n\
2783[workspace.dependencies.inner]\n\
2784path = \"crates/inner\"\n\
2785version = \"2.3.0\"\n";
2786 let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
2787 assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
2788 assert!(out.contains(
2789 "[workspace.dependencies.inner]\npath = \"crates/inner\"\nversion = \"2.4.0\"\n"
2790 ));
2791 }
2792
2793 #[test]
2798 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_key_form() {
2799 let toml = "\
2800[workspace.package]\n\
2801version = \"2.3.0\"\n\
2802\n\
2803[workspace.dependencies]\n\
2804inner.path = \"crates/inner\"\n\
2805inner.version = \"2.3.0\"\n";
2806 let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
2807 assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
2808 assert!(out.contains("inner.path = \"crates/inner\"\ninner.version = \"2.4.0\"\n"));
2809 }
2810
2811 #[test]
2814 fn cargo_version_rewrite_leaves_a_path_only_workspace_dependency_untouched() {
2815 let toml = "\
2816[workspace.package]\n\
2817version = \"0.1.0\"\n\
2818\n\
2819[workspace.dependencies]\n\
2820internal-only = { path = \"crates/internal-only\" }\n";
2821 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
2822 assert!(out.contains("internal-only = { path = \"crates/internal-only\" }"));
2823 }
2824
2825 #[test]
2829 fn cargo_version_rewrite_leaves_an_external_dependency_untouched() {
2830 let toml = "\
2831[workspace.package]\n\
2832version = \"0.1.0\"\n\
2833\n\
2834[workspace.dependencies]\n\
2835serde = { version = \"1\", features = [\"derive\"] }\n\
2836inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
2837 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
2838 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
2839 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
2840 }
2841
2842 #[test]
2846 fn cargo_version_rewrite_without_workspace_dependencies_table_still_bumps_package() {
2847 let toml = "[workspace.package]\nversion = \"0.9.0\"\nedition = \"2024\"\n";
2848 let out = rewrite_cargo_version(toml, "0.10.0").unwrap();
2849 assert_eq!(
2850 out,
2851 "[workspace.package]\nversion = \"0.10.0\"\nedition = \"2024\"\n"
2852 );
2853 }
2854
2855 #[test]
2858 fn cargo_version_rewrite_handles_a_kanade_shaped_workspace_dependencies_table() {
2859 let toml = "\
2860[workspace.package]\n\
2861version = \"0.48.2\"\n\
2862\n\
2863[workspace.dependencies]\n\
2864anyhow = { version = \"1\" }\n\
2865serde = { version = \"1\", features = [\"derive\"] }\n\
2866kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n\
2867kanade-core = { path = \"crates/kanade-core\", version = \"0.48.2\" }\n\
2868kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }\n";
2869 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
2870 assert!(out.contains("anyhow = { version = \"1\" }"));
2871 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
2872 assert!(
2873 out.contains(
2874 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
2875 )
2876 );
2877 assert!(
2878 out.contains("kanade-core = { path = \"crates/kanade-core\", version = \"0.48.3\" }")
2879 );
2880 assert!(out.contains("kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }"));
2881 }
2882
2883 #[test]
2887 fn cargo_version_rewrite_bails_on_an_unrepresentable_inline_table() {
2888 let toml = "\
2889[workspace.package]\n\
2890version = \"0.1.0\"\n\
2891\n\
2892[workspace.dependencies]\n\
2893inner = { path = \"crates/inner\",\n\
2894 version = \"0.1.0\" }\n";
2895 assert!(rewrite_cargo_version(toml, "0.2.0").is_err());
2896 }
2897
2898 #[test]
2901 fn cargo_version_rewrite_recognises_a_commented_workspace_dependencies_header() {
2902 let toml = "\
2903[workspace.package]\n\
2904version = \"0.1.0\"\n\
2905\n\
2906[workspace.dependencies] # internal pins\n\
2907inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
2908 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
2909 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
2910 }
2911
2912 #[test]
2915 fn cargo_version_rewrite_bumps_a_quoted_dependency_key() {
2916 let toml = "\
2917[workspace.package]\n\
2918version = \"0.1.0\"\n\
2919\n\
2920[workspace.dependencies]\n\
2921\"inner\" = { path = \"crates/inner\", version = \"0.1.0\" }\n";
2922 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
2923 assert!(out.contains("\"inner\" = { path = \"crates/inner\", version = \"0.2.0\" }"));
2924 }
2925
2926 #[test]
2930 fn cargo_version_rewrite_bumps_a_literal_string_version_pin() {
2931 let toml = "\
2932[workspace.package]\n\
2933version = \"0.1.0\"\n\
2934\n\
2935[workspace.dependencies]\n\
2936inner = { path = 'crates/inner', version = '0.1.0' }\n";
2937 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
2938 assert!(out.contains("inner = { path = 'crates/inner', version = '0.2.0' }"));
2939 }
2940
2941 #[test]
2947 fn cargo_version_rewrite_does_not_require_the_whole_file_to_parse() {
2948 let toml = "\
2949[workspace.package]\n\
2950version = \"0.1.0\"\n\
2951\n\
2952[workspace.dependencies]\n\
2953inner = { path = \"crates/inner\", version = \"0.1.0\" }\n\
2954\n\
2955[workspace.package]\n\
2956edition = \"2024\"\n";
2957 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
2958 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
2959 assert!(
2960 toml::from_str::<toml::Value>(toml).is_err(),
2961 "the fixture itself must be invalid as a whole file, or this test proves nothing"
2962 );
2963 }
2964
2965 #[test]
2966 fn current_version_prefers_the_package_table_when_both_exist() {
2967 let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
2968 assert_eq!(current_version(toml).unwrap(), "0.8.0");
2969 }
2970
2971 #[test]
2974 fn current_version_falls_back_to_workspace_package_without_a_package_table() {
2975 let toml = "\
2976[workspace]\n\
2977members = [\"crates/a\", \"crates/b\"]\n\
2978\n\
2979[workspace.package]\n\
2980version = \"0.45.18\"\n";
2981 assert_eq!(current_version(toml).unwrap(), "0.45.18");
2982 }
2983
2984 #[test]
2985 fn coalesce_proceeds_with_nothing_pending() {
2986 assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
2987 }
2988
2989 fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
2992 PendingBump {
2993 target_version: target_version.to_owned(),
2994 level,
2995 branch: format!("chore/release-v{target_version}"),
2996 pr_url: "https://example.invalid/pull/9".to_owned(),
2997 }
2998 }
2999
3000 #[test]
3001 fn coalesce_skips_while_the_pending_target_is_still_ahead() {
3002 let pending = test_pending("0.9.0", BumpLevel::Minor);
3003 assert_eq!(
3004 coalesce(Some(&pending), "0.8.0").unwrap(),
3005 Coalesce::Skip {
3006 target_version: "0.9.0".to_owned()
3007 }
3008 );
3009 }
3010
3011 #[test]
3012 fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
3013 let pending = test_pending("0.9.0", BumpLevel::Minor);
3014 assert_eq!(
3016 coalesce(Some(&pending), "0.9.0").unwrap(),
3017 Coalesce::Proceed
3018 );
3019 assert_eq!(
3021 coalesce(Some(&pending), "1.0.0").unwrap(),
3022 Coalesce::Proceed
3023 );
3024 }
3025
3026 #[test]
3027 fn pending_action_escalates_only_for_a_more_severe_decision() {
3028 assert_eq!(
3029 pending_action(BumpLevel::Patch, BumpLevel::Patch),
3030 PendingAction::AlreadyCovered
3031 );
3032 assert_eq!(
3033 pending_action(BumpLevel::Patch, BumpLevel::Minor),
3034 PendingAction::Escalate
3035 );
3036 assert_eq!(
3037 pending_action(BumpLevel::Patch, BumpLevel::Major),
3038 PendingAction::Escalate
3039 );
3040 assert_eq!(
3041 pending_action(BumpLevel::Minor, BumpLevel::Patch),
3042 PendingAction::AlreadyCovered
3043 );
3044 assert_eq!(
3045 pending_action(BumpLevel::Major, BumpLevel::Minor),
3046 PendingAction::AlreadyCovered
3047 );
3048 assert_eq!(
3049 pending_action(BumpLevel::Major, BumpLevel::Major),
3050 PendingAction::AlreadyCovered
3051 );
3052 }
3053
3054 #[test]
3055 fn pr_state_parsing_reads_open_and_not_open() {
3056 assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
3057 assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
3058 assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
3059 }
3060
3061 #[test]
3062 fn a_lock_is_exclusive_until_dropped() {
3063 let dir = tempfile::tempdir().unwrap();
3064 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3065 let first = MarkerLock::acquire(&marker)
3066 .unwrap()
3067 .expect("first attempt takes the lock");
3068 assert!(
3069 MarkerLock::acquire(&marker).unwrap().is_none(),
3070 "a second attempt must be refused while the first holds it"
3071 );
3072 drop(first);
3073 assert!(
3074 MarkerLock::acquire(&marker).unwrap().is_some(),
3075 "dropping the guard releases the lock for the next attempt"
3076 );
3077 }
3078
3079 #[test]
3080 fn a_stale_lock_is_reclaimed() {
3081 let dir = tempfile::tempdir().unwrap();
3082 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3083 let lock_path = marker.with_extension("lock");
3084 std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
3085 std::fs::write(&lock_path, b"").unwrap();
3086 let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
3087 std::fs::OpenOptions::new()
3088 .write(true)
3089 .open(&lock_path)
3090 .unwrap()
3091 .set_modified(old)
3092 .unwrap();
3093 assert!(
3094 MarkerLock::acquire(&marker).unwrap().is_some(),
3095 "a lock older than the stale window must be reclaimed rather than block forever"
3096 );
3097 }
3098
3099 #[tokio::test]
3100 async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
3101 let dir = tempfile::tempdir().unwrap();
3102 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3103 let held = MarkerLock::acquire(&marker)
3104 .unwrap()
3105 .expect("seed the contention");
3106 let releaser = tokio::spawn(async move {
3107 tokio::time::sleep(Duration::from_millis(20)).await;
3108 drop(held);
3109 });
3110 let waited =
3111 wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
3112 .await
3113 .unwrap();
3114 assert!(
3115 waited.is_some(),
3116 "a merge landing behind another's still-running decision must not be dropped - it \
3117 must wait for that decision to finish and then judge against what it left behind"
3118 );
3119 releaser.await.unwrap();
3120 }
3121
3122 #[tokio::test]
3123 async fn a_lock_held_past_the_ceiling_gives_up() {
3124 let dir = tempfile::tempdir().unwrap();
3125 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3126 let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
3127 let waited =
3128 wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
3129 .await
3130 .unwrap();
3131 assert!(
3132 waited.is_none(),
3133 "a lock genuinely held past the ceiling must eventually give up rather than wait \
3134 forever"
3135 );
3136 }
3137
3138 #[test]
3139 fn level_between_reads_off_the_differing_digit() {
3140 assert_eq!(
3141 level_between(
3142 Version::parse("0.8.0").unwrap(),
3143 Version::parse("1.0.0").unwrap()
3144 ),
3145 Some(BumpLevel::Major)
3146 );
3147 assert_eq!(
3148 level_between(
3149 Version::parse("0.8.0").unwrap(),
3150 Version::parse("0.9.0").unwrap()
3151 ),
3152 Some(BumpLevel::Minor)
3153 );
3154 assert_eq!(
3155 level_between(
3156 Version::parse("0.8.0").unwrap(),
3157 Version::parse("0.8.1").unwrap()
3158 ),
3159 Some(BumpLevel::Patch)
3160 );
3161 assert_eq!(
3162 level_between(
3163 Version::parse("0.8.0").unwrap(),
3164 Version::parse("0.8.0").unwrap()
3165 ),
3166 None
3167 );
3168 }
3169
3170 #[test]
3171 fn open_release_pr_is_found_among_unrelated_pull_requests() {
3172 let json = r#"[
3173 {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
3174 {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
3175 ]"#;
3176 let found = parse_open_release_pr(json).unwrap();
3177 assert_eq!(
3178 found,
3179 Some((
3180 "chore/release-v0.9.0".to_owned(),
3181 "https://example.invalid/pull/2".to_owned()
3182 ))
3183 );
3184 }
3185
3186 #[test]
3187 fn no_open_release_pr_reads_as_none_not_an_error() {
3188 let json =
3189 r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
3190 assert_eq!(parse_open_release_pr(json).unwrap(), None);
3191 assert_eq!(parse_open_release_pr("[]").unwrap(), None);
3192 }
3193
3194 #[test]
3195 fn marker_round_trips_through_disk() {
3196 let dir = tempfile::tempdir().unwrap();
3197 let path = marker_path(dir.path(), Path::new("/repos/magi"));
3198 assert!(read_marker(&path).is_none());
3199
3200 let marker = test_pending("0.9.0", BumpLevel::Patch);
3201 write_marker(&path, &marker).unwrap();
3202 let read_back = read_marker(&path).unwrap();
3203 assert_eq!(read_back.target_version, "0.9.0");
3204 assert_eq!(read_back.level, BumpLevel::Patch);
3205 assert_eq!(read_back.pr_url, marker.pr_url);
3206
3207 clear_marker(&path);
3208 assert!(read_marker(&path).is_none());
3209 }
3210
3211 #[test]
3212 fn different_repos_get_different_marker_files() {
3213 let dir = tempfile::tempdir().unwrap();
3214 let a = marker_path(dir.path(), Path::new("/repos/a"));
3215 let b = marker_path(dir.path(), Path::new("/repos/b"));
3216 assert_ne!(a, b);
3217 }
3218
3219 #[test]
3223 fn a_bump_pull_requests_own_merge_does_not_retrigger() {
3224 let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
3225 assert!(
3226 is_release_only(&files),
3227 "the bump pull request's own diff must read as release-only"
3228 );
3229 }
3230
3231 #[test]
3232 fn should_release_bump_reads_only_a_merged_status() {
3233 assert!(should_release_bump(RunStatus::Merged));
3234 for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
3235 assert!(!should_release_bump(other));
3236 }
3237 }
3238
3239 #[test]
3243 fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
3244 let pr = land::PrState {
3245 url: "https://github.com/o/r/pull/1".to_owned(),
3246 number: 1,
3247 state: PrLifecycle::Merged,
3248 checks: land::Checks::Green,
3249 failing: Vec::new(),
3250 review_comments: Vec::new(),
3251 blocking: land::Blocking::No,
3252 };
3253 assert_eq!(
3254 land::decide(&pr, 0, 4, Duration::ZERO),
3255 land::Step::Done { merged: true }
3256 );
3257 assert!(should_release_bump(RunStatus::Merged));
3258 }
3259
3260 #[test]
3265 fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
3266 let pr = land::PrState {
3267 url: "https://github.com/o/r/pull/2".to_owned(),
3268 number: 2,
3269 state: PrLifecycle::Open,
3270 checks: land::Checks::Green,
3271 failing: Vec::new(),
3272 review_comments: Vec::new(),
3273 blocking: land::Blocking::No,
3274 };
3275 assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
3276 assert!(should_release_bump(RunStatus::Merged));
3279 }
3280
3281 #[test]
3284 fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
3285 let argv = land::merge_argv(3, "feat: something");
3286 let outcome = land::merged_after_all(
3287 &argv,
3288 "could not determine current branch: not on any branch",
3289 Some(PrLifecycle::Merged),
3290 );
3291 assert!(outcome.is_some(), "the forge's confirmation must win");
3292 assert!(should_release_bump(RunStatus::Merged));
3293
3294 assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
3297 assert!(land::merged_after_all(&argv, "network error", None).is_none());
3298 }
3299
3300 #[test]
3302 fn a_close_or_a_give_up_does_not_trigger_a_bump() {
3303 let pr = land::PrState {
3304 url: "https://github.com/o/r/pull/4".to_owned(),
3305 number: 4,
3306 state: PrLifecycle::Closed,
3307 checks: land::Checks::Green,
3308 failing: Vec::new(),
3309 review_comments: Vec::new(),
3310 blocking: land::Blocking::No,
3311 };
3312 assert_eq!(
3313 land::decide(&pr, 0, 4, Duration::ZERO),
3314 land::Step::Done { merged: false }
3315 );
3316 assert!(!should_release_bump(RunStatus::Blocked));
3317 }
3318}