carte 0.5.0

Runs your apps' processes on demand behind *.localhost hostnames, one stack per git worktree
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
//! The log pane's buffer: the lines followed for the selected node, the search and
//! the scroll position.

use std::collections::VecDeque;

use carte_api::LogLine;
use unicode_width::UnicodeWidthStr;

/// What a line is prefixed with, which depends on how wide the merged view is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Prefix {
    None,
    Process,
    AppProcess,
    Full,
}

impl Prefix {
    pub fn label(self, line: &LogLine) -> Option<String> {
        if line.marker {
            return None;
        }
        match self {
            Prefix::None => None,
            Prefix::Process => Some(line.process.clone()),
            Prefix::AppProcess => Some(format!("{}/{}", line.app, line.process)),
            Prefix::Full => Some(format!("{}@{}/{}", line.app, line.stack, line.process)),
        }
    }
}

/// The lines a pane of some height shows.
#[derive(Debug)]
pub struct Window<'a> {
    pub lines: Vec<(u64, &'a LogLine)>,
    /// Rows of the oldest line that don't fit above the pane.
    pub skip: usize,
    /// Columns before each line's text, which its wrapped rows start at too.
    pub indent: usize,
}

#[derive(Debug)]
pub struct Logs {
    pub generation: u64,
    /// The address the stream follows; a new one means a new stream.
    pub key: Option<String>,
    pub prefix: Prefix,
    lines: VecDeque<LogLine>,
    /// Lines dropped from the front so far; a line's sequence number is this plus its
    /// index, which stays put while lines come and go.
    dropped: u64,
    /// Prefix labels in order of appearance, which picks their colours.
    labels: Vec<String>,
    /// Text to highlight; every line stays visible.
    pub search: String,
    /// The match `n` and `N` last moved to, by sequence number.
    pub current: Option<u64>,
    /// Lines above the bottom; 0 follows new lines.
    pub scroll: usize,
    pub ended: Option<String>,
    /// Rows the pane showed last time it was drawn.
    pub height: usize,
    /// Columns the pane showed last time it was drawn, which long lines wrap at; 0
    /// before the first draw.
    pub width: usize,
    /// Keep the view still while lines arrive, even when following.
    pub hold: bool,
}

const CAPACITY: usize = 5000;

impl Default for Logs {
    fn default() -> Self {
        Logs {
            generation: 0,
            key: None,
            prefix: Prefix::None,
            lines: VecDeque::new(),
            dropped: 0,
            labels: Vec::new(),
            search: String::new(),
            current: None,
            scroll: 0,
            ended: None,
            height: 0,
            width: 0,
            hold: false,
        }
    }
}

impl Logs {
    /// Starts over for a new stream and returns its generation.
    pub fn restart(&mut self, key: Option<String>, prefix: Prefix) -> u64 {
        self.generation += 1;
        self.key = key;
        self.prefix = prefix;
        self.dropped += self.lines.len() as u64;
        self.lines.clear();
        self.hold = false;
        self.labels.clear();
        self.current = None;
        self.scroll = 0;
        self.ended = None;
        self.generation
    }

    pub fn push(&mut self, generation: u64, line: LogLine) {
        if generation != self.generation {
            return;
        }
        if let Some(label) = self.prefix.label(&line)
            && !self.labels.contains(&label)
        {
            self.labels.push(label);
        }
        if self.scroll > 0 || self.hold {
            self.scroll += 1;
        }
        self.lines.push_back(line);
        if self.lines.len() > CAPACITY {
            self.lines.pop_front();
            self.dropped += 1;
        }
    }

    pub fn end(&mut self, generation: u64, error: Option<String>) {
        if generation == self.generation {
            self.ended = Some(error.unwrap_or_else(|| "the stream ended".into()));
        }
    }

    pub fn color_index(&self, label: &str) -> usize {
        self.labels.iter().position(|l| l == label).unwrap_or(0)
    }

    fn matches(&self, line: &LogLine) -> bool {
        !line.marker
            && !self.search.is_empty()
            && line
                .text
                .to_lowercase()
                .contains(&self.search.to_lowercase())
    }

    #[cfg(test)]
    pub fn visible(&self) -> Vec<&LogLine> {
        self.lines.iter().collect()
    }

    /// The lines with their sequence numbers.
    fn numbered(&self) -> Vec<(u64, &LogLine)> {
        self.lines
            .iter()
            .enumerate()
            .map(|(i, l)| (self.dropped + i as u64, l))
            .collect()
    }

    /// The sequence numbers of the lines that match the search, oldest first.
    pub fn match_seqs(&self) -> Vec<u64> {
        self.numbered()
            .into_iter()
            .filter(|(_, l)| self.matches(l))
            .map(|(seq, _)| seq)
            .collect()
    }

