baztet 1.1.0

Standalone Bazel project sync and execution CLI (Rust port of the hirschgarten engine)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::io::Read;
use std::time::{Duration, Instant};

use ratatui::{
    backend::{Backend, CrosstermBackend},
    crossterm,
    layout::{Constraint, Direction, Layout},
    style::{Color, Style, Stylize},
    widgets::{Block, Cell, Paragraph, Row, Table},
    Terminal,
};

use baztet_core::baztet_bep::BepOutput;
use baztet_core::exec::{ExecChild, ExecResult};

/// Which command the dashboard mirrors: `test` shows BEP verdicts,
/// `build`/`coverage` show target completions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DashMode {
    Test,
    Build,
}

/// A forked bazel command driven through the alt screen; returns the same
/// [`ExecResult`] the non-dashboard path would have produced, terminal
/// restored on every exit path.
pub async fn run(
    mode: DashMode,
    child: ExecChild,
    pending: Vec<String>,
) -> anyhow::Result<ExecResult> {
    let mut terminal = TuiTerminal::enter()?;
    let result = terminal.drive(mode, child, pending).await;
    drop(terminal);
    result
}
/// Owns the alt-screen/raw-mode pair until dropped.
struct TuiTerminal {
    terminal: Terminal<CrosstermBackend<std::io::Stdout>>,
}

impl TuiTerminal {
    fn enter() -> anyhow::Result<Self> {
        crossterm::terminal::enable_raw_mode()?;
        crossterm::execute!(std::io::stdout(), crossterm::terminal::EnterAlternateScreen)?;
        let terminal = match Terminal::new(CrosstermBackend::new(std::io::stdout())) {
            Ok(t) => t,
            Err(e) => {
                restore();
                return Err(e.into());
            }
        };
        Ok(Self { terminal })
    }

    async fn drive(
        &mut self,
        mode: DashMode,
        child: ExecChild,
        pending: Vec<String>,
    ) -> anyhow::Result<ExecResult> {
        let started = Instant::now();
        let bep_path = child.bep_path().to_owned();
        // clone before the move: the dashboard's live progress lives in the
        // console capture, and the waiter task consumes the ExecChild
        let console = child.console_handle();
        // Option: awaiting consumes the handle; ownership back-checks the
        // early-abort path in the loop below
        let mut waiter = Some(tokio::spawn(async move {
            child.wait().await.map_err(anyhow::Error::from)
        }));
        let mut state = BepOutput::default();
        let mut offset = 0usize;
        // the loop breaks through several paths; if it bails out early the
        // waiter still owns the live Child — aborting drops the Child and
        // kill_on_drop terminates bazel
        let outcome: anyhow::Result<ExecResult> = loop {
            if waiter.as_ref().unwrap().is_finished() {
                // the waiter's wait() already read and deleted the sidecar;
                // the completed verdicts are in the result's BEP output —
                // draw this final frame so the dashboard closes showing the
                // run's state, not a mid-run one
                let result = match waiter.take().unwrap().await {
                    Ok(Ok(res)) => Ok(res),
                    Ok(Err(e)) => Err(e),
                    Err(e) => Err(e.into()),
                };
                if let Ok(res) = &result {
                    if let Some(bep) = &res.bep {
                        state = bep.clone();
                    }
                }
                let _ = draw(
                    &mut self.terminal,
                    mode,
                    &state,
                    pending.len(),
                    started.elapsed(),
                    &console,
                );
                break result;
            }
            // read only when poll says an event is ready: a bare read blocks
            // forever when no key was pressed, freezing the whole draw loop
            let key_ready = match crossterm::event::poll(Duration::from_millis(200)) {
                Ok(ready) => ready,
                Err(e) => break Err(e.into()),
            };
            if key_ready {
                match crossterm::event::read() {
                    Ok(crossterm::event::Event::Key(k)) => {
                        let quit = k.kind == crossterm::event::KeyEventKind::Press
                            && (k.code == crossterm::event::KeyCode::Char('q')
                                || (k
                                    .modifiers
                                    .contains(crossterm::event::KeyModifiers::CONTROL)
                                    && k.code == crossterm::event::KeyCode::Char('c')));
                        if quit {
                            if waiter.as_ref().unwrap().is_finished() {
                                // bazel exited in the poll window: take the real
                                // result instead of fabricating a cancellation
                                break match waiter.take().unwrap().await {
                                    Ok(Ok(res)) => Ok(res),
                                    Ok(Err(e)) => Err(e),
                                    Err(e) => Err(e.into()),
                                };
                            }
                            // capture what bazel wrote so far, then kill it
                            waiter.as_ref().unwrap().abort();
                            ingest(&mut state, &bep_path, offset);
                            break Ok(ExecResult {
                                code: 130,
                                bep: Some(state),
                                ..Default::default()
                            });
                        }
                    }
                    Err(e) => break Err(e.into()),
                    _ => {}
                }
            }
            offset = ingest(&mut state, &bep_path, offset);
            if let Err(e) = draw(
                &mut self.terminal,
                mode,
                &state,
                pending.len(),
                started.elapsed(),
                &console,
            ) {
                break Err(e);
            }
        };
        if outcome.is_err() {
            if let Some(h) = waiter.as_ref() {
                h.abort();
            }
        }
        outcome
    }
}

