ghtui 0.2.0

A keyboard-driven terminal client for GitHub, with a pull request diff viewer that goes further than GitHub's
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
//! What ghtui does with GitHub Actions beyond showing it: saving a run's
//! artifacts where you say, and running a workflow by hand
//! (`workflow_dispatch`) from a form of its inputs, read from its file,
//! then following the run it started.

use crate::route::{Route, runs};
use std::collections::HashMap;
use std::path::PathBuf;

use crate::api::browse::{Blob, Refs, Workflow, WorkflowRun};
use crate::api::model::RepoId;
use crate::api::workflows::{Input, InputKind, dispatch_inputs};
use crate::data::DataKey;
use crate::forms::filling;
use crate::keymap::Action;
use crate::nav::Doable;
use crate::state::{Cmd, State};
use crate::ui::form::Row;
use crate::ui::page::Page;
use crate::ui::pages::{self, DispatchView};
use crate::work::{self, Cx, Failure, Job};

/// What's chosen on the form that runs a workflow by hand.
#[derive(Debug, Default, Clone)]
struct Form {
    /// The branch; the default branch until one is chosen.
    git_ref: Option<String>,
    values: HashMap<String, String>,
}

impl crate::forms::Fields for Form {}

/// Saving a run's artifact to `path` (over a file there, with
/// `replace`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SaveArtifact {
    pub repo: RepoId,
    pub id: u64,
    pub name: String,
    pub path: PathBuf,
    pub replace: bool,
}

/// Running a workflow by hand.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dispatch {
    pub repo: RepoId,
    pub file: String,
    pub git_ref: String,
    pub inputs: Vec<(String, String)>,
}

impl Job for SaveArtifact {
    /// Its size.
    type Out = u64;
    const WRITES: bool = false;

    async fn run(&self, cx: &Cx) -> Result<u64, Failure> {
        let saved = (cx.gh).download_artifact(&self.repo, self.id, &self.path, self.replace);
        Ok(saved.await?)
    }

    fn done(self, state: &mut State, result: Result<u64, Failure>) -> Vec<Cmd> {
        let (name, path) = (self.name, self.path.display());
        match result {
            Ok(size) => {
                let size = crate::ui::text::size(size);
                state.info(format!("Saved {name} ({size}) to {path}"));
            }
            Err(err) => state.error(format!("Couldn't save {name} to {path}: {err}")),
        }
        Vec::new()
    }
}

// ---- artifacts --------------------------------------------------------------

/// A picker of this module's.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pick {
    /// Where to save an artifact: the field is the path.
    Save { repo: RepoId, id: u64, name: String },
    /// The branch a workflow runs on.
    Ref,
    /// A workflow input's value.
    Input(String),
}

impl Pick {
    pub fn title(&self) -> &'static str {
        match self {
            Pick::Save { .. } => "Save the artifact",
            Pick::Ref => "Use workflow from",
            Pick::Input(_) => "Set the input",
        }
    }

    pub fn placeholder(&self) -> &'static str {
        match self {
            Pick::Save { .. } => "A file or folder (↵ saves in the current folder)",
            Pick::Ref => "Find a branch",
            Pick::Input(_) => "Type a value",
        }
    }
}

