pma-core 0.7.0

pma's store, scanning, dispatch and workflows, and the Query/Action API its front ends share
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
//! The one key table every front end reads: which key opens which tab, moves
//! the selection, or does which action. Keys are DOM `KeyboardEvent.key`
//! names (`j`, `Enter`, `Escape`, `ArrowDown`), so the web uses the table as
//! it is and the TUI maps its key codes to the same names. Plain keys only:
//! a browser or screen reader reserves most combinations with a modifier.

use crate::api::{Action, Query, Selection};
use crate::report_runs::By;

/// A screen: one query, rendered as a list or as text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Tab {
    Next,
    Matrix,
    Runs,
    Jobs,
    Agents,
    Workflows,
    Campaigns,
    Report,
    Notes,
    Status,
    /// One project, opened from a row that names it. It has no key of its
    /// own: which project is the front end's to remember.
    Project,
}

impl Tab {
    pub const ALL: [Tab; 11] = [
        Tab::Next,
        Tab::Matrix,
        Tab::Runs,
        Tab::Jobs,
        Tab::Agents,
        Tab::Workflows,
        Tab::Campaigns,
        Tab::Report,
        Tab::Notes,
        Tab::Status,
        Tab::Project,
    ];

    pub fn title(self) -> &'static str {
        match self {
            Tab::Next => "next",
            Tab::Matrix => "matrix",
            Tab::Runs => "runs",
            Tab::Jobs => "jobs",
            Tab::Agents => "agents",
            Tab::Workflows => "workflows",
            Tab::Campaigns => "campaigns",
            Tab::Report => "report",
            Tab::Notes => "notes",
            Tab::Status => "status",
            Tab::Project => "project",
        }
    }

    /// What the tab shows. Lists are not cut short: a front end scrolls.
    /// `project` names the project the project tab shows.
    pub fn query(self, by: By, project: &str) -> Query {
        let of = Selection::default();
        match self {
            Tab::Next => Query::Next { of, all: true },
            Tab::Matrix => Query::Matrix {
                of,
                quadrant: None,
                all: true,
            },
            Tab::Runs => Query::Runs,
            Tab::Jobs => Query::Jobs,
            Tab::Agents => Query::Agents,
            Tab::Workflows => Query::Workflows,
            Tab::Campaigns => Query::Campaigns,
            Tab::Report => Query::Report { by },
            Tab::Notes => Query::Notes,
            // Every project, untiered ones too: it is the list a project is
            // opened from.
            Tab::Status => Query::Status {
                of,
                explain: false,
                all: true,
            },
            Tab::Project => Query::Project {
                name: project.to_string(),
            },
        }
    }
}

/// An action by kind, without its arguments: what a key names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Act {
    ApproveRun,
    ApproveRuns,
    RejectRun,
    AddReviewTime,
    SettlePrs,
    StopJob,
    ApproveJob,
    StopWorkflow,
    AddNote,
    EditNote,
    RemoveNote,
    Scan,
    /// Scans the project the project view shows, and nothing else.
    ScanProject,
    Dispatch,
    /// Resumes the selected instance.
    ResumeWorkflow,
    /// Starts an instance from a typed `<workflow> <target> [flags]`.
    StartWorkflow,
    ReworkRun,
    Pr,
    Push,
    RunCampaign,
    Sync,
    Verify,
}

impl Act {
    pub const ALL: [Act; 22] = [
        Act::ApproveRun,
        Act::ApproveRuns,
        Act::RejectRun,
        Act::AddReviewTime,
        Act::SettlePrs,
        Act::StopJob,
        Act::ApproveJob,
        Act::StopWorkflow,
        Act::AddNote,
        Act::EditNote,
        Act::RemoveNote,
        Act::Scan,
        Act::ScanProject,
        Act::Dispatch,
        Act::ResumeWorkflow,
        Act::StartWorkflow,
        Act::ReworkRun,
        Act::Pr,
        Act::Push,
        Act::RunCampaign,
        Act::Sync,
        Act::Verify,
    ];

    pub fn name(self) -> String {
        format!("{self:?}")
    }

    /// Whether the act needs a selected row; one that does not acts on the
    /// whole tab or on nothing in particular.
    pub fn on_row(self) -> bool {
        !matches!(
            self,
            Act::Scan
                | Act::ScanProject
                | Act::Sync
                | Act::AddNote
                | Act::SettlePrs
                | Act::ApproveRuns
                | Act::StartWorkflow
        )
    }

