shep 0.25.2

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
Documentation
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Assembling the pane: which lines the chrome takes, which rows the body
//! gets, and what happens when neither fits.
//!
//! Height is the scarce thing. Every line of chrome is paid for out of the
//! same budget as the rows, so this is where a short terminal sheds the
//! legend, then the tab row, and finally everything but the cursor.

use ratatui::text::Line;

use super::super::super::pane::{ConfigPane, PaneRow};
use super::super::super::theme::Palette;
use super::super::scroll::{self, Attempt};
use super::dogs::dogs_body_lines;
use super::entry_row::{arm_line, choice_line, entry_line};
use super::env::pending_and_env_lines;
use super::field_row::{field_line, section_header, table_line};

/// The body every pane layout draws: the field rows [`body_from`] lays out
/// through [`scroll::to_cursor`], then [`pending_and_env_lines`] appended
/// after. Named for what it is rather than for the layout that first used
/// it, since a dog's pane, which has no groups at all, needs the same body
/// for the same reason: its env rows are rows of [`ConfigPane::rows`] that
/// no field row can stand in for. A sheep's `dogs` tab draws its own body
/// instead: see [`dogs_body_lines`].
pub(super) fn body_lines(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    budget: usize,
    show_lands: bool,
) -> Vec<Line<'static>> {
    if pane.shows_dogs() {
        return dogs_body_lines(pane, palette, width, budget, show_lands);
    }
    // The cursor's own row has to draw somewhere in this budget, per the rule
    // every screen in this file holds. When it is on an env row or
    // `+ add a key`, the field body's own windowing would spend the whole
    // budget on fields none of which is selected.
    if matches!(pane.cursor(), Some(PaneRow::Env(_) | PaneRow::AddEnv)) {
        let tail = pending_and_env_lines(pane, palette, width, budget, show_lands);
        let remaining = budget.saturating_sub(tail.len());
        let mut lines = if !pane.field_rows().is_empty() && remaining > 0 {
            body_from(pane, palette, width, remaining, 0, false, show_lands).lines
        } else {
            Vec::new()
        };
        lines.extend(tail);
        return lines;
    }
    let mut lines = if !pane.field_rows().is_empty() && budget > 0 {
        let field_rows = pane.field_rows();
        let cursor_row = field_rows
            .iter()
            .position(|row| Some(*row) == pane.cursor())
            .unwrap_or(0);
        scroll::to_cursor(
            cursor_row,
            pane.view().offset(),
            |offset| body_from(pane, palette, width, budget, offset, false, show_lands),
            || cursor_only(pane, palette, width, budget, cursor_row, show_lands),
        )
    } else {
        Vec::new()
    };
    let remaining = budget.saturating_sub(lines.len());
    lines.extend(pending_and_env_lines(
        pane, palette, width, remaining, show_lands,
    ));
    lines
}

