1use crate::names::BIN;
35use std::ffi::OsString;
36use std::io::{IsTerminal, Read, Write};
37use std::ops::ControlFlow;
38use std::path::PathBuf;
39use std::process::{Command, Stdio};
40use std::time::{Duration, SystemTime, UNIX_EPOCH};
41
42use crate::attest::{classify_push_stderr, PushFailure};
43use crate::git::{self, Probe};
44use crate::hooks::pull_rebase::PUSH_AGAIN;
45use crate::json;
46use crate::rehearsal::signal_of;
47
48pub const LAND_REMOTE_MOVED: &str = "amont-land: remote-moved";
53pub const LAND_EVIDENCE_MISSING: &str = "amont-land: evidence-missing";
56
57const REREADS: u32 = 3;
60const REREAD_PAUSE: Duration = Duration::from_secs(2);
61
62const RECEIPT_KEEP: Duration = Duration::from_secs(7 * 24 * 60 * 60);
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum Mode {
68 Plain,
70 Force,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum Status {
78 Landed,
79 Refused,
80 Usage,
81 Unreachable,
82 Unverified,
83 NotObserved,
84 Interrupted(i32),
86}
87
88impl Status {
89 pub fn code(self) -> i32 {
90 match self {
91 Status::Landed => 0,
92 Status::Refused => 1,
93 Status::Usage => 2,
94 Status::Unreachable | Status::Unverified => 3,
95 Status::NotObserved => 4,
96 Status::Interrupted(sig) => 128 + sig,
97 }
98 }
99
100 pub fn as_str(self) -> &'static str {
101 match self {
102 Status::Landed => "landed",
103 Status::Refused => "refused",
104 Status::Usage => "usage",
105 Status::Unreachable => "unreachable",
106 Status::Unverified => "unverified",
107 Status::NotObserved => "not-observed",
108 Status::Interrupted(_) => "interrupted",
109 }
110 }
111}
112
113#[derive(Debug, Clone)]
116pub struct Report {
117 pub branch: String,
118 pub remote: String,
119 pub push_url: String,
120 pub pushed: String,
121 pub dst: String,
123 pub remote_before: String,
124 pub remote_after: String,
125 pub retried: bool,
126 pub status: Status,
127 pub next: Vec<String>,
129 pub gates_owed: Vec<String>,
132 pub prestage: PrestageState,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum PrestageState {
138 NotRun,
140 Stamped,
142 Ran,
144 Failed,
146 Refused,
148 Interrupted,
150}
151
152impl PrestageState {
153 pub fn as_str(self) -> &'static str {
154 match self {
155 PrestageState::NotRun => "",
156 PrestageState::Stamped => "stamped",
157 PrestageState::Ran => "ran",
158 PrestageState::Failed => "failed",
159 PrestageState::Refused => "refused",
160 PrestageState::Interrupted => "interrupted",
161 }
162 }
163}
164
165impl Report {
166 fn new(status: Status) -> Self {
167 Report {
168 branch: String::new(),
169 remote: String::new(),
170 push_url: String::new(),
171 pushed: String::new(),
172 dst: String::new(),
173 remote_before: String::new(),
174 remote_after: String::new(),
175 retried: false,
176 status,
177 next: Vec::new(),
178 gates_owed: Vec::new(),
179 prestage: PrestageState::NotRun,
180 }
181 }
182
183 fn json(&self) -> String {
184 json::object(&[
185 json::string_field("branch", &self.branch),
186 json::string_field("remote", &self.remote),
187 json::string_field("push_url", &self.push_url),
188 json::string_field("pushed", &self.pushed),
189 json::string_field("ref", &self.dst),
190 json::string_field("remote_before", &self.remote_before),
191 json::string_field("remote_after", &self.remote_after),
192 json::bool_field("retried", self.retried),
193 json::string_field("status", self.status.as_str()),
194 format!(
195 "\"gates\":{}",
196 json::object(&[
197 json::string_array_field("owed", &self.gates_owed),
198 json::string_field("prestage", self.prestage.as_str()),
199 ])
200 ),
201 ])
202 }
203}
204
205const VERDICT_WIDTH: usize = 80;
207
208pub fn truncate_middle(s: &str, max: usize) -> String {
212 let n = s.chars().count();
213 if n <= max {
214 return s.to_string();
215 }
216 if max <= 1 {
217 return "…".chars().take(max).collect();
218 }
219 let keep = max - 1;
220 let head = keep.div_ceil(2);
221 let tail = keep - head;
222 let front: String = s.chars().take(head).collect();
223 let back: String = s.chars().skip(n - tail).collect();
224 format!("{front}…{back}")
225}
226
227fn short(sha: &str) -> String {
228 if sha.is_empty() {
229 "-------".to_string()
230 } else {
231 sha.chars().take(7).collect()
232 }
233}
234
235pub fn verdict(status: Status, before: &str, after: &str, branch: &str) -> String {
239 verdict_word(status.as_str(), before, after, branch)
240}
241
242fn verdict_word(word: &str, before: &str, after: &str, branch: &str) -> String {
243 let head = format!("{word} {}..{}", short(before), short(after));
244 let room = VERDICT_WIDTH.saturating_sub(head.chars().count() + 1);
245 if branch.is_empty() || room == 0 {
246 return head;
247 }
248 format!("{head} {}", truncate_middle(branch, room))
249}
250
251pub fn parse_tip(ls_remote: &str) -> String {
254 ls_remote
255 .lines()
256 .find_map(|l| l.split_whitespace().next())
257 .unwrap_or("")
258 .to_string()
259}
260
261enum Seen {
263 Tip(String),
264 Unreachable,
265}
266
267fn read_tip(url: &str, rb: &str, budget: u64) -> Seen {
268 read_ref(url, &format!("refs/heads/{rb}"), budget)
269}
270
271fn read_ref(url: &str, refname: &str, budget: u64) -> Seen {
273 match git::probe_remote_stdout(&["ls-remote", url, refname], budget) {
274 (Probe::Exit(0), out) => Seen::Tip(parse_tip(&out)),
275 _ => Seen::Unreachable,
276 }
277}
278
279pub fn command(args: &[OsString]) -> i32 {
282 let json_out = args.iter().any(|a| a == "--json");
283 let dry_run = args.iter().any(|a| a == "--dry-run");
284 let mode = if args.iter().any(|a| a == "--force") {
285 Mode::Force
286 } else {
287 Mode::Plain
288 };
289 let mut tag: Option<String> = None;
290 let mut it = args.iter().map(|a| a.to_string_lossy().into_owned());
291 while let Some(a) = it.next() {
292 match a.as_str() {
293 "--force" | "--json" | "--dry-run" => {}
294 "--tag" => match it.next() {
295 Some(name) if !name.is_empty() && !name.starts_with('-') => tag = Some(name),
296 _ => {
297 eprintln!("{BIN}: land: --tag needs a tag name");
298 return finish(&Report::new(Status::Usage), json_out);
299 }
300 },
301 other if other.starts_with("--tag=") => match &other["--tag=".len()..] {
302 "" => {
303 eprintln!("{BIN}: land: --tag needs a tag name");
304 return finish(&Report::new(Status::Usage), json_out);
305 }
306 name => tag = Some(name.to_string()),
307 },
308 _ => {
309 eprintln!(
310 "{BIN}: land: takes no arguments, only [--force] [--json] [--dry-run] [--tag <name>]"
311 );
312 return finish(&Report::new(Status::Usage), json_out);
313 }
314 }
315 }
316 if let Some(name) = tag {
317 if mode == Mode::Force {
318 eprintln!("{BIN}: land: a tag is never forced; --tag takes no --force");
319 return finish(&Report::new(Status::Usage), json_out);
320 }
321 if dry_run {
322 let (report, verdict) = dry_run_tag(&name);
323 say_dry_run(&report, verdict);
324 if json_out {
325 println!("{}", dry_run_json(&report, verdict, mode));
326 }
327 return i32::from(verdict != "would-land");
328 }
329 let started = now_nanos();
330 let report = land_tag(&name);
331 write_receipt(&report, started, now_nanos());
332 return finish(&report, json_out);
333 }
334 if dry_run {
335 let (report, verdict) = dry_run_branch();
336 say_dry_run(&report, verdict);
337 if json_out {
338 println!("{}", dry_run_json(&report, verdict, mode));
339 }
340 return i32::from(verdict != "would-land");
341 }
342 let started = now_nanos();
343 let report = land(mode);
344 write_receipt(&report, started, now_nanos());
345 finish(&report, json_out)
346}
347
348pub fn usage_json() -> String {
351 Report::new(Status::Usage).json()
352}
353
354fn finish(report: &Report, json_out: bool) -> i32 {
355 for line in &report.next {
356 eprintln!(" {line}");
357 }
358 eprintln!(
359 "{}",
360 verdict(
361 report.status,
362 &report.remote_before,
363 &report.remote_after,
364 shown_ref(report)
365 )
366 );
367 if json_out {
368 println!("{}", report.json());
369 }
370 report.status.code()
371}
372
373fn shown_ref(report: &Report) -> &str {
376 if report.branch.is_empty() {
377 report.dst.strip_prefix("refs/tags/").unwrap_or(&report.dst)
378 } else {
379 &report.branch
380 }
381}
382
383fn refuse(mut report: Report, why: &str, next: &[&str]) -> Report {
384 eprintln!("{BIN}: land: {why}");
385 report.status = Status::Refused;
386 report.next = next.iter().map(|s| s.to_string()).collect();
387 report
388}
389
390struct Resolved {
392 remote: String,
393 rb: String,
394 url: String,
395 has_upstream: bool,
396}
397
398fn one_push_url(remote: &str, mut report: Report) -> Result<(String, Report), Box<Report>> {
400 let Some(urls) = git::stdout(&["remote", "get-url", "--push", "--all", remote]) else {
401 return Err(Box::new(refuse(
402 report,
403 &format!("no remote named {remote:?}"),
404 &["git remote -v"],
405 )));
406 };
407 let urls: Vec<&str> = urls.lines().filter(|l| !l.is_empty()).collect();
408 if urls.len() != 1 {
409 return Err(Box::new(refuse(
410 report,
411 &format!(
412 "{remote:?} has {} push destinations; land verifies exactly one",
413 urls.len()
414 ),
415 &[&format!("git remote get-url --push --all {remote}")],
416 )));
417 }
418 let url = urls[0].to_string();
419 report.push_url = redact_url(&url);
420 Ok((url, report))
421}
422
423fn redact_url(url: &str) -> String {
427 let Some((scheme, rest)) = url.split_once("://") else {
428 return url.to_string(); };
430 let authority_end = rest.find('/').unwrap_or(rest.len());
431 let (authority, path) = rest.split_at(authority_end);
432 let Some((user, host)) = authority.rsplit_once('@') else {
433 return url.to_string();
434 };
435 let user = if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
436 "***".to_string()
437 } else {
438 match user.split_once(':') {
439 Some((name, _)) => format!("{name}:***"),
440 None => user.to_string(),
441 }
442 };
443 format!("{scheme}://{user}@{host}{path}")
444}
445
446fn resolve() -> Result<(Resolved, Report), Box<Report>> {
450 let mut report = Report::new(Status::Refused);
451
452 let Some(branch) = git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"]) else {
454 return Err(Box::new(refuse(
455 report,
456 "HEAD is detached; there is no branch to land",
457 &[],
458 )));
459 };
460 report.branch = branch.clone();
461 let upstream_remote = git::stdout(&["config", "--get", &format!("branch.{branch}.remote")]);
462 let upstream_merge = git::stdout(&["config", "--get", &format!("branch.{branch}.merge")]);
463 let (upstream_remote, upstream_merge) = match upstream_remote.as_deref() {
467 Some(".") => (None, None),
468 _ => (upstream_remote, upstream_merge),
469 };
470 let upstream_merge = upstream_merge.filter(|m| {
477 let tracked = m.strip_prefix("refs/heads/").unwrap_or(m);
478 !is_protected(tracked) || is_protected(&branch)
479 });
480 let has_upstream = upstream_remote.is_some() && upstream_merge.is_some();
481 let remote = upstream_remote.unwrap_or_else(|| "origin".to_string());
482 let rb = upstream_merge
483 .as_deref()
484 .and_then(|m| m.strip_prefix("refs/heads/"))
485 .unwrap_or(&branch)
486 .to_string();
487 report.remote = remote.clone();
488 report.dst = format!("refs/heads/{rb}");
489
490 if is_protected(&branch) || is_protected(&rb) {
491 return Err(Box::new(refuse(
492 report,
493 "main and master change by pull request, never by a push",
494 &["git switch -c <name>"],
495 )));
496 }
497 if git::stdout(&["status", "--porcelain", "--untracked-files=no"])
498 .is_some_and(|s| !s.is_empty())
499 {
500 return Err(Box::new(refuse(
501 report,
502 "tracked files have uncommitted changes; the push would not include them",
503 &["git status", "git stash"],
504 )));
505 }
506
507 let (url, report) = one_push_url(&remote, report)?;
509 Ok((
510 Resolved {
511 remote,
512 rb,
513 url,
514 has_upstream,
515 },
516 report,
517 ))
518}
519
520fn land(mode: Mode) -> Report {
521 let settings = crate::config::Settings::default();
522 let budget = crate::hooks::common::network_probe_budget(&settings);
523 let (
524 Resolved {
525 remote,
526 rb,
527 url,
528 has_upstream,
529 },
530 mut report,
531 ) = match resolve() {
532 Ok(r) => r,
533 Err(refused) => return *refused,
534 };
535
536 let mut expected_old = match read_tip(&url, &rb, budget) {
538 Seen::Tip(t) => t,
539 Seen::Unreachable => {
540 report.status = Status::Unreachable;
541 eprintln!("{BIN}: land: could not read {rb} from {remote}");
542 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
543 return report;
544 }
545 };
546 report.remote_before = expected_old.clone();
547
548 let mut attempt = 0;
550 let pushed = loop {
551 let Some(sha) = git::stdout(&["rev-parse", "HEAD"]) else {
552 return refuse(report, "cannot resolve HEAD", &[]);
553 };
554 report.pushed = sha.clone();
555 let lease = match mode {
556 Mode::Force => Some(expected_old.as_str()),
557 Mode::Plain => None,
558 };
559 let local_ref = format!("refs/heads/{}", report.branch);
563 let dst = format!("refs/heads/{rb}");
564 report = match prestage(&local_ref, &sha, &dst, &expected_old, (&remote, &url))
565 .into_report(report)
566 {
567 ControlFlow::Continue(report) => report,
568 ControlFlow::Break(stopped) => return *stopped,
569 };
570 let land_env = format!("{sha} {}", or_zeros(&expected_old));
571 let run = push(&url, &sha, &dst, lease, &land_env);
572 match run.outcome {
573 PushOutcome::Done => break sha,
574 PushOutcome::Signal(sig) => {
575 report.status = Status::Interrupted(sig);
576 return report;
577 }
578 PushOutcome::Failed => {}
579 }
580 let head_now = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
581 let hook_moved_head = run.seen.contains(PUSH_AGAIN)
582 && head_now != sha
583 && (expected_old.is_empty()
584 || git::succeeds(&["merge-base", "--is-ancestor", &expected_old, &head_now]));
585 if attempt == 0 && hook_moved_head {
586 attempt = 1;
587 report.retried = true;
588 eprintln!(
589 "{BIN}: land: retrying once: pre-push hook fast-forwarded HEAD {} -> {}",
590 short(&sha),
591 short(&head_now)
592 );
593 match read_tip(&url, &rb, budget) {
594 Seen::Tip(t) => {
595 expected_old = t;
596 report.remote_before = expected_old.clone();
597 }
598 Seen::Unreachable => {
599 report.status = Status::Unreachable;
600 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
601 return report;
602 }
603 }
604 continue;
605 }
606 if run.seen.contains(crate::land::LAND_REMOTE_MOVED) {
609 report.status = Status::Refused;
610 report.next = vec![format!("{BIN} land")];
611 return report;
612 }
613 if run.seen.contains(crate::land::LAND_EVIDENCE_MISSING) {
614 report.status = Status::Refused;
615 report.next = vec![format!("{BIN} rehearse --wait"), format!("{BIN} land")];
616 return report;
617 }
618 report.status = status_of_failed_push(&run.stderr);
619 return report;
620 };
621
622 let mut observed = Seen::Unreachable;
624 for i in 0..=REREADS {
625 if i > 0 {
626 std::thread::sleep(crate::clock::scaled(REREAD_PAUSE));
627 }
628 observed = read_tip(&url, &rb, budget);
629 if matches!(&observed, Seen::Tip(t) if *t == pushed) {
630 break;
631 }
632 }
633 match observed {
634 Seen::Tip(t) if t == pushed => {
635 report.remote_after = t;
636 report.status = Status::Landed;
637 move_tracking_ref(&remote, &rb, &pushed);
638 if !has_upstream {
639 set_upstream(&remote, &rb);
640 }
641 }
642 Seen::Tip(t) => {
643 report.remote_after = t;
644 report.status = Status::NotObserved;
645 eprintln!(
646 "{BIN}: land: the remote accepted the push but {rb} reads {}, not {}",
647 short(&report.remote_after),
648 short(&pushed)
649 );
650 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
651 }
652 Seen::Unreachable => {
653 report.status = Status::Unverified;
654 eprintln!("{BIN}: land: the push was accepted but {rb} could not be read back");
655 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
656 }
657 }
658 report
659}
660
661const ZEROS: &str = "0000000000000000000000000000000000000000";
663
664fn or_zeros(tip: &str) -> &str {
665 if tip.is_empty() {
666 ZEROS
667 } else {
668 tip
669 }
670}
671
672enum Prestage {
674 Ready,
676 Refused(String, Vec<String>),
678 Interrupted(i32),
680}
681
682struct Staged {
685 owed: Vec<String>,
686 state: PrestageState,
687 end: Prestage,
688}
689
690impl Staged {
691 fn ended(owed: Vec<String>, state: PrestageState, end: Prestage) -> Staged {
692 Staged { owed, state, end }
693 }
694
695 fn refused(owed: Vec<String>, state: PrestageState, why: String) -> Staged {
696 Staged::ended(owed, state, Prestage::Refused(why, Vec::new()))
697 }
698
699 fn into_report(self, mut report: Report) -> ControlFlow<Box<Report>, Report> {
702 report.gates_owed = self.owed;
703 report.prestage = self.state;
704 match self.end {
705 Prestage::Ready => ControlFlow::Continue(report),
706 Prestage::Refused(why, next) => {
707 eprintln!("{BIN}: land: {why}");
708 report.status = Status::Refused;
709 report.next = next;
710 ControlFlow::Break(Box::new(report))
711 }
712 Prestage::Interrupted(sig) => {
713 report.status = Status::Interrupted(sig);
714 ControlFlow::Break(Box::new(report))
715 }
716 }
717 }
718}
719
720fn status_of_failed_push(stderr: &str) -> Status {
722 match classify_push_stderr(stderr) {
723 PushFailure::Unreachable => Status::Unreachable,
724 PushFailure::Raced | PushFailure::Refused => Status::Refused,
725 _ => Status::Refused,
728 }
729}
730
731fn last_rehearsal() -> Option<(u32, u64, bool)> {
735 crate::rehearsal::read().map(|s| (s.pid, s.started, s.alive()))
736}
737
738fn prestage(
746 local_ref: &str,
747 sha: &str,
748 dst: &str,
749 remote_tip: &str,
750 (remote, url): (&str, &str),
751) -> Staged {
752 let again = match dst.strip_prefix("refs/tags/") {
754 Some(tag) => format!("{BIN} land --tag {tag}"),
755 None => format!("{BIN} land"),
756 };
757 let root = match crate::hooks::common::repo_root_checked() {
758 Ok(root) => root,
759 Err(e) => return Staged::refused(Vec::new(), PrestageState::Refused, e),
760 };
761 let manifest = crate::manifest::load(std::path::Path::new(&root));
762 let settings = crate::config::Settings::new(manifest.policy.clone());
763 if !remote_tip.is_empty() && !has_commit(remote_tip) {
768 eprintln!(
769 "{BIN}: land: fetching {} ({dst}) from the remote",
770 short(remote_tip)
771 );
772 let budget = crate::hooks::common::check_timeout(&settings);
773 let (probe, _) = git::probe_remote_stdout(&["fetch", "-q", "--no-tags", url, dst], budget);
774 if !has_commit(remote_tip) {
775 let how = match probe {
776 Probe::Exit(0) => "it fetched, but not that commit".to_string(),
777 Probe::Exit(code) => format!("git fetch exited {code}"),
778 Probe::TimedOut(secs) => format!("git fetch did not finish within {secs}s"),
779 Probe::Failed => "git fetch did not run".to_string(),
780 };
781 return Staged::ended(
782 Vec::new(),
783 PrestageState::Refused,
784 Prestage::Refused(
785 format!(
786 "the remote's {dst} is at {}, a commit this clone does not have ({how})",
787 short(remote_tip)
788 ),
789 vec![format!("git fetch --no-tags {remote} {dst}"), again],
791 ),
792 );
793 }
794 }
795 let line = crate::pushrefs::PushRef {
796 local_ref: local_ref.to_string(),
797 local_oid: sha.to_string(),
798 remote_ref: dst.to_string(),
799 remote_oid: or_zeros(remote_tip).to_string(),
800 };
801 let changed = crate::pushrefs::changed_files(std::slice::from_ref(&line));
802 let mut owed = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
803 let audits = crate::hooks::audit::Ledger::default();
804 for audit in
805 crate::dispatch::owed_audits(&settings, &manifest, &audits, std::slice::from_ref(&line))
806 {
807 if !owed.contains(&audit) {
808 owed.push(audit);
809 }
810 }
811 if owed.is_empty() {
812 return Staged::ended(owed, PrestageState::Stamped, Prestage::Ready);
813 }
814 if !crate::gate_stamp::push_stamps_enabled(&settings) {
815 return Staged::ended(
816 owed,
817 PrestageState::Refused,
818 Prestage::Refused(
819 "stamp reuse is off (amont.pushStamps false), so the gates land runs \
820 cannot count at the push"
821 .to_string(),
822 vec!["git config amont.pushStamps true".to_string(), again],
823 ),
824 );
825 }
826 let exe = match std::env::current_exe() {
827 Ok(exe) => exe,
828 Err(e) => {
829 return Staged::refused(
830 owed,
831 PrestageState::Refused,
832 format!("cannot locate the {BIN} binary for the pre-stage: {e}"),
833 )
834 }
835 };
836 let names: Vec<&str> = owed.iter().map(String::as_str).collect();
837 eprintln!(
838 "{BIN}: land: {} push gate{} to check before git connects:",
839 owed.len(),
840 if owed.len() == 1 { "" } else { "s" }
841 );
842 for wrapped in crate::dispatch::wrap_names(&names) {
843 eprintln!("{wrapped}");
844 }
845 let before = last_rehearsal();
846 let status = Command::new(exe)
847 .args(["rehearse", "--wait"])
848 .env(
849 crate::rehearsal::PRESTAGE_ENV,
850 format!(
851 "{} {} {} {}",
852 line.local_ref, line.local_oid, line.remote_ref, line.remote_oid
853 ),
854 )
855 .stdin(Stdio::null())
856 .stdout(Stdio::from(std::io::stderr()))
857 .status();
858 let status = match status {
859 Ok(status) => status,
860 Err(e) => {
861 return Staged::refused(
862 owed,
863 PrestageState::Refused,
864 format!("could not start the pre-stage: {e}"),
865 )
866 }
867 };
868 if let Some(sig) = signal_of(&status) {
869 return Staged::ended(owed, PrestageState::Interrupted, Prestage::Interrupted(sig));
870 }
871 match status.code() {
872 Some(0) => {
873 let followed = before.is_some_and(|(_, _, running)| running);
877 let state = if followed
878 || last_rehearsal().map(|(p, t, _)| (p, t)) != before.map(|(p, t, _)| (p, t))
879 {
880 PrestageState::Ran
881 } else {
882 PrestageState::Stamped
883 };
884 Staged::ended(owed, state, Prestage::Ready)
885 }
886 Some(1) => Staged::ended(
887 owed,
888 PrestageState::Failed,
889 Prestage::Refused(
890 "a push gate failed before the push (named above); nothing was pushed".to_string(),
891 vec![format!("{BIN} rehearse --status"), again],
892 ),
893 ),
894 Some(code) if code > 128 => Staged::ended(
896 owed,
897 PrestageState::Interrupted,
898 Prestage::Interrupted(code - 128),
899 ),
900 code => Staged::refused(
901 owed,
902 PrestageState::Refused,
903 format!(
904 "the pre-stage could not run (exit {}); nothing was pushed",
905 code.map_or("by signal".to_string(), |c| c.to_string())
906 ),
907 ),
908 }
909}
910
911fn has_commit(oid: &str) -> bool {
912 git::succeeds(&["cat-file", "-e", &format!("{oid}^{{commit}}")])
913}
914
915fn resolve_tag(name: &str) -> Result<(Report, String, String), Box<Report>> {
922 let mut report = Report::new(Status::Refused);
923 let dst = format!("refs/tags/{name}");
924 report.dst = dst.clone();
925 let Some(oid) = git::stdout(&["rev-parse", "--verify", "-q", &dst]) else {
926 return Err(Box::new(refuse(
927 report,
928 &format!("there is no local tag {name:?}"),
929 &["git tag --list"],
930 )));
931 };
932 report.pushed = oid.clone();
933 let remote = git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"])
934 .and_then(|b| git::stdout(&["config", &format!("branch.{b}.remote")]))
935 .filter(|r| r != ".")
936 .unwrap_or_else(|| "origin".to_string());
937 report.remote = remote.clone();
938 let (url, report) = one_push_url(&remote, report)?;
939 Ok((report, url, oid))
940}
941
942fn dry_run_tag(name: &str) -> (Report, &'static str) {
945 match resolve_tag(name) {
946 Ok((report, _, _)) => (report, "would-land"),
947 Err(refused) => (*refused, "refused"),
948 }
949}
950
951fn land_tag(name: &str) -> Report {
952 let settings = crate::config::Settings::default();
953 let budget = crate::hooks::common::network_probe_budget(&settings);
954 let (mut report, url, oid) = match resolve_tag(name) {
955 Ok(resolved) => resolved,
956 Err(refused) => return *refused,
957 };
958 let (dst, remote) = (report.dst.clone(), report.remote.clone());
959 match read_ref(&url, &dst, budget) {
960 Seen::Tip(t) if t.is_empty() => {}
961 Seen::Tip(t) => {
962 report.remote_before = t.clone();
963 return refuse(
964 report,
965 &format!("{dst} already exists on {remote}; a tag is never moved"),
966 &[&format!("git ls-remote {remote} {dst}")],
967 );
968 }
969 Seen::Unreachable => {
970 report.status = Status::Unreachable;
971 eprintln!("{BIN}: land: could not read {dst} from {remote}");
972 report.next = vec![format!("git ls-remote {remote} {dst}")];
973 return report;
974 }
975 }
976 report = match prestage(&dst, &oid, &dst, "", (&remote, &url)).into_report(report) {
977 ControlFlow::Continue(report) => report,
978 ControlFlow::Break(stopped) => return *stopped,
979 };
980 let land_env = format!("{oid} {ZEROS}");
981 let run = push(&url, &dst, &dst, None, &land_env);
982 match run.outcome {
983 PushOutcome::Done => {}
984 PushOutcome::Signal(sig) => {
985 report.status = Status::Interrupted(sig);
986 return report;
987 }
988 PushOutcome::Failed => {
989 report.status = status_of_failed_push(&run.stderr);
990 if run.seen.contains(LAND_EVIDENCE_MISSING) {
991 report.next = vec![format!("{BIN} land --tag {name}")];
994 }
995 return report;
996 }
997 }
998 let mut observed = Seen::Unreachable;
999 for i in 0..=REREADS {
1000 if i > 0 {
1001 std::thread::sleep(crate::clock::scaled(REREAD_PAUSE));
1002 }
1003 observed = read_ref(&url, &dst, budget);
1004 if matches!(&observed, Seen::Tip(t) if *t == oid) {
1005 break;
1006 }
1007 }
1008 match observed {
1009 Seen::Tip(t) if t == oid => {
1010 report.remote_after = t;
1011 report.status = Status::Landed;
1012 }
1013 Seen::Tip(t) => {
1014 report.remote_after = t;
1015 report.status = Status::NotObserved;
1016 report.next = vec![format!("git ls-remote {remote} {dst}")];
1017 }
1018 Seen::Unreachable => {
1019 report.status = Status::Unverified;
1020 report.next = vec![format!("git ls-remote {remote} {dst}")];
1021 }
1022 }
1023 report
1024}
1025
1026fn dry_run_branch() -> (Report, &'static str) {
1029 match resolve() {
1030 Ok((_, mut report)) => {
1031 report.pushed = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
1032 (report, "would-land")
1033 }
1034 Err(refused) => (*refused, "refused"),
1035 }
1036}
1037
1038fn say_dry_run(report: &Report, verdict: &str) {
1040 for line in &report.next {
1041 eprintln!(" {line}");
1042 }
1043 eprintln!(
1044 "{}",
1045 verdict_word(verdict, "", &report.pushed, shown_ref(report))
1046 );
1047}
1048
1049fn dry_run_json(report: &Report, verdict: &str, mode: Mode) -> String {
1051 let dir = receipt_dir()
1052 .map(|d| d.to_string_lossy().into_owned())
1053 .unwrap_or_default();
1054 json::object(&[
1055 json::string_field("branch", &report.branch),
1056 json::string_field("remote", &report.remote),
1057 json::string_field("push_url", &report.push_url),
1058 json::string_field("pushed", &report.pushed),
1059 json::string_field("dst", &report.dst),
1060 json::string_field("ref", &report.dst),
1061 json::bool_field("retried", false),
1062 json::string_field("status", verdict),
1063 json::string_field("receipt_dir", &dir),
1064 json::bool_field("lease", mode == Mode::Force),
1065 ])
1066}
1067
1068fn now_nanos() -> i64 {
1069 SystemTime::now()
1070 .duration_since(UNIX_EPOCH)
1071 .ok()
1072 .and_then(|d| i64::try_from(d.as_nanos()).ok())
1073 .unwrap_or(0)
1074}
1075
1076fn receipt_dir() -> Option<PathBuf> {
1078 git::stdout(&["rev-parse", "--absolute-git-dir"])
1079 .map(|d| PathBuf::from(d).join("amont").join("land"))
1080}
1081
1082fn write_receipt(report: &Report, started: i64, ended: i64) {
1087 if report.branch.is_empty() && report.dst.is_empty() {
1088 return;
1089 }
1090 let Some(dir) = receipt_dir() else {
1091 eprintln!("{BIN}: land: could not find the git directory; no landing receipt written");
1092 return;
1093 };
1094 if let Err(e) = std::fs::create_dir_all(&dir) {
1095 eprintln!(
1096 "{BIN}: land: could not write a landing receipt in {}: {e}",
1097 dir.display()
1098 );
1099 return;
1100 }
1101 prune_receipts(&dir);
1102 let path = dir.join(format!("{started}-{}.json", std::process::id()));
1103 let body = json::object(&[
1104 json::int_field("started", started),
1105 json::int_field("ended", ended),
1106 json::string_field("branch", &report.branch),
1107 json::string_field("remote", &report.remote),
1108 json::string_field("push_url", &report.push_url),
1109 json::string_field("dst", &report.dst),
1110 json::string_field("pushed", &report.pushed),
1111 json::bool_field("retried", report.retried),
1112 json::string_field("status", report.status.as_str()),
1113 ]);
1114 if let Err(e) = std::fs::write(&path, format!("{body}\n")) {
1115 eprintln!(
1116 "{BIN}: land: could not write the landing receipt {}: {e}",
1117 path.display()
1118 );
1119 }
1120}
1121
1122fn prune_receipts(dir: &std::path::Path) {
1124 let Ok(entries) = std::fs::read_dir(dir) else {
1125 return;
1126 };
1127 for entry in entries.flatten() {
1128 let path = entry.path();
1129 if path.extension().map_or(true, |e| e != "json") {
1130 continue;
1131 }
1132 let old = entry
1133 .metadata()
1134 .and_then(|m| m.modified())
1135 .ok()
1136 .and_then(|t| t.elapsed().ok())
1137 .is_some_and(|age| age > RECEIPT_KEEP);
1138 if old {
1139 if let Err(e) = std::fs::remove_file(&path) {
1140 eprintln!(
1141 "{BIN}: land: could not delete the old receipt {}: {e}",
1142 path.display()
1143 );
1144 }
1145 }
1146 }
1147}
1148
1149fn is_protected(branch: &str) -> bool {
1150 matches!(branch, "main" | "master")
1151}
1152
1153fn move_tracking_ref(remote: &str, rb: &str, sha: &str) {
1157 let tracking = format!("refs/remotes/{remote}/{rb}");
1158 if !git::succeeds(&["update-ref", &tracking, sha]) {
1159 eprintln!(
1160 "{BIN}: land: landed, but could not move {tracking} to {}",
1161 short(sha)
1162 );
1163 }
1164}
1165
1166fn set_upstream(remote: &str, rb: &str) {
1168 let upstream = format!("{remote}/{rb}");
1169 if !git::succeeds(&["branch", "--set-upstream-to", &upstream]) {
1170 eprintln!("{BIN}: land: landed, but could not set the upstream to {upstream}");
1171 }
1172}
1173
1174enum PushOutcome {
1175 Done,
1176 Failed,
1177 Signal(i32),
1178}
1179
1180struct PushRun {
1181 outcome: PushOutcome,
1182 stderr: String,
1184 seen: String,
1186}
1187
1188fn push(url: &str, src: &str, dst: &str, lease: Option<&str>, land_env: &str) -> PushRun {
1200 let mut cmd = Command::new("git");
1201 cmd.env(crate::rehearsal::LAND_ENV, land_env);
1203 if !std::io::stdin().is_terminal() {
1204 let (pre, env) = git::remote_env(git::configured_ssh());
1205 cmd.args(pre).envs(env);
1206 }
1207 cmd.arg("push");
1208 if let Some(old) = lease {
1209 cmd.arg(format!("--force-with-lease={dst}:{old}"));
1210 }
1211 cmd.arg(url)
1212 .arg(format!("{src}:{dst}"))
1213 .stdin(Stdio::inherit())
1214 .stdout(Stdio::piped())
1215 .stderr(Stdio::piped());
1216 let mut child = match cmd.spawn() {
1217 Ok(c) => c,
1218 Err(e) => {
1219 let why = format!("could not run git push: {e}\n");
1220 eprint!("{BIN}: land: {why}");
1221 return PushRun {
1222 outcome: PushOutcome::Failed,
1223 stderr: why.clone(),
1224 seen: why,
1225 };
1226 }
1227 };
1228 let tee = |mut from: Box<dyn Read + Send>| {
1229 std::thread::spawn(move || {
1230 let mut kept = Vec::new();
1231 let mut buf = [0u8; 4096];
1232 let mut err = std::io::stderr();
1233 while let Ok(n) = from.read(&mut buf) {
1234 if n == 0 {
1235 break;
1236 }
1237 let _ = err.write_all(&buf[..n]);
1238 let _ = err.flush();
1239 kept.extend_from_slice(&buf[..n]);
1240 }
1241 String::from_utf8_lossy(&kept).into_owned()
1242 })
1243 };
1244 let out_thread = child.stdout.take().map(|s| tee(Box::new(s)));
1245 let err_thread = child.stderr.take().map(|s| tee(Box::new(s)));
1246 let status = child.wait();
1247 let out = out_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1248 let err = err_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1249 let outcome = match status {
1250 Ok(s) if s.success() => PushOutcome::Done,
1251 Ok(s) => match signal_of(&s) {
1252 Some(sig) => PushOutcome::Signal(sig),
1253 None => PushOutcome::Failed,
1254 },
1255 Err(_) => PushOutcome::Failed,
1256 };
1257 PushRun {
1258 outcome,
1259 seen: format!("{out}{err}"),
1260 stderr: err,
1261 }
1262}
1263
1264#[cfg(test)]
1265mod tests {
1266
1267 #[test]
1269 fn a_push_url_is_reported_without_its_credentials() {
1270 let r = super::redact_url;
1271 assert_eq!(
1272 r("https://x:tok@github.com/o/r.git"),
1273 "https://***@github.com/o/r.git"
1274 );
1275 assert_eq!(
1276 r("https://tok@github.com/o/r.git"),
1277 "https://***@github.com/o/r.git"
1278 );
1279 assert_eq!(r("ssh://git:pw@host/o/r"), "ssh://git:***@host/o/r");
1280 assert_eq!(
1281 r("ssh://git@github.com/o/r.git"),
1282 "ssh://git@github.com/o/r.git"
1283 );
1284 assert_eq!(r("git@github.com:o/r.git"), "git@github.com:o/r.git");
1285 assert_eq!(
1286 r("https://github.com/o/r.git"),
1287 "https://github.com/o/r.git"
1288 );
1289 assert_eq!(r("/tmp/bare.git"), "/tmp/bare.git");
1290 }
1291 use super::*;
1292
1293 #[test]
1294 fn exit_codes_keep_usage_apart_from_the_lost_ref() {
1295 assert_eq!(Status::Landed.code(), 0);
1296 assert_eq!(Status::Refused.code(), 1);
1297 assert_eq!(Status::Usage.code(), 2);
1298 assert_eq!(Status::Unreachable.code(), 3);
1299 assert_eq!(Status::Unverified.code(), 3);
1300 assert_eq!(Status::NotObserved.code(), 4);
1301 assert_eq!(Status::Interrupted(2).code(), 130);
1302 }
1303
1304 #[test]
1305 fn every_status_has_its_own_word() {
1306 let all = [
1307 Status::Landed,
1308 Status::Refused,
1309 Status::Usage,
1310 Status::Unreachable,
1311 Status::Unverified,
1312 Status::NotObserved,
1313 Status::Interrupted(15),
1314 ];
1315 let words: std::collections::HashSet<_> = all.iter().map(|s| s.as_str()).collect();
1316 assert_eq!(words.len(), all.len());
1317 }
1318
1319 #[test]
1320 fn the_verdict_fits_eighty_columns_for_any_branch() {
1321 let long = "feature/".to_string() + &"x".repeat(120);
1322 for status in [Status::Landed, Status::NotObserved, Status::Unverified] {
1323 let line = verdict(status, "0123456789abcdef", "fedcba9876543210", &long);
1324 assert!(line.chars().count() <= 80, "{line}");
1325 assert!(line.contains('…'), "{line}");
1326 assert!(line.starts_with(status.as_str()));
1327 }
1328 }
1329
1330 #[test]
1331 fn a_short_branch_is_shown_whole_and_a_new_ref_has_a_placeholder() {
1332 let line = verdict(Status::Landed, "", "fedcba9876543210", "feat/x");
1333 assert_eq!(line, "landed -------..fedcba9 feat/x");
1334 }
1335
1336 #[test]
1337 fn the_verdict_is_plain_text() {
1338 let line = verdict(Status::Refused, "a", "b", "feat/ünï");
1339 assert!(!line.contains('\u{1b}'));
1340 }
1341
1342 #[test]
1343 fn truncation_keeps_both_ends() {
1344 assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
1345 assert_eq!(truncate_middle("abc", 5), "abc");
1346 assert_eq!(truncate_middle("abcdefghij", 1), "…");
1347 }
1348
1349 #[test]
1350 fn the_tip_is_the_first_field_and_absence_is_empty() {
1351 assert_eq!(parse_tip("abc123\trefs/heads/x\n"), "abc123");
1352 assert_eq!(parse_tip(""), "");
1353 }
1354
1355 #[test]
1356 fn json_carries_every_field_the_contract_names() {
1357 let mut r = Report::new(Status::NotObserved);
1358 r.branch = "feat/x".into();
1359 r.retried = true;
1360 let j = r.json();
1361 for key in [
1362 "branch",
1363 "remote",
1364 "push_url",
1365 "pushed",
1366 "remote_before",
1367 "remote_after",
1368 "retried",
1369 "status",
1370 ] {
1371 assert!(j.contains(&format!("\"{key}\"")), "{key} missing in {j}");
1372 }
1373 assert!(j.contains("\"status\":\"not-observed\""), "{j}");
1374 assert!(j.contains("\"retried\":true"), "{j}");
1375 assert!(usage_json().contains("\"status\":\"usage\""));
1376 }
1377}