repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
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
//! The header's own five items and the width-degradation rule that picks a prefix of them:
//! [actions.md](../../../../docs/spec/actions.md#the-run-on-screen)'s ladder, measured with
//! no warning outstanding. Priority, highest to lowest: the entity count, run progress, the
//! Filter's match count, the worktrees note, then timing. Items are separated by ` · ` and
//! degrade under [`degrade::budget`], the same mechanism [`crate::footer`] uses, per
//! [0026](../../../../docs/adr/0026-the-status-row-is-one-list-not-a-stack-of-surfaces.md)'s
//! citation of the footer's own mechanics rather than a second one.
//!
//! What this owns stops at the priority ladder over these five items, following
//! [actions.md](../../../../docs/spec/actions.md#the-run-on-screen)'s own boundary: the
//! active Set name ahead of them, a live Notice or an outstanding warning sharing the same
//! row, and the reserved warning indicator, are the status row's composition
//! ([layout-and-provenance.md](../../../../docs/spec/layout-and-provenance.md#the-status-row),
//! [0026](../../../../docs/adr/0026-the-status-row-is-one-list-not-a-stack-of-surfaces.md)),
//! owned by [`crate::status_row`] instead, which is why [`trailing_items`] rather than
//! [`render`] is this module's real production export: `status_row` splices its own rank-1
//! item (the active Set's name and the entity count) ahead of the four items below it rather
//! than taking this module's own entity-count-only rank 1. [`render`] itself stays
//! `#[allow(dead_code)]`, kept for this module's own tests against
//! [actions.md](../../../../docs/spec/actions.md#the-run-on-screen)'s published ladder: `App`
//! still has no in-flight Action progress counter or elapsed timer, so `run_progress` and
//! `elapsed` are always `None` in production for now, the same "absent costs nothing" rule
//! this ladder already encodes. `filter_match_count` and `worktrees_note` are live
//! (`crate::app::App::status_row_content`).

use std::time::Duration;

use crate::degrade::{self, Priority};
use crate::elapsed::format_elapsed;

/// Why Worktree rows are off when [`HeaderContent::worktrees_note`] is `Some`: config.toml's
/// own `show_worktrees` ([config.md](../../../../docs/spec/config.md)'s "the stake on
/// `show_worktrees`"), or `t`'s own toggle overriding it, whether it fired this session or a
/// prior one this scope's `state.toml` remembered
/// ([keybindings.md](../../../../docs/spec/keybindings.md)'s "The worktrees toggle").
/// [`trailing_items`] picks its wording from this so a toggled-off scope never reads as if
/// config.toml said so.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum WorktreesHiddenBy {
    Preference,
    Toggle,
}

/// One value for each of the header's six items, already computed by whatever owns that
/// piece of state. `None` means the item has nothing to report this frame: no run in flight
/// (`run_progress`, `elapsed`), no Filter committed (`filter_match_count`), Worktree rows
/// already shown (`worktrees_note`), or no row hidden for being ignored (`ignored_note`).
/// `entity_count` alone is never absent.
pub(crate) struct HeaderContent {
    pub(crate) entity_count: usize,
    pub(crate) run_progress: Option<(usize, usize)>,
    pub(crate) filter_match_count: Option<usize>,
    pub(crate) worktrees_note: Option<(usize, WorktreesHiddenBy)>,
    /// How many rows the ignored toggle is currently hiding, absent when it is hiding none.
    /// Unlike `worktrees_note` this carries no reason: only the toggle can hide these, so
    /// there is no second cause to tell it apart from.
    pub(crate) ignored_note: Option<usize>,
    pub(crate) elapsed: Option<Duration>,
}

const SEPARATOR: &str = " · ";
const ELLIPSIS: &str = " ...";