/// Read and decode the BEP bytes appended since `offset`; returns the new
/// cursor. The sidecar is written whole at bazel's exit, so this mostly
/// serves mid-write tails and the quit path; the completed state comes
/// from the waiter's parsed result instead.
fn ingest(state: &mut BepOutput, path: &std::path::Path, offset: usize) -> usize {
    use std::io::{Seek, SeekFrom};
    if let Ok(mut f) = std::fs::File::open(path) {
        if f.seek(SeekFrom::Start(offset as u64)).is_ok() {
            let mut buf = Vec::new();
            if f.read_to_end(&mut buf).is_ok() {
                // a truncated tail is normal mid-write: keep the old
                // state and the cursor where it was
                if let Ok((delta, consumed)) = baztet_core::baztet_bep::parse_prefix(&buf, 0) {
                    state.extend(delta);
                    return offset + consumed;
                }
            }
        }
    }
    offset
}

impl Drop for TuiTerminal {
    fn drop(&mut self) {
        restore();
    }
}

fn restore() {
    let _ = crossterm::execute!(
        std::io::stdout(),
        crossterm::terminal::LeaveAlternateScreen,
        crossterm::cursor::Show,
    );
    let _ = crossterm::terminal::disable_raw_mode();
}

fn draw(
    terminal: &mut Terminal<impl Backend>,
    mode: DashMode,
    out: &BepOutput,
    requested: usize,
    elapsed: Duration,
    console: &baztet_core::exec::ConsoleCapture,
) -> anyhow::Result<()> {
    let (done, mut rows): (usize, Vec<Row>) = match mode {
        DashMode::Test => {
            let rows: Vec<Row> = out
                .test_summaries
                .iter()
                .map(|s| {
                    Row::new([Cell::from(s.label.clone()), Cell::from(s.status.clone())])
                        .style(test_style(&s.status))
                })
                .collect();
            (out.test_summaries.len(), rows)
        }
        // build rows: failures first, then completions, then the running tail
        DashMode::Build => {
            let mut failures: Vec<Row> = Vec::new();
            let mut built: Vec<Row> = Vec::new();
            out.target_status.iter().for_each(|(label, success)| {
                let verdict = |txt: &str| {
                    Row::new([Cell::from(label.clone()), Cell::from(txt.to_string())]).style(
                        if *success {
                            Style::new().fg(Color::Green)
                        } else {
                            Style::new().fg(Color::Red)
                        },
                    )
                };
                if *success {
                    built.push(verdict("BUILT"));
                } else {
                    failures.push(verdict("FAILED"));
                }
            });
            let done = out.target_status.len();
            (done, [failures, built].concat())
        }
    };
    // the denominator is the requested list: it never grows while targets finish
    let total = requested.max(done);
    let header = format!(
        " baztet {} — {done}/{total} targets · {:.0}s",
        mode_title(mode),
        elapsed.as_secs_f64()
    );
    if requested > done {
        rows.push(
            Row::new([Cell::from(format!(
                "… {} still running/pending",
                requested - done
            ))])
            .style(Style::new().dim()),
        );
    }
    terminal.draw(|f| {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1), Constraint::Length(1)])
            .split(f.area());
        let table = Table::new(
            rows,
            [Constraint::Percentage(75), Constraint::Percentage(25)],
        )
        .header(Row::new(["target", "status"]).style(Style::new().bold()))
        .block(Block::bordered().title(header));
        f.render_widget(table, chunks[0]);
        // live bazel progress in the footer: the console is the streaming
        // source (the BEP sidecar is written whole at exit)
        let progress = console.last_progress();
        let footer = if progress.is_empty() {
            "q / ctrl-c cancels bazel".to_string()
        } else {
            format!("q cancels bazel · {progress}")
        };
        f.render_widget(Paragraph::new(footer), chunks[1]);
    })?;
    Ok(())
}