    /// How much an act weighs: `primary` moves work forward, `danger`
    /// discards or publishes something that cannot be called back.
    pub fn weight(self) -> &'static str {
        match self {
            Act::ApproveRun | Act::ApproveJob | Act::Dispatch => "primary",
            Act::RejectRun | Act::StopJob | Act::StopWorkflow | Act::RemoveNote | Act::Push => {
                "danger"
            }
            _ => "default",
        }
    }

    /// The kinds an action can be. A new `Action` variant fails to compile
    /// here until it has a kind, and the tests then require it a key.
    pub fn of(a: &Action) -> &'static [Act] {
        match a {
            Action::ApproveRun { .. } => &[Act::ApproveRun],
            Action::ApproveRuns { .. } => &[Act::ApproveRuns],
            Action::RejectRun { .. } => &[Act::RejectRun],
            Action::AddReviewTime { .. } => &[Act::AddReviewTime],
            Action::SettlePrs => &[Act::SettlePrs],
            Action::StopJob { .. } => &[Act::StopJob],
            Action::ApproveJob { .. } => &[Act::ApproveJob],
            Action::StopWorkflow { .. } => &[Act::StopWorkflow],
            Action::AddNote { .. } => &[Act::AddNote],
            Action::EditNote { .. } => &[Act::EditNote],
            Action::RemoveNote { .. } => &[Act::RemoveNote],
            Action::Scan { .. } => &[Act::Scan, Act::ScanProject],
            Action::Dispatch { .. } => &[Act::Dispatch],
            Action::WorkflowRun { .. } => &[Act::ResumeWorkflow, Act::StartWorkflow],
            Action::ReworkRun { .. } => &[Act::ReworkRun],
            Action::Publish { .. } => &[Act::Pr, Act::Push],
            Action::RunCampaign { .. } => &[Act::RunCampaign],
            Action::Sync { .. } => &[Act::Sync],
            Action::Verify { .. } => &[Act::Verify],
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
    Tab(Tab),
    Act(Act),
    Down,
    Up,
    First,
    Last,
    /// The next list on a tab with several.
    NextPane,
    PrevPane,
    /// The selected item in full: a run's diff, a job's log.
    Open,
    /// Closes what `Open` or a prompt opened.
    Back,
    /// The report's next dimension.
    ReportBy,
    /// The project of the selected row.
    OpenProject,
    Help,
    /// The TUI only; a browser tab is closed by the browser.
    Quit,
}

/// What a front end asks before it acts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ask {
    Nothing,
    /// Yes or no: the action cannot be undone from here.
    Confirm,
    /// A line of text, with this label.
    Text(&'static str),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Binding {
    pub key: &'static str,
    pub command: Command,
    /// Where the key applies; empty is every tab.
    pub tabs: &'static [Tab],
    pub ask: Ask,
    pub label: &'static str,
}

const fn bind(key: &'static str, command: Command, label: &'static str) -> Binding {
    Binding {
        key,
        command,
        tabs: &[],
        ask: Ask::Nothing,
        label,
    }
}

const fn on(
    key: &'static str,
    tabs: &'static [Tab],
    act: Act,
    ask: Ask,
    label: &'static str,
) -> Binding {
    Binding {
        key,
        command: Command::Act(act),
        tabs,
        ask,
        label,
    }
}

const TASKS: &[Tab] = &[Tab::Next, Tab::Matrix, Tab::Project];
const PANES: &[Tab] = &[
    Tab::Next,
    Tab::Matrix,
    Tab::Agents,
    Tab::Workflows,
    Tab::Project,
];
const RUNS: &[Tab] = &[Tab::Runs, Tab::Project];

