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
//! What GitHub Actions says beyond runs and jobs: why a check failed (its
//! annotations), what a run made (its artifacts), and running a workflow
//! by hand (its `workflow_dispatch` inputs).

use serde::{Deserialize, Serialize};

use crate::api::client::{ApiError, GitHub};
use crate::api::model::{Capped, RepoId};
use crate::schema::schema;

/// How serious an annotation is.
#[derive(cynic::Enum, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cynic(graphql_type = "CheckAnnotationLevel")]
pub enum Level {
    Failure,
    Warning,
    Notice,
}

impl Level {
    pub fn word(self) -> &'static str {
        match self {
            Level::Failure => "Error",
            Level::Warning => "Warning",
            Level::Notice => "Notice",
        }
    }
}

/// What a check run says about a file's lines: a failure, a warning or a
/// notice.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Annotation {
    /// The file, or `None` for one about the run (GitHub names the
    /// workflow's folder, `.github`, for those).
    pub path: Option<String>,
    pub start_line: u32,
    pub end_line: u32,
    pub level: Level,
    /// Empty when it has none.
    pub title: String,
    pub message: String,
    /// The file at the commit checked, at its lines; `None` for one about
    /// the run.
    pub url: Option<String>,
}

/// An annotation as GitHub sends it.
struct Raw {
    path: String,
    start: i64,
    end: i64,
    level: Level,
    title: String,
    message: String,
    /// The file at the commit checked.
    blob: String,
}

impl Annotation {
    fn new(raw: Raw) -> Self {
        let line = |n: i64| u32::try_from(n).unwrap_or(0);
        let path = Some(raw.path).filter(|p| !p.is_empty() && p != ".github");
        let (start_line, end_line) = (line(raw.start), line(raw.end.max(raw.start)));
        let lines = match (start_line, end_line) {
            (0, _) => String::new(),
            (a, b) if a == b => format!("#L{a}"),
            (a, b) => format!("#L{a}-L{b}"),
        };
        Self {
            url: path.as_ref().map(|_| format!("{}{lines}", raw.blob)),
            path,
            start_line,
            end_line,
            level: raw.level,
            title: raw.title,
            message: raw.message,
        }
    }

    /// Where it is, as people say it: `src/a.rs:12`, or "the run".
    pub fn place(&self) -> String {
        match &self.path {
            Some(path) if self.start_line > 0 => format!("{path}:{}", self.start_line),
            Some(path) => path.clone(),
            None => "the run".to_owned(),
        }
    }
}

/// Annotations, worst first, then by file and line.
pub fn sorted(mut list: Vec<Annotation>) -> Vec<Annotation> {
    list.sort_by(|a, b| (a.level, &a.path, a.start_line).cmp(&(b.level, &b.path, b.start_line)));
    list
}

/// What a run made to keep: a file to download, for a while.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Artifact {
    pub id: u64,
    pub name: String,
    /// Bytes, as stored (zipped).
    pub size: u64,
    /// ISO 8601.
    pub expires_at: Option<String>,
    /// Gone: it can't be downloaded.
    pub expired: bool,
}

/// A `workflow_dispatch` input, as its workflow file declares it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Input {
    pub name: String,
    pub description: String,
    pub kind: InputKind,
    /// As the file has it (`true`, a choice, text).
    pub default: Option<String>,
    pub required: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputKind {
    /// One of these.
    Choice(Vec<String>),
    Boolean,
    /// Text, a number, or an environment's name: typed.
    Text,
}

impl Input {
    /// What's offered for it before anything is chosen: its default, or a
    /// choice's first option, or a boolean's `false`.
    pub fn start(&self) -> String {
        match (&self.default, &self.kind) {
            (Some(d), _) => d.clone(),
            (None, InputKind::Choice(options)) => options.first().cloned().unwrap_or_default(),
            (None, InputKind::Boolean) => "false".into(),
            (None, InputKind::Text) => String::new(),
        }
    }
}

