1use std::cell::RefCell;
43use std::io::{IsTerminal, Write};
44use std::sync::atomic::{AtomicBool, Ordering};
45use std::sync::{Arc, Mutex, Weak};
46use std::time::Instant;
47
48const FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
51
52const MAX_LINES: usize = 12;
55
56struct Slot {
58 name: String,
61 started: Instant,
64 last_output: Instant,
67 next_beat: u64,
69 buf: Vec<u8>,
70 running: bool,
72 done: bool,
73 activity: Option<Arc<crate::hooks::common::Activity>>,
77 queued: Option<(Instant, u64)>,
80 capture: Option<crate::capture::Capture>,
84 runner_exit: Option<i32>,
86 announced: bool,
88}
89
90const ANNOUNCE_SECS: u64 = 5;
93
94pub struct Stage {
97 slots: Mutex<Vec<Slot>>,
98 out: Mutex<usize>,
101 live: bool,
103 on_push: bool,
108 way_out: WayOut,
111 quiet: bool,
114 log_dir: Option<std::path::PathBuf>,
115 named: AtomicBool,
119 stop: AtomicBool,
120}
121
122thread_local! {
123 static SINK: RefCell<Option<(Arc<Stage>, usize)>> = const { RefCell::new(None) };
125}
126
127impl Stage {
128 pub fn begin(settings: &crate::config::Settings, names: &[&str]) -> Arc<Stage> {
131 let now = Instant::now();
132 let stage = Arc::new(Stage {
133 slots: Mutex::new(
134 names
135 .iter()
136 .map(|n| Slot {
137 name: crate::ui::sanitize(
141 n.strip_prefix("pre-commit-")
142 .or_else(|| n.strip_prefix("pre-push-"))
143 .unwrap_or(n),
144 ),
145 started: now,
146 last_output: now,
147 next_beat: HEARTBEAT_SECS,
148 buf: Vec::new(),
149 running: false,
150 done: false,
151 activity: None,
152 queued: None,
153 capture: None,
154 runner_exit: None,
155 announced: false,
156 })
157 .collect(),
158 ),
159 out: Mutex::new(0),
160 live: enabled(settings) && watching(),
161 on_push: holds_a_push_connection(names, crate::rehearsal::in_snapshot()),
165 way_out: WayOut::for_snapshot(crate::rehearsal::in_snapshot()),
166 quiet: quiet(settings),
167 named: AtomicBool::new(false),
168 log_dir: if quiet(settings) {
169 crate::capture::log_dir()
170 } else {
171 None
172 },
173 stop: AtomicBool::new(false),
174 });
175 if stage.live {
176 let weak = Arc::downgrade(&stage);
179 let own = settings.for_thread();
180 let _ = std::thread::Builder::new()
181 .name("greengate-live".into())
182 .spawn(move || tick(own, weak));
183 } else if enabled(settings) || stage.quiet {
184 let weak = Arc::downgrade(&stage);
190 let own = settings.for_thread();
191 let _ = std::thread::Builder::new()
192 .name("greengate-heartbeat".into())
193 .spawn(move || heartbeat(own, weak));
194 }
195 stage
196 }
197
198 pub fn enter(self: &Arc<Stage>, idx: usize) -> SinkGuard {
202 {
203 let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
204 if let Some(slot) = slots.get_mut(idx) {
205 slot.running = true;
206 slot.started = Instant::now();
207 slot.last_output = slot.started;
208 slot.next_beat = HEARTBEAT_SECS;
209 if self.quiet {
210 slot.capture = Some(crate::capture::Capture::open(
211 self.log_dir.clone(),
212 &slot.name,
213 ));
214 }
215 }
216 }
217 SINK.with(|s| *s.borrow_mut() = Some((Arc::clone(self), idx)));
218 SinkGuard
219 }
220
221 pub fn queue(&self, idx: usize, since: Option<(Instant, u64)>) {
223 let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
224 if let Some(slot) = slots.get_mut(idx) {
225 slot.queued = since;
226 }
227 }
228
229 pub fn attach(
233 self: &Arc<Stage>,
234 idx: usize,
235 activity: Arc<crate::hooks::common::Activity>,
236 ) -> AttachGuard {
237 let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
238 if let Some(slot) = slots.get_mut(idx) {
239 slot.activity = Some(activity);
240 }
241 AttachGuard {
242 stage: Arc::clone(self),
243 idx,
244 }
245 }
246
247 pub fn append_raw(&self, idx: usize, bytes: &[u8]) {
249 let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
250 if let Some(slot) = slots.get_mut(idx) {
251 if !slot.done {
252 match slot.capture.as_mut() {
253 Some(capture) => capture.take(bytes),
254 None => slot.buf.extend_from_slice(bytes),
255 }
256 slot.last_output = Instant::now();
257 }
258 }
259 }
260
261 pub fn named(&self) {
263 self.named.store(true, Ordering::Relaxed);
264 }
265
266 pub fn runner_exit(&self, idx: usize, code: Option<i32>) {
268 let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
269 if let Some(slot) = slots.get_mut(idx) {
270 slot.runner_exit = code;
271 }
272 }
273
274 fn append_line(&self, idx: usize, line: &str) {
275 let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
276 if let Some(slot) = slots.get_mut(idx) {
277 if !slot.done {
278 slot.buf.extend_from_slice(line.as_bytes());
279 slot.buf.push(b'\n');
280 slot.last_output = Instant::now();
281 }
282 }
283 }
284
285 pub fn finish(
296 &self,
297 settings: &crate::config::Settings,
298 idx: usize,
299 outcome: Option<crate::check::Outcome>,
300 ) {
301 let block = {
302 let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
303 let Some(slot) = slots.get_mut(idx) else {
304 return;
305 };
306 slot.done = true;
307 slot.running = false;
308 let said = std::mem::take(&mut slot.buf);
309 match slot.capture.take() {
310 None => QuietOut::plain(said),
311 Some(capture) => quiet_block(QuietEnd {
312 name: &slot.name,
313 secs: slot.started.elapsed().as_secs_f64(),
314 outcome,
315 said,
316 capture,
317 runner_exit: slot.runner_exit,
318 ci: in_ci(),
319 ok_line: self.named.load(Ordering::Relaxed),
320 }),
321 }
322 };
323 if block.is_empty() && !self.live {
324 return;
325 }
326 let mut drawn = self.out.lock().unwrap_or_else(|p| p.into_inner());
327 if !block.is_empty() {
328 if *drawn > 0 {
329 let mut err = std::io::stderr().lock();
330 let _ = write!(err, "\x1b[{}A\x1b[J", *drawn);
331 let _ = err.flush();
332 *drawn = 0;
333 }
334 let stdout = std::io::stdout();
335 let mut handle = stdout.lock();
336 block.write(&mut handle);
337 let _ = handle.flush();
338 }
339 self.repaint(settings, &mut drawn);
340 }
341
342 fn repaint(&self, settings: &crate::config::Settings, drawn: &mut usize) {
345 if !self.live {
346 return;
347 }
348 let entries: Vec<Row> = {
349 let slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
350 let now = Instant::now();
351 slots
352 .iter()
353 .filter(|s| s.running && !s.done)
354 .map(|s| row_of(s, now, now.duration_since(s.started).as_secs_f64()))
355 .collect()
356 };
357 let text = region(&entries, term_width(), budgets(settings));
358 let mut paint = String::new();
359 if *drawn > 0 {
360 paint.push_str(&format!("\x1b[{}A\x1b[J", *drawn));
361 }
362 paint.push_str(&text);
363 if paint.is_empty() {
364 return;
365 }
366 let mut err = std::io::stderr().lock();
367 let _ = err.write_all(paint.as_bytes());
368 let _ = err.flush();
369 *drawn = text.matches('\n').count();
370 }
371}
372
373impl Drop for Stage {
374 fn drop(&mut self) {
379 self.stop.store(true, Ordering::Relaxed);
380 if !self.live {
381 return;
382 }
383 let drawn = self.out.get_mut().unwrap_or_else(|p| p.into_inner());
384 if *drawn > 0 {
385 let mut err = std::io::stderr().lock();
386 let _ = write!(err, "\x1b[{}A\x1b[J", *drawn);
387 let _ = err.flush();
388 *drawn = 0;
389 }
390 }
391}
392
393fn tick(settings: crate::config::Settings, weak: Weak<Stage>) {
399 loop {
400 std::thread::sleep(std::time::Duration::from_millis(80));
401 let Some(stage) = weak.upgrade() else { return };
402 if stage.stop.load(Ordering::Relaxed) {
403 return;
404 }
405 let mut drawn = stage.out.lock().unwrap_or_else(|p| p.into_inner());
406 stage.repaint(&settings, &mut drawn);
407 }
408}
409
410#[derive(Debug, Clone)]
412pub struct Row {
413 pub name: String,
414 pub elapsed: f64,
416 pub quiet: f64,
418 pub still: f64,
421 pub cpu: RowCpu,
422 pub wait: Option<(crate::hooks::wait::WaitKind, f64)>,
426 pub load: Option<(u64, crate::load::Load, u32)>,
430 pub queued: Option<(f64, u64)>,
433}
434
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
437pub enum RowCpu {
438 None,
441 NotSampled,
445 Unmeasured,
448 Busy(u32),
450 Idle,
452}
453
454fn row_of(s: &Slot, now: Instant, elapsed: f64) -> Row {
458 use crate::hooks::common::{CpuState, BUSY_MILLI_CORES};
459 let slot_quiet = now.duration_since(s.last_output).as_secs_f64();
460 let (quiet, still, cpu, wait, load) = match &s.activity {
461 None => (slot_quiet, slot_quiet, RowCpu::None, None, None),
462 Some(a) => {
463 let quiet = slot_quiet.min(a.quiet_for().as_secs_f64());
464 let still = quiet.min(a.still_for().as_secs_f64());
465 let cpu = match (a.cpu_state(), a.fresh_rate()) {
466 (CpuState::Off, _) => RowCpu::NotSampled,
467 (_, Some(r)) if r >= BUSY_MILLI_CORES => RowCpu::Busy(r),
468 (_, Some(_)) => RowCpu::Idle,
469 (_, None) => RowCpu::Unmeasured,
470 };
471 let wait = a.waiting().map(|(k, d)| (k, d.as_secs_f64()));
472 (quiet, still, cpu, wait, a.load_scale())
473 }
474 };
475 Row {
476 name: s.name.clone(),
477 elapsed,
478 quiet,
479 still,
480 cpu,
481 wait,
482 load,
483 queued: s
484 .queued
485 .map(|(since, n)| (now.duration_since(since).as_secs_f64(), n)),
486 }
487}
488
489impl Row {
490 fn applied_idle(&self, budgets: Budgets) -> u64 {
493 match self.load {
494 Some((applied, _, _)) if applied > 0 => applied,
495 _ => budgets.idle,
496 }
497 }
498}
499
500#[derive(Debug, Clone, Copy)]
504pub struct Budgets {
505 pub idle: u64,
506 pub ceiling: u64,
507 pub lock_wait: u64,
508 pub extended: u64,
511}
512
513fn budgets(settings: &crate::config::Settings) -> Budgets {
514 let idle = crate::hooks::common::idle_timeout(settings);
515 Budgets {
516 idle,
517 extended: idle.saturating_mul(crate::hooks::common::idle_load_scale(settings)),
518 ceiling: crate::hooks::common::check_timeout(settings),
519 lock_wait: match crate::hooks::common::lock_wait(settings) {
520 crate::hooks::common::LockWait::Secs(s) => s,
521 crate::hooks::common::LockWait::UntilCeiling => 0,
522 },
523 }
524}
525
526const QUIET_NOTE_SECS: f64 = 30.0;
530
531const HEARTBEAT_SECS: u64 = 60;
533
534fn elapsed_column(secs: f64) -> String {
538 if secs < 60.0 {
539 format!("{secs:>5.1}s")
540 } else {
541 format!("{:>6}", crate::hooks::common::human_secs(secs as u64))
542 }
543}
544
545fn region(entries: &[Row], width: usize, budgets: Budgets) -> String {
554 if entries.is_empty() {
555 return String::new();
556 }
557 let pad = entries
558 .iter()
559 .take(MAX_LINES)
560 .map(|r| r.name.chars().count())
561 .max()
562 .unwrap_or(0);
563 let mut out = String::new();
564 for row in entries.iter().take(MAX_LINES) {
565 let frame = FRAMES[((row.elapsed * 10.0) as usize) % FRAMES.len()];
566 let name = &row.name;
567 let mut line = format!("{frame} {name:<pad$} {}", elapsed_column(row.elapsed));
568 if let Some((secs, n)) = row.queued {
569 line.push_str(&format!(
570 " · queued {} (slots {n}/{n})",
571 crate::hooks::common::human_secs(secs as u64)
572 ));
573 } else if let Some((kind, waited)) = row.wait {
574 line.push_str(&format!(
577 " · {} {}",
578 kind.short(),
579 crate::hooks::common::human_secs(waited as u64)
580 ));
581 if budgets.lock_wait > 0 {
582 line.push_str(&format!(
583 "/{}",
584 crate::hooks::common::human_secs(budgets.lock_wait)
585 ));
586 }
587 } else if row.quiet >= QUIET_NOTE_SECS {
588 let quiet = crate::hooks::common::human_secs(row.quiet as u64);
589 match row.cpu {
590 RowCpu::Busy(m) => line.push_str(&format!(
592 " · quiet {quiet} · {}",
593 crate::hooks::common::cores(m)
594 )),
595 _ if budgets.idle == 0 => line.push_str(&format!(" · quiet {quiet}")),
596 RowCpu::Unmeasured => line.push_str(&format!(
602 " · quiet {quiet}/{} (CPU unmeasured)",
603 crate::hooks::common::human_secs(budgets.extended.max(budgets.idle))
604 )),
605 RowCpu::Idle if row.quiet - row.still >= 1.0 => line.push_str(&format!(
606 " · quiet {quiet} · idle {}/{}",
607 crate::hooks::common::human_secs(row.still as u64),
608 crate::hooks::common::human_secs(row.applied_idle(budgets))
609 )),
610 _ => line.push_str(&format!(
611 " · quiet {quiet}/{}",
612 crate::hooks::common::human_secs(row.applied_idle(budgets))
613 )),
614 }
615 if let (Some((_, _, factor)), false) = (row.load, row.cpu == RowCpu::Unmeasured) {
616 line.push_str(&format!(" (load {})", crate::load::factor_text(factor)));
617 }
618 }
619 if budgets.ceiling > 0 && row.elapsed >= 0.8 * budgets.ceiling as f64 {
620 line.push_str(&format!(
621 " · {}/{}",
622 crate::hooks::common::human_secs(row.elapsed as u64),
623 crate::hooks::common::human_secs(budgets.ceiling)
624 ));
625 }
626 if line.chars().count() > width {
627 out.extend(line.chars().take(width));
628 } else {
629 out.push_str(&line);
630 }
631 out.push('\n');
632 }
633 if entries.len() > MAX_LINES {
634 out.push_str(&format!("… and {} more\n", entries.len() - MAX_LINES));
635 }
636 out
637}
638
639struct QuietEnd<'a> {
651 name: &'a str,
652 secs: f64,
653 outcome: Option<crate::check::Outcome>,
654 said: Vec<u8>,
656 capture: crate::capture::Capture,
657 runner_exit: Option<i32>,
658 ci: bool,
659 ok_line: bool,
661}
662
663fn in_ci() -> bool {
666 std::env::var("CI").is_ok_and(|v| !v.is_empty() && v != "false" && v != "0")
667}
668
669fn quiet_block(mut end: QuietEnd) -> QuietOut {
673 let stored = end.capture.finish();
674 let failed = is_failure(end.outcome);
675 let exit = match (end.outcome, failed) {
678 (None, _) => None,
679 (Some(_), true) => Some(end.runner_exit.filter(|c| *c != 0).unwrap_or(1)),
680 (Some(_), false) => Some(0),
681 };
682 end.capture.end_entry(exit, stored.path());
683 let passed = end.outcome == Some(crate::check::Outcome::Passed);
684 if end.capture.seen == 0 {
685 if let Some(p) = stored.path() {
691 let _ = std::fs::remove_file(p);
692 }
693 let mut head = end.said;
694 if failed && end.runner_exit.is_some() {
695 head.extend_from_slice(b"(no output)\n");
696 if let Some(code) = end.runner_exit.filter(|c| *c != 0) {
697 head.extend_from_slice(
698 format!("{} failed, runner exit {code}\n", end.name).as_bytes(),
699 );
700 }
701 }
702 return QuietOut::plain(head);
703 }
704 if passed && !end.ok_line {
705 return QuietOut::plain(end.said);
708 }
709 let path = stored.path().map(|p| p.display().to_string());
710 if passed {
711 let mut out = format!("ok {} {:.1}s", end.name, end.secs);
712 if let (crate::capture::Stored::Saved(_), Some(p)) = (&stored, &path) {
713 out.push_str(&format!(" log={p}"));
714 }
715 out.push('\n');
716 if let Some(note) = stored.note() {
717 out.push_str(¬e);
718 out.push('\n');
719 }
720 return QuietOut::plain(out.into_bytes());
721 }
722 let excerpt = end.capture.acc.finish(path.as_deref().unwrap_or("-"));
723 let mut tail = String::new();
724 if failed {
725 if let Some(code) = end.runner_exit.filter(|c| *c != 0) {
726 tail.push_str(&format!("{} failed, runner exit {code}\n", end.name));
727 }
728 }
729 if let Some(p) = &path {
730 tail.push_str(&format!("full log: {p}\n"));
731 }
732 if let Some(note) = stored.note() {
733 tail.push_str(¬e);
734 tail.push('\n');
735 }
736 match (&stored, end.ci && failed) {
740 (crate::capture::Stored::Saved(p), true) => QuietOut {
741 head: end.said,
742 stream: Some((p.clone(), excerpt)),
743 tail: tail.into_bytes(),
744 },
745 _ => {
746 let mut head = end.said;
747 head.extend_from_slice(excerpt.as_bytes());
748 QuietOut {
749 head,
750 stream: None,
751 tail: tail.into_bytes(),
752 }
753 }
754 }
755}
756
757struct QuietOut {
760 head: Vec<u8>,
761 stream: Option<(std::path::PathBuf, String)>,
762 tail: Vec<u8>,
763}
764
765impl QuietOut {
766 fn plain(head: Vec<u8>) -> QuietOut {
767 QuietOut {
768 head,
769 stream: None,
770 tail: Vec::new(),
771 }
772 }
773
774 fn is_empty(&self) -> bool {
775 self.head.is_empty() && self.stream.is_none() && self.tail.is_empty()
776 }
777
778 fn write(self, to: &mut impl Write) {
779 let _ = to.write_all(&self.head);
780 if let Some((path, excerpt)) = self.stream {
781 let copied = std::fs::File::open(&path).and_then(|mut f| std::io::copy(&mut f, to));
782 if let Err(e) = copied {
783 let _ = to.write_all(excerpt.as_bytes());
784 let _ = writeln!(to, "log not read: {e}");
785 }
786 }
787 let _ = to.write_all(&self.tail);
788 }
789}
790
791fn is_failure(outcome: Option<crate::check::Outcome>) -> bool {
795 use crate::check::Outcome;
796 match outcome {
797 None => true,
798 Some(Outcome::Failed) => true,
799 Some(
800 Outcome::Passed
801 | Outcome::Warned
802 | Outcome::Fixed
803 | Outcome::Unavailable
804 | Outcome::Inert
805 | Outcome::Deferred
806 | Outcome::Skipped,
807 ) => false,
808 }
809}
810
811fn heartbeat(settings: crate::config::Settings, weak: Weak<Stage>) {
812 loop {
813 std::thread::sleep(crate::clock::scaled(std::time::Duration::from_secs(1)));
814 let Some(stage) = weak.upgrade() else { return };
815 if stage.stop.load(Ordering::Relaxed) {
816 return;
817 }
818 let mut announce: Vec<String> = Vec::new();
819 let due: Vec<(Row, bool)> = {
820 let mut slots = stage.slots.lock().unwrap_or_else(|p| p.into_inner());
821 let now = Instant::now();
822 let mut due = Vec::new();
823 for s in slots.iter_mut().filter(|s| s.running && !s.done) {
824 let ran = now.duration_since(s.started);
825 let elapsed = ran.as_secs();
826 if !s.announced
829 && ran >= crate::clock::scaled(std::time::Duration::from_secs(ANNOUNCE_SECS))
830 {
831 if let Some(c) = s.capture.as_ref().filter(|c| c.writing() && c.seen > 0) {
832 s.announced = true;
833 announce.push(format!("running {}, log {}\n", s.name, c.tmp.display()));
834 }
835 }
836 if elapsed >= s.next_beat {
837 let first = s.next_beat == HEARTBEAT_SECS;
838 s.next_beat += HEARTBEAT_SECS;
839 due.push((row_of(s, now, elapsed as f64), first));
840 }
841 }
842 due
843 };
844 if due.is_empty() && announce.is_empty() {
845 continue;
846 }
847 let text: String = announce.concat()
848 + &due
849 .iter()
850 .map(|(row, first)| {
851 beat_line(
852 row,
853 *first,
854 budgets(&settings),
855 stage.on_push,
856 stage.way_out,
857 )
858 })
859 .collect::<String>();
860 let _guard = stage.out.lock().unwrap_or_else(|p| p.into_inner());
861 let mut err = std::io::stderr().lock();
862 let _ = err.write_all(text.as_bytes());
863 let _ = err.flush();
864 }
865}
866
867fn beat_line(row: &Row, first: bool, budgets: Budgets, on_push: bool, way_out: WayOut) -> String {
892 use crate::hooks::common::human_secs;
893 let mut line = format!(
896 " … {} still running: {}, last output {} ago",
897 row.name,
898 human_secs(row.elapsed as u64),
899 human_secs(row.quiet as u64)
900 );
901 if let Some((secs, n)) = row.queued {
902 line.push_str(&queued_note(secs, n, budgets.ceiling));
903 } else if let Some((kind, waited)) = row.wait {
904 line.push_str(&format!(
905 ", waiting for {} {}",
906 kind.describe(),
907 human_secs(waited as u64)
908 ));
909 match budgets.lock_wait {
910 0 => line.push_str(" (greengate.lockWait 0: until the ceiling)"),
911 s => line.push_str(&format!(" (greengate.lockWait {})", human_secs(s))),
912 }
913 } else {
914 match row.cpu {
915 RowCpu::Busy(m) => line.push_str(&format!(", busy {}", crate::hooks::common::cores(m))),
916 RowCpu::Idle => line.push_str(&format!(", CPU idle {}", human_secs(row.still as u64))),
917 RowCpu::Unmeasured if budgets.idle > 0 => line.push_str(&format!(
918 ", CPU unmeasured — extended budget {}",
919 human_secs(budgets.extended.max(budgets.idle))
920 )),
921 RowCpu::Unmeasured => line.push_str(", CPU unmeasured"),
922 RowCpu::None | RowCpu::NotSampled => {}
923 }
924 if let (Some((applied, load, factor)), false) = (row.load, row.cpu == RowCpu::Unmeasured) {
925 line.push_str(&format!(
926 ", budget {} (load avg {} on {} cores, {} — greengate.idleLoadScale)",
927 human_secs(applied),
928 load.avg1_text(),
929 load.cores,
930 crate::load::factor_text(factor)
931 ));
932 }
933 }
934 if first {
935 let idle = match row.applied_idle(budgets) {
936 0 => "off".to_string(),
937 s => human_secs(s),
938 };
939 let ceiling = match budgets.ceiling {
940 0 => "off".to_string(),
941 s => human_secs(s),
942 };
943 match row.cpu {
944 _ if row.wait.is_some() => line.push_str(&format!(
947 " (killed after {} in the wait, or {ceiling} in total — greengate.lockWait / \
948 greengate.timeout)",
949 match budgets.lock_wait {
950 0 => ceiling.clone(),
951 s => human_secs(s),
952 }
953 )),
954 RowCpu::Unmeasured if budgets.idle > 0 => line.push_str(&format!(
957 " (killed after {} with no output while its CPU is unmeasured, or {ceiling} \
958 in total — greengate.idleTimeout × greengate.idleLoadScale / greengate.timeout)",
959 human_secs(budgets.extended.max(budgets.idle))
960 )),
961 RowCpu::Busy(_) | RowCpu::Idle if budgets.idle > 0 => line.push_str(&format!(
962 " (killed after {idle} with no output and under 0.1 core of CPU, or \
963 {ceiling} in total — greengate.idleTimeout / greengate.timeout)"
964 )),
965 _ => line.push_str(&format!(
966 " (killed after {idle} of silence or {ceiling} in total — greengate.idleTimeout / greengate.timeout)"
967 )),
968 }
969 if row.cpu == RowCpu::NotSampled && budgets.idle > 0 {
970 line.push_str("; CPU not sampled here, silence alone counts");
971 }
972 line.push_str(&skip_clause(row, way_out));
976 if on_push {
977 line.push_str(concat!(
982 "\n git opened its connection to the remote before calling this",
983 "\n gate, and it stays idle until the gate finishes. A remote may",
984 "\n close it first — GitHub does — and the push then fails with",
985 "\n \"Connection reset by peer\", naming the network rather than the",
986 "\n wait. ssh keepalive does not prevent this.",
987 "\n Declaring this check at pre-commit moves it off the push path —",
988 "\n see \"Moving a gate entry earlier\" in the docs.",
989 ));
990 }
991 }
992 if !first {
993 line.push_str(&skip_clause(row, way_out));
994 }
995 line.push('\n');
996 line
997}
998
999#[derive(Clone, Copy)]
1002enum WayOut {
1003 Offered,
1004 Withheld,
1005}
1006
1007impl WayOut {
1008 fn for_snapshot(in_snapshot: bool) -> Self {
1009 if in_snapshot {
1010 WayOut::Withheld
1011 } else {
1012 WayOut::Offered
1013 }
1014 }
1015}
1016
1017fn queued_note(secs: f64, slots: u64, timeout: u64) -> String {
1022 use crate::hooks::common::human_secs;
1023 let left = crate::host_slots::wait_ceiling_secs(timeout).saturating_sub(secs as u64);
1024 format!(
1025 ", queued {} for a host slot (greengate.hostSlots {slots}), defers to CI \
1026 in at most {} (greengate.timeout)",
1027 human_secs(secs as u64),
1028 human_secs(left)
1029 )
1030}
1031
1032fn skip_clause(row: &Row, way_out: WayOut) -> String {
1037 match (row.queued, way_out) {
1038 (Some(_), WayOut::Offered) => format!("; skip the queue: rerun with {SKIP_QUEUE}"),
1039 (Some(_), WayOut::Withheld) | (None, _) => String::new(),
1040 }
1041}
1042
1043const SKIP_QUEUE: &str = "GREENGATE_ON_BUSY=now";
1045
1046fn holds_a_push_connection(names: &[&str], in_snapshot: bool) -> bool {
1051 names.iter().any(|n| n.starts_with("pre-push-")) && !in_snapshot
1052}
1053
1054pub fn term_width() -> usize {
1063 std::env::var("COLUMNS")
1064 .ok()
1065 .and_then(|c| c.parse::<usize>().ok())
1066 .filter(|w| *w >= 20)
1067 .unwrap_or(80)
1068}
1069
1070pub struct FinishOnDrop<'a> {
1074 stage: &'a Stage,
1075 idx: usize,
1076 outcome: std::cell::Cell<Option<crate::check::Outcome>>,
1078 settings: &'a crate::config::Settings,
1081}
1082
1083impl<'a> FinishOnDrop<'a> {
1084 pub fn new(
1085 settings: &'a crate::config::Settings,
1086 stage: &'a Stage,
1087 idx: usize,
1088 ) -> FinishOnDrop<'a> {
1089 FinishOnDrop {
1090 stage,
1091 idx,
1092 outcome: std::cell::Cell::new(None),
1093 settings,
1094 }
1095 }
1096
1097 pub fn outcome(&self, outcome: crate::check::Outcome) {
1099 self.outcome.set(Some(outcome));
1100 }
1101}
1102
1103impl Drop for FinishOnDrop<'_> {
1104 fn drop(&mut self) {
1105 self.stage
1106 .finish(self.settings, self.idx, self.outcome.get());
1107 }
1108}
1109
1110pub struct SinkGuard;
1112
1113impl Drop for SinkGuard {
1114 fn drop(&mut self) {
1115 SINK.with(|s| *s.borrow_mut() = None);
1116 }
1117}
1118
1119pub struct AttachGuard {
1122 stage: Arc<Stage>,
1123 idx: usize,
1124}
1125
1126impl Drop for AttachGuard {
1127 fn drop(&mut self) {
1128 let mut slots = self.stage.slots.lock().unwrap_or_else(|p| p.into_inner());
1129 if let Some(slot) = slots.get_mut(self.idx) {
1130 slot.activity = None;
1131 }
1132 }
1133}
1134
1135pub fn current_sink() -> Option<(Arc<Stage>, usize)> {
1138 SINK.with(|s| s.borrow().clone())
1139}
1140
1141pub fn say(line: &str) {
1147 let routed = SINK.with(|s| {
1148 s.borrow().as_ref().map(|(stage, idx)| {
1149 stage.append_line(*idx, line);
1150 })
1151 });
1152 if routed.is_none() {
1153 println!("{line}");
1154 }
1155}
1156
1157#[macro_export]
1162macro_rules! say {
1163 ($($arg:tt)*) => {
1164 $crate::live::say(&format!($($arg)*))
1165 };
1166}
1167
1168pub fn quiet(settings: &crate::config::Settings) -> bool {
1193 *settings.quiet.get_or_init(|| {
1194 decide(
1195 crate::config::enumerated_or(settings, "greengate.quiet", QUIET_VALUES, "auto"),
1196 watching(),
1197 )
1198 })
1199}
1200
1201pub const QUIET_VALUES: &[&str] = &["never", "auto", "always"];
1202
1203fn decide(setting: &str, watching: bool) -> bool {
1205 match setting {
1206 "always" => true,
1207 "auto" => !watching,
1208 _ => false,
1211 }
1212}
1213
1214pub fn enabled(settings: &crate::config::Settings) -> bool {
1217 *settings
1218 .progress
1219 .get_or_init(|| crate::config::boolean_or(settings, "greengate.progress", true))
1220}
1221
1222pub fn watching() -> bool {
1228 static WATCHING: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1229 *WATCHING.get_or_init(|| {
1230 if !std::io::stderr().is_terminal() {
1231 return false;
1232 }
1233 match std::env::var("TERM") {
1234 Ok(term) => term != "dumb",
1235 Err(_) => !cfg!(windows),
1236 }
1237 })
1238}
1239
1240#[cfg(test)]
1241mod tests {
1242 use super::*;
1243
1244 fn test_settings() -> crate::config::Settings {
1245 crate::config::Settings::default()
1246 }
1247
1248 #[test]
1249 fn quiet_asks_who_is_reading() {
1250 assert!(!decide("never", true));
1251 assert!(!decide("never", false));
1252 assert!(always_and_auto_agree_at_a_terminal());
1253 assert!(decide("auto", false), "captured: nobody is watching");
1254 assert!(decide("always", true));
1255 assert!(decide("always", false));
1256 assert!(!decide("shhh", false));
1259 }
1260
1261 fn always_and_auto_agree_at_a_terminal() -> bool {
1262 !decide("auto", true) && decide("always", true)
1263 }
1264
1265 #[test]
1269 fn slots_do_not_share_a_buffer() {
1270 let stage = Stage::begin(&test_settings(), &["a", "b"]);
1271 std::thread::scope(|scope| {
1272 for idx in 0..2 {
1273 let stage = Arc::clone(&stage);
1274 scope.spawn(move || {
1275 let _guard = stage.enter(idx);
1276 for i in 0..50 {
1277 say(&format!("check-{idx} line-{i}"));
1278 std::thread::yield_now();
1279 }
1280 });
1281 }
1282 });
1283 let slots = stage.slots.lock().unwrap();
1284 for idx in 0..2 {
1285 let text = String::from_utf8(slots[idx].buf.clone()).unwrap();
1286 assert_eq!(text.lines().count(), 50);
1287 assert!(
1288 text.lines()
1289 .all(|l| l.starts_with(&format!("check-{idx} "))),
1290 "a foreign line landed in slot {idx}"
1291 );
1292 }
1293 }
1294
1295 #[test]
1297 fn no_sink_means_no_capture() {
1298 let stage = Stage::begin(&test_settings(), &["a"]);
1299 say("goes to stdout, not to a slot");
1300 let slots = stage.slots.lock().unwrap();
1301 assert!(slots[0].buf.is_empty());
1302 }
1303
1304 #[test]
1307 fn a_finished_slot_takes_no_more_writes() {
1308 let stage = Stage::begin(&test_settings(), &["a"]);
1309 stage.append_raw(0, b"before\n");
1310 stage.finish(&test_settings(), 0, None);
1311 stage.append_raw(0, b"after\n");
1312 let slots = stage.slots.lock().unwrap();
1313 assert!(slots[0].buf.is_empty(), "a write landed after finish");
1314 }
1315
1316 #[test]
1319 fn a_slot_name_is_sanitised_at_begin() {
1320 let stage = Stage::begin(&test_settings(), &["evil\u{1b}[2Jname\rhere"]);
1321 let slots = stage.slots.lock().unwrap();
1322 assert!(!slots[0].name.contains('\u{1b}'), "{:?}", slots[0].name);
1323 assert!(!slots[0].name.contains('\r'), "{:?}", slots[0].name);
1324 }
1325
1326 #[test]
1329 fn a_slot_name_drops_the_stage_prefix() {
1330 let stage = Stage::begin(
1331 &test_settings(),
1332 &["pre-commit-clippy", "pre-push-run-tests", "bare"],
1333 );
1334 let slots = stage.slots.lock().unwrap();
1335 assert_eq!(slots[0].name, "clippy");
1336 assert_eq!(slots[1].name, "run-tests");
1337 assert_eq!(slots[2].name, "bare");
1338 }
1339
1340 fn row(name: &str, elapsed: f64) -> Row {
1341 Row {
1342 name: name.into(),
1343 elapsed,
1344 quiet: 0.0,
1345 still: 0.0,
1346 cpu: RowCpu::None,
1347 wait: None,
1348 load: None,
1349 queued: None,
1350 }
1351 }
1352
1353 #[test]
1356 fn a_queued_check_says_it_waits_for_a_host_slot() {
1357 let mut r = row("pre-push-run-tests-js", 42.0);
1358 r.queued = Some((42.0, 2));
1359 let text = region(&[r.clone()], 80, B);
1360 assert!(text.contains("· queued 42s (slots 2/2)"), "{text:?}");
1361 assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1362 r.elapsed = 60.0;
1363 r.quiet = 60.0;
1364 r.queued = Some((60.0, 2));
1365 let beat = beat_line(&r, false, B, false, WayOut::Offered);
1366 assert_eq!(
1367 beat,
1368 " … pre-push-run-tests-js still running: 1m00s, last output 1m00s ago, \
1369 queued 1m00s for a host slot (greengate.hostSlots 2), defers to CI in \
1370 at most 59m00s (greengate.timeout); \
1371 skip the queue: rerun with GREENGATE_ON_BUSY=now\n"
1372 );
1373 }
1374
1375 #[test]
1379 fn a_queued_note_counts_down_to_the_ceiling() {
1380 assert!(queued_note(3590.0, 2, 3600).contains("in at most 10s (greengate.timeout)"));
1381 assert!(queued_note(7200.0, 2, 3600).contains("in at most 0s (greengate.timeout)"));
1382 assert!(queued_note(60.0, 2, 0).contains("in at most 59m00s (greengate.timeout)"));
1383 assert!(!queued_note(60.0, 2, 3600).contains('\x1b'));
1384 }
1385
1386 #[test]
1391 fn the_way_out_of_a_queue_ends_the_line_and_is_withheld_in_a_land() {
1392 let mut queued_row = row("pre-push-run-tests-js", 60.0);
1393 queued_row.queued = Some((60.0, 2));
1394 let skip = "skip the queue: rerun with GREENGATE_ON_BUSY=now";
1395 let offered = |first, on_push| beat_line(&queued_row, first, B, on_push, WayOut::Offered);
1396 let first = offered(true, false);
1397 assert!(first.contains("(killed after"), "{first:?}");
1398 assert!(first.ends_with(&format!("; {skip}\n")), "{first:?}");
1399 assert!(!first.contains("\x1b"), "{first:?}");
1400 assert_eq!(offered(false, true), offered(false, false));
1401 let pushing = offered(true, true);
1402 let way_out_at = pushing.find(skip).expect("the way out");
1403 assert!(pushing.find("git opened its connection").unwrap() > way_out_at);
1404 for first_beat in [true, false] {
1405 let withheld = beat_line(&queued_row, first_beat, B, false, WayOut::Withheld);
1406 assert!(!withheld.contains("GREENGATE_ON_BUSY"), "{withheld:?}");
1407 assert!(
1408 withheld.contains("defers to CI in at most 59m00s"),
1409 "{withheld:?}"
1410 );
1411 }
1412 }
1413
1414 #[test]
1418 fn a_load_stretched_budget_is_shown_with_its_load() {
1419 let mut r = row("pre-push-run-tests-js", 240.0);
1420 r.quiet = 130.0;
1421 r.still = 130.0;
1422 r.cpu = RowCpu::Idle;
1423 r.load = Some((
1424 468,
1425 crate::load::Load {
1426 avg1_milli: 31_200,
1427 cores: 8,
1428 },
1429 3900,
1430 ));
1431 let text = region(&[r.clone()], 80, B);
1432 assert!(text.contains("· quiet 2m10s/7m48s (load ×3.9)"), "{text:?}");
1433 assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1434 let beat = beat_line(&r, false, B, false, WayOut::Offered);
1435 assert!(
1436 beat.ends_with(
1437 ", CPU idle 2m10s, budget 7m48s (load avg 31.2 on 8 cores, ×3.9 — greengate.idleLoadScale)\n"
1438 ),
1439 "{beat:?}"
1440 );
1441 let first = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1442 assert!(
1443 first.contains("killed after 7m48s with no output and under 0.1 core of CPU"),
1444 "{first:?}"
1445 );
1446 }
1447
1448 const B: Budgets = Budgets {
1449 idle: 120,
1450 ceiling: 3600,
1451 lock_wait: 600,
1452 extended: 480,
1453 };
1454
1455 #[test]
1459 fn an_unmeasured_check_is_shown_against_the_extended_budget() {
1460 let mut r = row("pre-push-run-tests-js", 240.0);
1461 r.quiet = 130.0;
1462 r.still = 130.0;
1463 r.cpu = RowCpu::Unmeasured;
1464 let text = region(&[r.clone()], 80, B);
1465 assert!(
1466 text.contains("· quiet 2m10s/8m00s (CPU unmeasured)"),
1467 "{text:?}"
1468 );
1469 assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1470 let beat = beat_line(&r, false, B, false, WayOut::Offered);
1471 assert!(
1472 beat.ends_with(", CPU unmeasured — extended budget 8m00s\n"),
1473 "{beat:?}"
1474 );
1475 let first = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1476 assert!(
1477 first.contains(
1478 "killed after 8m00s with no output while its CPU is unmeasured, or 1h00m in total"
1479 ),
1480 "{first:?}"
1481 );
1482 assert!(first.contains("greengate.idleLoadScale"), "{first:?}");
1483 }
1484
1485 #[test]
1489 fn a_declared_wait_is_shown_against_its_own_budget() {
1490 use crate::hooks::wait::{CargoLockWhat, WaitKind};
1491 let mut r = row("pre-push-run-tests-js", 240.0);
1492 r.quiet = 130.0;
1493 r.still = 0.0;
1494 r.cpu = RowCpu::Unmeasured;
1495 r.wait = Some((WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 90.0));
1496 let text = region(&[r.clone()], 80, B);
1497 assert!(text.contains("· cargo lock 1m30s/10m00s"), "{text:?}");
1498 assert!(!text.contains("quiet"), "no silence countdown: {text:?}");
1499 assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1500 let until = Budgets { lock_wait: 0, ..B };
1501 let text = region(&[r.clone()], 80, until);
1502 assert!(
1503 text.contains("· cargo lock 1m30s") && !text.contains("1m30s/"),
1504 "{text:?}"
1505 );
1506
1507 let beat = beat_line(&r, false, B, false, WayOut::Offered);
1508 assert_eq!(
1509 beat,
1510 " … pre-push-run-tests-js still running: 4m00s, last output 2m10s ago, \
1511 waiting for the cargo lock on the build directory 1m30s (greengate.lockWait 10m00s)\n"
1512 );
1513 let beat = beat_line(&r, false, until, false, WayOut::Offered);
1514 assert!(
1515 beat.contains("(greengate.lockWait 0: until the ceiling)"),
1516 "{beat:?}"
1517 );
1518 let first = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1521 assert!(
1522 first.contains(
1523 "(killed after 10m00s in the wait, or 1h00m in total — greengate.lockWait"
1524 ),
1525 "{first:?}"
1526 );
1527 assert!(!first.contains("unmeasured"), "{first:?}");
1528 }
1529
1530 #[test]
1533 fn frames_advance_with_time() {
1534 let a = region(&[row("clippy", 0.0)], 80, B);
1535 let b = region(&[row("clippy", 0.1)], 80, B);
1536 let c = region(&[row("clippy", 1.0)], 80, B);
1537 assert_ne!(a.chars().next(), b.chars().next());
1538 assert_eq!(a.chars().next(), c.chars().next(), "10 frames per second");
1539 }
1540
1541 #[test]
1544 fn region_lines_align() {
1545 let text = region(&[row("a", 0.0), row("longer-name", 0.0)], 80, B);
1546 let widths: Vec<usize> = text.lines().map(|l| l.chars().count()).collect();
1547 assert_eq!(widths[0], widths[1], "{text:?}");
1548 let text = region(&[row("a", 3.2), row("b", 492.0)], 80, B);
1549 let widths: Vec<usize> = text.lines().map(|l| l.chars().count()).collect();
1550 assert_eq!(widths[0], widths[1], "{text:?}");
1551 assert!(text.contains("8m12s"), "{text:?}");
1552 }
1553
1554 #[test]
1556 fn region_caps_and_counts_the_rest() {
1557 let entries: Vec<Row> = (0..13).map(|i| row(&format!("check-{i}"), 0.0)).collect();
1558 let text = region(&entries, 80, B);
1559 assert_eq!(text.lines().count(), MAX_LINES + 1);
1560 assert!(text.ends_with("… and 1 more\n"), "{text:?}");
1561 }
1562
1563 #[test]
1566 fn region_respects_width() {
1567 let text = region(&[row("a-name-much-longer-than-the-terminal", 0.0)], 20, B);
1568 assert!(text.lines().all(|l| l.chars().count() <= 20), "{text:?}");
1569 }
1570
1571 #[test]
1573 fn an_empty_region_is_empty() {
1574 assert_eq!(region(&[], 80, B), "");
1575 }
1576
1577 #[test]
1581 fn a_quiet_check_shows_its_silence_against_the_budget() {
1582 let mut r = row("cargo-test", 300.0);
1583 r.quiet = 5.0;
1584 assert!(!region(&[r.clone()], 80, B).contains("quiet"));
1585 r.quiet = 45.0;
1586 let text = region(&[r.clone()], 80, B);
1587 assert!(text.contains("quiet 45s/2m00s"), "{text:?}");
1588 let off = Budgets { idle: 0, ..B };
1589 let text = region(&[r], 80, off);
1590 assert!(
1591 text.contains("quiet 45s") && !text.contains('/'),
1592 "{text:?}"
1593 );
1594 }
1595
1596 #[test]
1601 fn a_quiet_busy_check_shows_cores_and_an_idle_one_counts_down_the_still_time() {
1602 let mut r = row("vitest-workspace", 240.0);
1603 r.quiet = 130.0;
1604 r.still = 130.0;
1605 r.cpu = RowCpu::Busy(3900);
1606 let busy = region(&[r.clone()], 80, B);
1607 assert!(busy.contains("· quiet 2m10s · ~3.9 cores"), "{busy:?}");
1608 assert!(
1609 !busy.contains("/2m00s"),
1610 "no countdown while busy: {busy:?}"
1611 );
1612
1613 r.cpu = RowCpu::Idle;
1614 r.still = 40.0;
1615 let idle = region(&[r.clone()], 80, B);
1616 assert!(idle.contains("· quiet 2m10s · idle 40s/2m00s"), "{idle:?}");
1617
1618 r.cpu = RowCpu::Unmeasured;
1619 r.still = 130.0;
1620 let plain = region(&[r], 80, B);
1621 assert!(
1622 plain.contains("· quiet 2m10s/8m00s (CPU unmeasured)"),
1623 "{plain:?}"
1624 );
1625
1626 for text in [busy, idle, plain] {
1627 assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1628 }
1629 }
1630
1631 #[test]
1634 fn a_heartbeat_appends_the_cpu_state_after_an_unchanged_prefix() {
1635 let mut r = row("vitest", 240.0);
1636 r.quiet = 130.0;
1637 r.still = 40.0;
1638 let prefix = " … vitest still running: 4m00s, last output 2m10s ago";
1639 for (cpu, suffix) in [
1640 (RowCpu::Busy(3900), ", busy ~3.9 cores\n"),
1641 (RowCpu::Idle, ", CPU idle 40s\n"),
1642 (
1643 RowCpu::Unmeasured,
1644 ", CPU unmeasured — extended budget 8m00s\n",
1645 ),
1646 (RowCpu::None, "\n"),
1647 (RowCpu::NotSampled, "\n"),
1648 ] {
1649 r.cpu = cpu;
1650 assert_eq!(
1651 beat_line(&r, false, B, false, WayOut::Offered),
1652 format!("{prefix}{suffix}")
1653 );
1654 }
1655 }
1656
1657 #[test]
1659 fn the_first_beat_states_the_rule_in_force() {
1660 let mut r = row("vitest", 60.0);
1661 r.cpu = RowCpu::Idle;
1662 let sampled = beat_line(&r, true, B, false, WayOut::Offered);
1663 assert!(
1664 flat(&sampled).contains(
1665 "killed after 2m00s with no output and under 0.1 core of CPU, or 1h00m in total"
1666 ),
1667 "{sampled:?}"
1668 );
1669 r.cpu = RowCpu::NotSampled;
1670 let not = beat_line(&r, true, B, false, WayOut::Offered);
1671 assert!(
1672 not.contains("2m00s of silence or 1h00m in total"),
1673 "{not:?}"
1674 );
1675 assert!(
1676 not.contains("CPU not sampled here, silence alone counts"),
1677 "{not:?}"
1678 );
1679 }
1680
1681 #[test]
1684 fn the_ceiling_shows_only_when_it_is_near() {
1685 assert!(!region(&[row("cargo-test", 1000.0)], 80, B).contains("/1h00m"));
1686 let text = region(&[row("cargo-test", 3000.0)], 80, B);
1687 assert!(text.contains("50m00s/1h00m"), "{text:?}");
1688 let off = Budgets { ceiling: 0, ..B };
1689 assert!(!region(&[row("cargo-test", 3000.0)], 80, off).contains("/"));
1690 }
1691
1692 #[test]
1696 fn a_heartbeat_names_the_budgets_once() {
1697 let mut r = row("cargo-test", 60.0);
1698 r.quiet = 2.0;
1699 let first = beat_line(&r, true, B, false, WayOut::Offered);
1700 assert!(
1701 first.contains("cargo-test still running: 1m00s"),
1702 "{first:?}"
1703 );
1704 assert!(first.contains("last output 2s ago"), "{first:?}");
1705 assert!(
1706 first.contains("2m00s of silence or 1h00m in total"),
1707 "{first:?}"
1708 );
1709 assert!(first.contains("greengate.idleTimeout"), "{first:?}");
1710 let later = beat_line(&r, false, B, false, WayOut::Offered);
1711 assert!(!later.contains("greengate.idleTimeout"), "{later:?}");
1712 let off = beat_line(
1713 &r,
1714 true,
1715 Budgets {
1716 idle: 0,
1717 ceiling: 0,
1718 lock_wait: 0,
1719 extended: 0,
1720 },
1721 false,
1722 WayOut::Offered,
1723 );
1724 assert!(off.contains("off of silence or off in total"), "{off:?}");
1725 }
1726
1727 fn flat(line: &str) -> String {
1734 line.split_whitespace().collect::<Vec<_>>().join(" ")
1735 }
1736
1737 #[test]
1744 fn a_long_push_gate_is_told_what_it_is_sitting_on() {
1745 let r = row("cargo-test", 60.0);
1746
1747 let pushing = flat(&beat_line(&r, true, B, true, WayOut::Offered));
1748 assert!(
1749 pushing.contains("A remote may close it first"),
1750 "{pushing:?}"
1751 );
1752 assert!(pushing.contains("Connection reset by peer"), "{pushing:?}");
1753 assert!(
1754 pushing.contains("Moving a gate entry earlier"),
1755 "{pushing:?}"
1756 );
1757
1758 let later = flat(&beat_line(&r, false, B, true, WayOut::Offered));
1760 assert!(!later.contains("close it first"), "{later:?}");
1761
1762 let committing = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1764 assert!(!committing.contains("close it first"), "{committing:?}");
1765 }
1766
1767 #[test]
1772 fn a_push_stage_in_a_snapshot_holds_no_connection() {
1773 let push = ["pre-push-greenspotter-cli-probe"];
1774 assert!(holds_a_push_connection(&push, false));
1775 assert!(!holds_a_push_connection(&push, true));
1776 assert!(!holds_a_push_connection(&["pre-commit-clippy"], false));
1777 }
1778
1779 #[test]
1788 fn the_push_note_does_not_recommend_ssh_keepalive() {
1789 let r = row("cargo-test", 60.0);
1790 let pushing = flat(&beat_line(&r, true, B, true, WayOut::Offered));
1791 assert!(
1792 !pushing.contains("ServerAlive"),
1793 "keepalive was already on when this failed; recommending it \
1794 would be useless advice: {pushing:?}"
1795 );
1796 assert!(
1797 pushing.contains("ssh keepalive does not prevent this"),
1798 "say so, rather than leaving the reader to try it: {pushing:?}"
1799 );
1800 }
1801}