    /// Moves to the next older match (`older`) or the next newer one, starting from
    /// the newest, and scrolls it into the middle of the pane. False when nothing matches.
    pub fn find(&mut self, older: bool) -> bool {
        let seqs = self.match_seqs();
        let next = match (self.current, older) {
            (None, _) => seqs.last(),
            (Some(at), true) => seqs.iter().rev().find(|&&s| s < at).or(seqs.last()),
            (Some(at), false) => seqs.iter().find(|&&s| s > at).or(seqs.first()),
        };
        let Some(&seq) = next else {
            self.current = None;
            return false;
        };
        self.current = Some(seq);
        let index = (seq - self.dropped) as usize;
        let below = self.lines.len() - 1 - index;
        self.scroll = below.saturating_sub(self.height / 2);
        self.scroll_by(0);
        true
    }

    /// The lines that fill `height` rows at the current scroll position, long lines
    /// wrapped at the pane's width, ending with the newest one shown.
    pub fn window_rows(&self, height: usize) -> Window<'_> {
        let visible = self.numbered();
        let scroll = self.scroll.min(visible.len().saturating_sub(height));
        let end = visible.len() - scroll;
        let candidates = &visible[end.saturating_sub(height)..end];
        let indent = self.indent(candidates);
        let mut rows = 0;
        let mut start = end;
        while start > end.saturating_sub(height) && rows < height {
            start -= 1;
            rows += self.rows(visible[start].1, indent);
        }
        Window {
            lines: visible[start..end].to_vec(),
            skip: rows.saturating_sub(height),
            indent,
        }
    }

    /// The columns before a line's text: its prefix label, padded to the widest in
    /// the window, and a space.
    fn indent(&self, lines: &[(u64, &LogLine)]) -> usize {
        lines
            .iter()
            .filter_map(|(_, line)| self.prefix.label(line))
            .map(|label| label.width() + 1)
            .max()
            .unwrap_or(0)
    }

    /// How many rows a line takes in the pane, wrapped after `indent` columns.
    pub fn rows(&self, line: &LogLine, indent: usize) -> usize {
        if line.marker || self.width == 0 {
            return 1;
        }
        let room = self.width.saturating_sub(indent).max(1);
        line.text.width().div_ceil(room).max(1)
    }

    #[cfg(test)]
    pub fn window(&self, height: usize) -> Vec<&LogLine> {
        self.window_rows(height)
            .lines
            .into_iter()
            .map(|(_, line)| line)
            .collect()
    }

    /// The sequence number of the line on a row of the pane, or of the last line when
    /// the row is below it.
    pub fn seq_at(&self, row: usize) -> Option<u64> {
        let window = self.window_rows(self.height);
        let mut row = row + window.skip;
        for (seq, line) in &window.lines {
            let rows = self.rows(line, window.indent);
            if row < rows {
                return Some(*seq);
            }
            row -= rows;
        }
        window.lines.last().map(|(seq, _)| *seq)
    }

    /// The visible lines between two sequence numbers, inclusive, as plain text with
    /// their prefixes.
    pub fn text_between(&self, a: u64, b: u64) -> (String, usize) {
        let range = a.min(b)..=a.max(b);
        let lines: Vec<String> = self
            .numbered()
            .into_iter()
            .filter(|(seq, _)| range.contains(seq))
            .map(|(_, line)| match self.prefix.label(line) {
                _ if line.marker => crate::logs::marker_rule(line.at_ms, 40),
                Some(label) => format!("{label} {}", line.text),
                None => line.text.clone(),
            })
            .collect();
        (lines.join("\n"), lines.len())
    }

    pub fn scroll_by(&mut self, delta: isize) {
        let max = self.lines.len().saturating_sub(self.height.max(1));
        self.scroll = self.scroll.min(max).saturating_add_signed(delta).min(max);
    }

    pub fn scroll_to_top(&mut self) {
        self.scroll = self.lines.len().saturating_sub(self.height.max(1));
    }

    pub fn follow(&mut self) {
        self.scroll = 0;
    }

    /// Searches for `search` from the newest line.
    pub fn set_search(&mut self, search: String) {
        self.search = search;
        self.current = None;
        if !self.find(true) {
            self.scroll = 0;
        }
    }

    pub fn is_empty(&self) -> bool {
        self.lines.is_empty()
    }
}

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

    fn line(text: &str) -> LogLine {
        LogLine {
            project: "nova".into(),
            app: "nova-billing".into(),
            stack: "main".into(),
            process: "web".into(),
            at_ms: 0,
            text: text.into(),
            marker: false,
        }
    }

    fn texts(lines: Vec<&LogLine>) -> Vec<&str> {
        lines.iter().map(|l| l.text.as_str()).collect()
    }

    #[test]
    fn long_lines_wrap_and_fill_the_window_from_the_bottom() {
        let mut logs = Logs::default();
        let generation = logs.restart(None, Prefix::Process);
        logs.width = 14;
        for text in ["one", "a line of twenty-one!", "two", "three"] {
            logs.push(generation, line(text));
        }
        // "web " takes 4 columns, leaving 10 per row: the long line takes 3 rows.
        let window = logs.window_rows(5);
        assert_eq!(window.indent, 4);
        assert_eq!(
            texts(window.lines.iter().map(|(_, l)| *l).collect()),
            ["a line of twenty-one!", "two", "three"]
        );
        assert_eq!(window.skip, 0);
        let window = logs.window_rows(4);
        assert_eq!(
            window.skip, 1,
            "the long line's first row is above the pane"
        );
        assert_eq!(logs.rows(&line("a line of twenty-one!"), 4), 3);
        assert_eq!(logs.rows(&line(""), 4), 1);

        logs.height = 4;
        let seq = |text: &str| {
            logs.numbered()
                .into_iter()
                .find(|(_, l)| l.text == text)
                .map(|(seq, _)| seq)
        };
        assert_eq!(logs.seq_at(0), seq("a line of twenty-one!"));
        assert_eq!(logs.seq_at(1), seq("a line of twenty-one!"));
        assert_eq!(logs.seq_at(2), seq("two"));
        assert_eq!(logs.seq_at(3), seq("three"));
        assert_eq!(logs.seq_at(9), seq("three"));
    }

    #[test]
    fn markers_never_match_a_search_and_have_no_label() {
        let mut logs = Logs::default();
        let generation = logs.restart(None, Prefix::Process);
        logs.push(generation, line("GET /up"));
        logs.push(
            generation,
            LogLine {
                process: String::new(),
                marker: true,
                ..line("")
            },
        );
        logs.search = "e".into();
        assert_eq!(logs.match_seqs().len(), 1);
        let visible = logs.visible();
        assert_eq!(visible.len(), 2);
        assert!(visible[1].marker);
        assert_eq!(Prefix::Process.label(visible[1]), None);
    }

    #[test]
    fn drops_lines_from_old_streams() {
        let mut logs = Logs::default();
        let old = logs.restart(None, Prefix::None);
        let new = logs.restart(None, Prefix::None);
        logs.push(old, line("stale"));
        logs.push(new, line("fresh"));
        assert_eq!(texts(logs.visible()), ["fresh"]);
    }

    #[test]
    fn scrolling_up_holds_the_view_while_lines_arrive() {
        let mut logs = Logs::default();
        let generation = logs.restart(None, Prefix::None);
        for i in 0..10 {
            logs.push(generation, line(&format!("{i}")));
        }
        logs.height = 3;
        assert_eq!(texts(logs.window(3)), ["7", "8", "9"]);
        logs.scroll_by(2);
        assert_eq!(texts(logs.window(3)), ["5", "6", "7"]);
        logs.push(generation, line("10"));
        assert_eq!(texts(logs.window(3)), ["5", "6", "7"]);
        logs.follow();
        assert_eq!(texts(logs.window(3)), ["8", "9", "10"]);
        logs.scroll_to_top();
        assert_eq!(texts(logs.window(3)), ["0", "1", "2"]);
    }

    #[test]
    fn selections_keep_their_lines_while_lines_come_and_go() {
        let mut logs = Logs::default();
        let generation = logs.restart(None, Prefix::Process);
        for i in 0..CAPACITY {
            logs.push(generation, line(&format!("{i}")));
        }
        logs.height = 3;
        logs.hold = true;
        let (first, last) = (logs.seq_at(0).unwrap(), logs.seq_at(1).unwrap());
        logs.push(generation, line("new"));
        assert_eq!(
            texts(logs.window(3)),
            ["4997", "4998", "4999"],
            "a hold keeps the view still"
        );
        assert_eq!(
            logs.text_between(last, first),
            ("web 4997\nweb 4998".to_string(), 2)
        );
        assert_eq!(
            logs.seq_at(10),
            logs.seq_at(2),
            "below the lines is the last"
        );
    }

    #[test]
    fn search_keeps_every_line_and_steps_through_matches() {
        let mut logs = Logs::default();
        let generation = logs.restart(None, Prefix::Process);
        for i in 0..20 {
            let text = if i % 5 == 0 {
                format!("GET /up {i}")
            } else {
                format!("{i}")
            };
            logs.push(generation, line(&text));
        }
        logs.height = 3;
        logs.set_search("get".into());
        assert_eq!(logs.visible().len(), 20, "nothing is filtered away");
        assert_eq!(logs.match_seqs(), [0, 5, 10, 15]);
        assert_eq!(logs.current, Some(15), "starts at the newest");
        assert_eq!(texts(logs.window(3)), ["14", "GET /up 15", "16"]);
        assert!(logs.find(true));
        assert_eq!(logs.current, Some(10));
        assert_eq!(texts(logs.window(3)), ["9", "GET /up 10", "11"]);
        assert!(logs.find(false));
        assert_eq!(logs.current, Some(15));
        assert!(logs.find(false), "wraps around");
        assert_eq!(logs.current, Some(0));
        assert_eq!(texts(logs.window(3)), ["GET /up 0", "1", "2"]);

        logs.set_search("nothing".into());
        assert_eq!(logs.current, None);
        assert_eq!(logs.scroll, 0);
    }
}