splashboard 2.10.0

A customizable terminal splash screen with plugin-based data sources
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
//! `github_action_status` — current CI state for a repo, as a single badge plus optional
//! `Text` summary. Uses the latest workflow run across every workflow.

use async_trait::async_trait;
use serde::Deserialize;

use crate::options::OptionSchema;
use crate::payload::{BadgeData, Body, EntriesData, Entry, Payload, Status, TextData};
use crate::render::Shape;
use crate::samples;

use super::super::{FetchContext, FetchError, Fetcher, Safety};
use super::client::rest_get;
use super::common::{RepoSlug, cache_key, parse_options, payload, resolve_repo};

const SHAPES: &[Shape] = &[Shape::Badge, Shape::Text, Shape::Entries];

const OPTION_SCHEMAS: &[OptionSchema] = &[
    OptionSchema {
        name: "repo",
        type_hint: "\"owner/name\"",
        required: false,
        default: Some("git remote of cwd"),
        description: "Repository to query.",
    },
    OptionSchema {
        name: "branch",
        type_hint: "string",
        required: false,
        default: None,
        description: "Branch to filter the latest run by. Omit for the most recent run on any branch.",
    },
];

pub struct GithubActionStatus;

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Options {
    #[serde(default)]
    pub repo: Option<String>,
    #[serde(default)]
    pub branch: Option<String>,
}

#[async_trait]
impl Fetcher for GithubActionStatus {
    fn name(&self) -> &str {
        "github_action_status"
    }
    fn safety(&self) -> Safety {
        Safety::Safe
    }
    fn description(&self) -> &'static str {
        "The latest CI workflow run for a repo as a pass/fail badge or short text line. Use `github_action_history` for a series of recent runs rather than the single most recent one."
    }
    fn refresh_interval(&self) -> u64 {
        60 * 5
    }
    fn shapes(&self) -> &[Shape] {
        SHAPES
    }
    fn default_shape(&self) -> Shape {
        Shape::Badge
    }
    fn option_schemas(&self) -> &[OptionSchema] {
        OPTION_SCHEMAS
    }
    fn cache_key(&self, ctx: &FetchContext) -> String {
        let extra = repo_for_key(ctx);
        cache_key(self.name(), ctx, &extra)
    }
    fn sample_body(&self, shape: Shape) -> Option<Body> {
        Some(match shape {
            Shape::Badge => samples::badge(Status::Ok, "ci passing"),
            Shape::Text => samples::text("main · passing"),
            Shape::Entries => Body::Entries(EntriesData {
                items: vec![
                    entry("status", Some(Status::Ok), "passing"),
                    entry("branch", None, "main"),
                    entry("conclusion", None, "success"),
                ],
            }),
            _ => return None,
        })
    }
    async fn fetch(&self, ctx: &FetchContext) -> Result<Payload, FetchError> {
        let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?;
        let slug = resolve_repo(opts.repo.as_deref())?;
        let mut path = format!(
            "/repos/{}/{}/actions/runs?per_page=1",
            slug.owner, slug.name
        );
        if let Some(branch) = opts.branch.as_deref() {
            path.push_str(&format!("&branch={branch}"));
        }
        let res: RunsResponse = rest_get(&path).await?;
        let shape = ctx.shape.unwrap_or(Shape::Badge);
        let Some(run) = res.workflow_runs.into_iter().next() else {
            return Ok(payload(no_runs_body(shape)));
        };
        Ok(payload(render_body(&run, shape)))
    }
}

fn no_runs_body(shape: Shape) -> Body {
    match shape {
        Shape::Text => Body::Text(TextData {
            value: "no runs".into(),
        }),
        Shape::Entries => Body::Entries(EntriesData {
            items: vec![
                entry("status", Some(Status::Warn), "no runs"),
                entry("branch", None, "?"),
                entry("conclusion", None, "?"),
            ],
        }),
        _ => Body::Badge(BadgeData {
            status: Status::Warn,
            label: "no runs".into(),
        }),
    }
}

#[derive(Debug, Deserialize)]
struct RunsResponse {
    #[serde(default)]
    workflow_runs: Vec<WorkflowRun>,
}

#[derive(Debug, Deserialize)]
struct WorkflowRun {
    #[serde(default)]
    status: String,
    #[serde(default)]
    conclusion: Option<String>,
    #[serde(default)]
    head_branch: Option<String>,
}

fn render_body(run: &WorkflowRun, shape: Shape) -> Body {
    let (status, label_word) = classify(run);
    let branch = run.head_branch.as_deref().unwrap_or("?");
    match shape {
        Shape::Text => Body::Text(TextData {
            value: format!("{branch} · {label_word}"),
        }),
        Shape::Entries => Body::Entries(EntriesData {
            items: vec![
                entry("status", Some(status), label_word),
                entry("branch", None, branch),
                entry("conclusion", None, run.conclusion.as_deref().unwrap_or("?")),
            ],
        }),
        _ => Body::Badge(BadgeData {
            status,
            label: format!("{branch} · {label_word}"),
        }),
    }
}