/// A workflow file's `workflow_dispatch` inputs; `None` if it can't be
/// run by hand.
pub fn dispatch_inputs(file: &str) -> Option<Vec<Input>> {
    use crate::yaml::{self, Value};
    let doc = yaml::parse(file);
    // `on` is a name, a list of names, or a map of them.
    let on = doc.get("on").or_else(|| doc.get("true"))?;
    let dispatch = match on {
        Value::Text(name) => return (name == "workflow_dispatch").then(Vec::new),
        Value::List(names) => {
            let named = names.iter().any(|n| n.text() == Some("workflow_dispatch"));
            return named.then(Vec::new);
        }
        Value::Map(_) => on.get("workflow_dispatch")?,
        Value::Null => return None,
    };
    let Some(Value::Map(inputs)) = dispatch.get("inputs") else {
        return Some(Vec::new());
    };
    let text = |v: &Value, key: &str| v.get(key).and_then(Value::text).map(str::to_owned);
    let inputs = inputs.iter().map(|(name, spec)| {
        let kind = match text(spec, "type").as_deref() {
            Some("choice") => {
                let options = spec.get("options").map(Value::names).unwrap_or_default();
                InputKind::Choice(options)
            }
            Some("boolean") => InputKind::Boolean,
            _ => InputKind::Text,
        };
        Input {
            name: name.clone(),
            description: text(spec, "description").unwrap_or_default(),
            default: text(spec, "default"),
            required: spec.get("required").and_then(Value::text) == Some("true"),
            kind,
        }
    });
    Some(inputs.collect())
}

/// Annotations as GraphQL has them, on a check run.
#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "CheckAnnotationConnection")]
pub struct WireAnnotations {
    pub total_count: i32,
    pub nodes: Option<Vec<Option<WireAnnotation>>>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "CheckAnnotation")]
pub struct WireAnnotation {
    pub path: String,
    pub blob_url: crate::api::queries::Uri,
    pub location: WireSpan,
    pub annotation_level: Option<Level>,
    pub title: Option<String>,
    pub message: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "CheckAnnotationSpan")]
pub struct WireSpan {
    pub start: WirePosition,
    pub end: WirePosition,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "CheckAnnotationPosition")]
pub struct WirePosition {
    pub line: i32,
}

impl WireAnnotations {
    pub fn into_capped(self) -> Capped<Annotation> {
        Capped::from_nodes(self.total_count, self.nodes, |a| {
            Annotation::new(Raw {
                path: a.path,
                start: a.location.start.line.into(),
                end: a.location.end.line.into(),
                level: a.annotation_level.unwrap_or(Level::Notice),
                title: a.title.unwrap_or_default(),
                message: a.message,
                blob: a.blob_url.0,
            })
        })
    }
}

/// REST's shapes.
mod rest {
    use serde::Deserialize;

    #[derive(Deserialize)]
    pub struct Annotation {
        pub path: String,
        pub blob_href: String,
        pub start_line: i64,
        pub end_line: i64,
        pub annotation_level: String,
        pub title: Option<String>,
        pub message: String,
    }

    #[derive(Deserialize)]
    pub struct CheckRun {
        pub output: Output,
    }

    #[derive(Deserialize)]
    pub struct Output {
        pub annotations_count: u64,
    }

    #[derive(Deserialize)]
    pub struct Artifacts {
        pub total_count: u64,
        pub artifacts: Vec<Artifact>,
    }

    #[derive(Deserialize)]
    pub struct Artifact {
        pub id: u64,
        pub name: String,
        pub size_in_bytes: u64,
        pub expires_at: Option<String>,
        pub expired: bool,
    }

    #[derive(Deserialize)]
    pub struct Dispatched {
        pub workflow_run_id: Option<u64>,
    }
}

/// How many of a job's annotations are fetched.
const ANNOTATIONS: u64 = 50;
/// How many of a run's artifacts are fetched.
const ARTIFACTS: u64 = 100;

impl GitHub {
    /// A job's annotations (an Actions job is a check run), worst first.
    pub async fn job_annotations(
        &self,
        repo: &RepoId,
        job: u64,
    ) -> Result<Capped<Annotation>, ApiError> {
        let base = format!("/repos/{}/{}/check-runs/{job}", repo.owner, repo.name);
        let what = format!("{repo}'s check run {job}");
        let run: rest::CheckRun = serde_json::from_str(&self.rest_get(&base, &what).await?)?;
        let total = run.output.annotations_count;
        if total == 0 {
            return Ok(Capped::default());
        }
        let path = format!("{base}/annotations?per_page={ANNOTATIONS}");
        let wire: Vec<rest::Annotation> =
            serde_json::from_str(&self.rest_get(&path, &what).await?)?;
        let list = wire.into_iter().map(|a| {
            let level = match a.annotation_level.as_str() {
                "failure" => Level::Failure,
                "warning" => Level::Warning,
                _ => Level::Notice,
            };
            Annotation::new(Raw {
                path: a.path,
                start: a.start_line,
                end: a.end_line,
                level,
                title: a.title.unwrap_or_default(),
                message: a.message,
                blob: a.blob_href,
            })
        });
        Ok(Capped::new(sorted(list.collect()), total))
    }