/// The picker's rows for `pick`, with `q` typed.
pub fn rows(state: &State, pick: &Pick, q: &str) -> crate::picker::Rows {
    let item = crate::picker::item;
    let note = |text: String| vec![(item(text, ""), None)];
    match pick {
        Pick::Save { repo, id, name } => {
            let file = format!("{name}.zip");
            crate::picker::save_rows(q, &file, "a zip", |path, replace| {
                let (repo, id, name) = (repo.clone(), *id, name.clone());
                SaveArtifact {
                    repo,
                    id,
                    name,
                    path,
                    replace,
                }
                .into()
            })
        }
        Pick::Ref => {
            let Some((repo, file)) = here(state) else {
                return note("The form isn't on screen".into());
            };
            let key = DataKey::Refs(repo.clone());
            let route = form_route((repo, file));
            let refs = match crate::picker::listed::<Refs, _>(state, &key, "the branches") {
                Ok(refs) => refs,
                Err(why) => return why,
            };
            let chosen = form_ref(state);
            let mut rows: Vec<_> = (refs.branches.iter())
                .filter(|b| crate::picker::fuzzy_score(q, b).is_some())
                .map(|b| {
                    let hint = if chosen.as_deref() == Some(b.as_str()) {
                        "chosen"
                    } else {
                        ""
                    };
                    (item(b.clone(), hint), Some(filling(&route, Row::Ref, b)))
                })
                .collect();
            if refs.branches.left_out() > 0 {
                rows.extend(note(format!("{} more on GitHub", refs.branches.left_out())));
            }
            rows
        }
        Pick::Input(name) => {
            let input = inputs_here(state).and_then(|i| i.into_iter().find(|i| i.name == *name));
            let (Some(input), Some(route)) = (input, here(state).map(form_route)) else {
                return note("The form isn't on screen".into());
            };
            let set = |value: &str| Some(filling(&route, Row::Input(name.clone()), value));
            match &input.kind {
                InputKind::Choice(options) => (options.iter())
                    .filter(|o| crate::picker::fuzzy_score(q, o).is_some())
                    .map(|o| (item(o.clone(), ""), set(o)))
                    .collect(),
                InputKind::Boolean => ["true", "false"]
                    .into_iter()
                    .filter(|o| crate::picker::fuzzy_score(q, o).is_some())
                    .map(|o| (item(o.to_owned(), ""), set(o)))
                    .collect(),
                InputKind::Text => {
                    let label = if q.is_empty() {
                        "Set it empty".to_owned()
                    } else {
                        format!("Set it to “{q}”")
                    };
                    vec![(item(label, &input.description), set(q))]
                }
            }
        }
    }
}

/// The branch, or an input, chosen.
fn fill(state: &mut State, route: &Route, row: &Row, value: String) -> Vec<Cmd> {
    let form = state.forms.edit::<Form>(route);
    match row {
        Row::Ref => {
            form.git_ref = Some(value);
            // Its inputs are read from the file on that branch.
            blob_need(state).map_or_else(Vec::new, |need| state.ensure(need, false))
        }
        Row::Input(name) => {
            form.values.insert(name.clone(), value);
            Vec::new()
        }
        _ => Vec::new(),
    }
}

/// What the form that runs a workflow by hand does.
pub const FORM: crate::forms::Kind = crate::forms::Kind {
    compose: |_, _| Vec::new(),
    row: on_row,
    fill,
    submit: run,
    follow: |_| Vec::new(),
    offers: |_, _| {},
};

/// Enter on one of the form's rows.
#[must_use]
fn on_row(state: &mut State, row: &Row) -> Vec<Cmd> {
    match row {
        Row::Ref => {
            let repo = here(state).map(|(r, _)| r);
            let mut cmds = state.open_picker(crate::picker::Kind::Workflows(Pick::Ref));
            if let Some(repo) = repo {
                cmds.extend(state.ensure(DataKey::Refs(repo), false));
            }
            cmds
        }
        Row::Input(name) => {
            state.open_picker(crate::picker::Kind::Workflows(Pick::Input(name.clone())))
        }
        _ => Vec::new(),
    }
}

/// Asks where to save artifact `id` of the run on screen.
#[must_use]
pub fn save(state: &mut State, id: u64, name: &str) -> Vec<Cmd> {
    let Some(Route::Runs(runs::WorkflowRun { repo, run, attempt })) = state.route().cloned() else {
        return Vec::new();
    };
    let key = DataKey::Run(repo.clone(), run, attempt);
    let expired = (state.picked::<WorkflowRun>(&key))
        .and_then(|r| r.artifacts.iter().find(|a| a.id == id))
        .is_some_and(|a| a.expired);
    if expired {
        return state.just_say(format!("{name} has expired: GitHub no longer keeps it"));
    }
    let pick = Pick::Save {
        repo,
        id,
        name: name.to_owned(),
    };
    state.open_picker(crate::picker::Kind::Workflows(pick))
}

