1use crate::names::BIN;
41use std::ffi::OsString;
42use std::io::{IsTerminal, Read, Write};
43use std::ops::ControlFlow;
44use std::path::PathBuf;
45use std::process::{Command, Stdio};
46use std::time::{Duration, SystemTime, UNIX_EPOCH};
47
48use crate::attest::{classify_push_stderr, PushFailure};
49use crate::git::{self, Probe};
50use crate::hooks::pull_rebase::PUSH_AGAIN;
51use crate::json;
52use crate::rehearsal::signal_of;
53
54pub const LAND_REMOTE_MOVED: &str = "greengate-land: remote-moved";
59pub const LAND_EVIDENCE_MISSING: &str = "greengate-land: evidence-missing";
62
63const REREADS: u32 = 3;
66const REREAD_PAUSE: Duration = Duration::from_secs(2);
67
68const RECEIPT_KEEP: Duration = Duration::from_secs(7 * 24 * 60 * 60);
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Mode {
74 Plain,
76 Force,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Status {
84 Landed,
85 Refused,
86 Usage,
87 Unreachable,
88 Unverified,
89 NotObserved,
90 Interrupted(i32),
92}
93
94impl Status {
95 pub fn code(self) -> i32 {
96 match self {
97 Status::Landed => 0,
98 Status::Refused => 1,
99 Status::Usage => 2,
100 Status::Unreachable | Status::Unverified => 3,
101 Status::NotObserved => 4,
102 Status::Interrupted(sig) => 128 + sig,
103 }
104 }
105
106 pub fn as_str(self) -> &'static str {
107 match self {
108 Status::Landed => "landed",
109 Status::Refused => "refused",
110 Status::Usage => "usage",
111 Status::Unreachable => "unreachable",
112 Status::Unverified => "unverified",
113 Status::NotObserved => "not-observed",
114 Status::Interrupted(_) => "interrupted",
115 }
116 }
117}
118
119#[derive(Debug, Clone)]
122pub struct Report {
123 pub branch: String,
124 pub remote: String,
125 pub push_url: String,
126 pub pushed: String,
127 pub dst: String,
129 pub remote_before: String,
130 pub remote_after: String,
131 pub retried: bool,
132 pub status: Status,
133 pub next: Vec<String>,
135 pub gates_owed: Vec<String>,
138 pub prestage: PrestageState,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum PrestageState {
144 NotRun,
146 Stamped,
148 Ran,
150 Failed,
152 Refused,
154 Interrupted,
156}
157
158impl PrestageState {
159 pub fn as_str(self) -> &'static str {
160 match self {
161 PrestageState::NotRun => "",
162 PrestageState::Stamped => "stamped",
163 PrestageState::Ran => "ran",
164 PrestageState::Failed => "failed",
165 PrestageState::Refused => "refused",
166 PrestageState::Interrupted => "interrupted",
167 }
168 }
169}
170
171impl Report {
172 pub(crate) fn new(status: Status) -> Self {
173 Report {
174 branch: String::new(),
175 remote: String::new(),
176 push_url: String::new(),
177 pushed: String::new(),
178 dst: String::new(),
179 remote_before: String::new(),
180 remote_after: String::new(),
181 retried: false,
182 status,
183 next: Vec::new(),
184 gates_owed: Vec::new(),
185 prestage: PrestageState::NotRun,
186 }
187 }
188
189 pub(crate) fn json(&self) -> String {
190 json::object(&[
191 json::string_field("branch", &self.branch),
192 json::string_field("remote", &self.remote),
193 json::string_field("push_url", &self.push_url),
194 json::string_field("pushed", &self.pushed),
195 json::string_field("ref", &self.dst),
196 json::string_field("remote_before", &self.remote_before),
197 json::string_field("remote_after", &self.remote_after),
198 json::bool_field("retried", self.retried),
199 json::string_field("status", self.status.as_str()),
200 format!(
201 "\"gates\":{}",
202 json::object(&[
203 json::string_array_field("owed", &self.gates_owed),
204 json::string_field("prestage", self.prestage.as_str()),
205 ])
206 ),
207 ])
208 }
209}
210
211const VERDICT_WIDTH: usize = 80;
213
214pub fn truncate_middle(s: &str, max: usize) -> String {
218 let n = s.chars().count();
219 if n <= max {
220 return s.to_string();
221 }
222 if max <= 1 {
223 return "…".chars().take(max).collect();
224 }
225 let keep = max - 1;
226 let head = keep.div_ceil(2);
227 let tail = keep - head;
228 let front: String = s.chars().take(head).collect();
229 let back: String = s.chars().skip(n - tail).collect();
230 format!("{front}…{back}")
231}
232
233pub(crate) fn short(sha: &str) -> String {
234 if sha.is_empty() {
235 "-------".to_string()
236 } else {
237 sha.chars().take(7).collect()
238 }
239}
240
241pub fn verdict(status: Status, before: &str, after: &str, branch: &str) -> String {
245 verdict_word(status.as_str(), before, after, branch)
246}
247
248pub(crate) fn verdict_word(word: &str, before: &str, after: &str, branch: &str) -> String {
249 let head = format!("{word} {}..{}", short(before), short(after));
250 let room = VERDICT_WIDTH.saturating_sub(head.chars().count() + 1);
251 if branch.is_empty() || room == 0 {
252 return head;
253 }
254 format!("{head} {}", truncate_middle(branch, room))
255}
256
257pub fn parse_tip(ls_remote: &str) -> String {
260 ls_remote
261 .lines()
262 .find_map(|l| l.split_whitespace().next())
263 .unwrap_or("")
264 .to_string()
265}
266
267enum Seen {
269 Tip(String),
270 Unreachable,
271}
272
273fn read_tip(url: &str, rb: &str, budget: u64) -> Seen {
274 read_ref(url, &format!("refs/heads/{rb}"), budget)
275}
276
277fn read_ref(url: &str, refname: &str, budget: u64) -> Seen {
279 match git::probe_remote_stdout(&["ls-remote", url, refname], budget) {
280 (Probe::Exit(0), out) => Seen::Tip(parse_tip(&out)),
281 _ => Seen::Unreachable,
282 }
283}
284
285#[derive(Default)]
287pub(crate) struct Options {
288 pub(crate) force: bool,
289 pub(crate) json: bool,
290 pub(crate) dry_run: bool,
291 pub(crate) detach: bool,
292 pub(crate) worker: bool,
293 pub(crate) tag: Option<String>,
294 pub(crate) receipt: Option<String>,
295 pub(crate) lock_fd: Option<i32>,
296 pub(crate) wait: Option<String>,
297}
298
299impl Options {
300 pub(crate) fn mode(&self) -> Mode {
301 if self.force {
302 Mode::Force
303 } else {
304 Mode::Plain
305 }
306 }
307
308 #[cfg(unix)]
311 pub(crate) fn rerun_flags(&self) -> Vec<String> {
312 let mut flags = Vec::new();
313 if self.force {
314 flags.push("--force".to_string());
315 }
316 if self.json {
317 flags.push("--json".to_string());
318 }
319 if let Some(tag) = &self.tag {
320 flags.push("--tag".to_string());
321 flags.push(tag.clone());
322 }
323 flags
324 }
325}
326
327fn parse_options(args: &[OsString]) -> Result<Options, String> {
328 let mut options = Options::default();
329 let mut it = args.iter().map(|a| a.to_string_lossy().into_owned());
330 let tag_needs_name = || "--tag needs a tag name".to_string();
331 let value_of = |flag: &str, it: &mut dyn Iterator<Item = String>| match it.next() {
332 Some(v) if !v.is_empty() && !v.starts_with('-') => Ok(v),
333 _ => Err(format!("{flag} needs a value")),
334 };
335 let mut others = 0usize;
336 while let Some(a) = it.next() {
337 match a.as_str() {
338 "--force" => {
339 options.force = true;
340 others += 1;
341 }
342 "--json" => {
343 options.json = true;
344 others += 1;
345 }
346 "--dry-run" => {
347 options.dry_run = true;
348 others += 1;
349 }
350 "--detach" => {
351 options.detach = true;
352 others += 1;
353 }
354 "--worker" => {
355 options.worker = true;
356 others += 1;
357 }
358 "--tag" => {
359 match it.next() {
360 Some(name) if !name.is_empty() && !name.starts_with('-') => {
361 options.tag = Some(name)
362 }
363 _ => return Err(tag_needs_name()),
364 }
365 others += 1;
366 }
367 "--receipt" => {
368 options.receipt = Some(value_of("--receipt", &mut it)?);
369 others += 1;
370 }
371 "--lock-fd" => {
372 let raw = value_of("--lock-fd", &mut it)?;
373 options.lock_fd = Some(
374 raw.parse::<i32>()
375 .map_err(|_| "--lock-fd needs a descriptor number".to_string())?,
376 );
377 others += 1;
378 }
379 "--wait" => options.wait = Some(value_of("--wait", &mut it)?),
380 other if other.starts_with("--tag=") => match &other["--tag=".len()..] {
381 "" => return Err(tag_needs_name()),
382 name => {
383 options.tag = Some(name.to_string());
384 others += 1;
385 }
386 },
387 other if other.starts_with("--wait=") => match &other["--wait=".len()..] {
388 "" => return Err("--wait needs a receipt path".to_string()),
389 path => options.wait = Some(path.to_string()),
390 },
391 other => {
392 return Err(format!(
393 "unknown argument `{other}`; takes only [--force] [--json] [--dry-run] \
394 [--tag <name>] [--detach], or --wait <receipt> alone"
395 ))
396 }
397 }
398 }
399 if options.wait.is_some() && others > 0 {
400 return Err("--wait takes a receipt and no other flag".to_string());
401 }
402 if options.detach && options.dry_run {
403 return Err("--detach cannot be combined with --dry-run".to_string());
404 }
405 if options.tag.is_some() && options.mode() == Mode::Force {
406 return Err("a tag is never forced; --tag takes no --force".to_string());
407 }
408 if options.worker && (options.receipt.is_none() || options.lock_fd.is_none()) {
409 return Err("--worker is internal: it needs --receipt and --lock-fd".to_string());
410 }
411 Ok(options)
412}
413
414pub fn command(args: &[OsString]) -> i32 {
418 let json_out = args.iter().any(|a| a == "--json");
419 let options = match parse_options(args) {
420 Ok(options) => options,
421 Err(why) => {
422 eprintln!("{BIN}: land: {why}");
423 return finish(&Report::new(Status::Usage), json_out);
424 }
425 };
426 let (dry_run, mode) = (options.dry_run, options.mode());
427 if let Some(receipt) = &options.wait {
428 return wait_on(receipt);
429 }
430 if options.worker {
431 return worker_of(&options);
432 }
433 if options.detach {
434 return launch_of(&options);
435 }
436 if let Some(name) = options.tag.clone() {
437 if dry_run {
439 let (report, verdict) = dry_run_tag(&name);
440 say_dry_run(&report, verdict);
441 if json_out {
442 println!("{}", dry_run_json(&report, verdict, mode));
443 }
444 return i32::from(verdict != "would-land");
445 }
446 let started = now_nanos();
447 let report = land_tag(&name, None);
448 write_receipt(&report, started, now_nanos());
449 return finish(&report, json_out);
450 }
451 if dry_run {
452 let (report, verdict) = dry_run_branch();
453 say_dry_run(&report, verdict);
454 if json_out {
455 println!("{}", dry_run_json(&report, verdict, mode));
456 }
457 return i32::from(verdict != "would-land");
458 }
459 let started = now_nanos();
460 let report = land(mode, None);
461 write_receipt(&report, started, now_nanos());
462 finish(&report, json_out)
463}
464
465#[cfg(unix)]
466fn launch_of(options: &Options) -> i32 {
467 crate::land_detach::launch(options)
468}
469
470#[cfg(not(unix))]
471fn launch_of(options: &Options) -> i32 {
472 eprintln!("{BIN}: land: --detach needs a unix host");
473 finish(&Report::new(Status::Usage), options.json)
474}
475
476#[cfg(unix)]
477fn worker_of(options: &Options) -> i32 {
478 crate::land_detach::worker(options)
479}
480
481#[cfg(not(unix))]
482fn worker_of(options: &Options) -> i32 {
483 eprintln!("{BIN}: land: --worker needs a unix host");
484 finish(&Report::new(Status::Usage), options.json)
485}
486
487#[cfg(unix)]
488fn wait_on(receipt: &str) -> i32 {
489 crate::land_detach::wait(receipt)
490}
491
492#[cfg(not(unix))]
493fn wait_on(_receipt: &str) -> i32 {
494 eprintln!("{BIN}: land: --wait needs a unix host");
495 finish(&Report::new(Status::Usage), false)
496}
497
498pub fn usage_json() -> String {
501 Report::new(Status::Usage).json()
502}
503
504pub(crate) fn finish(report: &Report, json_out: bool) -> i32 {
505 for line in &report.next {
506 eprintln!(" {line}");
507 }
508 eprintln!(
509 "{}",
510 verdict(
511 report.status,
512 &report.remote_before,
513 &report.remote_after,
514 shown_ref(report)
515 )
516 );
517 if json_out {
518 println!("{}", report.json());
519 }
520 report.status.code()
521}
522
523pub(crate) fn shown_ref(report: &Report) -> &str {
526 if report.branch.is_empty() {
527 report.dst.strip_prefix("refs/tags/").unwrap_or(&report.dst)
528 } else {
529 &report.branch
530 }
531}
532
533pub(crate) fn refuse(mut report: Report, why: &str, next: &[&str]) -> Report {
534 eprintln!("{BIN}: land: {why}");
535 report.status = Status::Refused;
536 report.next = next.iter().map(|s| s.to_string()).collect();
537 report
538}
539
540pub(crate) struct Resolved {
542 remote: String,
543 rb: String,
544 url: String,
545 has_upstream: bool,
546}
547
548fn one_push_url(remote: &str, mut report: Report) -> Result<(String, Report), Box<Report>> {
550 let Some(urls) = git::stdout(&["remote", "get-url", "--push", "--all", remote]) else {
551 return Err(Box::new(refuse(
552 report,
553 &format!("no remote named {remote:?}"),
554 &["git remote -v"],
555 )));
556 };
557 let urls: Vec<&str> = urls.lines().filter(|l| !l.is_empty()).collect();
558 if urls.len() != 1 {
559 return Err(Box::new(refuse(
560 report,
561 &format!(
562 "{remote:?} has {} push destinations; land verifies exactly one",
563 urls.len()
564 ),
565 &[&format!("git remote get-url --push --all {remote}")],
566 )));
567 }
568 let url = urls[0].to_string();
569 report.push_url = redact_url(&url);
570 Ok((url, report))
571}
572
573fn redact_url(url: &str) -> String {
577 let Some((scheme, rest)) = url.split_once("://") else {
578 return url.to_string(); };
580 let authority_end = rest.find('/').unwrap_or(rest.len());
581 let (authority, path) = rest.split_at(authority_end);
582 let Some((user, host)) = authority.rsplit_once('@') else {
583 return url.to_string();
584 };
585 let user = if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
586 "***".to_string()
587 } else {
588 match user.split_once(':') {
589 Some((name, _)) => format!("{name}:***"),
590 None => user.to_string(),
591 }
592 };
593 format!("{scheme}://{user}@{host}{path}")
594}
595
596pub(crate) fn resolve() -> Result<(Resolved, Report), Box<Report>> {
600 let mut report = Report::new(Status::Refused);
601
602 let Some(branch) = git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"]) else {
604 return Err(Box::new(refuse(
605 report,
606 "HEAD is detached; there is no branch to land",
607 &[],
608 )));
609 };
610 report.branch = branch.clone();
611 let upstream_remote = git::stdout(&["config", "--get", &format!("branch.{branch}.remote")]);
612 let upstream_merge = git::stdout(&["config", "--get", &format!("branch.{branch}.merge")]);
613 let (upstream_remote, upstream_merge) = match upstream_remote.as_deref() {
617 Some(".") => (None, None),
618 _ => (upstream_remote, upstream_merge),
619 };
620 let upstream_merge = upstream_merge.filter(|m| {
627 let tracked = m.strip_prefix("refs/heads/").unwrap_or(m);
628 !is_protected(tracked) || is_protected(&branch)
629 });
630 let has_upstream = upstream_remote.is_some() && upstream_merge.is_some();
631 let remote = upstream_remote.unwrap_or_else(|| "origin".to_string());
632 let rb = upstream_merge
633 .as_deref()
634 .and_then(|m| m.strip_prefix("refs/heads/"))
635 .unwrap_or(&branch)
636 .to_string();
637 report.remote = remote.clone();
638 report.dst = format!("refs/heads/{rb}");
639
640 if is_protected(&branch) || is_protected(&rb) {
641 return Err(Box::new(refuse(
642 report,
643 "main and master change by pull request, never by a push",
644 &["git switch -c <name>"],
645 )));
646 }
647 if git::stdout(&["status", "--porcelain", "--untracked-files=no"])
648 .is_some_and(|s| !s.is_empty())
649 {
650 return Err(Box::new(refuse(
651 report,
652 "tracked files have uncommitted changes; the push would not include them",
653 &["git status", "git stash"],
654 )));
655 }
656
657 let (url, report) = one_push_url(&remote, report)?;
659 Ok((
660 Resolved {
661 remote,
662 rb,
663 url,
664 has_upstream,
665 },
666 report,
667 ))
668}
669
670pub(crate) fn land(mode: Mode, pin: Option<&str>) -> Report {
673 let settings = crate::config::Settings::default();
674 let budget = crate::hooks::common::network_probe_budget(&settings);
675 let (
676 Resolved {
677 remote,
678 rb,
679 url,
680 has_upstream,
681 },
682 mut report,
683 ) = match resolve() {
684 Ok(r) => r,
685 Err(refused) => return *refused,
686 };
687
688 let mut expected_old = match read_tip(&url, &rb, budget) {
690 Seen::Tip(t) => t,
691 Seen::Unreachable => {
692 report.status = Status::Unreachable;
693 eprintln!("{BIN}: land: could not read {rb} from {remote}");
694 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
695 return report;
696 }
697 };
698 report.remote_before = expected_old.clone();
699
700 let mut attempt = 0;
702 let pushed = loop {
703 let Some(sha) = git::stdout(&["rev-parse", "HEAD"]) else {
704 return refuse(report, "cannot resolve HEAD", &[]);
705 };
706 if let Some(judged) = pin {
707 if let Some(refusal) = head_moved(&report, judged, &sha) {
708 return refusal;
709 }
710 }
711 report.pushed = sha.clone();
712 let lease = match mode {
713 Mode::Force => Some(expected_old.as_str()),
714 Mode::Plain => None,
715 };
716 let local_ref = format!("refs/heads/{}", report.branch);
720 let dst = format!("refs/heads/{rb}");
721 report = match prestage(&local_ref, &sha, &dst, &expected_old, (&remote, &url))
722 .into_report(report)
723 {
724 ControlFlow::Continue(report) => report,
725 ControlFlow::Break(stopped) => return *stopped,
726 };
727 if let Some(judged) = pin {
728 let now = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
729 if let Some(refusal) = head_moved(&report, judged, &now) {
730 return refusal;
731 }
732 }
733 let land_env = format!("{sha} {}", or_zeros(&expected_old));
734 let run = push(&url, &sha, &dst, lease, &land_env);
735 match run.outcome {
736 PushOutcome::Done => break sha,
737 PushOutcome::Signal(sig) => {
738 report.status = Status::Interrupted(sig);
739 return report;
740 }
741 PushOutcome::Failed => {}
742 }
743 let head_now = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
744 let hook_moved_head = run.seen.contains(PUSH_AGAIN)
745 && head_now != sha
746 && (expected_old.is_empty()
747 || git::succeeds(&["merge-base", "--is-ancestor", &expected_old, &head_now]));
748 if pin.is_some() && hook_moved_head {
749 eprintln!(
750 "{BIN}: land: the pre-push hook moved HEAD {} -> {}; a detached land never \
751 pushes a sha it did not judge",
752 short(&sha),
753 short(&head_now)
754 );
755 report.status = Status::Refused;
756 report.next = vec![format!("{BIN} land --detach")];
757 return report;
758 }
759 if attempt == 0 && hook_moved_head {
760 attempt = 1;
761 report.retried = true;
762 eprintln!(
763 "{BIN}: land: retrying once: pre-push hook fast-forwarded HEAD {} -> {}",
764 short(&sha),
765 short(&head_now)
766 );
767 match read_tip(&url, &rb, budget) {
768 Seen::Tip(t) => {
769 expected_old = t;
770 report.remote_before = expected_old.clone();
771 }
772 Seen::Unreachable => {
773 report.status = Status::Unreachable;
774 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
775 return report;
776 }
777 }
778 continue;
779 }
780 if run.seen.contains(crate::land::LAND_REMOTE_MOVED) {
783 report.status = Status::Refused;
784 report.next = vec![format!("{BIN} land")];
785 return report;
786 }
787 if run.seen.contains(crate::land::LAND_EVIDENCE_MISSING) {
788 report.status = Status::Refused;
789 report.next = vec![format!("{BIN} rehearse --wait"), format!("{BIN} land")];
790 return report;
791 }
792 report.status = status_of_failed_push(&run.stderr);
793 return report;
794 };
795
796 let mut observed = Seen::Unreachable;
798 for i in 0..=REREADS {
799 if i > 0 {
800 std::thread::sleep(crate::clock::scaled(REREAD_PAUSE));
801 }
802 observed = read_tip(&url, &rb, budget);
803 if matches!(&observed, Seen::Tip(t) if *t == pushed) {
804 break;
805 }
806 }
807 match observed {
808 Seen::Tip(t) if t == pushed => {
809 report.remote_after = t;
810 report.status = Status::Landed;
811 move_tracking_ref(&remote, &rb, &pushed);
812 if !has_upstream {
813 set_upstream(&remote, &rb);
814 }
815 }
816 Seen::Tip(t) => {
817 report.remote_after = t;
818 report.status = Status::NotObserved;
819 eprintln!(
820 "{BIN}: land: the remote accepted the push but {rb} reads {}, not {}",
821 short(&report.remote_after),
822 short(&pushed)
823 );
824 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
825 }
826 Seen::Unreachable => {
827 report.status = Status::Unverified;
828 eprintln!("{BIN}: land: the push was accepted but {rb} could not be read back");
829 report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
830 }
831 }
832 report
833}
834
835fn head_moved(report: &Report, judged: &str, now: &str) -> Option<Report> {
837 if now == judged {
838 return None;
839 }
840 Some(refuse(
841 report.clone(),
842 &format!(
843 "HEAD moved from {} to {} since the launch; nothing was pushed",
844 short(judged),
845 short(now)
846 ),
847 &[&format!("{BIN} land --detach")],
848 ))
849}
850
851const ZEROS: &str = "0000000000000000000000000000000000000000";
853
854fn or_zeros(tip: &str) -> &str {
855 if tip.is_empty() {
856 ZEROS
857 } else {
858 tip
859 }
860}
861
862enum Prestage {
864 Ready,
866 Refused(String, Vec<String>),
868 Interrupted(i32),
870}
871
872struct Staged {
875 owed: Vec<String>,
876 state: PrestageState,
877 end: Prestage,
878}
879
880impl Staged {
881 fn ended(owed: Vec<String>, state: PrestageState, end: Prestage) -> Staged {
882 Staged { owed, state, end }
883 }
884
885 fn refused(owed: Vec<String>, state: PrestageState, why: String) -> Staged {
886 Staged::ended(owed, state, Prestage::Refused(why, Vec::new()))
887 }
888
889 fn into_report(self, mut report: Report) -> ControlFlow<Box<Report>, Report> {
892 report.gates_owed = self.owed;
893 report.prestage = self.state;
894 match self.end {
895 Prestage::Ready => ControlFlow::Continue(report),
896 Prestage::Refused(why, next) => {
897 eprintln!("{BIN}: land: {why}");
898 report.status = Status::Refused;
899 report.next = next;
900 ControlFlow::Break(Box::new(report))
901 }
902 Prestage::Interrupted(sig) => {
903 report.status = Status::Interrupted(sig);
904 ControlFlow::Break(Box::new(report))
905 }
906 }
907 }
908}
909
910fn status_of_failed_push(stderr: &str) -> Status {
912 match classify_push_stderr(stderr) {
913 PushFailure::Unreachable => Status::Unreachable,
914 PushFailure::Raced | PushFailure::Refused => Status::Refused,
915 _ => Status::Refused,
918 }
919}
920
921fn last_rehearsal() -> Option<(u32, u64, bool)> {
925 crate::rehearsal::read().map(|s| (s.pid, s.started, s.alive()))
926}
927
928fn prestage(
936 local_ref: &str,
937 sha: &str,
938 dst: &str,
939 remote_tip: &str,
940 (remote, url): (&str, &str),
941) -> Staged {
942 let again = match dst.strip_prefix("refs/tags/") {
944 Some(tag) => format!("{BIN} land --tag {tag}"),
945 None => format!("{BIN} land"),
946 };
947 let root = match crate::hooks::common::repo_root_checked() {
948 Ok(root) => root,
949 Err(e) => return Staged::refused(Vec::new(), PrestageState::Refused, e),
950 };
951 let (manifest, settings) = crate::manifest::load_resolved(std::path::Path::new(&root));
952 if !remote_tip.is_empty() && !has_commit(remote_tip) {
957 eprintln!(
958 "{BIN}: land: fetching {} ({dst}) from the remote",
959 short(remote_tip)
960 );
961 let budget = crate::hooks::common::check_timeout(&settings);
962 let (probe, _) = git::probe_remote_stdout(&["fetch", "-q", "--no-tags", url, dst], budget);
963 if !has_commit(remote_tip) {
964 let how = match probe {
965 Probe::Exit(0) => "it fetched, but not that commit".to_string(),
966 Probe::Exit(code) => format!("git fetch exited {code}"),
967 Probe::TimedOut(secs) => format!("git fetch did not finish within {secs}s"),
968 Probe::Failed => "git fetch did not run".to_string(),
969 };
970 return Staged::ended(
971 Vec::new(),
972 PrestageState::Refused,
973 Prestage::Refused(
974 format!(
975 "the remote's {dst} is at {}, a commit this clone does not have ({how})",
976 short(remote_tip)
977 ),
978 vec![format!("git fetch --no-tags {remote} {dst}"), again],
980 ),
981 );
982 }
983 }
984 let line = crate::pushrefs::PushRef {
985 local_ref: local_ref.to_string(),
986 local_oid: sha.to_string(),
987 remote_ref: dst.to_string(),
988 remote_oid: or_zeros(remote_tip).to_string(),
989 };
990 let changed = crate::pushrefs::changed_files(std::slice::from_ref(&line));
991 let mut owed = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
992 let audits = crate::hooks::audit::Ledger::default();
993 for audit in
994 crate::dispatch::owed_audits(&settings, &manifest, &audits, std::slice::from_ref(&line))
995 {
996 if !owed.contains(&audit) {
997 owed.push(audit);
998 }
999 }
1000 if owed.is_empty() {
1001 return Staged::ended(owed, PrestageState::Stamped, Prestage::Ready);
1002 }
1003 if !crate::gate_stamp::push_stamps_enabled(&settings) {
1004 return Staged::ended(
1005 owed,
1006 PrestageState::Refused,
1007 Prestage::Refused(
1008 "stamp reuse is off (greengate.pushStamps false), so the gates land runs \
1009 cannot count at the push"
1010 .to_string(),
1011 vec!["git config greengate.pushStamps true".to_string(), again],
1012 ),
1013 );
1014 }
1015 let exe = match std::env::current_exe() {
1016 Ok(exe) => exe,
1017 Err(e) => {
1018 return Staged::refused(
1019 owed,
1020 PrestageState::Refused,
1021 format!("cannot locate the {BIN} binary for the pre-stage: {e}"),
1022 )
1023 }
1024 };
1025 let names: Vec<&str> = owed.iter().map(String::as_str).collect();
1026 eprintln!(
1027 "{BIN}: land: {} push gate{} to check before git connects:",
1028 owed.len(),
1029 if owed.len() == 1 { "" } else { "s" }
1030 );
1031 for wrapped in crate::dispatch::wrap_names(&names) {
1032 eprintln!("{wrapped}");
1033 }
1034 let before = last_rehearsal();
1035 let status = Command::new(exe)
1036 .args(["rehearse", "--wait"])
1037 .env(
1038 crate::rehearsal::PRESTAGE_ENV,
1039 format!(
1040 "{} {} {} {}",
1041 line.local_ref, line.local_oid, line.remote_ref, line.remote_oid
1042 ),
1043 )
1044 .stdin(Stdio::null())
1045 .stdout(Stdio::from(std::io::stderr()))
1046 .status();
1047 let status = match status {
1048 Ok(status) => status,
1049 Err(e) => {
1050 return Staged::refused(
1051 owed,
1052 PrestageState::Refused,
1053 format!("could not start the pre-stage: {e}"),
1054 )
1055 }
1056 };
1057 if let Some(sig) = signal_of(&status) {
1058 return Staged::ended(owed, PrestageState::Interrupted, Prestage::Interrupted(sig));
1059 }
1060 match status.code() {
1061 Some(0) => {
1062 let followed = before.is_some_and(|(_, _, running)| running);
1066 let state = if followed
1067 || last_rehearsal().map(|(p, t, _)| (p, t)) != before.map(|(p, t, _)| (p, t))
1068 {
1069 PrestageState::Ran
1070 } else {
1071 PrestageState::Stamped
1072 };
1073 Staged::ended(owed, state, Prestage::Ready)
1074 }
1075 Some(1) => Staged::ended(
1076 owed,
1077 PrestageState::Failed,
1078 Prestage::Refused(
1079 "a push gate failed before the push (named above); nothing was pushed".to_string(),
1080 vec![format!("{BIN} rehearse --status"), again],
1081 ),
1082 ),
1083 Some(code) if code > 128 => Staged::ended(
1085 owed,
1086 PrestageState::Interrupted,
1087 Prestage::Interrupted(code - 128),
1088 ),
1089 code => Staged::refused(
1090 owed,
1091 PrestageState::Refused,
1092 format!(
1093 "the pre-stage could not run (exit {}); nothing was pushed",
1094 code.map_or("by signal".to_string(), |c| c.to_string())
1095 ),
1096 ),
1097 }
1098}
1099
1100fn has_commit(oid: &str) -> bool {
1101 git::succeeds(&["cat-file", "-e", &format!("{oid}^{{commit}}")])
1102}
1103
1104pub(crate) fn resolve_tag(name: &str) -> Result<(Report, String, String), Box<Report>> {
1111 let mut report = Report::new(Status::Refused);
1112 let dst = format!("refs/tags/{name}");
1113 report.dst = dst.clone();
1114 let Some(oid) = git::stdout(&["rev-parse", "--verify", "-q", &dst]) else {
1115 return Err(Box::new(refuse(
1116 report,
1117 &format!("there is no local tag {name:?}"),
1118 &["git tag --list"],
1119 )));
1120 };
1121 report.pushed = oid.clone();
1122 let remote = git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"])
1123 .and_then(|b| git::stdout(&["config", &format!("branch.{b}.remote")]))
1124 .filter(|r| r != ".")
1125 .unwrap_or_else(|| "origin".to_string());
1126 report.remote = remote.clone();
1127 let (url, report) = one_push_url(&remote, report)?;
1128 Ok((report, url, oid))
1129}
1130
1131fn dry_run_tag(name: &str) -> (Report, &'static str) {
1134 match resolve_tag(name) {
1135 Ok((report, _, _)) => (report, "would-land"),
1136 Err(refused) => (*refused, "refused"),
1137 }
1138}
1139
1140pub(crate) fn land_tag(name: &str, pin: Option<&str>) -> Report {
1141 let settings = crate::config::Settings::default();
1142 let budget = crate::hooks::common::network_probe_budget(&settings);
1143 let (mut report, url, oid) = match resolve_tag(name) {
1144 Ok(resolved) => resolved,
1145 Err(refused) => return *refused,
1146 };
1147 let (dst, remote) = (report.dst.clone(), report.remote.clone());
1148 if let Some(judged) = pin {
1149 if let Some(refusal) = head_moved(&report, judged, &oid) {
1150 return refusal;
1151 }
1152 }
1153 match read_ref(&url, &dst, budget) {
1154 Seen::Tip(t) if t.is_empty() => {}
1155 Seen::Tip(t) => {
1156 report.remote_before = t.clone();
1157 return refuse(
1158 report,
1159 &format!("{dst} already exists on {remote}; a tag is never moved"),
1160 &[&format!("git ls-remote {remote} {dst}")],
1161 );
1162 }
1163 Seen::Unreachable => {
1164 report.status = Status::Unreachable;
1165 eprintln!("{BIN}: land: could not read {dst} from {remote}");
1166 report.next = vec![format!("git ls-remote {remote} {dst}")];
1167 return report;
1168 }
1169 }
1170 report = match prestage(&dst, &oid, &dst, "", (&remote, &url)).into_report(report) {
1171 ControlFlow::Continue(report) => report,
1172 ControlFlow::Break(stopped) => return *stopped,
1173 };
1174 let land_env = format!("{oid} {ZEROS}");
1175 let run = push(&url, &dst, &dst, None, &land_env);
1176 match run.outcome {
1177 PushOutcome::Done => {}
1178 PushOutcome::Signal(sig) => {
1179 report.status = Status::Interrupted(sig);
1180 return report;
1181 }
1182 PushOutcome::Failed => {
1183 report.status = status_of_failed_push(&run.stderr);
1184 if run.seen.contains(LAND_EVIDENCE_MISSING) {
1185 report.next = vec![format!("{BIN} land --tag {name}")];
1188 }
1189 return report;
1190 }
1191 }
1192 let mut observed = Seen::Unreachable;
1193 for i in 0..=REREADS {
1194 if i > 0 {
1195 std::thread::sleep(crate::clock::scaled(REREAD_PAUSE));
1196 }
1197 observed = read_ref(&url, &dst, budget);
1198 if matches!(&observed, Seen::Tip(t) if *t == oid) {
1199 break;
1200 }
1201 }
1202 match observed {
1203 Seen::Tip(t) if t == oid => {
1204 report.remote_after = t;
1205 report.status = Status::Landed;
1206 }
1207 Seen::Tip(t) => {
1208 report.remote_after = t;
1209 report.status = Status::NotObserved;
1210 report.next = vec![format!("git ls-remote {remote} {dst}")];
1211 }
1212 Seen::Unreachable => {
1213 report.status = Status::Unverified;
1214 report.next = vec![format!("git ls-remote {remote} {dst}")];
1215 }
1216 }
1217 report
1218}
1219
1220fn dry_run_branch() -> (Report, &'static str) {
1223 match resolve() {
1224 Ok((_, mut report)) => {
1225 report.pushed = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
1226 (report, "would-land")
1227 }
1228 Err(refused) => (*refused, "refused"),
1229 }
1230}
1231
1232fn say_dry_run(report: &Report, verdict: &str) {
1234 for line in &report.next {
1235 eprintln!(" {line}");
1236 }
1237 eprintln!(
1238 "{}",
1239 verdict_word(verdict, "", &report.pushed, shown_ref(report))
1240 );
1241}
1242
1243fn dry_run_json(report: &Report, verdict: &str, mode: Mode) -> String {
1245 let dir = receipt_dir()
1246 .map(|d| d.to_string_lossy().into_owned())
1247 .unwrap_or_default();
1248 json::object(&[
1249 json::string_field("branch", &report.branch),
1250 json::string_field("remote", &report.remote),
1251 json::string_field("push_url", &report.push_url),
1252 json::string_field("pushed", &report.pushed),
1253 json::string_field("dst", &report.dst),
1254 json::string_field("ref", &report.dst),
1255 json::bool_field("retried", false),
1256 json::string_field("status", verdict),
1257 json::string_field("receipt_dir", &dir),
1258 json::bool_field("lease", mode == Mode::Force),
1259 ])
1260}
1261
1262pub(crate) fn now_nanos() -> i64 {
1263 SystemTime::now()
1264 .duration_since(UNIX_EPOCH)
1265 .ok()
1266 .and_then(|d| i64::try_from(d.as_nanos()).ok())
1267 .unwrap_or(0)
1268}
1269
1270pub(crate) fn receipt_dir() -> Option<PathBuf> {
1272 git::stdout(&["rev-parse", "--absolute-git-dir"])
1273 .map(|d| PathBuf::from(d).join(crate::names::STATE_DIR).join("land"))
1274}
1275
1276#[derive(Debug, Clone)]
1278pub(crate) struct Meta {
1279 pub(crate) judged: String,
1281 pub(crate) log: String,
1282 pub(crate) worker_pid: Option<u32>,
1283 pub(crate) flags: Vec<String>,
1285}
1286
1287pub(crate) fn receipt_body(
1289 report: &Report,
1290 word: &str,
1291 exit: Option<i32>,
1292 (started, ended): (i64, Option<i64>),
1293 meta: Option<&Meta>,
1294) -> String {
1295 let mut fields = vec![json::int_field("started", started)];
1296 if let Some(ended) = ended {
1297 fields.push(json::int_field("ended", ended));
1298 }
1299 fields.extend([
1300 json::string_field("branch", &report.branch),
1301 json::string_field("remote", &report.remote),
1302 json::string_field("push_url", &report.push_url),
1303 json::string_field("dst", &report.dst),
1304 json::string_field("pushed", &report.pushed),
1305 json::bool_field("retried", report.retried),
1306 json::string_field("status", word),
1307 json::string_field("remote_before", &report.remote_before),
1308 json::string_field("remote_after", &report.remote_after),
1309 format!(
1310 "\"gates\":{}",
1311 json::object(&[
1312 json::string_array_field("owed", &report.gates_owed),
1313 json::string_field("prestage", report.prestage.as_str()),
1314 ])
1315 ),
1316 ]);
1317 if let Some(code) = exit {
1318 fields.push(json::int_field("exit", i64::from(code)));
1319 }
1320 if let Some(meta) = meta {
1321 fields.push(json::string_field("judged", &meta.judged));
1322 fields.push(json::string_field("log", &meta.log));
1323 if let Some(pid) = meta.worker_pid {
1324 fields.push(json::int_field("worker_pid", i64::from(pid)));
1325 }
1326 fields.push(json::string_array_field("flags", &meta.flags));
1327 }
1328 json::object(&fields)
1329}
1330
1331pub(crate) fn write_atomic(path: &std::path::Path, body: &str) -> std::io::Result<()> {
1334 let mut tmp = path.as_os_str().to_owned();
1335 tmp.push(".tmp");
1336 let tmp = PathBuf::from(tmp);
1337 std::fs::write(&tmp, format!("{body}\n"))?;
1338 std::fs::rename(&tmp, path)
1339}
1340
1341fn write_receipt(report: &Report, started: i64, ended: i64) {
1346 if report.branch.is_empty() && report.dst.is_empty() {
1347 return;
1348 }
1349 let Some(dir) = receipt_dir() else {
1350 eprintln!("{BIN}: land: could not find the git directory; no landing receipt written");
1351 return;
1352 };
1353 if let Err(e) = std::fs::create_dir_all(&dir) {
1354 eprintln!(
1355 "{BIN}: land: could not write a landing receipt in {}: {e}",
1356 dir.display()
1357 );
1358 return;
1359 }
1360 prune_receipts(&dir);
1361 let path = dir.join(format!("{started}-{}.json", std::process::id()));
1362 let body = receipt_body(
1363 report,
1364 report.status.as_str(),
1365 Some(report.status.code()),
1366 (started, Some(ended)),
1367 None,
1368 );
1369 if let Err(e) = write_atomic(&path, &body) {
1370 eprintln!(
1371 "{BIN}: land: could not write the landing receipt {}: {e}",
1372 path.display()
1373 );
1374 }
1375}
1376
1377pub(crate) fn lock_held(receipt: &std::path::Path) -> bool {
1379 #[cfg(unix)]
1380 {
1381 let mut lock = receipt.as_os_str().to_owned();
1382 lock.push(".lock");
1383 match std::fs::File::open(&lock) {
1384 Ok(file) => !crate::fdlock::try_exclusive(&file),
1385 Err(_) => false,
1386 }
1387 }
1388 #[cfg(not(unix))]
1389 {
1390 let _ = receipt;
1391 false
1392 }
1393}
1394
1395pub(crate) fn prune_receipts(dir: &std::path::Path) {
1399 let Ok(entries) = std::fs::read_dir(dir) else {
1400 return;
1401 };
1402 for entry in entries.flatten() {
1403 let path = entry.path();
1404 if path.extension().map_or(true, |e| e != "json") {
1405 continue;
1406 }
1407 let old = entry
1408 .metadata()
1409 .and_then(|m| m.modified())
1410 .ok()
1411 .and_then(|t| t.elapsed().ok())
1412 .is_some_and(|age| age > RECEIPT_KEEP);
1413 if !old || lock_held(&path) {
1414 continue;
1415 }
1416 let mut lock = path.as_os_str().to_owned();
1417 lock.push(".lock");
1418 let mut tmp = path.as_os_str().to_owned();
1419 tmp.push(".tmp");
1420 for doomed in [
1421 path.clone(),
1422 path.with_extension("log"),
1423 PathBuf::from(lock),
1424 PathBuf::from(tmp),
1425 ] {
1426 match std::fs::remove_file(&doomed) {
1427 Ok(()) => {}
1428 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1429 Err(e) => eprintln!(
1430 "{BIN}: land: could not delete the old receipt file {}: {e}",
1431 doomed.display()
1432 ),
1433 }
1434 }
1435 }
1436}
1437
1438fn is_protected(branch: &str) -> bool {
1439 matches!(branch, "main" | "master")
1440}
1441
1442fn move_tracking_ref(remote: &str, rb: &str, sha: &str) {
1446 let tracking = format!("refs/remotes/{remote}/{rb}");
1447 if !git::succeeds(&["update-ref", &tracking, sha]) {
1448 eprintln!(
1449 "{BIN}: land: landed, but could not move {tracking} to {}",
1450 short(sha)
1451 );
1452 }
1453}
1454
1455fn set_upstream(remote: &str, rb: &str) {
1457 let upstream = format!("{remote}/{rb}");
1458 if !git::succeeds(&["branch", "--set-upstream-to", &upstream]) {
1459 eprintln!("{BIN}: land: landed, but could not set the upstream to {upstream}");
1460 }
1461}
1462
1463enum PushOutcome {
1464 Done,
1465 Failed,
1466 Signal(i32),
1467}
1468
1469struct PushRun {
1470 outcome: PushOutcome,
1471 stderr: String,
1473 seen: String,
1475}
1476
1477fn push(url: &str, src: &str, dst: &str, lease: Option<&str>, land_env: &str) -> PushRun {
1489 let mut cmd = Command::new("git");
1490 cmd.env(crate::rehearsal::LAND_ENV, land_env);
1492 if !std::io::stdin().is_terminal() {
1493 let (pre, env) = git::remote_env(git::configured_ssh());
1494 cmd.args(pre).envs(env);
1495 }
1496 cmd.arg("push");
1497 if let Some(old) = lease {
1498 cmd.arg(format!("--force-with-lease={dst}:{old}"));
1499 }
1500 cmd.arg(url)
1501 .arg(format!("{src}:{dst}"))
1502 .stdin(Stdio::inherit())
1503 .stdout(Stdio::piped())
1504 .stderr(Stdio::piped());
1505 let mut child = match cmd.spawn() {
1506 Ok(c) => c,
1507 Err(e) => {
1508 let why = format!("could not run git push: {e}\n");
1509 eprint!("{BIN}: land: {why}");
1510 return PushRun {
1511 outcome: PushOutcome::Failed,
1512 stderr: why.clone(),
1513 seen: why,
1514 };
1515 }
1516 };
1517 let tee = |mut from: Box<dyn Read + Send>| {
1518 std::thread::spawn(move || {
1519 let mut kept = Vec::new();
1520 let mut buf = [0u8; 4096];
1521 let mut err = std::io::stderr();
1522 while let Ok(n) = from.read(&mut buf) {
1523 if n == 0 {
1524 break;
1525 }
1526 let _ = err.write_all(&buf[..n]);
1527 let _ = err.flush();
1528 kept.extend_from_slice(&buf[..n]);
1529 }
1530 String::from_utf8_lossy(&kept).into_owned()
1531 })
1532 };
1533 let out_thread = child.stdout.take().map(|s| tee(Box::new(s)));
1534 let err_thread = child.stderr.take().map(|s| tee(Box::new(s)));
1535 let status = child.wait();
1536 let out = out_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1537 let err = err_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1538 let outcome = match status {
1539 Ok(s) if s.success() => PushOutcome::Done,
1540 Ok(s) => match signal_of(&s) {
1541 Some(sig) => PushOutcome::Signal(sig),
1542 None => PushOutcome::Failed,
1543 },
1544 Err(_) => PushOutcome::Failed,
1545 };
1546 PushRun {
1547 outcome,
1548 seen: format!("{out}{err}"),
1549 stderr: err,
1550 }
1551}
1552
1553#[cfg(test)]
1554mod tests {
1555
1556 #[test]
1558 fn a_push_url_is_reported_without_its_credentials() {
1559 let r = super::redact_url;
1560 assert_eq!(
1561 r("https://x:tok@github.com/o/r.git"),
1562 "https://***@github.com/o/r.git"
1563 );
1564 assert_eq!(
1565 r("https://tok@github.com/o/r.git"),
1566 "https://***@github.com/o/r.git"
1567 );
1568 assert_eq!(r("ssh://git:pw@host/o/r"), "ssh://git:***@host/o/r");
1569 assert_eq!(
1570 r("ssh://git@github.com/o/r.git"),
1571 "ssh://git@github.com/o/r.git"
1572 );
1573 assert_eq!(r("git@github.com:o/r.git"), "git@github.com:o/r.git");
1574 assert_eq!(
1575 r("https://github.com/o/r.git"),
1576 "https://github.com/o/r.git"
1577 );
1578 assert_eq!(r("/tmp/bare.git"), "/tmp/bare.git");
1579 }
1580 use super::*;
1581
1582 #[test]
1583 fn exit_codes_keep_usage_apart_from_the_lost_ref() {
1584 assert_eq!(Status::Landed.code(), 0);
1585 assert_eq!(Status::Refused.code(), 1);
1586 assert_eq!(Status::Usage.code(), 2);
1587 assert_eq!(Status::Unreachable.code(), 3);
1588 assert_eq!(Status::Unverified.code(), 3);
1589 assert_eq!(Status::NotObserved.code(), 4);
1590 assert_eq!(Status::Interrupted(2).code(), 130);
1591 }
1592
1593 #[test]
1594 fn every_status_has_its_own_word() {
1595 let all = [
1596 Status::Landed,
1597 Status::Refused,
1598 Status::Usage,
1599 Status::Unreachable,
1600 Status::Unverified,
1601 Status::NotObserved,
1602 Status::Interrupted(15),
1603 ];
1604 let words: std::collections::HashSet<_> = all.iter().map(|s| s.as_str()).collect();
1605 assert_eq!(words.len(), all.len());
1606 }
1607
1608 #[test]
1609 fn the_verdict_fits_eighty_columns_for_any_branch() {
1610 let long = "feature/".to_string() + &"x".repeat(120);
1611 for status in [Status::Landed, Status::NotObserved, Status::Unverified] {
1612 let line = verdict(status, "0123456789abcdef", "fedcba9876543210", &long);
1613 assert!(line.chars().count() <= 80, "{line}");
1614 assert!(line.contains('…'), "{line}");
1615 assert!(line.starts_with(status.as_str()));
1616 }
1617 }
1618
1619 #[test]
1620 fn a_short_branch_is_shown_whole_and_a_new_ref_has_a_placeholder() {
1621 let line = verdict(Status::Landed, "", "fedcba9876543210", "feat/x");
1622 assert_eq!(line, "landed -------..fedcba9 feat/x");
1623 }
1624
1625 #[test]
1626 fn the_verdict_is_plain_text() {
1627 let line = verdict(Status::Refused, "a", "b", "feat/ünï");
1628 assert!(!line.contains('\u{1b}'));
1629 }
1630
1631 #[test]
1632 fn truncation_keeps_both_ends() {
1633 assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
1634 assert_eq!(truncate_middle("abc", 5), "abc");
1635 assert_eq!(truncate_middle("abcdefghij", 1), "…");
1636 }
1637
1638 #[test]
1639 fn the_tip_is_the_first_field_and_absence_is_empty() {
1640 assert_eq!(parse_tip("abc123\trefs/heads/x\n"), "abc123");
1641 assert_eq!(parse_tip(""), "");
1642 }
1643
1644 #[test]
1645 fn json_carries_every_field_the_contract_names() {
1646 let mut r = Report::new(Status::NotObserved);
1647 r.branch = "feat/x".into();
1648 r.retried = true;
1649 let j = r.json();
1650 for key in [
1651 "branch",
1652 "remote",
1653 "push_url",
1654 "pushed",
1655 "remote_before",
1656 "remote_after",
1657 "retried",
1658 "status",
1659 ] {
1660 assert!(j.contains(&format!("\"{key}\"")), "{key} missing in {j}");
1661 }
1662 assert!(j.contains("\"status\":\"not-observed\""), "{j}");
1663 assert!(j.contains("\"retried\":true"), "{j}");
1664 assert!(usage_json().contains("\"status\":\"usage\""));
1665 }
1666}