fn entry(key: &str, status: Option<Status>, value: &str) -> Entry {
    Entry {
        key: key.into(),
        value: Some(value.into()),
        status,
    }
}

fn classify(run: &WorkflowRun) -> (Status, &'static str) {
    if run.status == "completed" {
        match run.conclusion.as_deref() {
            Some("success") => (Status::Ok, "passing"),
            Some("failure") | Some("timed_out") | Some("startup_failure") => {
                (Status::Error, "failing")
            }
            Some("cancelled") => (Status::Warn, "cancelled"),
            Some("neutral") | Some("skipped") => (Status::Warn, "skipped"),
            _ => (Status::Warn, "completed"),
        }
    } else {
        (Status::Warn, "running")
    }
}

fn repo_for_key(ctx: &FetchContext) -> String {
    ctx.options
        .as_ref()
        .and_then(|v| v.get("repo"))
        .and_then(|v| v.as_str())
        .map(String::from)
        .or_else(|| resolve_repo(None).ok().map(|s: RepoSlug| s.as_path()))
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    fn run(status: &str, conclusion: Option<&str>) -> WorkflowRun {
        WorkflowRun {
            status: status.into(),
            conclusion: conclusion.map(String::from),
            head_branch: Some("main".into()),
        }
    }

    fn run_with_branch(
        status: &str,
        conclusion: Option<&str>,
        head_branch: Option<&str>,
    ) -> WorkflowRun {
        WorkflowRun {
            status: status.into(),
            conclusion: conclusion.map(String::from),
            head_branch: head_branch.map(String::from),
        }
    }

    fn ctx(options: Option<&str>, shape: Option<Shape>) -> FetchContext {
        FetchContext {
            widget_id: "ci".into(),
            format: Some("compact".into()),
            timeout: Duration::from_secs(1),
            file_format: None,
            shape,
            options: options.map(|raw| toml::from_str(raw).unwrap()),
            timezone: None,
            locale: None,
        }
    }

    #[test]
    fn options_default_to_none() {
        let opts = Options::default();
        assert!(opts.repo.is_none());
        assert!(opts.branch.is_none());
    }

    #[test]
    fn options_deserialize_repo_and_branch() {
        let raw: toml::Value = toml::from_str("repo = \"foo/bar\"\nbranch = \"main\"").unwrap();
        let opts: Options = raw.try_into().unwrap();
        assert_eq!(opts.repo.as_deref(), Some("foo/bar"));
        assert_eq!(opts.branch.as_deref(), Some("main"));
    }

    #[test]
    fn options_reject_unknown_keys() {
        let raw: toml::Value = toml::from_str("repo = \"foo/bar\"\nbogus = true").unwrap();
        assert!(raw.try_into::<Options>().is_err());
    }

    #[test]
    fn fetcher_metadata_and_samples_cover_supported_shapes() {
        let fetcher = GithubActionStatus;
        assert_eq!(fetcher.name(), "github_action_status");
        assert_eq!(fetcher.safety(), Safety::Safe);
        assert!(fetcher.description().contains("latest CI workflow run"));
        assert_eq!(fetcher.shapes(), SHAPES);
        assert_eq!(fetcher.default_shape(), Shape::Badge);
        assert_eq!(fetcher.option_schemas().len(), 2);

        let Some(Body::Badge(badge)) = fetcher.sample_body(Shape::Badge) else {
            panic!("expected badge sample");
        };
        assert_eq!(badge.status, Status::Ok);
        assert_eq!(badge.label, "ci passing");

        let Some(Body::Text(text)) = fetcher.sample_body(Shape::Text) else {
            panic!("expected text sample");
        };
        assert_eq!(text.value, "main · passing");

        let Some(Body::Entries(e)) = fetcher.sample_body(Shape::Entries) else {
            panic!("expected entries sample");
        };
        let keys: Vec<&str> = e.items.iter().map(|i| i.key.as_str()).collect();
        assert_eq!(keys, vec!["status", "branch", "conclusion"]);
        assert!(fetcher.sample_body(Shape::Timeline).is_none());
    }

    #[test]
    fn completed_success_is_ok() {
        assert_eq!(classify(&run("completed", Some("success"))).0, Status::Ok);
    }

    #[test]
    fn completed_failure_is_error() {
        assert_eq!(
            classify(&run("completed", Some("failure"))).0,
            Status::Error
        );
    }

    #[test]
    fn in_progress_is_warn() {
        assert_eq!(classify(&run("in_progress", None)).0, Status::Warn);
    }

    #[test]
    fn completed_timed_out_and_startup_failure_are_errors() {
        ["timed_out", "startup_failure"]
            .into_iter()
            .for_each(|conclusion| {
                assert_eq!(
                    classify(&run("completed", Some(conclusion))),
                    (Status::Error, "failing")
                );
            });
    }

    #[test]
    fn completed_cancelled_and_skipped_stay_warn() {
        ["cancelled", "neutral", "skipped"]
            .into_iter()
            .map(|conclusion| (conclusion, classify(&run("completed", Some(conclusion)))))
            .for_each(|(conclusion, actual)| {
                let expected = if conclusion == "cancelled" {
                    (Status::Warn, "cancelled")
                } else {
                    (Status::Warn, "skipped")
                };
                assert_eq!(actual, expected);
            });
    }

    #[test]
    fn completed_unknown_conclusion_falls_back_to_completed() {
        assert_eq!(
            classify(&run("completed", Some("action_required"))),
            (Status::Warn, "completed")
        );
        assert_eq!(
            classify(&run("completed", None)),
            (Status::Warn, "completed")
        );
    }

    #[test]
    fn render_badge_uses_branch_and_classified_label() {
        let body = render_body(&run("completed", Some("cancelled")), Shape::Badge);
        let Body::Badge(badge) = body else {
            panic!("expected badge");
        };
        assert_eq!(badge.status, Status::Warn);
        assert_eq!(badge.label, "main · cancelled");
    }

    #[test]
    fn no_runs_body_respects_each_advertised_shape() {
        // Empty workflow_runs used to always degrade to Badge regardless of `ctx.shape`,
        // breaking shape consistency once Entries was advertised in #243.
        let Body::Badge(b) = no_runs_body(Shape::Badge) else {
            panic!("expected badge");
        };
        assert_eq!(b.label, "no runs");
        let Body::Text(t) = no_runs_body(Shape::Text) else {
            panic!("expected text");
        };
        assert_eq!(t.value, "no runs");
        let Body::Entries(e) = no_runs_body(Shape::Entries) else {
            panic!("expected entries");
        };
        assert_eq!(e.items[0].value.as_deref(), Some("no runs"));
        assert_eq!(e.items[0].status, Some(Status::Warn));
    }

    #[test]
    fn render_entries_lists_classified_status_branch_and_conclusion() {
        assert!(matches!(
            render_body(&run("completed", Some("failure")), Shape::Entries),
            Body::Entries(e)
                if e.items.len() == 3
                    && e.items[0].key == "status"
                    && e.items[0].status == Some(Status::Error)
                    && e.items[0].value.as_deref() == Some("failing")
                    && e.items[1].key == "branch"
                    && e.items[1].status.is_none()
                    && e.items[1].value.as_deref() == Some("main")
                    && e.items[2].key == "conclusion"
                    && e.items[2].value.as_deref() == Some("failure"),
        ));
    }

    #[test]
    fn render_entries_conclusion_falls_back_to_question_mark_when_absent() {
        // A still-running workflow has no `conclusion`; the Entries row must degrade to `?`
        // rather than carry an empty string.
        assert!(matches!(
            render_body(&run("in_progress", None), Shape::Entries),
            Body::Entries(e)
                if e.items[0].value.as_deref() == Some("running")
                    && e.items[0].status == Some(Status::Warn)
                    && e.items[2].key == "conclusion"
                    && e.items[2].value.as_deref() == Some("?"),
        ));
    }

    #[test]
    fn render_text_falls_back_to_question_mark_for_missing_branch() {
        let body = render_body(
            &run_with_branch("completed", Some("success"), None),
            Shape::Text,
        );
        let Body::Text(text) = body else {
            panic!("expected text");
        };
        assert_eq!(text.value, "? · passing");
    }

    #[test]
    fn repo_for_key_prefers_explicit_repo_option() {
        assert_eq!(
            repo_for_key(&ctx(Some("repo = \"foo/bar\""), Some(Shape::Badge))),
            "foo/bar"
        );
    }

    #[test]
    fn repo_for_key_falls_back_to_resolved_repo() {
        let _lock = crate::paths::TEST_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        assert_eq!(
            repo_for_key(&ctx(None, Some(Shape::Badge))),
            resolve_repo(None).unwrap().as_path()
        );
    }

    #[test]
    fn cache_key_changes_with_repo_option() {
        let fetcher = GithubActionStatus;
        let a = fetcher.cache_key(&ctx(Some("repo = \"foo/bar\""), Some(Shape::Badge)));
        let b = fetcher.cache_key(&ctx(Some("repo = \"foo/baz\""), Some(Shape::Badge)));
        assert_ne!(a, b);
    }
}