/// The five items ranked below rank 1 (run progress, the Filter's match count, the
/// worktrees note, the ignored note, then timing), present only where `content` carries a
/// value:
/// [`degrade::budget`] drops from the low-priority end first, so an absent item costs the
/// ladder nothing rather than leaving a hole in the middle of it. `pub(crate)` so
/// [`crate::status_row`] can splice its own rank-1 item ahead of these instead of
/// [`items`]'s own entity-count-only one.
pub(crate) fn trailing_items(content: &HeaderContent) -> Vec<degrade::Item<String>> {
    let mut items = Vec::new();
    if let Some((done, total)) = content.run_progress {
        items.push(degrade::Item {
            content: format!("run {done}/{total}"),
            priority: Priority::Drop(4),
        });
    }
    if let Some(count) = content.filter_match_count {
        items.push(degrade::Item {
            content: format!("filter: {count} matches"),
            priority: Priority::Drop(3),
        });
    }
    if let Some((count, reason)) = content.worktrees_note {
        let reason = match reason {
            WorktreesHiddenBy::Preference => "preference off",
            WorktreesHiddenBy::Toggle => "toggled off",
        };
        items.push(degrade::Item {
            content: format!("worktrees: {count} ({reason})"),
            priority: Priority::Drop(2),
        });
    }
    if let Some(count) = content.ignored_note {
        // Rank 2 is the worktrees note's, shared deliberately: [`degrade::budget`] drops a
        // shared rank as one group, and the two answer the same question
        // ([keybindings.md](../../../../docs/spec/keybindings.md#the-ignored-toggle)).
        items.push(degrade::Item {
            content: format!("ignored: {count} (i shows)"),
            priority: Priority::Drop(2),
        });
    }
    if let Some(elapsed) = content.elapsed {
        items.push(degrade::Item {
            content: format_elapsed(elapsed),
            priority: Priority::Drop(1),
        });
    }
    debug_assert!(
        items.iter().all(|item| item.content.is_ascii()),
        "a header item must be ASCII, or the char-count width in degrade::budget is wrong"
    );
    items
}

/// `content`'s six items in priority order, highest first: [`render`]'s own entity-count
/// rank 1 followed by [`trailing_items`].
fn items(content: &HeaderContent) -> Vec<degrade::Item<String>> {
    let mut items = vec![degrade::Item {
        content: format!("{} entities", content.entity_count),
        priority: Priority::Pinned,
    }];
    items.extend(trailing_items(content));
    items
}