pub const BINDINGS: &[Binding] = &[
    bind("1", Command::Tab(Tab::Next), "next"),
    bind("2", Command::Tab(Tab::Matrix), "matrix"),
    bind("3", Command::Tab(Tab::Runs), "runs"),
    bind("4", Command::Tab(Tab::Jobs), "jobs"),
    bind("5", Command::Tab(Tab::Agents), "agents"),
    bind("6", Command::Tab(Tab::Workflows), "workflows"),
    bind("7", Command::Tab(Tab::Campaigns), "campaigns"),
    bind("8", Command::Tab(Tab::Report), "report"),
    bind("9", Command::Tab(Tab::Notes), "notes"),
    bind("0", Command::Tab(Tab::Status), "status"),
    bind("j", Command::Down, "down"),
    bind("ArrowDown", Command::Down, "down"),
    bind("k", Command::Up, "up"),
    bind("ArrowUp", Command::Up, "up"),
    bind("g", Command::First, "first"),
    bind("G", Command::Last, "last"),
    Binding {
        tabs: PANES,
        ..bind("Tab", Command::NextPane, "next list")
    },
    Binding {
        tabs: PANES,
        ..bind("l", Command::NextPane, "next list")
    },
    Binding {
        tabs: PANES,
        ..bind("h", Command::PrevPane, "previous list")
    },
    Binding {
        tabs: &[Tab::Runs, Tab::Jobs, Tab::Project],
        ..bind("Enter", Command::Open, "open")
    },
    Binding {
        tabs: &[Tab::Next, Tab::Matrix, Tab::Runs, Tab::Agents, Tab::Status],
        ..bind("o", Command::OpenProject, "open project")
    },
    bind("Escape", Command::Back, "back"),
    Binding {
        tabs: &[Tab::Report],
        ..bind("b", Command::ReportBy, "by")
    },
    bind("?", Command::Help, "keys"),
    bind("q", Command::Quit, "quit"),
    // Anywhere.
    on("c", &[], Act::Scan, Ask::Nothing, "scan"),
    on("i", &[], Act::Sync, Ask::Confirm, "sync issues"),
    on("n", &[], Act::AddNote, Ask::Text("note"), "add note"),
    on(
        "r",
        &[Tab::Project],
        Act::ScanProject,
        Ask::Nothing,
        "rescan project",
    ),
    // A task.
    on("d", TASKS, Act::Dispatch, Ask::Confirm, "dispatch"),
    on("v", TASKS, Act::Verify, Ask::Nothing, "verify project"),
    // A run.
    on("a", RUNS, Act::ApproveRun, Ask::Nothing, "approve"),
    on("b", RUNS, Act::ApproveRuns, Ask::Confirm, "approve clean"),
    on("x", RUNS, Act::RejectRun, Ask::Confirm, "reject"),
    on("w", RUNS, Act::ReworkRun, Ask::Text("feedback"), "rework"),
    on(
        "t",
        RUNS,
        Act::AddReviewTime,
        Ask::Text("minutes"),
        "review time",
    ),
    on("p", RUNS, Act::Pr, Ask::Confirm, "pull request"),
    on("u", RUNS, Act::Push, Ask::Confirm, "push"),
    on("y", RUNS, Act::SettlePrs, Ask::Nothing, "check PRs"),
    // A job.
    on(
        "a",
        &[Tab::Jobs],
        Act::ApproveJob,
        Ask::Nothing,
        "approve plan",
    ),
    on("s", &[Tab::Jobs], Act::StopJob, Ask::Confirm, "stop"),
    // A workflow instance.
    on(
        "r",
        &[Tab::Workflows],
        Act::ResumeWorkflow,
        Ask::Nothing,
        "resume",
    ),
    on(
        "f",
        &[Tab::Workflows],
        Act::StartWorkflow,
        Ask::Text("workflow target [--local] [--unattended]"),
        "start",
    ),
    on(
        "s",
        &[Tab::Workflows],
        Act::StopWorkflow,
        Ask::Confirm,
        "stop",
    ),
    // A campaign.
    on(
        "r",
        &[Tab::Campaigns],
        Act::RunCampaign,
        Ask::Confirm,
        "run",
    ),
    // A note.
    on("e", &[Tab::Notes], Act::EditNote, Ask::Text("note"), "edit"),
    on("x", &[Tab::Notes], Act::RemoveNote, Ask::Confirm, "remove"),
];

/// The binding `key` has on `tab`. One applying to that tab alone wins over
/// one applying everywhere.
pub fn lookup(key: &str, tab: Tab) -> Option<&'static Binding> {
    let fits = |b: &&Binding| b.key == key;
    BINDINGS
        .iter()
        .filter(fits)
        .find(|b| b.tabs.contains(&tab))
        .or_else(|| BINDINGS.iter().filter(fits).find(|b| b.tabs.is_empty()))
}

/// The bindings that apply on `tab`, for a help screen.
pub fn on_tab(tab: Tab) -> Vec<&'static Binding> {
    BINDINGS
        .iter()
        .filter(|b| b.tabs.is_empty() || b.tabs.contains(&tab))
        .collect()
}

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

    /// Every action a front end may take has a key, so no front end can do
    /// what the other has no key for.
    #[test]
    fn every_act_has_a_key() {
        for act in Act::ALL {
            assert!(
                BINDINGS.iter().any(|b| b.command == Command::Act(act)),
                "{act:?} has no key"
            );
        }
        for tab in Tab::ALL.into_iter().filter(|t| *t != Tab::Project) {
            assert!(
                BINDINGS.iter().any(|b| b.command == Command::Tab(tab)),
                "{tab:?} has no key"
            );
        }
        assert!(
            BINDINGS.iter().any(|b| b.command == Command::OpenProject),
            "a project opens from a row"
        );
    }

    /// One key means one thing on a tab: two bindings for the same tab, or a
    /// tab binding that hides an everywhere binding, would make it ambiguous.
    #[test]
    fn no_key_means_two_things_on_one_tab() {
        for tab in Tab::ALL {
            let keys: Vec<&str> = on_tab(tab).iter().map(|b| b.key).collect();
            for k in &keys {
                assert_eq!(
                    keys.iter().filter(|x| *x == k).count(),
                    1,
                    "`{k}` is bound twice on {tab:?}"
                );
            }
        }
    }

    #[test]
    fn keys_are_plain() {
        for b in BINDINGS {
            assert!(
                b.key.chars().count() == 1 || b.key.chars().all(|c| c.is_ascii_alphabetic()),
                "{}",
                b.key
            );
        }
    }

    #[test]
    fn lookup_prefers_the_tab() {
        assert_eq!(
            lookup("a", Tab::Jobs).map(|b| b.command),
            Some(Command::Act(Act::ApproveJob))
        );
        assert_eq!(
            lookup("a", Tab::Runs).map(|b| b.command),
            Some(Command::Act(Act::ApproveRun))
        );
        assert!(lookup("a", Tab::Next).is_none());
        assert_eq!(
            lookup("c", Tab::Notes).map(|b| b.command),
            Some(Command::Act(Act::Scan))
        );
    }
}