rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! What a review panel shows and the clicks that act on it: the opened change, the pull
//! request picker, tabs, things to check.

use super::*;

/// What the panel wants the app to do.
#[derive(Debug, PartialEq)]
pub enum Request {
    Nothing,
    /// Close the panel for good.
    Close,
    /// Back to the pane's terminal, keeping the panel as it is.
    Hide,
    /// Start the current job (see [`ReviewView::job`]).
    Load,
    /// Put text on the clipboard, and say this.
    Copy(String, String),
    /// Type a command at the prompt without running it.
    Type(String),
    OpenFile(PathBuf, u32),
    OpenUrl(String),
    /// Approve pull request (repository, number, the commit reviewed); see [`spawn_approve`].
    Approve(PathBuf, u64, String),
    /// Merge pull request (repository, number, the commit reviewed, how); see [`spawn_merge`].
    Merge(PathBuf, u64, String, Method),
    /// The person confirmed a new pull request; see [`spawn_create`].
    Create(Box<Proposal>),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Tab {
    #[default]
    Guide,
    Findings,
    Description,
}

impl Tab {
    pub const ALL: [Tab; 3] = [Tab::Guide, Tab::Findings, Tab::Description];
}

/// One thing to do in a stage: read a file, or check or test an item.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Thing {
    File(usize),
    Item(usize),
}

/// Something on screen that can be clicked.
#[derive(Clone, Debug, PartialEq)]
pub enum Click {
    GitRow(usize),
    GitAction(workspace::Control),
    Close,
    /// To the list of things to review.
    Back,
    Reload,
    Tab(Tab),
    /// Go to a stage of the guide.
    Stage(usize),
    /// On to the next thing still to do, or the next stage when this one is done.
    Continue,
    Step(usize),
    Verdict(Verdict),
    Clear,
    Prev,
    Next,
    EditNote,
    Copy(String),
    Type(String),
    /// A file of the change, at a line.
    File(String, u32),
    Url(String),
    Finding(usize),
    /// A changed file: choose it, or fold it if it is chosen.
    ChangedFile(usize),
    /// Tick a changed file as read, or untick it.
    Seen(usize),
    Approve,
    Merge(Method),
    /// Open a pull request for the branch being reviewed.
    Propose,
    CopyResults,
    Reset,
    /// A line of the picker.
    Choose(usize),
    /// Show or put away the list of actions.
    Menu,
    /// A line of that list.
    MenuRow(usize),
    /// Part of the screen that takes a click and does nothing with it.
    Inert,
    /// To the terminal.
    Hide,
    Create(create::Press),
}

#[derive(Default)]
pub enum Pulls {
    #[default]
    Loading,
    Done(&'static str, Vec<Entry>),
    Failed(String),
}

#[derive(Default)]
pub struct Picker {
    pub local: Option<Result<Local, String>>,
    pub pulls: Pulls,
    pub filter: String,
    /// Among the rows that can be chosen.
    pub selected: usize,
    /// What to have selected once it is listed: what was open before coming back here.
    pub want: Option<String>,
}

/// The picker's entry that is not a change to review: it starts a new pull request.
pub(super) const NEW_PULL: &str = "new-pull-request";

pub enum Row {
    Heading(String),
    /// Something to say: loading, empty, or what went wrong.
    Note(String),
    Entry(Entry),
}

impl Picker {
    /// The list as shown: sections, narrowed to what matches the filter.
    pub fn rows(&self) -> Vec<Row> {
        // Every word typed has to be there. Looser matching would find nearly anything in
        // commit subjects and descriptions.
        let words: Vec<String> = self.filter.split_whitespace().map(str::to_lowercase).collect();
        let matches = |e: &Entry| {
            let text = format!("{} {}", e.title, e.detail).to_lowercase();
            words.iter().all(|w| text.contains(w))
        };
        let mut rows = Vec::new();
        let section = |rows: &mut Vec<Row>, name: &str, entries: &[Entry]| {
            let found: Vec<Entry> = entries.iter().filter(|e| matches(e)).cloned().collect();
            if !found.is_empty() {
                rows.push(Row::Heading(name.to_string()));
                rows.extend(found.into_iter().map(Row::Entry));
            }
        };
        let typed = self.filter.trim();
        // Anything typed can be opened as it is: a number, a hash, a branch not listed.
        if !typed.is_empty() {
            rows.push(Row::Entry(Entry {
                target: typed.to_string(),
                title: format!("Review \u{201c}{typed}\u{201d}"),
                detail: "a pull request number or address, a branch, or a commit".into(),
            }));
        }
        match &self.pulls {
            Pulls::Loading => {
                rows.push(Row::Heading("Pull requests".into()));
                rows.push(Row::Note("asking the host\u{2026}".into()));
            }
            Pulls::Failed(why) => {
                rows.push(Row::Heading("Pull requests".into()));
                rows.push(Row::Note(why.clone()));
            }
            Pulls::Done(host, list) if list.is_empty() => {
                rows.push(Row::Heading(format!("Pull requests on {host}")));
                rows.push(Row::Note("none are open".into()));
            }
            Pulls::Done(host, list) => section(&mut rows, &format!("Pull requests on {host}"), list),
        }
        if matches!(self.local, Some(Ok(_))) {
            let new = Entry {
                target: NEW_PULL.into(),
                title: "+ New pull request".into(),
                detail: "propose the current branch\u{2019}s commits".into(),
            };
            section(&mut rows, "Create", &[new]);
        }
        match &self.local {
            None => rows.push(Row::Note("reading the repository\u{2026}".into())),
            Some(Err(why)) => rows.push(Row::Note(why.clone())),
            Some(Ok(l)) => {
                section(&mut rows, "Work in progress", &l.work);
                section(&mut rows, "Branches", &l.branches);
                section(&mut rows, "Recent commits", &l.commits);
            }
        }
        let demo = Entry {
            target: "demo".into(),
            title: "Demo pull request".into(),
            detail: "a made-up change to try this on".into(),
        };
        section(&mut rows, "Try it", &[demo]);
        rows
    }