/// The header's text at `width` display columns, ASCII throughout apart from the ` · `
/// separator's own middle dot, which [0020](../../../../docs/adr/0020-the-ascii-glyph-set-is-vetted-over-the-row-interior.md)
/// measures at one column regardless of glyph set.
#[allow(dead_code)] // kept for this module's own tests; [`trailing_items`] is the real production export
pub(crate) fn render(content: &HeaderContent, width: u16) -> String {
    let items = items(content);
    degrade::budget(&items, width as usize, SEPARATOR, ELLIPSIS).render(SEPARATOR, ELLIPSIS)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// [actions.md](../../../../docs/spec/actions.md#the-run-on-screen)'s own figures,
    /// matching the documented ladder's widest rung, which that measurement predates the
    /// ignored note by and so leaves absent.
    fn sample_content() -> HeaderContent {
        HeaderContent {
            entity_count: 242,
            run_progress: Some((7, 12)),
            filter_match_count: Some(12),
            worktrees_note: Some((161, WorktreesHiddenBy::Preference)),
            ignored_note: None,
            elapsed: Some(Duration::from_millis(12000)),
        }
    }

    // --- criterion: every item is width-checked including the first ---

    #[test]
    fn header_width_checks_the_first_item_not_only_later_ones() {
        // "403 entities" alone is 12 columns. At width 5, even the entity count, the header's
        // one pinned item, cannot fit; an implementation that exempted the first surviving
        // item from the width check would still emit it, 7 columns over budget.
        let content = HeaderContent {
            entity_count: 403,
            run_progress: None,
            filter_match_count: None,
            worktrees_note: None,
            ignored_note: None,
            elapsed: None,
        };
        let rendered = render(&content, 5);
        assert!(
            rendered.chars().count() <= 5,
            "must never overrun the given width, got {rendered:?}"
        );
        assert_eq!(rendered, "");
    }

    // --- criterion: the render is never wider than the given budget, at every width ---

    #[test]
    fn header_never_overruns_its_budget_at_any_width_from_zero_to_full() {
        let content = sample_content();
        let full_width = items(&content)
            .iter()
            .map(|item| item.content.clone())
            .collect::<Vec<_>>()
            .join(SEPARATOR)
            .chars()
            .count();
        for width in 0..=full_width {
            let rendered = render(&content, width as u16);
            assert!(
                rendered.chars().count() <= width,
                "width {width}: rendered {rendered:?} is {} columns",
                rendered.chars().count()
            );
        }
    }

    // --- criterion: the worktrees note's wording names which of the two actually hid them ---

    #[test]
    fn the_worktrees_note_reads_toggled_off_rather_than_preference_off_when_the_toggle_is_why() {
        let content = HeaderContent {
            entity_count: 403,
            run_progress: None,
            filter_match_count: None,
            worktrees_note: Some((161, WorktreesHiddenBy::Toggle)),
            ignored_note: None,
            elapsed: None,
        };
        let rendered = render(&content, 200);
        assert!(
            rendered.contains("worktrees: 161 (toggled off)"),
            "the toggle, not config.toml, hid these rows: {rendered:?}"
        );
        assert!(
            !rendered.contains("preference off"),
            "must never claim config.toml said so when the toggle is why: {rendered:?}"
        );
    }

    // --- criterion: rows hidden because they are ignored are counted, never silent ---

    #[test]
    fn the_ignored_note_names_how_many_rows_are_hidden_and_the_key_that_shows_them() {
        let content = HeaderContent {
            entity_count: 12,
            run_progress: None,
            filter_match_count: None,
            worktrees_note: None,
            ignored_note: Some(3),
            elapsed: None,
        };
        let rendered = render(&content, 200);
        assert!(
            rendered.contains("ignored: 3 (i shows)"),
            "a row that vanished on an ignore must be accounted for: {rendered:?}"
        );
    }

    // --- criterion: the ascii ellipsis is reserved inside the budget, not appended after ---

    #[test]
    fn header_reserves_the_ellipsis_inside_the_budget_rather_than_appending_it_after_a_fit_check() {
        // "run 7/12" alone is 8 columns; "run 7/12 ..." is 12. A budget that fit "run 7/12"
        // first and appended the ellipsis after would overrun a width of 8 through 11.
        let content = HeaderContent {
            entity_count: 403,
            run_progress: Some((7, 12)),
            filter_match_count: None,
            worktrees_note: None,
            ignored_note: None,
            elapsed: None,
        };
        for width in 8u16..12 {
            let rendered = render(&content, width);
            assert!(
                rendered.chars().count() <= width as usize,
                "width {width}: rendered {rendered:?} overruns"
            );
            assert!(
                !rendered.contains("run 7/12"),
                "width {width}: run progress should have been dropped to make room for its \
                 own ellipsis, got {rendered:?}"
            );
        }
    }

    // --- criterion: the run timer moves up a unit as it crosses one, rather than counting
    // milliseconds forever ---

    /// Isolates the timing item by dropping every other item, so a low width still keeps it.
    fn elapsed_only(elapsed: Duration) -> HeaderContent {
        HeaderContent {
            entity_count: 403,
            run_progress: None,
            filter_match_count: None,
            worktrees_note: None,
            ignored_note: None,
            elapsed: Some(elapsed),
        }
    }

    #[test]
    fn the_run_timer_moves_up_a_unit_as_it_crosses_one() {
        let cases = [
            (Duration::from_millis(0), "0ms"),
            (Duration::from_millis(168), "168ms"),
            (Duration::from_millis(999), "999ms"),
            (Duration::from_millis(1000), "1.0s"),
            (Duration::from_millis(12000), "12.0s"),
            (Duration::from_secs(59), "59.0s"),
            (Duration::from_secs(60), "1m00s"),
            (Duration::from_secs(168), "2m48s"),
        ];
        for (elapsed, expected) in cases {
            let content = elapsed_only(elapsed);
            let rendered = render(&content, 999);
            assert!(
                rendered.ends_with(expected),
                "elapsed {elapsed:?}: expected the timer to end with {expected:?}, got {rendered:?}"
            );
        }
    }

    // --- criterion: priority while a run is in flight, one discriminating width per pair ---

    /// One `width  expected text` row of the documented ladder, the active Set name's own
    /// `work ` prefix already stripped: [actions.md](../../../../docs/spec/actions.md#the-run-on-screen)
    /// names that column layout-and-provenance.md's to own, not this module's.
    struct Row {
        width: u16,
        expected: String,
    }

    const SET_NAME_PREFIX: &str = "work ";

    /// Finds the fenced code block that follows `after` in `spec`, and parses each
    /// `<width>  <text>` line, stripping [`SET_NAME_PREFIX`] and its own columns from both
    /// the width and the text. Panics naming the offending line on anything else, including a
    /// row that does not start with the prefix, rather than skipping it: a row this cannot
    /// read is a width case this test could never have caught wrong.
    fn parse_header_ladder(spec: &str, after: &str) -> Vec<Row> {
        let start = spec
            .find(after)
            .unwrap_or_else(|| panic!("actions.md no longer contains {after:?}"));
        let rest = &spec[start..];
        let fence_start = rest
            .find("```\n")
            .expect("a fenced code block must follow the marker");
        let after_fence = &rest[fence_start + 4..];
        let fence_end = after_fence
            .find("```")
            .expect("the fenced code block must close");
        let block = &after_fence[..fence_end];

        block
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| {
                let trimmed = line.trim_start();
                let (width_text, rendered) = trimmed
                    .split_once("  ")
                    .unwrap_or_else(|| panic!("ladder row is not `<width>  <text>`: {line:?}"));
                let width: u16 = width_text
                    .trim()
                    .parse()
                    .unwrap_or_else(|_| panic!("ladder row has no numeric width: {line:?}"));
                let rendered = rendered.trim_end();
                let header_text = rendered.strip_prefix(SET_NAME_PREFIX).unwrap_or_else(|| {
                    panic!(
                        "ladder row does not start with {SET_NAME_PREFIX:?}: {line:?}; this \
                         module owns only what follows the active Set name"
                    )
                });
                Row {
                    width: width - SET_NAME_PREFIX.chars().count() as u16,
                    expected: header_text.to_string(),
                }
            })
            .collect()
    }

    fn read_spec() -> String {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        std::fs::read_to_string(manifest_dir.join("../../docs/spec/actions.md"))
            .expect("read the actions spec")
    }

    #[test]
    fn header_matches_the_documented_ladder_at_every_named_width() {
        let spec = read_spec();
        let rows = parse_header_ladder(
            &spec,
            "The ladder for the header's own five items, with no warning outstanding.",
        );
        assert!(!rows.is_empty(), "expected at least one documented width");
        for row in &rows {
            assert_eq!(
                render(&sample_content(), row.width),
                row.expected,
                "header mismatch at width {}",
                row.width
            );
        }
    }

    #[test]
    fn each_adjacent_priority_pair_has_a_documented_width_that_discriminates_them() {
        let spec = read_spec();
        let rows = parse_header_ladder(
            &spec,
            "The ladder for the header's own five items, with no warning outstanding.",
        );
        // (higher-priority marker, lower-priority marker): a row carrying the first without
        // the second is the width at which the pair is told apart, read off the same parsed
        // ladder the conformance test above pins against the spec, never a hand-typed width.
        let pairs = [
            ("worktrees: 161 (preference off)", "12.0s"),
            ("filter: 12 matches", "worktrees: 161 (preference off)"),
            ("run 7/12", "filter: 12 matches"),
            ("242 entities", "run 7/12"),
        ];
        for (present, absent) in pairs {
            let row = rows
                .iter()
                .find(|row| row.expected.contains(present) && !row.expected.contains(absent))
                .unwrap_or_else(|| {
                    panic!("no documented row shows {present:?} without {absent:?}")
                });
            assert_eq!(render(&sample_content(), row.width), row.expected);
        }
    }

    // --- absences the spec names by name ---

    /// [0016](../../../../docs/adr/0016-one-binding-table-feeds-every-surface.md) names
    /// lazygit's `i > 0` guard that exempts the first item from the width check.
    /// [`degrade::tests::degrade_never_reintroduces_the_first_item_exemption_guard`] scans
    /// the shared algorithm; this scans `header.rs` itself in case a future edit grows a
    /// second, local shortcut around it.
    #[test]
    fn header_never_reintroduces_the_first_item_exemption_guard() {
        let banned = [
            format!("{} {} 0", "i", ">"),
            format!("{} {} 0", "index", ">"),
            format!("{}(1)", ".skip"),
        ];
        let source = crate::test_support::production_source(include_str!("header.rs"));
        let offending: Vec<&str> = source
            .lines()
            .filter(|line| !line.trim_start().starts_with("//"))
            .filter(|line| banned.iter().any(|needle| line.contains(needle.as_str())))
            .collect();
        assert!(
            offending.is_empty(),
            "found a first-item exemption guard: {offending:?}"
        );
    }
}