/// Lays the body out from field `offset`, spending at most `budget` lines.
///
/// Every line pushed is counted, including section headers, blank
/// separators between them and both markers. The two markers are reserved
/// before a row is admitted rather than appended afterwards, so a height
/// that binds cuts a row instead of the sentence saying a row was cut.
pub(super) fn body_from(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    budget: usize,
    offset: usize,
    show_group_headers: bool,
    show_lands: bool,
) -> Attempt {
    let rows = pane.field_rows();
    let total = rows.len();
    // The cursor may be on an env row rather than a field: nothing in
    // this body is selected then, and row 0 stands in so the first
    // attempt (offset 0) always finds it and never scrolls hunting for a
    // row that is not here. See [`body_lines`]'s own doc.
    let cursor_row = rows
        .iter()
        .position(|row| Some(*row) == pane.cursor())
        .unwrap_or(0)
        .min(total.saturating_sub(1));
    // The `... N above` marker is inserted at the top once everything under
    // it is laid out, so its line is held back from the very first check.
    let above = usize::from(offset > 0);
    // Whether a row at `index` still leaves room for `need` more lines. The
    // `... N below` marker is only owed when a row follows this one: a row
    // that fills the last line with nothing under it needs no marker.
    let room = |taken: usize, need: usize, index: usize| {
        taken + need + above + usize::from(index + 1 < total) <= budget
    };

    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut current_group: Option<&str> = None;
    // A group's header, and the blank line ahead of it for every group after
    // the first, held here rather than pushed straight away: it is pushed
    // alongside the first row of its group that survives the offset skip, so
    // a window opening in the middle of `control` still says `control`.
    let mut pending_header: Vec<Line<'static>> = Vec::new();
    let mut drawn = 0usize;

    for (index, row) in rows.iter().enumerate() {
        let field_index = match *row {
            PaneRow::Field(field_index) => field_index,
            PaneRow::Table(table_index) => {
                if index < offset {
                    continue;
                }
                if !room(lines.len(), 1, index) {
                    break;
                }
                lines.push(table_line(
                    pane,
                    table_index,
                    pane.cursor() == Some(*row),
                    width,
                    palette,
                    show_lands,
                ));
                drawn += 1;
                continue;
            }
            PaneRow::Entry(entry_index) => {
                if index < offset {
                    continue;
                }
                if !room(lines.len(), 1, index) {
                    break;
                }
                lines.push(entry_line(
                    pane,
                    entry_index,
                    pane.cursor() == Some(*row),
                    width,
                    palette,
                    show_lands,
                ));
                drawn += 1;
                continue;
            }
            PaneRow::Choice { .. } => {
                if index < offset {
                    continue;
                }
                if !room(lines.len(), 1, index) {
                    break;
                }
                lines.push(choice_line(
                    pane,
                    *row,
                    pane.cursor() == Some(*row),
                    width,
                    palette,
                ));
                drawn += 1;
                continue;
            }
            PaneRow::Arm { .. } => {
                if index < offset {
                    continue;
                }
                if !room(lines.len(), 1, index) {
                    break;
                }
                lines.push(arm_line(
                    pane,
                    *row,
                    pane.cursor() == Some(*row),
                    width,
                    palette,
                    show_lands,
                ));
                drawn += 1;
                continue;
            }
            PaneRow::Env(_) | PaneRow::AddEnv | PaneRow::Dog(_) | PaneRow::Under { .. } => continue,
        };
        let group = pane
            .fields()
            .fields()
            .get(field_index)
            .and_then(|field| field.group.as_deref());
        if show_group_headers && current_group != group {
            let mut header = Vec::new();
            if current_group.is_some() {
                header.push(Line::default());
            }
            if let Some(group) = group {
                header.push(section_header(group, palette));
            }
            pending_header = header;
            current_group = group;
        }
        if index < offset {
            continue;
        }
        if !room(lines.len(), pending_header.len() + 1, index) {
            break;
        }
        lines.append(&mut pending_header);
        lines.push(field_line(
            pane,
            field_index,
            pane.cursor() == Some(*row),
            width,
            palette,
            show_lands,
        ));
        drawn += 1;
    }

    // Counted off what this pass actually drew, not off the viewport's own
    // arithmetic: the viewport hides rows against a line budget it cannot
    // see spent, so its answer and this one disagree the moment the chrome
    // costs anything.
    let hidden_below = total.saturating_sub(offset + drawn);
    scroll::window_markers(&mut lines, hidden_below, offset, palette);

    Attempt {
        cursor_drawn: drawn > 0 && (offset..offset + drawn).contains(&cursor_row),
        lines,
    }
}

/// One row of the field body, drawn by the drawer for its kind. Empty for a
/// row the field body does not hold.
pub(super) fn row_line(
    pane: &ConfigPane,
    row: PaneRow,
    selected: bool,
    width: u16,
    palette: Palette,
    show_lands: bool,
) -> Line<'static> {
    match row {
        PaneRow::Field(index) => field_line(pane, index, selected, width, palette, show_lands),
        PaneRow::Table(index) => table_line(pane, index, selected, width, palette, show_lands),
        PaneRow::Entry(index) => entry_line(pane, index, selected, width, palette, show_lands),
        PaneRow::Choice { .. } => choice_line(pane, row, selected, width, palette),
        PaneRow::Arm { .. } => arm_line(pane, row, selected, width, palette, show_lands),
        PaneRow::Env(_) | PaneRow::AddEnv | PaneRow::Dog(_) | PaneRow::Under { .. } => {
            Line::default()
        }
    }
}