    /// Select what was open before, if it is listed by now.
    pub(super) fn select_wanted(&mut self) -> bool {
        let Some(wanted) = &self.want else { return false };
        let found = self.entries().iter().position(|e| &e.target == wanted);
        if let Some(i) = found {
            self.selected = i;
        }
        found.is_some()
    }

    pub fn entries(&self) -> Vec<Entry> {
        self.rows().into_iter().filter_map(|r| if let Row::Entry(e) = r { Some(e) } else { None }).collect()
    }
}

/// A change being reviewed.
pub struct Opened {
    pub change: Box<Change>,
    pub items: Vec<Item>,
    pub session: Session,
    /// The guide's stages, the one being gone through, and the thing chosen in it.
    pub stages: Vec<Stage>,
    pub stage: usize,
    pub cursor: usize,
    /// The chosen item, kept in step with the cursor.
    pub step: usize,
    pub tab: Tab,
    /// The finding chosen on the findings tab, and whether it is unfolded.
    pub finding: usize,
    pub unfolded: bool,
    /// The note being typed for the current step.
    pub note: Option<String>,
    /// Reset was pressed once; pressing it again does it.
    pub confirm_reset: bool,
    /// The chosen file, kept in step with the cursor, and whether its diff is shown.
    pub file: usize,
    pub file_open: bool,
    /// Approve was pressed once; pressing it again sends it.
    pub confirm_approve: bool,
    /// An approval is on its way to the host.
    pub approving: bool,
    /// This way of merging was pressed once; pressing it again does it.
    pub confirm_merge: Option<Method>,
    /// A merge is on its way to the host.
    pub merging: bool,
    /// The list of actions, while it shows.
    pub menu: Option<Menu>,
    /// The host took the merge.
    pub merged: bool,
}

impl Opened {
    pub fn new(change: Box<Change>, results: Option<&Path>) -> Opened {
        let items = session::items(&change.report);
        let session = Session::open(results, &change.root, &change.id, &change.revision);
        let stages = guide::build(&change.files, &change.report.findings, &items);
        let mut o = Opened {
            change,
            items,
            session,
            stages,
            stage: 0,
            cursor: 0,
            step: 0,
            tab: Tab::Guide,
            finding: 0,
            unfolded: true,
            note: None,
            confirm_reset: false,
            file: 0,
            file_open: true,
            confirm_approve: false,
            approving: false,
            confirm_merge: None,
            merging: false,
            menu: None,
            merged: false,
        };
        // Carry on where the review stopped: the first stage with something left, unless
        // nothing has been done yet, when it starts at the beginning.
        let started = (0..o.stages.len()).any(|s| o.things(s).iter().any(|&t| o.done(t)));
        let stage =
            if started { (0..o.stages.len()).find(|&s| !o.stage_done(s)).unwrap_or(o.stages.len() - 1) } else { 0 };
        let cursor = o.things(stage).iter().position(|&t| !o.done(t)).unwrap_or(0);
        o.focus(stage, cursor);
        o
    }

    pub fn current(&self) -> Option<&Item> {
        match self.thing() {
            Some(Thing::Item(i)) => self.items.get(i),
            _ => None,
        }
    }