fn test_style(status: &str) -> Style {
    match status {
        "PASSED" => Style::new().fg(Color::Green),
        "FAILED" | "TIMEOUT" | "ERROR" => Style::new().fg(Color::Red),
        "FLAKY" => Style::new().fg(Color::Yellow),
        _ => Style::new(),
    }
}

fn mode_title(mode: DashMode) -> &'static str {
    match mode {
        DashMode::Test => "test",
        DashMode::Build => "build/coverage",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use baztet_core::baztet_bep::TestSummary;
    use ratatui::backend::TestBackend;

    #[test]
    fn dashboard_rows_by_mode() {
        let out = BepOutput {
            target_status: [
                ("//a:good".to_string(), true),
                ("//a:bad".to_string(), false),
            ]
            .into(),
            ..BepOutput::default()
        };
        let backend = TestBackend::new(60, 12);
        let mut terminal = Terminal::new(backend).unwrap();
        draw(
            &mut terminal,
            DashMode::Build,
            &out,
            5,
            Duration::from_secs(3),
            &baztet_core::exec::ConsoleCapture::default(),
        )
        .unwrap();
        let text: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(text.contains("//a:bad"), "failure row missing: {text}");
        assert!(text.contains("FAILED"), "FAILED verdict missing: {text}");
        assert!(text.contains("2/5 targets"), "header got: {text}");
        assert!(text.contains("3 still running"), "pending missing: {text}");
    }

    fn summary(label: &str, status: &str) -> TestSummary {
        TestSummary {
            label: label.to_string(),
            status: status.to_string(),
        }
    }

    #[test]
    fn header_denominator_stabilizes() {
        let requested = 10;
        let out = BepOutput {
            test_summaries: [summary("//a:one", "PASSED"), summary("//a:two", "FAILED")].into(),
            ..BepOutput::default()
        };
        let backend = TestBackend::new(60, 8);
        let mut terminal = Terminal::new(backend).unwrap();
        draw(
            &mut terminal,
            DashMode::Test,
            &out,
            requested,
            Duration::from_secs(5),
            &baztet_core::exec::ConsoleCapture::default(),
        )
        .unwrap();
        let text: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(text.contains("2/10 targets"), "header got: {text}");
        assert!(text.contains("//a:one"), "row missing: {text}");
        assert!(
            text.contains("8 still running"),
            "pending row missing: {text}"
        );
    }

    #[test]
    fn header_shows_full_when_all_finish() {
        let requested = 2;
        let out = BepOutput {
            test_summaries: [summary("//a:one", "PASSED"), summary("//a:two", "FLAKY")].into(),
            ..BepOutput::default()
        };
        let backend = TestBackend::new(60, 8);
        let mut terminal = Terminal::new(backend).unwrap();
        draw(
            &mut terminal,
            DashMode::Test,
            &out,
            requested,
            Duration::from_secs(9),
            &baztet_core::exec::ConsoleCapture::default(),
        )
        .unwrap();
        let text: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(text.contains("2/2 targets"), "header got: {text}");
        assert!(!text.contains("still running"), "leftover: {text}");
    }

    #[test]
    fn test_statuses_map_to_verdicts() {
        assert_eq!(test_style("PASSED").fg, Some(Color::Green));
        assert_eq!(test_style("FAILED").fg, Some(Color::Red));
        assert_eq!(test_style("TIMEOUT").fg, Some(Color::Red));
        assert_eq!(test_style("ERROR").fg, Some(Color::Red));
        assert_eq!(test_style("FLAKY").fg, Some(Color::Yellow));
        assert_eq!(test_style("NO_STATUS").fg, None);
    }
}