/// The cursor's own row, alone, for a body too short to hold the chrome its
/// group costs.
///
/// The last resort, reached only when every offset down to the cursor's own
/// left it undrawn. A group's first row costs a blank line, a header and two
/// markers before it may be drawn at all: four lines for one row, where
/// `view::MIN_HEIGHT` leaves this pane three after its title.
pub(super) fn cursor_only(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    budget: usize,
    cursor_row: usize,
    show_lands: bool,
) -> Vec<Line<'static>> {
    let rows = pane.field_rows();
    let mut lines = Vec::new();
    if let Some(row) = rows.get(cursor_row).copied() {
        lines.push(row_line(pane, row, true, width, palette, show_lands));
    }
    let hidden_below = rows.len().saturating_sub(cursor_row + 1);
    scroll::cursor_markers(&mut lines, hidden_below, cursor_row, budget, palette);
    lines
}

#[cfg(test)]
mod tests {
    use super::super::draw::pane_lines;
    use super::super::fixtures::{
        bark_pane, blurb_anchor, config_pane_lines_for_tests, marked, screen_at, text_of, web_pane,
    };
    use super::super::layout::panel_width;
    use crate::lookout::app::{KeyPress, Msg};
    use crate::lookout::view::MIN_TERM_WIDTH;
    use crate::lookout::view::fixtures;
    use crate::output::width::visible_width;