// ---- running a workflow by hand -----------------------------------------------

/// The workflow file a page is about: a workflow's, a run's.
fn workflow_here(state: &State) -> Option<(RepoId, String)> {
    let file = |path: &str| path.rsplit('/').next().unwrap_or(path).to_owned();
    match state.route()? {
        Route::Runs(runs::Workflow { repo, file }) | Route::Runs(runs::Dispatch { repo, file }) => {
            Some((repo.clone(), file.clone()))
        }
        Route::Runs(runs::WorkflowRun { repo, run, attempt }) => {
            let key = DataKey::Run(repo.clone(), *run, *attempt);
            let r = state.picked::<WorkflowRun>(&key)?;
            Some((repo.clone(), file(&r.path))).filter(|(_, f)| !f.is_empty())
        }
        _ => None,
    }
}

/// The form on screen: its repository and workflow file.
fn here(state: &State) -> Option<(RepoId, String)> {
    match state.route()? {
        Route::Runs(runs::Dispatch { repo, file }) => Some((repo.clone(), file.clone())),
        _ => None,
    }
}

/// The form's page, for the workflow `file` in `repo`.
fn form_route((repo, file): (RepoId, String)) -> Route {
    Route::Runs(runs::Dispatch { repo, file })
}

/// The workflow's path in its repository.
pub(crate) fn workflow_path(file: &str) -> String {
    format!(".github/workflows/{file}")
}

/// The branch the form on screen runs on: chosen, or the default.
fn form_ref(state: &State) -> Option<String> {
    let (repo, file) = here(state)?;
    let chosen = state.forms.get::<Form>(&form_route((repo.clone(), file)));
    chosen
        .and_then(|f| f.git_ref.clone())
        .or_else(|| state.overview(&repo)?.default_branch.clone())
}

/// The workflow file on the form's branch.
fn blob_need(state: &State) -> Option<DataKey> {
    let (repo, file) = here(state)?;
    let chosen = state
        .forms
        .get::<Form>(&form_route((repo.clone(), file.clone())));
    let git_ref = chosen
        .and_then(|f| f.git_ref.clone())
        .unwrap_or_else(|| "HEAD".into());
    Some(DataKey::Blob(repo, git_ref, workflow_path(&file)))
}

/// The form's inputs, once the file is in; `Err` says why there are none.
fn inputs_of(state: &State) -> Result<Vec<Input>, String> {
    let Some(key) = blob_need(state) else {
        return Err("Loading…".into());
    };
    let Some(blob) = state.picked::<Blob>(&key) else {
        let failed = state.remote(&key).and_then(|r| r.error.clone());
        return Err(failed.map_or_else(
            || "Reading the workflow file…".to_owned(),
            |e| format!("Couldn't read the workflow file: {e}"),
        ));
    };
    let text = blob.text.as_deref().unwrap_or_default();
    dispatch_inputs(text).ok_or_else(|| {
        "This workflow can't be run by hand: its file has no workflow_dispatch trigger".into()
    })
}

fn inputs_here(state: &State) -> Option<Vec<Input>> {
    inputs_of(state).ok()
}

/// What the form page needs: the workflow (its name) and its file.
pub fn needs(repo: &RepoId, file: &str) -> Vec<DataKey> {
    vec![
        DataKey::Repo(repo.clone()),
        DataKey::Workflow(repo.clone(), file.to_owned()),
        DataKey::Blob(repo.clone(), "HEAD".into(), workflow_path(file)),
    ]
}

