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, settings) = crate::manifest::load_resolved(std::path::Path::new(&root));
762 if !remote_tip.is_empty() && !has_commit(remote_tip) {
767 eprintln!(
768 "{BIN}: land: fetching {} ({dst}) from the remote",
769 short(remote_tip)
770 );
771 let budget = crate::hooks::common::check_timeout(&settings);
772 let (probe, _) = git::probe_remote_stdout(&["fetch", "-q", "--no-tags", url, dst], budget);
773 if !has_commit(remote_tip) {
774 let how = match probe {
775 Probe::Exit(0) => "it fetched, but not that commit".to_string(),
776 Probe::Exit(code) => format!("git fetch exited {code}"),
777 Probe::TimedOut(secs) => format!("git fetch did not finish within {secs}s"),
778 Probe::Failed => "git fetch did not run".to_string(),
779 };
780 return Staged::ended(
781 Vec::new(),
782 PrestageState::Refused,
783 Prestage::Refused(
784 format!(
785 "the remote's {dst} is at {}, a commit this clone does not have ({how})",
786 short(remote_tip)
787 ),
788 vec![format!("git fetch --no-tags {remote} {dst}"), again],
790 ),
791 );
792 }
793 }
794 let line = crate::pushrefs::PushRef {
795 local_ref: local_ref.to_string(),
796 local_oid: sha.to_string(),
797 remote_ref: dst.to_string(),
798 remote_oid: or_zeros(remote_tip).to_string(),
799 };
800 let changed = crate::pushrefs::changed_files(std::slice::from_ref(&line));
801 let mut owed = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
802 let audits = crate::hooks::audit::Ledger::default();
803 for audit in
804 crate::dispatch::owed_audits(&settings, &manifest, &audits, std::slice::from_ref(&line))
805 {
806 if !owed.contains(&audit) {
807 owed.push(audit);
808 }
809 }
810 if owed.is_empty() {
811 return Staged::ended(owed, PrestageState::Stamped, Prestage::Ready);
812 }
813 if !crate::gate_stamp::push_stamps_enabled(&settings) {
814 return Staged::ended(
815 owed,
816 PrestageState::Refused,
817 Prestage::Refused(
818 "stamp reuse is off (amont.pushStamps false), so the gates land runs \
819 cannot count at the push"
820 .to_string(),
821 vec!["git config amont.pushStamps true".to_string(), again],
822 ),
823 );
824 }
825 let exe = match std::env::current_exe() {
826 Ok(exe) => exe,
827 Err(e) => {
828 return Staged::refused(
829 owed,
830 PrestageState::Refused,
831 format!("cannot locate the {BIN} binary for the pre-stage: {e}"),
832 )
833 }
834 };
835 let names: Vec<&str> = owed.iter().map(String::as_str).collect();
836 eprintln!(
837 "{BIN}: land: {} push gate{} to check before git connects:",
838 owed.len(),
839 if owed.len() == 1 { "" } else { "s" }
840 );
841 for wrapped in crate::dispatch::wrap_names(&names) {
842 eprintln!("{wrapped}");
843 }
844 let before = last_rehearsal();
845 let status = Command::new(exe)
846 .args(["rehearse", "--wait"])
847 .env(
848 crate::rehearsal::PRESTAGE_ENV,
849 format!(
850 "{} {} {} {}",
851 line.local_ref, line.local_oid, line.remote_ref, line.remote_oid
852 ),
853 )
854 .stdin(Stdio::null())
855 .stdout(Stdio::from(std::io::stderr()))
856 .status();
857 let status = match status {
858 Ok(status) => status,
859 Err(e) => {
860 return Staged::refused(
861 owed,
862 PrestageState::Refused,
863 format!("could not start the pre-stage: {e}"),
864 )
865 }
866 };
867 if let Some(sig) = signal_of(&status) {
868 return Staged::ended(owed, PrestageState::Interrupted, Prestage::Interrupted(sig));
869 }
870 match status.code() {
871 Some(0) => {
872 let followed = before.is_some_and(|(_, _, running)| running);
876 let state = if followed
877 || last_rehearsal().map(|(p, t, _)| (p, t)) != before.map(|(p, t, _)| (p, t))
878 {
879 PrestageState::Ran
880 } else {
881 PrestageState::Stamped
882 };
883 Staged::ended(owed, state, Prestage::Ready)
884 }
885 Some(1) => Staged::ended(
886 owed,
887 PrestageState::Failed,
888 Prestage::Refused(
889 "a push gate failed before the push (named above); nothing was pushed".to_string(),
890 vec![format!("{BIN} rehearse --status"), again],
891 ),
892 ),
893 Some(code) if code > 128 => Staged::ended(
895 owed,
896 PrestageState::Interrupted,
897 Prestage::Interrupted(code - 128),
898 ),
899 code => Staged::refused(
900 owed,
901 PrestageState::Refused,
902 format!(
903 "the pre-stage could not run (exit {}); nothing was pushed",
904 code.map_or("by signal".to_string(), |c| c.to_string())
905 ),
906 ),
907 }
908}
909
910fn has_commit(oid: &str) -> bool {
911 git::succeeds(&["cat-file", "-e", &format!("{oid}^{{commit}}")])
912}
913
914fn resolve_tag(name: &str) -> Result<(Report, String, String), Box<Report>> {
921 let mut report = Report::new(Status::Refused);
922 let dst = format!("refs/tags/{name}");
923 report.dst = dst.clone();
924 let Some(oid) = git::stdout(&["rev-parse", "--verify", "-q", &dst]) else {
925 return Err(Box::new(refuse(
926 report,
927 &format!("there is no local tag {name:?}"),
928 &["git tag --list"],
929 )));
930 };
931 report.pushed = oid.clone();
932 let remote = git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"])
933 .and_then(|b| git::stdout(&["config", &format!("branch.{b}.remote")]))
934 .filter(|r| r != ".")
935 .unwrap_or_else(|| "origin".to_string());
936 report.remote = remote.clone();
937 let (url, report) = one_push_url(&remote, report)?;
938 Ok((report, url, oid))
939}
940
941fn dry_run_tag(name: &str) -> (Report, &'static str) {
944 match resolve_tag(name) {
945 Ok((report, _, _)) => (report, "would-land"),
946 Err(refused) => (*refused, "refused"),
947 }
948}
949
950fn land_tag(name: &str) -> Report {
951 let settings = crate::config::Settings::default();
952 let budget = crate::hooks::common::network_probe_budget(&settings);
953 let (mut report, url, oid) = match resolve_tag(name) {
954 Ok(resolved) => resolved,
955 Err(refused) => return *refused,
956 };
957 let (dst, remote) = (report.dst.clone(), report.remote.clone());
958 match read_ref(&url, &dst, budget) {
959 Seen::Tip(t) if t.is_empty() => {}
960 Seen::Tip(t) => {
961 report.remote_before = t.clone();
962 return refuse(
963 report,
964 &format!("{dst} already exists on {remote}; a tag is never moved"),
965 &[&format!("git ls-remote {remote} {dst}")],
966 );
967 }
968 Seen::Unreachable => {
969 report.status = Status::Unreachable;
970 eprintln!("{BIN}: land: could not read {dst} from {remote}");
971 report.next = vec![format!("git ls-remote {remote} {dst}")];
972 return report;
973 }
974 }
975 report = match prestage(&dst, &oid, &dst, "", (&remote, &url)).into_report(report) {
976 ControlFlow::Continue(report) => report,
977 ControlFlow::Break(stopped) => return *stopped,
978 };
979 let land_env = format!("{oid} {ZEROS}");
980 let run = push(&url, &dst, &dst, None, &land_env);
981 match run.outcome {
982 PushOutcome::Done => {}
983 PushOutcome::Signal(sig) => {
984 report.status = Status::Interrupted(sig);
985 return report;
986 }
987 PushOutcome::Failed => {
988 report.status = status_of_failed_push(&run.stderr);
989 if run.seen.contains(LAND_EVIDENCE_MISSING) {
990 report.next = vec![format!("{BIN} land --tag {name}")];
993 }
994 return report;
995 }
996 }
997 let mut observed = Seen::Unreachable;
998 for i in 0..=REREADS {
999 if i > 0 {
1000 std::thread::sleep(crate::clock::scaled(REREAD_PAUSE));
1001 }
1002 observed = read_ref(&url, &dst, budget);
1003 if matches!(&observed, Seen::Tip(t) if *t == oid) {
1004 break;
1005 }
1006 }
1007 match observed {
1008 Seen::Tip(t) if t == oid => {
1009 report.remote_after = t;
1010 report.status = Status::Landed;
1011 }
1012 Seen::Tip(t) => {
1013 report.remote_after = t;
1014 report.status = Status::NotObserved;
1015 report.next = vec![format!("git ls-remote {remote} {dst}")];
1016 }
1017 Seen::Unreachable => {
1018 report.status = Status::Unverified;
1019 report.next = vec![format!("git ls-remote {remote} {dst}")];
1020 }
1021 }
1022 report
1023}
1024
1025fn dry_run_branch() -> (Report, &'static str) {
1028 match resolve() {
1029 Ok((_, mut report)) => {
1030 report.pushed = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
1031 (report, "would-land")
1032 }
1033 Err(refused) => (*refused, "refused"),
1034 }
1035}
1036
1037fn say_dry_run(report: &Report, verdict: &str) {
1039 for line in &report.next {
1040 eprintln!(" {line}");
1041 }
1042 eprintln!(
1043 "{}",
1044 verdict_word(verdict, "", &report.pushed, shown_ref(report))
1045 );
1046}
1047
1048fn dry_run_json(report: &Report, verdict: &str, mode: Mode) -> String {
1050 let dir = receipt_dir()
1051 .map(|d| d.to_string_lossy().into_owned())
1052 .unwrap_or_default();
1053 json::object(&[
1054 json::string_field("branch", &report.branch),
1055 json::string_field("remote", &report.remote),
1056 json::string_field("push_url", &report.push_url),
1057 json::string_field("pushed", &report.pushed),
1058 json::string_field("dst", &report.dst),
1059 json::string_field("ref", &report.dst),
1060 json::bool_field("retried", false),
1061 json::string_field("status", verdict),
1062 json::string_field("receipt_dir", &dir),
1063 json::bool_field("lease", mode == Mode::Force),
1064 ])
1065}
1066
1067fn now_nanos() -> i64 {
1068 SystemTime::now()
1069 .duration_since(UNIX_EPOCH)
1070 .ok()
1071 .and_then(|d| i64::try_from(d.as_nanos()).ok())
1072 .unwrap_or(0)
1073}
1074
1075fn receipt_dir() -> Option<PathBuf> {
1077 git::stdout(&["rev-parse", "--absolute-git-dir"])
1078 .map(|d| PathBuf::from(d).join("amont").join("land"))
1079}
1080
1081fn write_receipt(report: &Report, started: i64, ended: i64) {
1086 if report.branch.is_empty() && report.dst.is_empty() {
1087 return;
1088 }
1089 let Some(dir) = receipt_dir() else {
1090 eprintln!("{BIN}: land: could not find the git directory; no landing receipt written");
1091 return;
1092 };
1093 if let Err(e) = std::fs::create_dir_all(&dir) {
1094 eprintln!(
1095 "{BIN}: land: could not write a landing receipt in {}: {e}",
1096 dir.display()
1097 );
1098 return;
1099 }
1100 prune_receipts(&dir);
1101 let path = dir.join(format!("{started}-{}.json", std::process::id()));
1102 let body = json::object(&[
1103 json::int_field("started", started),
1104 json::int_field("ended", ended),
1105 json::string_field("branch", &report.branch),
1106 json::string_field("remote", &report.remote),
1107 json::string_field("push_url", &report.push_url),
1108 json::string_field("dst", &report.dst),
1109 json::string_field("pushed", &report.pushed),
1110 json::bool_field("retried", report.retried),
1111 json::string_field("status", report.status.as_str()),
1112 ]);
1113 if let Err(e) = std::fs::write(&path, format!("{body}\n")) {
1114 eprintln!(
1115 "{BIN}: land: could not write the landing receipt {}: {e}",
1116 path.display()
1117 );
1118 }
1119}
1120
1121fn prune_receipts(dir: &std::path::Path) {
1123 let Ok(entries) = std::fs::read_dir(dir) else {
1124 return;
1125 };
1126 for entry in entries.flatten() {
1127 let path = entry.path();
1128 if path.extension().map_or(true, |e| e != "json") {
1129 continue;
1130 }
1131 let old = entry
1132 .metadata()
1133 .and_then(|m| m.modified())
1134 .ok()
1135 .and_then(|t| t.elapsed().ok())
1136 .is_some_and(|age| age > RECEIPT_KEEP);
1137 if old {
1138 if let Err(e) = std::fs::remove_file(&path) {
1139 eprintln!(
1140 "{BIN}: land: could not delete the old receipt {}: {e}",
1141 path.display()
1142 );
1143 }
1144 }
1145 }
1146}
1147
1148fn is_protected(branch: &str) -> bool {
1149 matches!(branch, "main" | "master")
1150}
1151
1152fn move_tracking_ref(remote: &str, rb: &str, sha: &str) {
1156 let tracking = format!("refs/remotes/{remote}/{rb}");
1157 if !git::succeeds(&["update-ref", &tracking, sha]) {
1158 eprintln!(
1159 "{BIN}: land: landed, but could not move {tracking} to {}",
1160 short(sha)
1161 );
1162 }
1163}
1164
1165fn set_upstream(remote: &str, rb: &str) {
1167 let upstream = format!("{remote}/{rb}");
1168 if !git::succeeds(&["branch", "--set-upstream-to", &upstream]) {
1169 eprintln!("{BIN}: land: landed, but could not set the upstream to {upstream}");
1170 }
1171}
1172
1173enum PushOutcome {
1174 Done,
1175 Failed,
1176 Signal(i32),
1177}
1178
1179struct PushRun {
1180 outcome: PushOutcome,
1181 stderr: String,
1183 seen: String,
1185}
1186
1187fn push(url: &str, src: &str, dst: &str, lease: Option<&str>, land_env: &str) -> PushRun {
1199 let mut cmd = Command::new("git");
1200 cmd.env(crate::rehearsal::LAND_ENV, land_env);
1202 if !std::io::stdin().is_terminal() {
1203 let (pre, env) = git::remote_env(git::configured_ssh());
1204 cmd.args(pre).envs(env);
1205 }
1206 cmd.arg("push");
1207 if let Some(old) = lease {
1208 cmd.arg(format!("--force-with-lease={dst}:{old}"));
1209 }
1210 cmd.arg(url)
1211 .arg(format!("{src}:{dst}"))
1212 .stdin(Stdio::inherit())
1213 .stdout(Stdio::piped())
1214 .stderr(Stdio::piped());
1215 let mut child = match cmd.spawn() {
1216 Ok(c) => c,
1217 Err(e) => {
1218 let why = format!("could not run git push: {e}\n");
1219 eprint!("{BIN}: land: {why}");
1220 return PushRun {
1221 outcome: PushOutcome::Failed,
1222 stderr: why.clone(),
1223 seen: why,
1224 };
1225 }
1226 };
1227 let tee = |mut from: Box<dyn Read + Send>| {
1228 std::thread::spawn(move || {
1229 let mut kept = Vec::new();
1230 let mut buf = [0u8; 4096];
1231 let mut err = std::io::stderr();
1232 while let Ok(n) = from.read(&mut buf) {
1233 if n == 0 {
1234 break;
1235 }
1236 let _ = err.write_all(&buf[..n]);
1237 let _ = err.flush();
1238 kept.extend_from_slice(&buf[..n]);
1239 }
1240 String::from_utf8_lossy(&kept).into_owned()
1241 })
1242 };
1243 let out_thread = child.stdout.take().map(|s| tee(Box::new(s)));
1244 let err_thread = child.stderr.take().map(|s| tee(Box::new(s)));
1245 let status = child.wait();
1246 let out = out_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1247 let err = err_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1248 let outcome = match status {
1249 Ok(s) if s.success() => PushOutcome::Done,
1250 Ok(s) => match signal_of(&s) {
1251 Some(sig) => PushOutcome::Signal(sig),
1252 None => PushOutcome::Failed,
1253 },
1254 Err(_) => PushOutcome::Failed,
1255 };
1256 PushRun {
1257 outcome,
1258 seen: format!("{out}{err}"),
1259 stderr: err,
1260 }
1261}
1262
1263#[cfg(test)]
1264mod tests {
1265
1266 #[test]
1268 fn a_push_url_is_reported_without_its_credentials() {
1269 let r = super::redact_url;
1270 assert_eq!(
1271 r("https://x:tok@github.com/o/r.git"),
1272 "https://***@github.com/o/r.git"
1273 );
1274 assert_eq!(
1275 r("https://tok@github.com/o/r.git"),
1276 "https://***@github.com/o/r.git"
1277 );
1278 assert_eq!(r("ssh://git:pw@host/o/r"), "ssh://git:***@host/o/r");
1279 assert_eq!(
1280 r("ssh://git@github.com/o/r.git"),
1281 "ssh://git@github.com/o/r.git"
1282 );
1283 assert_eq!(r("git@github.com:o/r.git"), "git@github.com:o/r.git");
1284 assert_eq!(
1285 r("https://github.com/o/r.git"),
1286 "https://github.com/o/r.git"
1287 );
1288 assert_eq!(r("/tmp/bare.git"), "/tmp/bare.git");
1289 }
1290 use super::*;
1291
1292 #[test]
1293 fn exit_codes_keep_usage_apart_from_the_lost_ref() {
1294 assert_eq!(Status::Landed.code(), 0);
1295 assert_eq!(Status::Refused.code(), 1);
1296 assert_eq!(Status::Usage.code(), 2);
1297 assert_eq!(Status::Unreachable.code(), 3);
1298 assert_eq!(Status::Unverified.code(), 3);
1299 assert_eq!(Status::NotObserved.code(), 4);
1300 assert_eq!(Status::Interrupted(2).code(), 130);
1301 }
1302
1303 #[test]
1304 fn every_status_has_its_own_word() {
1305 let all = [
1306 Status::Landed,
1307 Status::Refused,
1308 Status::Usage,
1309 Status::Unreachable,
1310 Status::Unverified,
1311 Status::NotObserved,
1312 Status::Interrupted(15),
1313 ];
1314 let words: std::collections::HashSet<_> = all.iter().map(|s| s.as_str()).collect();
1315 assert_eq!(words.len(), all.len());
1316 }
1317
1318 #[test]
1319 fn the_verdict_fits_eighty_columns_for_any_branch() {
1320 let long = "feature/".to_string() + &"x".repeat(120);
1321 for status in [Status::Landed, Status::NotObserved, Status::Unverified] {
1322 let line = verdict(status, "0123456789abcdef", "fedcba9876543210", &long);
1323 assert!(line.chars().count() <= 80, "{line}");
1324 assert!(line.contains('…'), "{line}");
1325 assert!(line.starts_with(status.as_str()));
1326 }
1327 }
1328
1329 #[test]
1330 fn a_short_branch_is_shown_whole_and_a_new_ref_has_a_placeholder() {
1331 let line = verdict(Status::Landed, "", "fedcba9876543210", "feat/x");
1332 assert_eq!(line, "landed -------..fedcba9 feat/x");
1333 }
1334
1335 #[test]
1336 fn the_verdict_is_plain_text() {
1337 let line = verdict(Status::Refused, "a", "b", "feat/ünï");
1338 assert!(!line.contains('\u{1b}'));
1339 }
1340
1341 #[test]
1342 fn truncation_keeps_both_ends() {
1343 assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
1344 assert_eq!(truncate_middle("abc", 5), "abc");
1345 assert_eq!(truncate_middle("abcdefghij", 1), "…");
1346 }
1347
1348 #[test]
1349 fn the_tip_is_the_first_field_and_absence_is_empty() {
1350 assert_eq!(parse_tip("abc123\trefs/heads/x\n"), "abc123");
1351 assert_eq!(parse_tip(""), "");
1352 }
1353
1354 #[test]
1355 fn json_carries_every_field_the_contract_names() {
1356 let mut r = Report::new(Status::NotObserved);
1357 r.branch = "feat/x".into();
1358 r.retried = true;
1359 let j = r.json();
1360 for key in [
1361 "branch",
1362 "remote",
1363 "push_url",
1364 "pushed",
1365 "remote_before",
1366 "remote_after",
1367 "retried",
1368 "status",
1369 ] {
1370 assert!(j.contains(&format!("\"{key}\"")), "{key} missing in {j}");
1371 }
1372 assert!(j.contains("\"status\":\"not-observed\""), "{j}");
1373 assert!(j.contains("\"retried\":true"), "{j}");
1374 assert!(usage_json().contains("\"status\":\"usage\""));
1375 }
1376}