    #[test]
    fn a_sheep_pane_scrolled_to_the_last_field_of_a_group_shows_it() {
        // `cron` has only two fields, both of which always fit; `process`,
        // the group a fresh pane opens on, has ten, which is what forces
        // the scroll this test is about.
        let mut pane = web_pane();
        pane.set_rows(8);
        // Not `move_to_last`: that now lands on `+ add a key`, past every
        // field. `move_to_key` reaches `user`, `process`'s own last field,
        // directly.
        pane.move_to_key("user");
        let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, 9));
        assert!(text.len() <= 9, "{text:?}");
        assert!(text.iter().any(|line| line.contains("above")), "{text:?}");
        assert!(
            text.iter().any(|line| line.contains("user")),
            "process's last field is visible: {text:?}"
        );
        assert!(!text.iter().any(|line| line.contains("below")), "{text:?}");
    }

    #[test]
    fn the_env_rows_draw_on_the_process_tab_and_on_no_other() {
        let mut pane = web_pane();
        for digit in 1..=9 {
            pane.set_group(digit);
            let text = text_of(&pane_lines(&pane, fixtures::plain(), 160, 0)).join("\n");
            for needle in ["DB_HOST", "LOG_LEVEL", "+ add a key"] {
                assert_eq!(
                    text.contains(needle),
                    digit == 1,
                    "tab {digit}, {needle}:\n{text}"
                );
            }
        }
    }

    /// Guards against the class of bug where chrome eats the budget and
    /// the selected row is never drawn, while every static frame still
    /// looks right. Six is `view::MIN_HEIGHT`; three lines of body under
    /// the title is less than a group's first row costs, so those steps
    /// go through `cursor_only`.
    #[test]
    fn the_cursor_survives_every_step_of_a_walk_down_and_back_up() {
        for height in [6u16, 7, 8, 10, 14, 20, 45] {
            let mut app = fixtures::app_in_sheep_pane();
            let total = app.config_pane().unwrap().rows().len();
            for step in 0..=total {
                let text = screen_at(&mut app, height);
                assert_eq!(marked(&text), 1, "{height} rows, {step} down:\n{text}");
                app.update(Msg::Key(KeyPress::SelectDown));
            }
            for step in 0..=total {
                let text = screen_at(&mut app, height);
                assert_eq!(marked(&text), 1, "{height} rows, {step} up:\n{text}");
                app.update(Msg::Key(KeyPress::SelectUp));
            }
        }
    }

    /// A roomy terminal (`view::ROOMY_HEIGHT` and up) spends a blank row under
    /// the title. `body_rows` has to know about that row, or the `Rect` it
    /// hands the pane reaches one row past the status bar and the last row the
    /// pane draws gets overwritten rather than shown.
    #[test]
    fn the_cursor_survives_a_jump_to_the_last_field_at_a_roomy_height() {
        // 30 is `view::ROOMY_HEIGHT`, private to that module.
        for height in [24u16, 29, 30, 31, 45] {
            let mut app = fixtures::app_in_sheep_pane();
            app.update(Msg::Key(KeyPress::SelectLast));
            let text = screen_at(&mut app, height);
            assert_eq!(marked(&text), 1, "{height} rows:\n{text}");
        }
    }

    /// The marker that says rows were cut would itself become the row
    /// that gets cut.
    ///
    /// Both widths, because they take different code: 120 has a panel and
    /// never reaches the blurb loop's arithmetic, and 89 is one column under
    /// `panel_width`'s floor so the blurb draws.
    #[test]
    fn the_body_never_outgrows_the_height_it_was_given() {
        let mut pane = web_pane();
        for width in [120u16, 89] {
            for height in 1..=60u16 {
                pane.set_rows(usize::from(height.saturating_sub(1)));
                for cursor in [0usize, 7, 20, 38] {
                    pane.move_to_first();
                    pane.move_by(isize::try_from(cursor).unwrap());
                    let text = text_of(&pane_lines(&pane, fixtures::plain(), width, height));
                    assert!(
                        text.len() <= usize::from(height),
                        "width {width}, height {height}, cursor {cursor}: {text:?}"
                    );
                }
            }
        }
    }

    /// `push_wrapped_blurb` breaks on a budget of `<= 1` rather than `== 0`,
    /// so a long wrapped help must not spend the last line the cursor's own
    /// row needs. The height sweep above passes with the floor at either
    /// value, because losing the field row only makes the output shorter.
    ///
    /// So this asserts the pair: wherever the blurb reached the screen, the
    /// cursor's own row did too.
    #[test]
    fn the_blurb_never_spends_the_row_the_cursor_needs() {
        for (which, mut pane, key) in [
            ("grouped", web_pane(), "autorestart"),
            ("ungrouped", bark_pane(), "history_bytes"),
        ] {
            pane.move_to_key(key);
            let anchor = blurb_anchor(&pane);
            let mut checked = 0;
            for height in 1..=20u16 {
                let rows = text_of(&pane_lines(&pane, fixtures::plain(), 89, height));
                if !rows.iter().any(|row| row.contains(&anchor)) {
                    continue;
                }
                checked += 1;
                // Excludes the blurb row itself: a help string that ever
                // came to mention its own field's name would let a cut
                // cursor row hide behind the blurb row satisfying `key` by
                // coincidence.
                assert!(
                    rows.iter()
                        .any(|row| row.contains(key) && !row.contains(&anchor)),
                    "{which} at height {height}: the blurb drew and the cursor's row did not: {rows:?}"
                );
            }
            assert!(
                checked > 0,
                "{which}: the blurb never drew, so nothing was checked"
            );
        }
    }

    /// Nothing is armed and nothing is in flight, so the slot under the
    /// title carries no question. A filed edit shows in its own row's
    /// value cell, which is where the operator is already looking.
    #[test]
    fn a_filed_edit_draws_no_question_under_the_title() {
        let mut pane = web_pane();
        pane.move_to_key("autorestart");
        pane.cycle();
        let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, 0));
        assert!(
            !text.iter().any(|line| line.contains("enter confirms")),
            "{text:?}"
        );
        assert!(
            !text.iter().any(|line| line.contains("set autorestart")),
            "{text:?}"
        );
    }

    /// At a width with no explanation panel, the field under the cursor still
    /// has its help text on screen, with no key pressed.
    ///
    /// 89 columns is the widest terminal `panel_width` refuses. `contains`
    /// cannot see indentation drift, so this compares against the header
    /// row's own margin instead of a literal.
    #[test]
    fn the_blurb_shares_the_panes_own_indent() {
        let pane = web_pane();
        let lines = pane_lines(&pane, fixtures::plain(), 89, 40);
        let rows = text_of(&lines);
        let indent = |row: &str| row.len() - row.trim_start().len();
        let header = rows
            .iter()
            .find(|row| row.contains("FIELD") && row.contains("VALUE"))
            .expect("no column header");
        let anchor = blurb_anchor(&pane);
        let blurb = rows
            .iter()
            .find(|row| row.contains(&anchor))
            .expect("no blurb row");
        assert_eq!(
            indent(blurb),
            indent(header),
            "blurb {:?} against header {:?}",
            blurb.get(..12),
            header.get(..12)
        );
    }

    #[test]
    fn the_blurb_draws_at_a_width_with_no_panel() {
        let pane = web_pane();
        assert!(panel_width(89).is_none(), "89 must have no panel");
        let lines = pane_lines(&pane, fixtures::plain(), 89, 40);
        let anchor = blurb_anchor(&pane);
        let rows = text_of(&lines);
        assert!(
            rows.iter().any(|row| row.contains(&anchor)),
            "no blurb at 89 columns: {rows:?}"
        );
    }

    /// And it describes the row the cursor is on, not the first field.
    #[test]
    fn the_blurb_follows_the_cursor_with_no_panel() {
        let mut pane = web_pane();
        let first = blurb_anchor(&pane);
        pane.move_by(1);
        let second = blurb_anchor(&pane);
        // On the anchors, not the help strings: two fields can have different
        // help and share a longest word, and then the absence assertion below
        // cannot fail. Substring, not just inequality: "memory" !=
        // "max_memory" passes `assert_ne!` while one row holds the other.
        assert!(
            !first.contains(&second) && !second.contains(&first),
            "the fixture needs two fields whose longest help words are not substrings of each other: {first:?} / {second:?}"
        );
        let lines = pane_lines(&pane, fixtures::plain(), 89, 40);
        let rows = text_of(&lines);
        // The specific blurb row, not the whole screen: `first` scanned
        // against every row would false-fail on a coincidental substring
        // in an unrelated one, a field name or a value cell.
        let blurb_row = rows
            .iter()
            .find(|row| row.contains(&second))
            .unwrap_or_else(|| panic!("the cursor moved and the blurb did not: {rows:?}"));
        assert!(
            !blurb_row.contains(&first),
            "the previous field's blurb is still on screen: {rows:?}"
        );
    }

    /// The blurb rows under the title are counted against the same budget
    /// every other line in the pane is, at every width and height the pane
    /// claims to draw at.
    #[test]
    fn help_text_still_respects_the_width_and_height_budgets() {
        let mut pane = web_pane();
        pane.move_to_key("max_memory");
        for width in MIN_TERM_WIDTH..=200 {
            for line in text_of(&pane_lines(&pane, fixtures::plain(), width, 0)) {
                assert!(
                    visible_width(&line) <= usize::from(width),
                    "width {width}: {line:?}"
                );
            }
        }
        for height in 1..=30u16 {
            let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, height));
            assert!(
                text.len() <= usize::from(height),
                "height {height}: {text:?}"
            );
        }
    }

    /// The only place on screen that says which field the buffer belongs
    /// to.
    #[test]
    fn an_open_editor_draws_its_buffer_in_the_fields_own_row() {
        let mut pane = web_pane();
        pane.move_to_key("cwd");
        pane.begin_typing();
        for typed in "/srv".chars() {
            pane.type_char(typed);
        }
        let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, 0));
        let row = text
            .iter()
            .find(|line| line.contains(" cwd"))
            .expect("cwd is drawn at 120 columns");
        assert!(row.contains("/srv\u{258f}"), "{row:?}");
        assert!(
            !text.iter().any(|line| line.contains("set cwd")),
            "an editor is not a confirm: {text:?}"
        );
    }

    // --- the responsive ladder: what each width drops ---

    #[test]
    fn a_short_body_sheds_the_legend_before_the_tab_row() {
        let app = fixtures::app_in_sheep_pane();
        let rows = fixtures::render_all(&config_pane_lines_for_tests(&app, 160, 6));
        assert!(
            rows.contains("next / prev group"),
            "the tab row must survive"
        );
        assert!(!rows.contains("changed by you"), "the legend must go first");
    }
}