    /// A run's artifacts, newest first.
    pub async fn artifacts(&self, repo: &RepoId, run: u64) -> Result<Capped<Artifact>, ApiError> {
        let path = format!(
            "/repos/{}/{}/actions/runs/{run}/artifacts?per_page={ARTIFACTS}",
            repo.owner, repo.name
        );
        let wire: rest::Artifacts = serde_json::from_str(
            &self
                .rest_get(&path, format!("run {run}'s artifacts"))
                .await?,
        )?;
        let items = wire.artifacts.into_iter().map(|a| Artifact {
            id: a.id,
            name: a.name,
            size: a.size_in_bytes,
            expires_at: a.expires_at,
            expired: a.expired,
        });
        Ok(Capped::new(items.collect(), wire.total_count))
    }

    /// Saves artifact `id` (a zip) to `dest`, replacing what's there only
    /// if `replace`; its size.
    pub async fn download_artifact(
        &self,
        repo: &RepoId,
        id: u64,
        dest: &std::path::Path,
        replace: bool,
    ) -> Result<u64, ApiError> {
        let path = format!(
            "/repos/{}/{}/actions/artifacts/{id}/zip",
            repo.owner, repo.name
        );
        self.download(&path, dest, replace).await
    }

    /// Runs workflow `file` by hand on `git_ref` with `inputs`: the new
    /// run's ID, where GitHub says it (github.com does; an older
    /// Enterprise Server doesn't).
    pub async fn dispatch(
        &self,
        repo: &RepoId,
        file: &str,
        git_ref: &str,
        inputs: &[(String, String)],
    ) -> Result<Option<u64>, ApiError> {
        let path = format!(
            "/repos/{}/{}/actions/workflows/{}/dispatches",
            repo.owner,
            repo.name,
            crate::ui::pages::url::encode_path(file)
        );
        let inputs: serde_json::Map<String, serde_json::Value> = (inputs.iter())
            .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
            .collect();
        let body = serde_json::json!({
            "ref": git_ref,
            "inputs": inputs,
            "return_run_details": true,
        });
        let answer = self
            .rest_write_answer(http::Method::POST, &path, Some(&body))
            .await?;
        if answer.trim().is_empty() {
            return Ok(None);
        }
        let dispatched: rest::Dispatched = serde_json::from_str(&answer)?;
        Ok(dispatched.workflow_run_id)
    }
}

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

    /// Inputs are read from the workflow file as GitHub reads them:
    /// choices with their options, booleans, text, and defaults.
    #[test]
    fn dispatch_inputs_come_from_the_workflow_file() {
        let file = "name: actions\non:\n  workflow_dispatch:\n    inputs:\n      outcome:\n        description: How the job ends\n        type: choice\n        options: [fail, pass]\n        default: fail\n      seconds:\n        type: string\n        default: \"60\"\n        required: true\n      summary:\n        type: boolean\n  push:\njobs: {}\n";
        let inputs = dispatch_inputs(file).unwrap();
        let names: Vec<&str> = inputs.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(names, ["outcome", "seconds", "summary"]);
        assert_eq!(
            inputs[0].kind,
            InputKind::Choice(vec!["fail".into(), "pass".into()])
        );
        assert_eq!(inputs[0].description, "How the job ends");
        assert_eq!(inputs[1].start(), "60");
        assert!(inputs[1].required);
        assert_eq!(
            (&inputs[2].kind, inputs[2].start().as_str()),
            (&InputKind::Boolean, "false")
        );
        assert_eq!(
            dispatch_inputs("on: [push, workflow_dispatch]\n"),
            Some(Vec::new())
        );
        assert_eq!(dispatch_inputs("on: push\n"), None);
    }
}