    /// What there is to do in a stage: its files, then its items.
    pub fn things(&self, stage: usize) -> Vec<Thing> {
        let Some(s) = self.stages.get(stage) else { return Vec::new() };
        s.files.iter().map(|&f| Thing::File(f)).chain(s.items.iter().map(|&i| Thing::Item(i))).collect()
    }

    /// The chosen thing.
    pub fn thing(&self) -> Option<Thing> {
        self.things(self.stage).get(self.cursor).copied()
    }

    /// A file read, or an item judged, for this version of the change.
    pub fn done(&self, t: Thing) -> bool {
        match t {
            Thing::File(f) => self.change.files.get(f).is_some_and(|f| self.session.seen(f) == Seen::Yes),
            Thing::Item(i) => self.items.get(i).is_some_and(|i| matches!(self.session.state(&i.id), State::Done(_))),
        }
    }

    /// (done, total) in a stage.
    pub fn stage_counts(&self, stage: usize) -> (usize, usize) {
        let things = self.things(stage);
        (things.iter().filter(|&&t| self.done(t)).count(), things.len())
    }

    pub fn stage_done(&self, stage: usize) -> bool {
        let (done, total) = self.stage_counts(stage);
        done == total
    }

    /// Choose a thing, keeping the chosen item and file in step.
    pub fn focus(&mut self, stage: usize, cursor: usize) {
        self.stage = stage.min(self.stages.len().saturating_sub(1));
        self.cursor = cursor.min(self.things(self.stage).len().saturating_sub(1));
        self.note = None;
        match self.thing() {
            Some(Thing::Item(i)) => self.step = i,
            Some(Thing::File(f)) => {
                self.file = f;
                self.file_open = true;
            }
            None => {}
        }
    }

    /// The stage a thing is in, and where in it.
    pub fn locate(&self, t: Thing) -> Option<(usize, usize)> {
        (0..self.stages.len()).find_map(|s| self.things(s).iter().position(|&x| x == t).map(|c| (s, c)))
    }

    /// The next thing still to do in this stage after the chosen one, wrapping round.
    pub fn next_undone(&self) -> Option<usize> {
        let things = self.things(self.stage);
        (1..=things.len()).map(|k| (self.cursor + k) % things.len()).find(|&c| !self.done(things[c]))
    }

    /// A file of the change on disk, if it is safe to open and is there.
    pub fn file(&self, rel: &str) -> Option<PathBuf> {
        let rel = Path::new(rel);
        let inside = rel.components().all(|c| matches!(c, Component::Normal(_)));
        let path = self.change.root.join(rel);
        (inside && !rel.as_os_str().to_string_lossy().contains('"') && path.is_file()).then_some(path)
    }

    /// Where the current step's first finding points.
    pub(super) fn current_place(&self) -> Option<(String, u32)> {
        let report = &self.change.report;
        let of = |i: &usize| report.findings.get(*i)?.span.as_ref().map(|s| (s.file.clone(), s.line));
        match (self.tab, self.thing()) {
            (Tab::Findings, _) => of(&self.finding),
            (_, Some(Thing::File(f))) => {
                let file = self.change.files.get(f)?;
                let line =
                    file.lines().find(|l| l.kind != Kind::Context).and_then(|l| l.new_no.or(l.old_no)).unwrap_or(1);
                Some((file.path.clone(), line))
            }
            _ => self.current()?.findings.iter().find_map(of),
        }
    }

    /// The findings that point into a changed file.
    pub fn findings_in(&self, path: &str) -> Vec<usize> {
        let findings = &self.change.report.findings;
        (0..findings.len()).filter(|&i| findings[i].span.as_ref().is_some_and(|s| s.file == path)).collect()
    }

    /// What is still open before approving: unread files, unchecked findings, untried steps.
    pub fn still_open(&self) -> Vec<String> {
        let mut open = Vec::new();
        let unread = self.change.files.len() - self.session.seen_count(&self.change.files);
        let left = |check: bool| {
            self.items
                .iter()
                .filter(|i| i.check == check && !matches!(self.session.state(&i.id), State::Done(_)))
                .count()
        };
        let (unchecked, untested) = (left(true), left(false));
        let parts = [
            (unread, "file unread", "files unread"),
            (unchecked, "finding unchecked", "findings unchecked"),
            (untested, "step untried", "steps untried"),
        ];
        for (n, one, many) in parts {
            if n > 0 {
                open.push(format!("{n} {}", if n == 1 { one } else { many }));
            }
        }
        open
    }
}

pub enum Screen {
    Git(Box<GitView>),
    Create(Box<CreateView>),
    Pick(Picker),
    Loading(String),
    Open(Box<Opened>),
    /// Nothing to show, and why.
    Message {
        text: String,
        error: bool,
    },
}