/// The form page.
pub fn build(state: &State, page: &mut Page, repo: &RepoId, file: &str) {
    let path = workflow_path(file);
    let workflow = state.picked::<Workflow>(&DataKey::Workflow(repo.clone(), file.to_owned()));
    let name = workflow.map_or(file, |w| w.name.as_str());
    let route = form_route((repo.clone(), file.to_owned()));
    let form = state.forms.shown::<Form>(&route);
    let sent = state.forms.sent(&route);
    let git_ref = form_ref(state).unwrap_or_else(|| "the default branch".into());
    let inputs = inputs_of(state);
    let run_key = state.first_key(Action::RunWorkflow);
    let view = DispatchView {
        name,
        path: &path,
        git_ref: &git_ref,
        inputs: inputs.as_deref().map_err(String::clone),
        values: &form.values,
        sending: sent.sending,
        error: sent.error.as_deref(),
        run_key: &run_key,
    };
    pages::dispatch_form(page, &view);
}

/// Why the workflow on screen can't be run by hand, if it can't.
fn refused(state: &State, repo: &RepoId, file: &str) -> Option<String> {
    if state.overview(repo).is_some_and(|o| !o.can_write) {
        return Some(format!("Running a workflow takes write access to {repo}"));
    }
    let workflow = state.picked::<Workflow>(&DataKey::Workflow(repo.clone(), file.to_owned()));
    let disabled = workflow.and_then(|w| w.disabled.as_ref());
    disabled.map(|why| format!("The workflow is {why}: enable it on GitHub first"))
}

/// `,E`: from a workflow's page or a run's, the form; on the form, runs it.
#[must_use]
pub fn action(state: &mut State) -> Vec<Cmd> {
    if here(state).is_some() {
        return run(state);
    }
    let Some((repo, file)) = workflow_here(state) else {
        return state
            .just_say("Running a workflow by hand works on a workflow's page or one of its runs");
    };
    if let Some(why) = refused(state, &repo, &file) {
        return state.just_say(why);
    }
    state.push(Route::Runs(runs::Dispatch { repo, file }))
}

/// Runs the form's workflow, if it can.
#[must_use]
fn run(state: &mut State) -> Vec<Cmd> {
    let Some((repo, file)) = here(state) else {
        return Vec::new();
    };
    let route = form_route((repo.clone(), file.clone()));
    let why = refused(state, &repo, &file)
        .or_else(|| (state.forms.sent(&route).sending).then(|| "It's being started".to_owned()));
    let inputs = inputs_of(state);
    let (why, inputs) = match (why, inputs) {
        (Some(why), _) | (None, Err(why)) => (Some(why), Vec::new()),
        (None, Ok(inputs)) => (None, inputs),
    };
    let Some(git_ref) = form_ref(state) else {
        return state.just_say("Still loading the repository's default branch");
    };
    if let Some(why) = why {
        return state.just_say(why);
    }
    let form = state.forms.shown::<Form>(&route);
    let values: Vec<(String, String)> = (inputs.iter())
        .map(|i| {
            let value = form
                .values
                .get(&i.name)
                .cloned()
                .unwrap_or_else(|| i.start());
            (i.name.clone(), value)
        })
        .collect();
    if let Some(missing) = inputs
        .iter()
        .zip(&values)
        .find(|(i, (_, v))| i.required && v.is_empty())
    {
        let why = format!("{} is required", missing.0.name);
        state.forms.sent_mut(&route).fail(why);
        return Vec::new();
    }
    state.forms.sent_mut(&route).start();
    work::start(Dispatch {
        repo,
        file,
        git_ref,
        inputs: values,
    })
}

impl Job for Dispatch {
    /// The run it started, when GitHub says.
    type Out = Option<u64>;

    async fn run(&self, cx: &Cx) -> Result<Option<u64>, Failure> {
        let started = (cx.gh).dispatch(&self.repo, &self.file, &self.git_ref, &self.inputs);
        Ok(started.await?)
    }

