1use camino::{Utf8Path, Utf8PathBuf};
28use serde::Serialize;
29
30use crate::cli::integrate::IntegrateArgs;
31use crate::diagnostic::{Diagnostic, Reason};
32use crate::error::RkError;
33use crate::integrate::{self, Entry, Ledger};
34use crate::landing::{Integration, MergeForm};
35use crate::maintenance::{GIT_HOOK_VARS, last_line};
36use crate::output::Output;
37use crate::requirements::Tool;
38
39#[derive(Debug, Serialize)]
41struct Report {
42 schema: &'static str,
44 mode: &'static str,
46 target: String,
48 integration: &'static str,
50 authority_source: &'static str,
52 merge_form: &'static str,
54 branch: String,
56 trunk: String,
58 seat: String,
60 trunk_before: String,
62 #[serde(skip_serializing_if = "Option::is_none")]
65 trunk_commit: Option<String>,
66 steps: Vec<String>,
68 next: Vec<String>,
70}
71
72pub fn run(args: &IntegrateArgs) -> Result<(), RkError> {
80 let out = Output::new(args.json);
81 let target = &args.target;
82 let rust = rust_automatic(target);
88 let git_unmet = crate::requirements::unmet(&[Tool::Git], None);
89 if !git_unmet.is_empty() {
90 let mut found = git_unmet;
91 let mut tools = vec![Tool::Git];
92 if rust {
93 tools.push(Tool::Cargo);
94 found.extend(crate::requirements::check(
95 Tool::Cargo,
96 Some(target.as_std_path()),
97 ));
98 }
99 return Err(crate::requirements::refusal("rk integrate", &tools, &found));
100 }
101 let trunk = crate::config::trunk_of(target.as_std_path())?;
102
103 let (integration, authority_source) = authority(args, target)?;
104 let merge_form = recorded_merge_form(target)?;
105 let scope_required = recorded_scope_rule(target)?;
106 if let Some(reason) = integrate::refuse_branch_name(&args.branch, &trunk) {
107 return Err(refuse(Reason::Usage, reason));
108 }
109
110 let git_dir = common_git_dir(target)?;
111 let seats = seats(target)?;
112 let seat = match seat_for(&seats, &args.branch, target) {
113 Ok(seat) => seat,
114 Err(error) => {
115 return Err(left_detached(&seats, &args.branch, target, &trunk).unwrap_or(error));
116 }
117 };
118 if rust {
119 let unmet = crate::requirements::unmet(&[Tool::Git, Tool::Cargo], Some(seat.as_std_path()));
120 if !unmet.is_empty() {
121 return Err(crate::requirements::refusal(
122 "rk integrate",
123 &[Tool::Git, Tool::Cargo],
124 &unmet,
125 ));
126 }
127 }
128 let dirty = is_dirty(&seat)?;
129 if dirty {
130 return Err(refuse(
131 Reason::StateDrift,
132 format!(
133 "{seat} has uncommitted changes, so the gate would judge a tree nobody reviewed"
134 ),
135 ));
136 }
137
138 let run = LocalRun {
139 target,
140 git_dir: &git_dir,
141 seat: &seat,
142 seats: &seats,
143 trunk: &trunk,
144 authority_source,
145 merge_form,
146 scope_required,
147 };
148 match (integration, merge_form) {
149 (Integration::Forge, _) => forge_path(
150 args,
151 out,
152 &seat,
153 &trunk,
154 authority_source,
155 merge_form,
156 scope_required,
157 ),
158 (Integration::Local, MergeForm::Squash) => local_path(args, out, &run),
159 (Integration::Local, MergeForm::Rebase) => rebase_path(args, out, &run),
160 }
161}
162
163struct LocalRun<'a> {
165 target: &'a Utf8Path,
166 git_dir: &'a Utf8Path,
167 seat: &'a Utf8Path,
168 seats: &'a [crate::worktree::Worktree],
169 trunk: &'a str,
170 authority_source: &'static str,
171 merge_form: MergeForm,
172 scope_required: bool,
175}
176
177fn authority(
189 args: &IntegrateArgs,
190 target: &Utf8Path,
191) -> Result<(Integration, &'static str), RkError> {
192 if args.local {
193 return Ok((Integration::Local, "flag"));
194 }
195 if args.forge {
196 return Ok((Integration::Forge, "flag"));
197 }
198 let recorded = crate::landing::manifest::load(target)?.map(|record| record.git.integration);
199 Ok(recorded.map_or(
200 (crate::landing::manifest::integration_forge(), "default"),
201 |mode| (mode, "record"),
202 ))
203}
204
205fn recorded_merge_form(target: &Utf8Path) -> Result<MergeForm, RkError> {
213 Ok(crate::landing::manifest::load(target)?
214 .map_or_else(crate::landing::manifest::merge_form_squash, |record| {
215 record.git.merge_form
216 }))
217}
218
219fn recorded_scope_rule(target: &Utf8Path) -> Result<bool, RkError> {
225 Ok(crate::landing::manifest::load(target)?
226 .is_none_or(|record| record.profile.release.mode != crate::profile::ReleaseMode::None))
227}
228
229fn forge_path(
231 args: &IntegrateArgs,
232 out: Output,
233 seat: &Utf8Path,
234 trunk: &str,
235 authority_source: &'static str,
236 merge_form: MergeForm,
237 scope_required: bool,
238) -> Result<(), RkError> {
239 let mut steps = Vec::new();
240 if args.apply {
241 let pushed = git(seat, &["push", "--set-upstream", "origin", &args.branch])?;
245 if !pushed.status.success() {
246 return Err(refuse(
247 Reason::RemoteConflict,
248 format!(
249 "pushing {} refused: {}",
250 args.branch,
251 last_line(&pushed.stderr)
252 ),
253 ));
254 }
255 steps.push(format!("pushed {} to origin", args.branch));
256 } else {
257 steps.push(format!("would push {} to origin", args.branch));
258 }
259 let next = request_commands(
260 &origin_url(seat),
261 trunk,
262 &args.branch,
263 merge_form,
264 scope_required,
265 );
266 for line in &steps {
267 out.result_line(line);
268 }
269 out.emit(&Report {
270 schema: "rk.integrate/1",
271 mode: if args.apply { "apply" } else { "preview" },
272 target: args.target.to_string(),
273 integration: Integration::Forge.as_str(),
274 authority_source,
275 merge_form: merge_form.as_str(),
276 branch: args.branch.clone(),
277 trunk: trunk.to_owned(),
278 seat: seat.to_string(),
279 trunk_before: String::new(),
280 trunk_commit: None,
281 steps,
282 next: next.clone(),
283 })?;
284 out.next(&next);
285 Ok(())
286}
287
288fn origin_url(seat: &Utf8Path) -> String {
290 git(seat, &["remote", "get-url", "origin"])
291 .ok()
292 .filter(|answer| answer.status.success())
293 .map(|answer| String::from_utf8_lossy(&answer.stdout).trim().to_owned())
294 .unwrap_or_default()
295}
296
297fn request_commands(
310 remote: &str,
311 trunk: &str,
312 branch: &str,
313 form: MergeForm,
314 scope_required: bool,
315) -> Vec<String> {
316 let squash = form == MergeForm::Squash;
317 let create = if remote.contains("gitlab") {
318 format!(
319 "glab mr create --source-branch {branch} --target-branch {trunk}{}",
320 if squash { " --squash-before-merge" } else { "" }
321 )
322 } else {
323 format!("gh pr create --base {trunk} --head {branch}")
324 };
325 let reaches = match (squash, scope_required) {
326 (true, true) => {
327 "the title is the trunk's commit message, so it is a scoped Conventional Commit"
328 }
329 (true, false) => {
330 "the title is the trunk's commit message, so it is a Conventional Commit, whose scope is preferred and not required"
331 }
332 (false, true) => {
333 "every commit of the branch reaches the trunk with its own message, so each one passes the commit-msg judgment: a scoped Conventional Commit with no guarded content"
334 }
335 (false, false) => {
336 "every commit of the branch reaches the trunk with its own message, so each one passes the commit-msg judgment: a Conventional Commit, whose scope is preferred and not required, with no guarded content"
337 }
338 };
339 vec![
340 create,
341 reaches.to_owned(),
342 "the body is yours; rk message --check --kind body judges it before you post it".to_owned(),
343 ]
344}
345
346fn rebase_onto(run: &LocalRun<'_>, branch: &str, onto: &str) -> Result<(), RkError> {
359 let rebased = git(
360 run.seat,
361 &REBASE_ARGS
362 .iter()
363 .copied()
364 .chain([onto])
365 .collect::<Vec<_>>(),
366 )?;
367 if !rebased.status.success() {
368 let _ = git(run.seat, &["rebase", "--abort"]);
369 return Err(refuse(
370 Reason::StateDrift,
371 format!(
372 "{branch} does not rebase onto {} cleanly: {}",
373 integrate::short(onto),
374 last_line(&rebased.stderr)
375 ),
376 ));
377 }
378 Ok(())
379}
380
381const REBASE_ARGS: [&str; 5] = [
385 "rebase",
386 "--no-rebase-merges",
387 "--no-update-refs",
388 "--no-autosquash",
389 "--no-autostash",
390];
391
392fn refuse_merges_in_range(run: &LocalRun<'_>, from: &str, tip: &str) -> Result<(), RkError> {
400 let listed = git(
401 run.seat,
402 &["rev-list", "--merges", &format!("{from}..{tip}")],
403 )?;
404 if !listed.status.success() {
405 return Err(refuse(
406 Reason::StateDrift,
407 format!(
408 "the range {}..{} could not be read for merge commits: {}",
409 integrate::short(from),
410 integrate::short(tip),
411 last_line(&listed.stderr)
412 ),
413 ));
414 }
415 let merges: Vec<String> = String::from_utf8_lossy(&listed.stdout)
416 .lines()
417 .filter(|line| !line.is_empty())
418 .map(integrate::short)
419 .collect();
420 if merges.is_empty() {
421 return Ok(());
422 }
423 Err(refuse(
424 Reason::StateDrift,
425 format!(
426 "the rebased range {}..{} still holds the merge commit {}, and the trunk takes no merge commit, so nothing was published",
427 integrate::short(from),
428 integrate::short(tip),
429 merges.join(", ")
430 ),
431 ))
432}
433
434fn preview(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
440 let mut steps = Vec::new();
441 let trunk_before = rev_parse(run.seat, run.trunk)?;
442 warn_if_uncounted(
443 out,
444 run,
445 args.message.as_deref().unwrap_or_default(),
446 &[&format!("{trunk_before}...{}", args.branch)],
447 true,
448 );
449 steps.push("no fetch and no lock: a preview refreshes nothing".to_owned());
450 steps.push(format!(
451 "would rebase {} onto {}, or onto whatever the fetch brings",
452 args.branch,
453 integrate::short(&trunk_before)
454 ));
455 steps.push("would run the pre-merge-commit hook in the seat".to_owned());
456 steps.push(format!("would write one squash commit onto {}", run.trunk));
457 report(
458 args,
459 out,
460 run,
461 &trunk_before,
462 None,
463 steps,
464 &[format!(
465 "rk integrate {} --target {} --apply performs it",
466 args.branch, run.target
467 )],
468 )
469}
470
471fn local_path(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
479 let message = args.message.as_deref().unwrap_or_default();
480 refuse_message(run.seat, message, run.scope_required)?;
481 let mut steps = Vec::new();
482
483 if !args.apply {
484 return preview(args, out, run);
485 }
486
487 let _held = crate::landing::lock::acquire(run.git_dir)?;
490
491 let ledger_path = run.git_dir.join(integrate::LEDGER_PATH);
495 let mut ledger = read_ledger(&ledger_path)?;
496
497 refresh_trunk(run, &mut steps)?;
498
499 let trunk_before = rev_parse(run.seat, run.trunk)?;
500
501 rebase_onto(run, &args.branch, &trunk_before)?;
504 steps.push(format!(
505 "rebased {} onto {}",
506 args.branch,
507 integrate::short(&trunk_before)
508 ));
509
510 let branch_tip = rev_parse(run.seat, &args.branch)?;
515
516 warn_if_uncounted(out, run, message, &[&trunk_before, &branch_tip], false);
519
520 let answer = gate(run.seat, &args.branch, &trunk_before, &branch_tip)?;
523 judge_gate(out, run, &args.branch, answer)?;
524 steps.push("the pre-merge-commit hook passed".to_owned());
525
526 let now = rev_parse(run.seat, &args.branch)?;
532 if now != branch_tip {
533 return Err(refuse(
534 Reason::StateDrift,
535 format!(
536 "{} moved from {} to {} while the gate ran, so the gate judged a tree that is no longer the branch's",
537 args.branch,
538 integrate::short(&branch_tip),
539 integrate::short(&now)
540 ),
541 ));
542 }
543 let commit = build_squash(run, &branch_tip, &trunk_before, message)?;
544 ledger.record(Entry {
553 branch: args.branch.clone(),
554 branch_tip,
555 trunk_commit: commit.clone(),
556 at: crate::landing::manifest::now(),
557 });
558 write_ledger(&ledger_path, &ledger)?;
559
560 let drift = publish(run, &commit, &trunk_before)?;
561 steps.push(format!(
562 "{} now carries {}",
563 run.trunk,
564 integrate::short(&commit)
565 ));
566 steps.push("recorded the integration".to_owned());
567 if let Some(drift) = &drift {
568 steps.push(drift.step(run.trunk));
569 }
570
571 report(
572 args,
573 out,
574 run,
575 &trunk_before,
576 Some(commit.clone()),
577 steps,
578 &[
579 format!(
580 "git -C {} push origin {} pushes the trunk; it is a fast-forward and never a force",
581 run.target, run.trunk
582 ),
583 format!(
584 "rk worktree prune --target {} retires the seat, then its branch",
585 run.target
586 ),
587 ],
588 )?;
589 drift.map_or(Ok(()), |drift| Err(drift.into_error(run.trunk, &commit)))
590}
591
592fn rebase_path(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
603 refuse_message_under_rebase(args)?;
604 if !args.apply {
605 return rebase_preview(args, out, run);
606 }
607 let mut steps = Vec::new();
608
609 let _held = crate::landing::lock::acquire(run.git_dir)?;
610 let ledger_path = run.git_dir.join(integrate::LEDGER_PATH);
611 let mut ledger = read_ledger(&ledger_path)?;
612
613 refresh_trunk(run, &mut steps)?;
614
615 let trunk_before = rev_parse(run.seat, run.trunk)?;
616
617 rebase_onto(run, &args.branch, &trunk_before)?;
618 steps.push(format!(
619 "rebased {} onto {}",
620 args.branch,
621 integrate::short(&trunk_before)
622 ));
623
624 let branch_tip = rev_parse(run.seat, &args.branch)?;
627 let commits = branch_commits(run.seat, &trunk_before, &branch_tip, &args.branch)?;
628 refuse_commit_messages(run.seat, &commits, run.scope_required)?;
629 steps.push(format!(
630 "judged the message of each of {} commit{}",
631 commits.len(),
632 if commits.len() == 1 { "" } else { "s" }
633 ));
634
635 let answer = gate(run.seat, &args.branch, &trunk_before, &branch_tip)?;
636 judge_gate(out, run, &args.branch, answer)?;
637 steps.push("the pre-merge-commit hook passed".to_owned());
638
639 let now = rev_parse(run.seat, &args.branch)?;
640 if now != branch_tip {
641 return Err(refuse(
642 Reason::StateDrift,
643 format!(
644 "{} moved from {} to {} while the gate ran, so the gate judged a tree that is no longer the branch's",
645 args.branch,
646 integrate::short(&branch_tip),
647 integrate::short(&now)
648 ),
649 ));
650 }
651
652 refuse_merges_in_range(run, &trunk_before, &branch_tip)?;
655
656 ledger.record(Entry {
661 branch: args.branch.clone(),
662 branch_tip: branch_tip.clone(),
663 trunk_commit: branch_tip.clone(),
664 at: crate::landing::manifest::now(),
665 });
666 write_ledger(&ledger_path, &ledger)?;
667
668 let drift = publish(run, &branch_tip, &trunk_before)?;
669 steps.push(format!(
670 "{} now carries {} at {}, with no new commit",
671 run.trunk,
672 args.branch,
673 integrate::short(&branch_tip)
674 ));
675 steps.push("recorded the integration".to_owned());
676 if let Some(drift) = &drift {
677 steps.push(drift.step(run.trunk));
678 }
679
680 report(
681 args,
682 out,
683 run,
684 &trunk_before,
685 Some(branch_tip.clone()),
686 steps,
687 &[
688 format!(
689 "git -C {} push origin {} pushes the trunk; it is a fast-forward and never a force",
690 run.target, run.trunk
691 ),
692 format!(
693 "rk worktree prune --target {} retires the seat, then its branch",
694 run.target
695 ),
696 ],
697 )?;
698 drift.map_or(
699 Ok(()),
700 |drift| Err(drift.into_error(run.trunk, &branch_tip)),
701 )
702}
703
704fn rebase_preview(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
709 let trunk_before = rev_parse(run.seat, run.trunk)?;
710 let branch_tip = rev_parse(run.seat, &args.branch)?;
711 let commits = branch_commits(run.seat, &trunk_before, &branch_tip, &args.branch)?;
712 refuse_commit_messages(run.seat, &commits, run.scope_required)?;
713 let steps = vec![
714 "no fetch and no lock: a preview refreshes nothing".to_owned(),
715 format!(
716 "would rebase {} onto {}, or onto whatever the fetch brings",
717 args.branch,
718 integrate::short(&trunk_before)
719 ),
720 "would run the pre-merge-commit hook in the seat".to_owned(),
721 format!(
722 "would move {} to the tip of {}, carrying its {} commit{} with their own messages and writing no new commit",
723 run.trunk,
724 args.branch,
725 commits.len(),
726 if commits.len() == 1 { "" } else { "s" }
727 ),
728 ];
729 report(
730 args,
731 out,
732 run,
733 &trunk_before,
734 None,
735 steps,
736 &[format!(
737 "rk integrate {} --target {} --apply performs it",
738 args.branch, run.target
739 )],
740 )
741}
742
743fn refuse_message_under_rebase(args: &IntegrateArgs) -> Result<(), RkError> {
749 if args.message.is_none() {
750 return Ok(());
751 }
752 Err(RkError::refusal(
753 Diagnostic::new(
754 Reason::MergeFormMismatch,
755 "-m names a trunk message, and the recorded merge form is rebase: every commit of the branch reaches the trunk with its own message, and no commit is written to carry this one",
756 )
757 .expected("no -m under git.merge_form = \"rebase\"")
758 .action(format!(
759 "rk integrate {} --apply integrates without it; git rebase -i on the branch rewords a commit",
760 args.branch
761 ))
762 .target_state("unchanged; the trunk stands where it stood"),
763 ))
764}
765
766struct BranchCommit {
768 id: String,
769 message: String,
770}
771
772fn branch_commits(
777 seat: &Utf8Path,
778 trunk: &str,
779 tip: &str,
780 branch: &str,
781) -> Result<Vec<BranchCommit>, RkError> {
782 let listed = git(seat, &["rev-list", "--reverse", &format!("{trunk}..{tip}")])?;
783 if !listed.status.success() {
784 return Err(refuse(
785 Reason::StateDrift,
786 format!(
787 "the commits of {branch} could not be listed: {}",
788 last_line(&listed.stderr)
789 ),
790 ));
791 }
792 let ids: Vec<String> = String::from_utf8_lossy(&listed.stdout)
793 .lines()
794 .filter(|line| !line.is_empty())
795 .map(str::to_owned)
796 .collect();
797 if ids.is_empty() {
798 return Err(refuse(
799 Reason::StateDrift,
800 format!(
801 "{branch} carries no commit {} does not already carry, so there is nothing to integrate",
802 integrate::short(trunk)
803 ),
804 ));
805 }
806 ids.into_iter()
807 .map(|id| {
808 let shown = git(seat, &["log", "-1", "--format=%B", &id])?;
809 if !shown.status.success() {
810 return Err(refuse(
811 Reason::StateDrift,
812 format!(
813 "the message of {} could not be read: {}",
814 integrate::short(&id),
815 last_line(&shown.stderr)
816 ),
817 ));
818 }
819 Ok(BranchCommit {
820 message: String::from_utf8_lossy(&shown.stdout).into_owned(),
821 id,
822 })
823 })
824 .collect()
825}
826
827fn refuse_commit_messages(
837 at: &Utf8Path,
838 commits: &[BranchCommit],
839 scope_required: bool,
840) -> Result<(), RkError> {
841 for commit in commits {
842 let subject = commit.message.lines().next().unwrap_or("").trim();
843 let named = format!("commit {}", integrate::short(&commit.id));
844 if subject.is_empty() {
845 return Err(refuse(
846 Reason::Usage,
847 format!(
848 "{named} carries no message, and every commit reaches the trunk with its own"
849 ),
850 ));
851 }
852 if let Some(reason) = misshapen_subject(subject, scope_required) {
853 return Err(refuse(Reason::Usage, format!("{named}: {reason}")));
854 }
855 let (findings, _) = crate::commands::message::judge(
856 &commit.message,
857 crate::cli::message::MessageKind::Commit,
858 at,
859 subject,
860 crate::commands::message::Judgment {
861 exempt: crate::commands::message::exempt_title(subject),
862 scope_required,
863 },
864 );
865 if findings.is_empty() {
866 continue;
867 }
868 let listed: Vec<String> = findings
869 .iter()
870 .map(|finding| format!("{}:{} {}", finding.class, finding.line, finding.detail))
871 .collect();
872 return Err(refuse(
873 Reason::Usage,
874 format!(
875 "{named} '{subject}' carries {} finding{} the landed commit-msg stage would refuse, and the trunk move fires no hook: {}",
876 findings.len(),
877 if findings.len() == 1 { "" } else { "s" },
878 listed.join("; ")
879 ),
880 ));
881 }
882 Ok(())
883}
884
885fn build_squash(
892 run: &LocalRun<'_>,
893 branch_tip: &str,
894 parent: &str,
895 message: &str,
896) -> Result<String, RkError> {
897 let tree = rev_parse(run.seat, &format!("{branch_tip}^{{tree}}"))?;
898 let built = git(
899 run.seat,
900 &["commit-tree", &tree, "-p", parent, "-m", message],
901 )?;
902 if !built.status.success() {
903 return Err(refuse(
904 Reason::Internal,
905 format!(
906 "the squash commit could not be built: {}",
907 last_line(&built.stderr)
908 ),
909 ));
910 }
911 Ok(String::from_utf8_lossy(&built.stdout).trim().to_owned())
912}
913
914fn refresh_trunk(run: &LocalRun<'_>, steps: &mut Vec<String>) -> Result<(), RkError> {
921 let named = git(run.seat, &["remote", "get-url", "origin"])?;
927 if !named.status.success() {
928 steps.push("no origin remote; the local trunk stands alone".to_owned());
929 return Ok(());
930 }
931 let fetched = git(run.seat, &["fetch", "--quiet", "origin"])?;
932 if !fetched.status.success() {
933 return Err(refuse(
934 Reason::ForgeTemporary,
935 format!(
936 "origin is configured and did not answer, so the trunk could not be refreshed: {}",
937 last_line(&fetched.stderr)
938 ),
939 ));
940 }
941 steps.push("fetched origin".to_owned());
942 let Some(remote) = rev_parse(run.seat, &format!("refs/remotes/origin/{}", run.trunk)).ok()
943 else {
944 steps.push(format!(
945 "origin carries no {} yet; the local trunk stands alone",
946 run.trunk
947 ));
948 return Ok(());
949 };
950 let local = rev_parse(run.seat, run.trunk)?;
951 let state = integrate::trunk_state(
952 local == remote,
953 is_ancestor(run.seat, &local, &remote),
954 is_ancestor(run.seat, &remote, &local),
955 );
956 if let Some(reason) = integrate::refuse_trunk_state(state) {
957 return Err(refuse(Reason::RemoteConflict, reason));
958 }
959 match state {
960 integrate::TrunkState::Behind => {
961 fast_forward_trunk(run, &remote, &local)?;
962 steps.push(format!(
963 "fast-forwarded {} to origin/{}",
964 run.trunk, run.trunk
965 ));
966 }
967 integrate::TrunkState::Ahead => {
968 steps.push(format!(
969 "{} carries integrations nobody pushed yet",
970 run.trunk
971 ));
972 }
973 integrate::TrunkState::Level | integrate::TrunkState::Diverged => {}
974 }
975 Ok(())
976}
977
978fn fast_forward_trunk(run: &LocalRun<'_>, to: &str, from: &str) -> Result<(), RkError> {
986 let PostPublication::Unsettled(unsettled) = trunk_move(run, to, from, "fast-forward")? else {
987 return Ok(());
988 };
989 Err(unsettled.into_refresh_error(run.trunk, from, to))
990}
991
992fn publish(run: &LocalRun<'_>, commit: &str, expected: &str) -> Result<Option<Unsettled>, RkError> {
999 Ok(match trunk_move(run, commit, expected, "integration")? {
1000 PostPublication::Confirmed => None,
1001 PostPublication::Unsettled(unsettled) => Some(unsettled),
1002 })
1003}
1004
1005#[derive(Debug, Clone, PartialEq, Eq)]
1013enum PostPublication {
1014 Confirmed,
1017 Unsettled(Unsettled),
1019}
1020
1021#[derive(Debug, Clone, PartialEq, Eq)]
1023enum Unsettled {
1024 Raced(Drift),
1027 Unconfirmed {
1029 expected: String,
1031 reason: String,
1033 },
1034}
1035
1036impl Unsettled {
1037 fn step(&self, trunk: &str) -> String {
1039 match self {
1040 Self::Raced(drift) => drift.step(trunk),
1041 Self::Unconfirmed { expected, reason } => format!(
1042 "{trunk}'s move from the observed {} is not confirmed: {reason}",
1043 integrate::short(expected)
1044 ),
1045 }
1046 }
1047
1048 fn into_error(self, trunk: &str, published: &str) -> RkError {
1052 match self {
1053 Self::Raced(drift) => drift.into_error(trunk, published),
1054 Self::Unconfirmed { expected, reason } => {
1055 unconfirmed_error(trunk, &expected, published, &reason)
1056 }
1057 }
1058 }
1059
1060 fn into_refresh_error(self, trunk: &str, from: &str, to: &str) -> RkError {
1064 let message = match &self {
1065 Self::Raced(drift) => format!(
1066 "{trunk} was fast-forwarded to its remote tip {}, and its last move went from {} to {} where this run observed {}: a writer outside rk moved it at the same time, so no integration was published",
1067 integrate::short(to),
1068 integrate::short(&drift.found_old),
1069 integrate::short(&drift.found_new),
1070 integrate::short(from)
1071 ),
1072 Self::Unconfirmed { reason, .. } => format!(
1073 "{trunk} was fast-forwarded to its remote tip {}, but rk could not confirm that the move started at the observed {}: {reason}; no integration was published",
1074 integrate::short(to),
1075 integrate::short(from)
1076 ),
1077 };
1078 RkError::refusal(
1079 Diagnostic::new(Reason::StateDrift, message)
1080 .action(format!(
1081 "read git reflog {trunk} and git log {}..{}, then run the integration again",
1082 integrate::short(from),
1083 integrate::short(to)
1084 ))
1085 .target_state(format!(
1086 "{trunk} was refreshed to its remote tip {}, with no rollback; no integration was published",
1087 integrate::short(to)
1088 )),
1089 )
1090 }
1091}
1092
1093fn unconfirmed_error(trunk: &str, expected: &str, published: &str, reason: &str) -> RkError {
1095 let expected = integrate::short(expected);
1096 let published = integrate::short(published);
1097 RkError::check_failed(
1098 Diagnostic::new(
1099 Reason::StateDrift,
1100 format!(
1101 "{trunk} now stands at the published {published}, but rk could not confirm that the move started at the observed {expected}: {reason}"
1102 ),
1103 )
1104 .expected(format!("a confirmed move of {trunk} from {expected} to {published}"))
1105 .action(format!(
1106 "read git reflog {trunk} and git log {expected}..{published}, and decide whether anything else moved {trunk}; rk moves nothing back"
1107 ))
1108 .target_state(format!(
1109 "{trunk} is published at {published}, with no rollback and no reset; the staged evidence names {published} and the trunk reaches it"
1110 )),
1111 )
1112}
1113
1114#[derive(Debug, Clone, PartialEq, Eq)]
1116struct Drift {
1117 expected: String,
1119 found_old: String,
1121 found_new: String,
1123}
1124
1125impl Drift {
1126 fn step(&self, trunk: &str) -> String {
1128 format!(
1129 "{trunk}'s last move went from {} to {}, where this run observed {}",
1130 integrate::short(&self.found_old),
1131 integrate::short(&self.found_new),
1132 integrate::short(&self.expected)
1133 )
1134 }
1135
1136 fn into_error(self, trunk: &str, published: &str) -> RkError {
1140 RkError::check_failed(
1141 Diagnostic::new(
1142 Reason::StateDrift,
1143 format!(
1144 "{trunk} now stands at the published {}, and its last move went from {} to {}, not from the observed {}: a writer outside rk moved it during the publication",
1145 integrate::short(published),
1146 integrate::short(&self.found_old),
1147 integrate::short(&self.found_new),
1148 integrate::short(&self.expected)
1149 ),
1150 )
1151 .expected(format!(
1152 "a move of {trunk} from the observed {} to the published {}",
1153 integrate::short(&self.expected),
1154 integrate::short(published)
1155 ))
1156 .action(format!(
1157 "read the commits between the observed and the found starting commit, git log {}..{}, and decide whether they belong on {trunk}; rk moves nothing back",
1158 integrate::short(&self.expected),
1159 integrate::short(&self.found_old)
1160 ))
1161 .target_state(format!(
1162 "{trunk} is published at {}, with no rollback and no reset; the staged evidence names {} and the trunk reaches it",
1163 integrate::short(published),
1164 integrate::short(published)
1165 )),
1166 )
1167 }
1168}
1169
1170fn trunk_move(
1187 run: &LocalRun<'_>,
1188 to: &str,
1189 expected: &str,
1190 what: &str,
1191) -> Result<PostPublication, RkError> {
1192 let observed = run
1193 .seats
1194 .iter()
1195 .find(|seat| seat.branch.as_deref() == Some(run.trunk))
1196 .map(|seat| seat.path.clone());
1197 let live_seats = seats(run.target)?;
1198 let holder = live_seats
1199 .iter()
1200 .find(|seat| seat.branch.as_deref() == Some(run.trunk));
1201 if let Some(changed) = holder_change(
1202 run.trunk,
1203 observed.as_deref(),
1204 holder.map(|seat| seat.path.as_path()),
1205 what,
1206 ) {
1207 return Err(refuse(Reason::StateDrift, changed));
1208 }
1209 let reference = format!("refs/heads/{}", run.trunk);
1210 let live = rev_parse(run.seat, &reference)?;
1211 if live != expected {
1212 return Err(moved(run.trunk, expected, &live));
1213 }
1214 let Some(holder) = holder else {
1215 let swapped = git(run.seat, &["update-ref", &reference, to, expected])?;
1216 if !swapped.status.success() {
1217 let now =
1218 rev_parse(run.seat, &reference).unwrap_or_else(|_| "an unreadable tip".to_owned());
1219 return Err(moved(run.trunk, expected, &now));
1220 }
1221 return Ok(PostPublication::Confirmed);
1222 };
1223 if is_dirty(&holder.path)? {
1224 return Err(refuse(
1225 Reason::StateDrift,
1226 format!(
1227 "{} has the trunk checked out and carries uncommitted changes, so the {what} would leave it behind its own HEAD",
1228 holder.path
1229 ),
1230 ));
1231 }
1232 let merged = git_in_c_locale(
1236 &holder.path,
1237 &[
1238 "-c",
1239 "core.logAllRefUpdates=always",
1240 "-c",
1241 "core.abbrev=no",
1242 "merge",
1243 "--ff-only",
1244 to,
1245 ],
1246 )?;
1247 if !merged.status.success() {
1248 return Err(refuse(
1249 Reason::StateDrift,
1250 format!(
1251 "the {what} is not a fast-forward of {}, so nothing was published: {}",
1252 holder.path,
1253 last_line(&merged.stderr)
1254 ),
1255 ));
1256 }
1257 let report = String::from_utf8_lossy(&merged.stdout).into_owned();
1258 Ok(confirm_move(run, &reference, expected, to, &report))
1259}
1260
1261fn confirm_move(
1274 run: &LocalRun<'_>,
1275 reference: &str,
1276 expected: &str,
1277 to: &str,
1278 merge_report: &str,
1279) -> PostPublication {
1280 let reflog = reflog_transition(run, reference);
1281 let reported = parse_updating(merge_report, expected.len());
1282 judge_move(expected, to, reflog, reported)
1283}
1284
1285fn judge_move(
1287 expected: &str,
1288 to: &str,
1289 reflog: Result<(String, String), String>,
1290 reported: Result<(String, String), String>,
1291) -> PostPublication {
1292 let unconfirmed = |reason: String| {
1293 PostPublication::Unsettled(Unsettled::Unconfirmed {
1294 expected: expected.to_owned(),
1295 reason,
1296 })
1297 };
1298 let transition = match (reflog, reported) {
1299 (Ok(logged), Ok(said)) if logged != said => {
1300 return unconfirmed(format!(
1301 "the reflog shows {}..{} and the fast-forward reported {}..{}",
1302 integrate::short(&logged.0),
1303 integrate::short(&logged.1),
1304 integrate::short(&said.0),
1305 integrate::short(&said.1)
1306 ));
1307 }
1308 (Ok(logged), _) => logged,
1309 (Err(_), Ok(said)) => said,
1310 (Err(logged), Err(said)) => {
1311 return unconfirmed(format!("{logged}, and {said}"));
1312 }
1313 };
1314 let (old, new) = transition;
1315 if new != to {
1316 return unconfirmed(format!(
1317 "the move read back ends at {}, not at the published {}",
1318 integrate::short(&new),
1319 integrate::short(to)
1320 ));
1321 }
1322 if old == expected {
1323 return PostPublication::Confirmed;
1324 }
1325 PostPublication::Unsettled(Unsettled::Raced(Drift {
1326 expected: expected.to_owned(),
1327 found_old: old,
1328 found_new: new,
1329 }))
1330}
1331
1332fn full_name(name: &str, len: usize) -> bool {
1334 name.len() == len && name.bytes().all(|byte| byte.is_ascii_hexdigit())
1335}
1336
1337fn reflog_transition(run: &LocalRun<'_>, reference: &str) -> Result<(String, String), String> {
1345 let path = run.git_dir.join("logs").join(reference);
1346 match std::fs::read_to_string(path.as_std_path()) {
1347 Ok(text) => {
1348 let line = text.lines().last().unwrap_or_default();
1349 let mut fields = line.split_whitespace();
1350 match (fields.next(), fields.next()) {
1351 (Some(old), Some(new))
1352 if full_name(old, new.len()) && full_name(new, old.len()) =>
1353 {
1354 Ok((old.to_owned(), new.to_owned()))
1355 }
1356 _ => Err(format!("the reflog file {path} holds no readable entry")),
1357 }
1358 }
1359 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1360 let listed = git(
1361 run.seat,
1362 &["reflog", "show", "--format=%H", "-n", "2", reference],
1363 )
1364 .map_err(|error| format!("git reflog did not run: {error}"))?;
1365 if !listed.status.success() {
1366 return Err(format!(
1367 "git reflog show {reference} failed: {}",
1368 last_line(&listed.stderr)
1369 ));
1370 }
1371 let text = String::from_utf8_lossy(&listed.stdout).into_owned();
1372 let mut lines = text.lines();
1373 match (lines.next(), lines.next()) {
1374 (Some(new), Some(old))
1375 if full_name(new, old.len()) && full_name(old, new.len()) =>
1376 {
1377 Ok((old.to_owned(), new.to_owned()))
1378 }
1379 _ => Err(format!(
1380 "the reflog of {reference} holds fewer than two readable entries"
1381 )),
1382 }
1383 }
1384 Err(error) => Err(format!("the reflog file {path} could not be read: {error}")),
1385 }
1386}
1387
1388fn parse_updating(report: &str, len: usize) -> Result<(String, String), String> {
1393 let lines: Vec<&str> = report
1394 .lines()
1395 .filter_map(|line| line.strip_prefix("Updating "))
1396 .collect();
1397 let [line] = lines.as_slice() else {
1398 return Err(if lines.is_empty() {
1399 "the fast-forward reported no Updating line".to_owned()
1400 } else {
1401 "the fast-forward reported more than one Updating line".to_owned()
1402 });
1403 };
1404 let Some((old, new)) = line.trim().split_once("..") else {
1405 return Err(format!(
1406 "the fast-forward's Updating line is malformed: {line}"
1407 ));
1408 };
1409 if !full_name(old, len) || !full_name(new, len) {
1410 return Err(format!(
1411 "the fast-forward's Updating line names no full object names: {line}"
1412 ));
1413 }
1414 Ok((old.to_owned(), new.to_owned()))
1415}
1416
1417fn holder_change(
1419 trunk: &str,
1420 observed: Option<&Utf8Path>,
1421 live: Option<&Utf8Path>,
1422 what: &str,
1423) -> Option<String> {
1424 match (observed, live) {
1425 (None, None) => None,
1426 (Some(before), Some(now)) if before == now => None,
1427 (None, Some(now)) => Some(format!(
1428 "{trunk} was checked out in {now} after this run observed it, so the {what} would leave that worktree behind its own HEAD; nothing was published"
1429 )),
1430 (Some(before), None) => Some(format!(
1431 "{trunk} stopped being checked out in {before} after this run observed it, so the {what} no longer has the worktree it was planned for; nothing was published"
1432 )),
1433 (Some(before), Some(now)) => Some(format!(
1434 "{trunk} moved from being checked out in {before} to {now} after this run observed it; nothing was published"
1435 )),
1436 }
1437}
1438
1439fn moved(trunk: &str, expected: &str, now: &str) -> RkError {
1446 RkError::refusal(
1447 Diagnostic::new(
1448 Reason::StateDrift,
1449 integrate::refuse_moved_trunk(expected, now).unwrap_or_else(|| {
1450 format!(
1451 "{trunk} could not be moved and stands at {}",
1452 integrate::short(now)
1453 )
1454 }),
1455 )
1456 .target_state(format!(
1457 "{trunk} stands where it stood; the staged evidence names a commit it does not reach, which every prune ignores"
1458 )),
1459 )
1460}
1461
1462fn warn_if_uncounted(
1476 out: Output,
1477 run: &LocalRun<'_>,
1478 message: &str,
1479 range: &[&str],
1480 previewed: bool,
1481) {
1482 let Some(intent) = integrate::release_intent(message) else {
1483 return;
1484 };
1485 if !rust_automatic(run.target) {
1486 return;
1487 }
1488 let mut diff = vec!["diff", "--name-only", "--no-renames", "-z"];
1489 diff.extend_from_slice(range);
1490 let Ok(changed) = git(run.seat, &diff) else {
1491 return;
1492 };
1493 if !changed.status.success() {
1494 return;
1495 }
1496 let changed = String::from_utf8_lossy(&changed.stdout).into_owned();
1497 let changed: Vec<&str> = changed
1498 .split('\0')
1499 .filter(|path| !path.is_empty())
1500 .collect();
1501 let root_manifest = run.seat.as_std_path().join("Cargo.toml");
1502 let probe = crate::cargo_package::probe(&root_manifest, &["--locked", "--offline"], |args| {
1503 cargo_in(run.seat, args)
1504 });
1505 let Ok(crate::cargo_package::Probe::Listed(listing)) = probe else {
1506 return;
1507 };
1508 if !listing.touched_by(changed.iter().copied()) {
1509 out.warn(integrate::uncounted_release(intent, previewed));
1510 }
1511}
1512
1513fn rust_automatic(target: &Utf8Path) -> bool {
1516 crate::landing::manifest::load(target)
1517 .ok()
1518 .flatten()
1519 .is_some_and(|record| {
1520 let release = &record.profile.release;
1521 release.mode == crate::profile::ReleaseMode::Automatic
1522 && release.driver.as_deref() == Some("rust")
1523 })
1524}
1525
1526fn cargo_in(seat: &Utf8Path, args: &[&str]) -> Result<crate::cargo_package::Answer, ()> {
1528 let mut command = std::process::Command::new("cargo");
1529 for var in GIT_HOOK_VARS {
1530 command.env_remove(var);
1531 }
1532 command
1533 .current_dir(seat.as_std_path())
1534 .args(args)
1535 .stdin(std::process::Stdio::null())
1536 .output()
1537 .map(|output| crate::cargo_package::Answer {
1538 success: output.status.success(),
1539 stdout: output.stdout,
1540 stderr: output.stderr,
1541 })
1542 .map_err(|_| ())
1543}
1544
1545const GATE_HOOK: &str = "pre-merge-commit";
1548
1549const NO_HOOK: &str = "cannot find a hook named pre-merge-commit";
1553
1554enum Gate {
1557 Ran(std::process::Output),
1559 ChangedTheSeat(SeatChange, std::process::Output),
1563}
1564
1565fn gate(
1575 seat: &Utf8Path,
1576 branch: &str,
1577 trunk_commit: &str,
1578 branch_tip: &str,
1579) -> Result<Gate, RkError> {
1580 let tree = rev_parse(seat, &format!("{branch_tip}^{{tree}}"))?;
1581 let pointed = git(
1582 seat,
1583 &[
1584 "update-ref",
1585 "--no-deref",
1586 "-m",
1587 "rk integrate: stage the squash for the pre-merge-commit hook",
1588 "HEAD",
1589 trunk_commit,
1590 ],
1591 )?;
1592 if !pointed.status.success() {
1593 return Err(refuse(
1594 Reason::StateDrift,
1595 format!(
1596 "the seat's HEAD in {seat} could not point at the trunk commit {}: {}",
1597 integrate::short(trunk_commit),
1598 last_line(&pointed.stderr)
1599 ),
1600 ));
1601 }
1602 let restore = SeatHead {
1603 seat,
1604 branch,
1605 armed: true,
1606 };
1607 let mut command = std::process::Command::new(crate::probes::git_bin());
1608 for var in GIT_HOOK_VARS {
1609 command.env_remove(var);
1610 }
1611 let ran = command
1612 .arg("-C")
1613 .arg(seat.as_std_path())
1614 .args(["hook", "run", GATE_HOOK])
1615 .stdin(std::process::Stdio::null())
1616 .output()
1617 .map_err(|source| {
1618 RkError::subprocess(
1619 Diagnostic::new(
1620 Reason::SubprocessSpawn,
1621 format!("git did not run in {seat}: {source}"),
1622 )
1623 .target_state("unchanged; the trunk stands where it stood"),
1624 )
1625 })?;
1626 if let Some(change) = seat_change(seat, trunk_commit, &tree)? {
1629 restore.leave();
1630 return Ok(Gate::ChangedTheSeat(change, ran));
1631 }
1632 restore.restore()?;
1633 Ok(Gate::Ran(ran))
1634}
1635
1636enum SeatChange {
1638 Committed(String),
1641 Staged,
1644}
1645
1646fn seat_change(
1650 seat: &Utf8Path,
1651 trunk_commit: &str,
1652 tree: &str,
1653) -> Result<Option<SeatChange>, RkError> {
1654 let inspect = |args: &[&str], what: &str| -> Result<String, RkError> {
1655 let answer = git(seat, args)?;
1656 if !answer.status.success() {
1657 return Err(refuse(
1658 Reason::StateDrift,
1659 format!(
1660 "{what} in {seat} after the pre-merge-commit hook could not be read: {}",
1661 last_line(&answer.stderr)
1662 ),
1663 ));
1664 }
1665 Ok(String::from_utf8_lossy(&answer.stdout).trim().to_owned())
1666 };
1667 let head = inspect(&["rev-parse", "--verify", "--quiet", "HEAD"], "HEAD")?;
1668 if head != trunk_commit {
1669 return Ok(Some(SeatChange::Committed(head)));
1670 }
1671 let written = inspect(&["write-tree"], "the index")?;
1672 Ok((written != tree).then_some(SeatChange::Staged))
1673}
1674
1675struct SeatHead<'a> {
1680 seat: &'a Utf8Path,
1681 branch: &'a str,
1682 armed: bool,
1683}
1684
1685impl SeatHead<'_> {
1686 fn point_back(&self) -> Result<std::process::Output, RkError> {
1688 git(
1689 self.seat,
1690 &[
1691 "symbolic-ref",
1692 "HEAD",
1693 &format!("refs/heads/{}", self.branch),
1694 ],
1695 )
1696 }
1697
1698 fn restore(mut self) -> Result<(), RkError> {
1700 self.armed = false;
1701 let answer = self.point_back()?;
1702 if answer.status.success() {
1703 return Ok(());
1704 }
1705 Err(refuse(
1706 Reason::StateDrift,
1707 format!(
1708 "the seat {} stays detached at the trunk commit, because HEAD did not point back at {}: {}; run git -C {} symbolic-ref HEAD refs/heads/{}",
1709 self.seat,
1710 self.branch,
1711 last_line(&answer.stderr),
1712 self.seat,
1713 self.branch
1714 ),
1715 ))
1716 }
1717
1718 fn leave(mut self) {
1720 self.armed = false;
1721 }
1722}
1723
1724impl Drop for SeatHead<'_> {
1725 fn drop(&mut self) {
1726 if self.armed {
1727 let _ = self.point_back();
1728 }
1729 }
1730}
1731
1732fn judge_gate(out: Output, run: &LocalRun<'_>, branch: &str, gate: Gate) -> Result<(), RkError> {
1735 let ran = match gate {
1736 Gate::Ran(ran) => ran,
1737 Gate::ChangedTheSeat(change, ran) => {
1738 out.child_passthrough(crate::events::ChildStream::Stderr, &ran.stderr);
1739 out.child_passthrough(crate::events::ChildStream::Stdout, &ran.stdout);
1740 let seat = run.seat;
1741 let repair = format!("git -C {seat} symbolic-ref HEAD refs/heads/{branch}");
1742 let (what, action) = match change {
1743 SeatChange::Committed(head) => (
1744 format!(
1745 "the hook committed, so HEAD moved from the trunk commit to {}",
1746 integrate::short(&head)
1747 ),
1748 format!(
1749 "read what the hook left in {seat}; keep the hook's commit if you want it with git -C {seat} branch <name> HEAD, because the next step leaves it on no ref; then run {repair} and integrate again"
1750 ),
1751 ),
1752 SeatChange::Staged => (
1753 "the hook staged a change, so the index no longer holds the branch tip's tree"
1754 .to_owned(),
1755 format!(
1756 "read what the hook staged in {seat}, then run {repair}, restore the index with git -C {seat} reset -q, and integrate again"
1757 ),
1758 ),
1759 };
1760 return Err(RkError::refusal(
1761 Diagnostic::new(
1762 Reason::StateDrift,
1763 format!(
1764 "the hook changed the seat {seat}: {what}; nothing reached {}",
1765 run.trunk
1766 ),
1767 )
1768 .expected("a pre-merge-commit hook that judges the staged squash and changes nothing")
1769 .action(action)
1770 .target_state(
1771 "unchanged; the trunk stands where it stood, and the seat stays as the hook left it",
1772 ),
1773 ));
1774 }
1775 };
1776 if ran.status.success() {
1777 return Ok(());
1778 }
1779 out.child_passthrough(crate::events::ChildStream::Stderr, &ran.stderr);
1780 out.child_passthrough(crate::events::ChildStream::Stdout, &ran.stdout);
1781 if String::from_utf8_lossy(&ran.stderr).contains(NO_HOOK) {
1782 return Err(RkError::subprocess(
1783 Diagnostic::new(
1784 Reason::SubprocessSpawn,
1785 format!(
1786 "the repository of {} installs no pre-merge-commit hook, so the gate has nothing to run",
1787 run.seat
1788 ),
1789 )
1790 .expected("a pre-merge-commit hook installed in this clone, the gate that the project's hook manager runs")
1791 .action("install the hook with the project's hook manager, for example prek install --hook-type pre-merge-commit, then integrate again")
1792 .target_state("unchanged; the trunk stands where it stood"),
1793 ));
1794 }
1795 Err(refuse(
1796 Reason::StateDrift,
1797 format!(
1798 "the pre-merge-commit hook failed in {}, so nothing reached {}",
1799 run.seat, run.trunk
1800 ),
1801 ))
1802}
1803
1804fn left_detached(
1808 seats: &[crate::worktree::Worktree],
1809 branch: &str,
1810 target: &Utf8Path,
1811 trunk: &str,
1812) -> Option<RkError> {
1813 let trunk_commit = rev_parse(target, trunk).ok()?;
1814 let tree = rev_parse(target, &format!("refs/heads/{branch}^{{tree}}")).ok()?;
1815 let seat = seats.iter().find(|seat| {
1816 !seat.bare
1817 && seat.branch.is_none()
1818 && seat.head == trunk_commit
1819 && git(&seat.path, &["write-tree"])
1820 .ok()
1821 .filter(|answer| answer.status.success())
1822 .is_some_and(|answer| String::from_utf8_lossy(&answer.stdout).trim() == tree)
1823 })?;
1824 Some(RkError::refusal(
1825 Diagnostic::new(
1826 Reason::StateDrift,
1827 format!(
1828 "{} is detached at the trunk commit with {branch}'s tree staged, as an interrupted gate leaves it",
1829 seat.path
1830 ),
1831 )
1832 .expected(format!("{branch} checked out in its seat"))
1833 .action(format!(
1834 "git -C {} symbolic-ref HEAD refs/heads/{branch} puts the seat back on the branch; then integrate again",
1835 seat.path
1836 ))
1837 .target_state("unchanged; the trunk stands where it stood"),
1838 ))
1839}
1840
1841fn report(
1843 args: &IntegrateArgs,
1844 out: Output,
1845 run: &LocalRun<'_>,
1846 trunk_before: &str,
1847 trunk_commit: Option<String>,
1848 steps: Vec<String>,
1849 next: &[String],
1850) -> Result<(), RkError> {
1851 for step in &steps {
1852 out.result_line(step);
1853 }
1854 out.emit(&Report {
1855 schema: "rk.integrate/1",
1856 mode: if args.apply { "apply" } else { "preview" },
1857 target: run.target.to_string(),
1858 integration: Integration::Local.as_str(),
1859 authority_source: run.authority_source,
1860 merge_form: run.merge_form.as_str(),
1861 branch: args.branch.clone(),
1862 trunk: run.trunk.to_owned(),
1863 seat: run.seat.to_string(),
1864 trunk_before: trunk_before.to_owned(),
1865 trunk_commit,
1866 steps,
1867 next: next.to_vec(),
1868 })?;
1869 out.next(next);
1870 Ok(())
1871}
1872
1873const SHAPE: &str = "a scoped Conventional Commit: <type>(<scope>): <description>";
1875
1876const SHAPE_SCOPE_PREFERRED: &str =
1879 "a Conventional Commit: <type>(<scope>): <description>, or <type>: <description>";
1880
1881const TYPES: [&str; 11] = [
1884 "build", "chore", "ci", "docs", "feat", "fix", "perf", "refactor", "revert", "style", "test",
1885];
1886
1887fn refuse_message(target: &Utf8Path, text: &str, scope_required: bool) -> Result<(), RkError> {
1908 let subject = text.lines().next().unwrap_or("").trim();
1909 if subject.is_empty() {
1910 return Err(refuse(
1911 Reason::Usage,
1912 "a local integration writes the trunk's commit message, so --message is required",
1913 ));
1914 }
1915 if let Some(reason) = misshapen_subject(subject, scope_required) {
1916 return Err(refuse(Reason::Usage, reason));
1917 }
1918 let (findings, _) = crate::commands::message::judge(
1919 text,
1920 crate::cli::message::MessageKind::Commit,
1921 target,
1922 subject,
1923 crate::commands::message::Judgment {
1924 exempt: crate::commands::message::exempt_title(subject),
1925 scope_required,
1926 },
1927 );
1928 if findings.is_empty() {
1929 return Ok(());
1930 }
1931 let named: Vec<String> = findings
1932 .iter()
1933 .map(|finding| format!("{}:{} {}", finding.class, finding.line, finding.detail))
1934 .collect();
1935 Err(refuse(
1936 Reason::Usage,
1937 format!(
1938 "the trunk message carries {} finding{} the landed commit-msg stage would refuse, and git commit-tree fires no hook: {}",
1939 findings.len(),
1940 if findings.len() == 1 { "" } else { "s" },
1941 named.join("; ")
1942 ),
1943 ))
1944}
1945
1946#[must_use]
1950fn misshapen_subject(subject: &str, scope_required: bool) -> Option<String> {
1951 let shape = if scope_required {
1952 SHAPE
1953 } else {
1954 SHAPE_SCOPE_PREFERRED
1955 };
1956 let Some((head, description)) = subject.split_once(": ") else {
1957 return Some(format!("'{subject}' is not {shape}"));
1958 };
1959 if description.trim().is_empty() {
1960 return Some(format!(
1961 "'{subject}' is not {shape}: it states no description"
1962 ));
1963 }
1964 let head = head.strip_suffix('!').unwrap_or(head);
1967 let (kind, scope) = match head.split_once('(') {
1968 None if scope_required => {
1969 return Some(format!("'{subject}' is not {shape}: it names no scope"));
1970 }
1971 None => (head, None),
1972 Some((kind, scope)) => {
1973 let Some(scope) = scope.strip_suffix(')') else {
1974 return Some(format!("'{subject}' is not {shape}: its scope is unclosed"));
1975 };
1976 (kind, Some(scope))
1977 }
1978 };
1979 if !TYPES.contains(&kind) {
1980 return Some(format!(
1981 "'{kind}' is not a Conventional Commit type; the types are: {}",
1982 TYPES.join(", ")
1983 ));
1984 }
1985 if let Some(scope) = scope
1986 && !crate::projection::scope_is_shaped(scope)
1987 {
1988 return Some(format!(
1989 "the scope '{scope}' is outside {}: lowercase letters, digits, and _ . / -",
1990 crate::projection::SCOPE_SHAPE
1991 ));
1992 }
1993 None
1994}
1995
1996fn seats(target: &Utf8Path) -> Result<Vec<crate::worktree::Worktree>, RkError> {
1998 let listed = git(target, &["worktree", "list", "--porcelain", "-z"])?;
1999 if !listed.status.success() {
2000 return Err(RkError::missing(
2001 Diagnostic::new(
2002 Reason::TargetNotFound,
2003 format!("target {target} is not a git repository"),
2004 )
2005 .expected("a repository whose worktrees git can list"),
2006 ));
2007 }
2008 crate::worktree::parse_worktrees(&listed.stdout)
2009 .map_err(|detail| refuse(Reason::PrerequisiteUnmet, detail))
2010}
2011
2012fn seat_for(
2014 seats: &[crate::worktree::Worktree],
2015 branch: &str,
2016 target: &Utf8Path,
2017) -> Result<Utf8PathBuf, RkError> {
2018 seats
2019 .iter()
2020 .find(|seat| seat.branch.as_deref() == Some(branch))
2021 .map(|seat| seat.path.clone())
2022 .ok_or_else(|| {
2023 refuse(
2024 Reason::StateDrift,
2025 format!(
2026 "no worktree of {target} has {branch} checked out; rk worktree add {branch} --apply seats it"
2027 ),
2028 )
2029 })
2030}
2031
2032fn is_dirty(seat: &Utf8Path) -> Result<bool, RkError> {
2034 let status = git(seat, &["status", "--porcelain"])?;
2035 Ok(!status.stdout.is_empty())
2036}
2037
2038fn rev_parse(seat: &Utf8Path, revision: &str) -> Result<String, RkError> {
2040 let answer = git(seat, &["rev-parse", "--verify", "--quiet", revision])?;
2041 if !answer.status.success() {
2042 return Err(refuse(
2043 Reason::StateDrift,
2044 format!("{revision} does not resolve in {seat}"),
2045 ));
2046 }
2047 Ok(String::from_utf8_lossy(&answer.stdout).trim().to_owned())
2048}
2049
2050fn is_ancestor(seat: &Utf8Path, ancestor: &str, descendant: &str) -> bool {
2052 git(seat, &["merge-base", "--is-ancestor", ancestor, descendant])
2053 .is_ok_and(|answer| answer.status.success())
2054}
2055
2056fn common_git_dir(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
2058 let answer = git(
2059 target,
2060 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2061 )?;
2062 if !answer.status.success() {
2063 return Err(RkError::missing(
2064 Diagnostic::new(
2065 Reason::TargetNotFound,
2066 format!("target {target} is not a git repository"),
2067 )
2068 .expected("a repository whose common git directory git can name"),
2069 ));
2070 }
2071 let path = String::from_utf8_lossy(&answer.stdout).trim().to_owned();
2072 Utf8PathBuf::from_path_buf(std::path::PathBuf::from(path)).map_err(|path| {
2073 refuse(
2074 Reason::PrerequisiteUnmet,
2075 format!("the common git directory {} is not UTF-8", path.display()),
2076 )
2077 })
2078}
2079
2080fn read_ledger(path: &Utf8Path) -> Result<Ledger, RkError> {
2082 match std::fs::read_to_string(path) {
2083 Ok(text) => {
2084 Ledger::parse(&text).map_err(|detail| refuse(Reason::UnsupportedSchema, detail))
2085 }
2086 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Ledger::default()),
2087 Err(error) => Err(RkError::Io(error)),
2088 }
2089}
2090
2091fn write_ledger(path: &Utf8Path, ledger: &Ledger) -> Result<(), RkError> {
2093 let text = ledger
2094 .render()
2095 .map_err(|detail| refuse(Reason::Internal, detail))?;
2096 if let Some(parent) = path.parent() {
2097 std::fs::create_dir_all(parent)?;
2098 }
2099 crate::atomic::write(path.as_std_path(), text.as_bytes())?;
2100 Ok(())
2101}
2102
2103fn refuse(reason: Reason, message: impl Into<String>) -> RkError {
2105 RkError::refusal(
2106 Diagnostic::new(reason, message).target_state("unchanged; the trunk stands where it stood"),
2107 )
2108}
2109
2110fn git_in_c_locale(at: &Utf8Path, args: &[&str]) -> Result<std::process::Output, RkError> {
2113 let mut command = std::process::Command::new(crate::probes::git_bin());
2114 for var in GIT_HOOK_VARS {
2115 command.env_remove(var);
2116 }
2117 command
2118 .env("LC_ALL", "C")
2119 .arg("-C")
2120 .arg(at.as_std_path())
2121 .args(args)
2122 .output()
2123 .map_err(|source| {
2124 RkError::subprocess(
2125 Diagnostic::new(
2126 Reason::SubprocessSpawn,
2127 format!("git did not run in {at}: {source}"),
2128 )
2129 .target_state("unchanged"),
2130 )
2131 })
2132}
2133
2134fn git(at: &Utf8Path, args: &[&str]) -> Result<std::process::Output, RkError> {
2136 let mut command = std::process::Command::new(crate::probes::git_bin());
2137 for var in GIT_HOOK_VARS {
2138 command.env_remove(var);
2139 }
2140 command
2141 .arg("-C")
2142 .arg(at.as_std_path())
2143 .args(args)
2144 .output()
2145 .map_err(|source| {
2146 RkError::subprocess(
2147 Diagnostic::new(
2148 Reason::SubprocessSpawn,
2149 format!("git did not run in {at}: {source}"),
2150 )
2151 .target_state("unchanged"),
2152 )
2153 })
2154}
2155
2156#[cfg(test)]
2157mod tests {
2158 use camino::Utf8Path;
2159
2160 use super::{
2161 BranchCommit, misshapen_subject, refuse_commit_messages, refuse_message, request_commands,
2162 };
2163 use crate::landing::MergeForm;
2164
2165 #[test]
2167 fn merge_form_rebase_asks_gitlab_for_no_squash() {
2168 let gitlab = "git@gitlab.com:acme/widget.git";
2169 let squash = request_commands(gitlab, "master", "feat/x", MergeForm::Squash, true);
2170 assert_eq!(
2171 squash[0],
2172 "glab mr create --source-branch feat/x --target-branch master --squash-before-merge"
2173 );
2174 assert!(squash[1].contains("the title is the trunk's commit message"));
2175 let rebase = request_commands(gitlab, "master", "feat/x", MergeForm::Rebase, true);
2176 assert_eq!(
2177 rebase[0],
2178 "glab mr create --source-branch feat/x --target-branch master"
2179 );
2180 assert!(
2181 !rebase.iter().any(|line| line.contains("squash")),
2182 "{rebase:?}"
2183 );
2184 assert!(
2185 rebase[1].contains("every commit of the branch reaches the trunk with its own message"),
2186 "{rebase:?}"
2187 );
2188 assert!(!rebase[1].contains("title"), "{rebase:?}");
2189 }
2190
2191 #[test]
2192 fn merge_form_keeps_the_github_request_command() {
2193 let github = "git@github.com:acme/widget.git";
2194 for form in [MergeForm::Squash, MergeForm::Rebase] {
2195 assert_eq!(
2196 request_commands(github, "master", "feat/x", form, true)[0],
2197 "gh pr create --base master --head feat/x"
2198 );
2199 }
2200 }
2201
2202 #[test]
2203 fn a_trunk_subject_is_held_to_the_landed_convention() {
2204 assert_eq!(
2205 misshapen_subject("feat(integrate): land the verb", true),
2206 None
2207 );
2208 assert_eq!(misshapen_subject("feat(a/b)!: break it", true), None);
2209 assert!(
2210 misshapen_subject("land the verb", true)
2211 .expect("an unscoped subject refuses")
2212 .contains("Conventional Commit")
2213 );
2214 assert!(
2215 misshapen_subject("feat: land the verb", true)
2216 .expect("a missing scope refuses")
2217 .contains("names no scope")
2218 );
2219 assert!(
2220 misshapen_subject("feat(integrate): ", true)
2221 .expect("an empty description refuses")
2222 .contains("no description")
2223 );
2224 assert!(
2225 misshapen_subject("wat(integrate): land it", true)
2226 .expect("an unknown type refuses")
2227 .contains("not a Conventional Commit type")
2228 );
2229 assert!(
2230 misshapen_subject("feat(Integrate): land it", true)
2231 .expect("a misshapen scope refuses")
2232 .contains("outside")
2233 );
2234 }
2235
2236 #[test]
2240 fn a_trunk_body_is_judged_by_the_one_message_owner() {
2241 let dir = tempfile::tempdir().expect("a scratch dir exists");
2242 let target = Utf8Path::from_path(dir.path()).expect("utf-8");
2243 refuse_message(
2244 target,
2245 "feat(integrate): land the verb\n\nThe context.\n",
2246 true,
2247 )
2248 .expect("a clean message passes");
2249 let error = refuse_message(
2250 target,
2251 "feat(integrate): land the verb\n\nCo-Authored-By: Claude <noreply@anthropic.com>\n",
2252 true,
2253 )
2254 .expect_err("agent attribution refuses")
2255 .to_string();
2256 assert!(error.contains("attribution"), "{error}");
2257 assert!(error.contains("commit-tree fires no hook"), "{error}");
2258 let error = refuse_message(
2259 target,
2260 "feat(integrate): land the verb\n\nSee .draft/plan.md for the rest.\n",
2261 true,
2262 )
2263 .expect_err("an internal path refuses")
2264 .to_string();
2265 assert!(error.contains("internal-path"), "{error}");
2266 let error = refuse_message(target, "", true)
2267 .expect_err("an empty message refuses")
2268 .to_string();
2269 assert!(error.contains("--message is required"), "{error}");
2270 }
2271
2272 #[test]
2276 fn rebase_integrate_judges_every_commit_message() {
2277 let dir = tempfile::tempdir().expect("a scratch dir exists");
2278 let target = Utf8Path::from_path(dir.path()).expect("utf-8");
2279 let commit = |id: &str, message: &str| BranchCommit {
2280 id: id.to_owned(),
2281 message: message.to_owned(),
2282 };
2283 refuse_commit_messages(
2284 target,
2285 &[
2286 commit("1111111aaaa", "feat(greeting): add it\n"),
2287 commit("2222222bbbb", "fix(greeting): mend it\n\nThe context.\n"),
2288 ],
2289 true,
2290 )
2291 .expect("clean messages pass");
2292 let error = refuse_commit_messages(
2293 target,
2294 &[
2295 commit("1111111aaaa", "feat(greeting): add it\n"),
2296 commit(
2297 "2222222bbbb",
2298 "fix(greeting): mend it\n\nCo-Authored-By: Claude <noreply@anthropic.com>\n",
2299 ),
2300 ],
2301 true,
2302 )
2303 .expect_err("agent attribution refuses")
2304 .to_string();
2305 assert!(error.contains("commit 2222222"), "{error}");
2306 assert!(error.contains("attribution"), "{error}");
2307 let error = refuse_commit_messages(target, &[commit("3333333cccc", "mend it\n")], true)
2308 .expect_err("an unscoped subject refuses")
2309 .to_string();
2310 assert!(error.contains("commit 3333333"), "{error}");
2311 assert!(error.contains("Conventional Commit"), "{error}");
2312 let error = refuse_commit_messages(target, &[commit("4444444dddd", "\n")], true)
2313 .expect_err("an empty message refuses")
2314 .to_string();
2315 assert!(error.contains("carries no message"), "{error}");
2316 }
2317
2318 #[test]
2324 fn workflow_only_a_trunk_subject_may_name_no_scope() {
2325 assert_eq!(misshapen_subject("fix: drop the stale path", false), None);
2326 assert_eq!(misshapen_subject("feat!: break it", false), None);
2327 assert_eq!(misshapen_subject("feat(a/b): add it", false), None);
2328 assert!(
2329 misshapen_subject("fix: drop the stale path", true)
2330 .expect("a release requires the scope")
2331 .contains("names no scope")
2332 );
2333 assert!(
2334 misshapen_subject("wat: drop it", false)
2335 .expect("an unknown type refuses")
2336 .contains("not a Conventional Commit type")
2337 );
2338 assert!(
2339 misshapen_subject("drop the stale path", false)
2340 .expect("a subject with no type refuses")
2341 .contains("<type>: <description>")
2342 );
2343 assert!(
2344 misshapen_subject("fix(Bad): mend it", false)
2345 .expect("a misshapen scope refuses")
2346 .contains("outside")
2347 );
2348 let dir = tempfile::tempdir().expect("a scratch dir exists");
2349 let target = Utf8Path::from_path(dir.path()).expect("utf-8");
2350 refuse_message(target, "fix: drop the stale path\n", false)
2351 .expect("a release-less trunk message names no scope");
2352 refuse_commit_messages(
2353 target,
2354 &[BranchCommit {
2355 id: "5555555eeee".to_owned(),
2356 message: "fix: drop the stale path\n".to_owned(),
2357 }],
2358 false,
2359 )
2360 .expect("a release-less branch commit names no scope");
2361 }
2362
2363 #[test]
2369 fn workflow_only_request_guidance_prefers_the_scope() {
2370 for remote in [
2371 "git@gitlab.com:acme/widget.git",
2372 "git@github.com:acme/widget.git",
2373 ] {
2374 for form in [MergeForm::Squash, MergeForm::Rebase] {
2375 let lines = request_commands(remote, "master", "feat/x", form, false);
2376 assert!(!lines[1].contains("scoped"), "{lines:?}");
2377 assert!(
2378 lines[1].contains("scope is preferred and not required"),
2379 "{lines:?}"
2380 );
2381 let releasing = request_commands(remote, "master", "feat/x", form, true);
2382 assert!(
2383 releasing[1].contains("scoped Conventional Commit"),
2384 "{releasing:?}"
2385 );
2386 assert_eq!(lines[0], releasing[0], "the command itself does not change");
2387 }
2388 }
2389 }
2390
2391 #[test]
2399 fn integrate_reports_a_raced_publication_as_published() {
2400 let drift = super::Drift {
2401 expected: "a".repeat(40),
2402 found_old: "b".repeat(40),
2403 found_new: "c".repeat(40),
2404 };
2405 assert!(drift.step("master").contains("bbbbbbb to ccccccc"));
2406 let error = drift.into_error("master", &"c".repeat(40));
2407 assert_eq!(error.exit_code(), 1);
2408 let diagnostic = error.diagnostic();
2409 assert_eq!(diagnostic.reason, crate::diagnostic::Reason::StateDrift);
2410 for named in [
2411 "published ccccccc",
2412 "bbbbbbb",
2413 "observed aaaaaaa",
2414 "outside rk",
2415 ] {
2416 assert!(
2417 diagnostic.message.contains(named),
2418 "{named}: {}",
2419 diagnostic.message
2420 );
2421 }
2422 assert!(
2423 !diagnostic.message.contains("nothing"),
2424 "{}",
2425 diagnostic.message
2426 );
2427 let state = diagnostic.target_state.unwrap_or_default();
2428 assert!(state.contains("published at ccccccc"), "{state}");
2429 assert!(state.contains("no rollback"), "{state}");
2430 assert!(!state.contains("where it stood"), "{state}");
2431 let action = diagnostic.action.unwrap_or_default();
2432 assert!(action.contains("git log aaaaaaa..bbbbbbb"), "{action}");
2433 }
2434
2435 #[test]
2440 fn integrate_refuses_a_changed_trunk_holder() {
2441 let main = Utf8Path::new("/repo");
2442 let other = Utf8Path::new("/repo@trunk");
2443 assert_eq!(
2444 super::holder_change("master", None, None, "integration"),
2445 None
2446 );
2447 assert_eq!(
2448 super::holder_change("master", Some(main), Some(main), "integration"),
2449 None
2450 );
2451 for (observed, live) in [
2452 (None, Some(other)),
2453 (Some(main), None),
2454 (Some(main), Some(other)),
2455 ] {
2456 let reason = super::holder_change("master", observed, live, "integration")
2457 .expect("a changed holder refuses");
2458 assert!(reason.contains("checked out"), "{reason}");
2459 assert!(reason.contains("nothing was published"), "{reason}");
2460 }
2461 }
2462
2463 #[test]
2472 fn integrate_reports_an_unconfirmed_move_as_published() {
2473 let expected = "a".repeat(40);
2474 let published = "c".repeat(40);
2475 let unsettled = super::Unsettled::Unconfirmed {
2476 expected: expected.clone(),
2477 reason: "the reflog holds one entry".to_owned(),
2478 };
2479 assert!(unsettled.step("master").contains("is not confirmed"));
2480 let error = unsettled.clone().into_error("master", &published);
2481 assert_eq!(error.exit_code(), 1);
2482 let diagnostic = error.diagnostic();
2483 assert_eq!(diagnostic.reason, crate::diagnostic::Reason::StateDrift);
2484 assert_eq!(
2485 diagnostic.message,
2486 "master now stands at the published ccccccc, but rk could not confirm that the move started at the observed aaaaaaa: the reflog holds one entry"
2487 );
2488 assert_eq!(
2489 diagnostic.expected.as_deref(),
2490 Some("a confirmed move of master from aaaaaaa to ccccccc")
2491 );
2492 assert_eq!(
2493 diagnostic.action.as_deref(),
2494 Some(
2495 "read git reflog master and git log aaaaaaa..ccccccc, and decide whether anything else moved master; rk moves nothing back"
2496 )
2497 );
2498 assert_eq!(
2499 diagnostic.target_state.as_deref(),
2500 Some(
2501 "master is published at ccccccc, with no rollback and no reset; the staged evidence names ccccccc and the trunk reaches it"
2502 )
2503 );
2504
2505 let raced = super::Unsettled::Raced(super::Drift {
2506 expected: expected.clone(),
2507 found_old: "b".repeat(40),
2508 found_new: published.clone(),
2509 });
2510 for refresh in [unsettled, raced] {
2511 let diagnostic = refresh
2512 .into_refresh_error("master", &expected, &published)
2513 .diagnostic();
2514 assert!(
2515 diagnostic
2516 .message
2517 .contains("was fast-forwarded to its remote tip ccccccc")
2518 );
2519 assert!(diagnostic.message.contains("no integration was published"));
2520 let state = diagnostic.target_state.unwrap_or_default();
2521 assert!(
2522 state.contains("refreshed to its remote tip ccccccc"),
2523 "{state}"
2524 );
2525 for unchanged in ["unchanged", "where it stood", "now stands at the published"] {
2526 assert!(!diagnostic.message.contains(unchanged), "{unchanged}");
2527 assert!(!state.contains(unchanged), "{unchanged}");
2528 }
2529 }
2530 }
2531
2532 #[test]
2537 fn integrate_parses_only_a_full_updating_line() {
2538 let old = "a".repeat(40);
2539 let new = "b".repeat(40);
2540 assert_eq!(
2541 super::parse_updating(&format!("Updating {old}..{new}\nFast-forward\n"), 40),
2542 Ok((old.clone(), new.clone()))
2543 );
2544 for report in [
2545 "Fast-forward\n".to_owned(),
2546 format!("Updating {}..{}\n", &old[..7], &new[..7]),
2547 format!("Updating {old}..{}\n", &new[..12]),
2548 format!("Updating {old} {new}\n"),
2549 format!("Updating {old}..{new}\nUpdating {new}..{old}\n"),
2550 format!("Updating {}..{new}\n", "g".repeat(40)),
2551 format!("Updating {old}..{new}\n").replace("Updating", "Mise à jour"),
2552 ] {
2553 assert!(super::parse_updating(&report, 40).is_err(), "{report}");
2554 }
2555 }
2556
2557 #[test]
2563 fn integrate_judges_the_read_backs_of_a_held_move() {
2564 use super::{PostPublication, Unsettled, judge_move};
2565 let expected = "a".repeat(40);
2566 let other = "b".repeat(40);
2567 let to = "c".repeat(40);
2568 let pair = |old: &str, new: &str| Ok((old.to_owned(), new.to_owned()));
2569 let none = || Err::<(String, String), String>("unavailable".to_owned());
2570 assert_eq!(
2571 judge_move(&expected, &to, pair(&expected, &to), none()),
2572 PostPublication::Confirmed
2573 );
2574 assert_eq!(
2575 judge_move(&expected, &to, none(), pair(&expected, &to)),
2576 PostPublication::Confirmed
2577 );
2578 assert_eq!(
2579 judge_move(&expected, &to, pair(&expected, &to), pair(&expected, &to)),
2580 PostPublication::Confirmed
2581 );
2582 assert!(matches!(
2583 judge_move(&expected, &to, pair(&other, &to), none()),
2584 PostPublication::Unsettled(Unsettled::Raced(_))
2585 ));
2586 for judged in [
2587 judge_move(&expected, &to, pair(&expected, &to), pair(&other, &to)),
2588 judge_move(&expected, &to, none(), pair(&expected, &other)),
2589 judge_move(&expected, &to, none(), none()),
2590 ] {
2591 assert!(
2592 matches!(
2593 judged,
2594 PostPublication::Unsettled(Unsettled::Unconfirmed { .. })
2595 ),
2596 "{judged:?}"
2597 );
2598 }
2599 }
2600}