    /// A new run is followed from the form; elsewhere it's said.
    fn done(self, state: &mut State, result: Result<Option<u64>, Failure>) -> Vec<Cmd> {
        let Dispatch { repo, file, .. } = self;
        let route = form_route((repo.clone(), file.clone()));
        let on_form = state.route() == Some(&route);
        match result {
            Err(err) => {
                let text = format!("Couldn't run {file}: {err}");
                crate::forms::failed(state, &route, text)
            }
            // It's a new run: the form starts over next time.
            Ok(run) => {
                state.forms.take::<Form>(&route);
                if !on_form {
                    return state.just_say(format!("Started {file}"));
                }
                let route = match run {
                    Some(run) => {
                        state.info(format!("Started {file}: following its run"));
                        Route::Runs(runs::WorkflowRun {
                            repo,
                            run,
                            attempt: None,
                        })
                    }
                    // GitHub didn't say which: its runs show it soon.
                    None => {
                        state.info(format!("Started {file}: it shows in its runs in a moment"));
                        Route::Runs(runs::Workflow { repo, file })
                    }
                };
                state.replace(route, true, None)
            }
        }
    }
}

/// What running a workflow by hand adds.
pub const FEATURE: crate::features::Feature = crate::features::Feature {
    owns: &[Action::RunWorkflow],
    act: |state, _| action(state),
    offers: doables,
    ..crate::features::Feature::NONE
};

/// What the menu offers here: running the workflow by hand.
pub fn doables(state: &State, out: &mut Vec<Doable>) {
    let Some((repo, file)) = workflow_here(state) else {
        return;
    };
    let label = if here(state).is_some() {
        "Run the workflow".to_owned()
    } else {
        format!("Run {file} by hand…")
    };
    let why = refused(state, &repo, &file);
    out.push(crate::nav::row(
        "Change",
        Action::RunWorkflow,
        label,
        "",
        why,
    ));
}

// ---- annotations in Files changed -----------------------------------------------

/// A pull request's checks came in: its diff shows their annotations.
pub fn checks_loaded(state: &mut State, pr: &crate::api::model::PrRef) {
    let key = DataKey::PrChecks(pr.clone());
    let Some(checks) = state.picked::<crate::api::browse::Checks>(&key) else {
        return;
    };
    let list: Vec<(String, crate::api::workflows::Annotation)> = (checks.items.iter())
        .flat_map(|c| c.annotations.iter().map(|a| (c.name.clone(), a.clone())))
        .filter(|(_, a)| a.path.is_some())
        .collect();
    let of = crate::diff_screen::DiffOf::Pr(pr.clone());
    if let Some(diff) = state.diffs.get_mut(&of)
        && diff.inputs().checks != list
    {
        diff.edit(|i| i.checks = list);
    }
}

/// Check annotations as the diff shows them: on their lines, as GitHub
/// shows them in Files changed, each a one-comment thread from its check.
pub fn in_diff(
    checks: &[(String, crate::api::workflows::Annotation)],
) -> Vec<crate::ui::annotations::Annotation> {
    use crate::api::workflows::Level;
    use crate::ui::annotations::{Annotation, AnnotationComment, AnnotationKey, Place};
    (checks.iter().enumerate())
        .filter_map(|(n, (check, a))| {
            let path = a.path.clone()?;
            let mark = match a.level {
                Level::Failure => "✗",
                Level::Warning => "!",
                Level::Notice => "i",
            };
            let place = match a.start_line {
                0 => Place::File { outdated: false },
                line => Place::Line {
                    at: crate::diff::anchor::LinePos {
                        side: crate::diff::anchor::Side::Right,
                        line: a.end_line.max(line),
                    },
                    start: (a.end_line > line).then_some(line),
                },
            };
            let body = if a.title.is_empty() {
                a.message.clone()
            } else {
                format!("**{}**\n\n{}", a.title, a.message)
            };
            Some(Annotation {
                key: AnnotationKey::Check(n),
                path,
                place,
                resolved: false,
                comments: vec![AnnotationComment {
                    author: format!("{mark} {check} · {}", a.level.word()),
                    body,
                    created_at: String::new(),
                    pending: false,
                    new: false,
                    editable: None,
                }],
                left_out: 0,
                error: None,
                can_reply: false,
                can_resolve: false,
                can_unresolve: false,
                new: false,
            })
        })
        .collect()
}