splashboard 2.10.2

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
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
//! `gitlab_pipeline_status` — current pipeline state for a GitLab project as a single badge,
//! optional text line, or `Entries` rollup (status / branch / sha / duration). Uses
//! `/api/v4/projects/{id}/pipelines?per_page=1[&ref=<branch>]`.

use async_trait::async_trait;
use serde::Deserialize;
use url::form_urlencoded::byte_serialize;

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::{default_host, rest_get};
use super::common::{ProjectPath, cache_key, parse_options, payload, resolve_project};
use super::my_mrs::resolve_host;

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

const OPTION_SCHEMAS: &[OptionSchema] = &[
    OptionSchema {
        name: "host",
        type_hint: "hostname",
        required: false,
        default: Some("gitlab.com"),
        description: "GitLab instance host. Use this for self-hosted GitLab.",
    },
    OptionSchema {
        name: "project",
        type_hint: "\"group/name\" or \"group/sub/name\"",
        required: false,
        default: Some("git remote of cwd"),
        description: "Project to query. Falls back to the current directory's GitLab remote.",
    },
    OptionSchema {
        name: "branch",
        type_hint: "string",
        required: false,
        default: None,
        description: "Branch (ref) to filter the latest pipeline by. Omit for the most recent pipeline on any branch.",
    },
];

pub struct GitlabPipelineStatus;

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

#[async_trait]
impl Fetcher for GitlabPipelineStatus {
    fn name(&self) -> &str {
        "gitlab_pipeline_status"
    }
    fn safety(&self) -> Safety {
        Safety::Safe
    }
    fn description(&self) -> &'static str {
        "Latest CI pipeline run for a GitLab project as a pass/fail badge, short text line, or status rollup."
    }
    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 {
        cache_key(self.name(), ctx, &cache_extra(ctx))
    }
    fn sample_body(&self, shape: Shape) -> Option<Body> {
        Some(match shape {
            Shape::Badge => samples::badge(Status::Ok, "main · 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("sha", None, "abc123de"),
                    entry("duration", None, "3m 12s"),
                ],
            }),
            _ => 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 host = resolve_host(opts.host.as_deref())?;
        let project = resolve_project(opts.project.as_deref(), &host)?;
        let mut path = format!("/projects/{}/pipelines?per_page=1", project.encoded());
        if let Some(branch) = opts.branch.as_deref() {
            // Branch names can carry `&`, `=`, `#`, `+`, `?`, and slashes (release/v2,
            // feature/foo&bar). Naive interpolation rewrote the URL semantics and silently
            // returned the wrong pipeline; percent-encode so the value stays a single
            // `ref=<branch>` pair.
            let encoded: String = byte_serialize(branch.as_bytes()).collect();
            path.push_str(&format!("&ref={encoded}"));
        }
        let pipelines: Vec<Pipeline> = rest_get(&host, &path).await?;
        let shape = ctx.shape.unwrap_or(Shape::Badge);
        let Some(latest) = pipelines.into_iter().next() else {
            return Ok(payload(no_runs_body(shape)));
        };
        Ok(payload(render_body(&latest, 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("sha", None, "?"),
                entry("duration", None, "?"),
            ],
        }),
        _ => Body::Badge(BadgeData {
            status: Status::Warn,
            label: "no runs".into(),
        }),
    }
}

#[derive(Debug, Deserialize)]
struct Pipeline {
    #[serde(default)]
    status: String,
    #[serde(default, rename = "ref")]
    branch: Option<String>,
    #[serde(default)]
    sha: Option<String>,
    #[serde(default)]
    duration: Option<u64>,
}

fn render_body(p: &Pipeline, shape: Shape) -> Body {
    let (status, label_word) = classify(&p.status);
    let branch = p.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("sha", None, &short_sha(p.sha.as_deref())),
                entry("duration", None, &format_duration(p.duration)),
            ],
        }),
        _ => Body::Badge(BadgeData {
            status,
            label: format!("{branch} · {label_word}"),
        }),
    }
}

fn classify(raw: &str) -> (Status, &'static str) {
    match raw {
        "success" => (Status::Ok, "passing"),
        "failed" => (Status::Error, "failing"),
        "canceled" => (Status::Warn, "cancelled"),
        "skipped" => (Status::Warn, "skipped"),
        "manual" => (Status::Warn, "manual"),
        "running" | "pending" | "created" | "waiting_for_resource" | "preparing" => {
            (Status::Warn, "running")
        }
        _ => (Status::Warn, "unknown"),
    }
}

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

fn short_sha(sha: Option<&str>) -> String {
    sha.unwrap_or("?").chars().take(8).collect::<String>()
}

fn format_duration(seconds: Option<u64>) -> String {
    let Some(s) = seconds else {
        return "?".into();
    };
    let m = s / 60;
    let r = s % 60;
    if m == 0 {
        format!("{r}s")
    } else {
        format!("{m}m {r:02}s")
    }
}

fn cache_extra(ctx: &FetchContext) -> String {
    let host = ctx
        .options
        .as_ref()
        .and_then(|v| v.get("host"))
        .and_then(|v| v.as_str())
        .unwrap_or(default_host())
        .to_string();
    let project = ctx
        .options
        .as_ref()
        .and_then(|v| v.get("project"))
        .and_then(|v| v.as_str())
        .map(String::from)
        .or_else(|| {
            resolve_project(None, &host)
                .ok()
                .map(|p: ProjectPath| p.as_str().to_string())
        })
        .unwrap_or_default();
    let branch = ctx
        .options
        .as_ref()
        .and_then(|v| v.get("branch"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    format!("{host}|{project}|{branch}")
}

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

    use super::*;

    fn pipeline(status: &str) -> Pipeline {
        Pipeline {
            status: status.into(),
            branch: Some("main".into()),
            sha: Some("abc123def456".into()),
            duration: Some(192),
        }
    }

    #[test]
    fn options_deserialize_all_fields() {
        let opts: Options =
            toml::from_str("host = \"git.example.org\"\nproject = \"g/p\"\nbranch = \"main\"")
                .unwrap();
        assert_eq!(opts.host.as_deref(), Some("git.example.org"));
        assert_eq!(opts.project.as_deref(), Some("g/p"));
        assert_eq!(opts.branch.as_deref(), Some("main"));
        assert!(toml::from_str::<Options>("bogus = 1").is_err());
    }

    #[test]
    fn shapes_table_lists_the_three_supported_variants() {
        let fetcher = GitlabPipelineStatus;
        assert_eq!(
            fetcher.shapes(),
            &[Shape::Badge, Shape::Text, Shape::Entries]
        );
        assert_eq!(fetcher.default_shape(), Shape::Badge);
    }

    #[test]
    fn classify_maps_each_documented_state() {
        for (raw, expected) in [
            ("success", Status::Ok),
            ("failed", Status::Error),
            ("canceled", Status::Warn),
            ("skipped", Status::Warn),
            ("manual", Status::Warn),
            ("running", Status::Warn),
            ("pending", Status::Warn),
            ("created", Status::Warn),
            ("waiting_for_resource", Status::Warn),
            ("preparing", Status::Warn),
            ("totally_unknown", Status::Warn),
        ] {
            assert_eq!(classify(raw).0, expected, "raw={raw}");
        }
    }

    #[test]
    fn render_badge_uses_branch_and_label_word() {
        let Body::Badge(b) = render_body(&pipeline("success"), Shape::Badge) else {
            panic!("expected badge");
        };
        assert_eq!(b.status, Status::Ok);
        assert_eq!(b.label, "main · passing");
    }

    #[test]
    fn render_text_falls_back_to_question_mark_for_missing_branch() {
        let mut p = pipeline("success");
        p.branch = None;
        let Body::Text(t) = render_body(&p, Shape::Text) else {
            panic!("expected text");
        };
        assert_eq!(t.value, "? · passing");
    }

    #[test]
    fn render_entries_carries_status_branch_sha_duration() {
        let Body::Entries(e) = render_body(&pipeline("failed"), Shape::Entries) else {
            panic!("expected entries");
        };
        assert_eq!(e.items[0].key, "status");
        assert_eq!(e.items[0].status, Some(Status::Error));
        assert_eq!(e.items[0].value.as_deref(), Some("failing"));
        assert_eq!(e.items[2].value.as_deref(), Some("abc123de"));
        assert_eq!(e.items[3].value.as_deref(), Some("3m 12s"));
    }

    #[test]
    fn short_sha_truncates_long_hexes_and_falls_back() {
        assert_eq!(short_sha(Some("abcdef1234567890")), "abcdef12");
        assert_eq!(short_sha(None), "?");
    }

    #[test]
    fn format_duration_renders_seconds_only_or_minutes_seconds() {
        assert_eq!(format_duration(Some(45)), "45s");
        assert_eq!(format_duration(Some(192)), "3m 12s");
        assert_eq!(format_duration(Some(60)), "1m 00s");
        assert_eq!(format_duration(None), "?");
    }

    #[test]
    fn byte_serialize_handles_reserved_branch_characters() {
        // Pin the encoding so a future url-crate version that loosens this set fails the
        // test rather than silently shipping a request that the GitLab API misroutes.
        let cases = [
            ("main", "main"),
            ("release/v2", "release%2Fv2"),
            ("feature/foo&bar", "feature%2Ffoo%26bar"),
            ("name=weird", "name%3Dweird"),
            ("with spaces", "with+spaces"),
        ];
        for (raw, expected) in cases {
            let actual: String = byte_serialize(raw.as_bytes()).collect();
            assert_eq!(actual, expected, "raw={raw}");
        }
    }

    #[test]
    fn no_runs_body_respects_each_advertised_shape() {
        // Empty pipeline list used to always degrade to Badge regardless of `ctx.shape`,
        // breaking shape consistency for Text / Entries consumers.
        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.len(), 4);
        assert_eq!(e.items[0].value.as_deref(), Some("no runs"));
        assert_eq!(e.items[0].status, Some(Status::Warn));
    }

    #[test]
    fn sample_entries_carries_the_four_rollup_rows() {
        let Some(Body::Entries(e)) = GitlabPipelineStatus.sample_body(Shape::Entries) else {
            panic!("expected entries");
        };
        let keys: Vec<&str> = e.items.iter().map(|i| i.key.as_str()).collect();
        assert_eq!(keys, vec!["status", "branch", "sha", "duration"]);
    }

    #[test]
    fn sample_badge_and_text_carry_the_passing_headline() {
        let Some(Body::Badge(b)) = GitlabPipelineStatus.sample_body(Shape::Badge) else {
            panic!("expected badge");
        };
        assert_eq!(b.status, Status::Ok);
        assert_eq!(b.label, "main · passing");
        let Some(Body::Text(t)) = GitlabPipelineStatus.sample_body(Shape::Text) else {
            panic!("expected text");
        };
        assert_eq!(t.value, "main · passing");
    }

    #[test]
    fn sample_body_returns_none_for_unsupported_shape() {
        assert!(GitlabPipelineStatus.sample_body(Shape::Ratio).is_none());
    }

    #[test]
    fn metadata_methods_have_content() {
        let fetcher = GitlabPipelineStatus;
        assert_eq!(fetcher.name(), "gitlab_pipeline_status");
        assert_eq!(fetcher.safety(), Safety::Safe);
        assert!(fetcher.description().contains("GitLab"));
        assert_eq!(fetcher.refresh_interval(), 60 * 5);
    }

    #[test]
    fn option_schemas_lists_host_project_and_branch() {
        let names: Vec<&str> = GitlabPipelineStatus
            .option_schemas()
            .iter()
            .map(|s| s.name)
            .collect();
        assert_eq!(names, vec!["host", "project", "branch"]);
    }

    #[test]
    fn cache_key_is_name_prefixed_and_varies_with_project_option() {
        let fetcher = GitlabPipelineStatus;
        let a = fetcher.cache_key(&FetchContext {
            options: Some(toml::from_str("project = \"a/b\"").unwrap()),
            ..Default::default()
        });
        let b = fetcher.cache_key(&FetchContext {
            options: Some(toml::from_str("project = \"a/c\"").unwrap()),
            ..Default::default()
        });
        assert!(a.starts_with("gitlab_pipeline_status-"));
        assert_ne!(a, b);
    }

    #[test]
    fn cache_key_varies_with_host_and_branch_options() {
        let fetcher = GitlabPipelineStatus;
        let base = fetcher.cache_key(&FetchContext {
            options: Some(toml::from_str("host = \"git.one.org\"\nproject = \"a/b\"").unwrap()),
            ..Default::default()
        });
        let other_host = fetcher.cache_key(&FetchContext {
            options: Some(toml::from_str("host = \"git.two.org\"\nproject = \"a/b\"").unwrap()),
            ..Default::default()
        });
        let with_branch = fetcher.cache_key(&FetchContext {
            options: Some(
                toml::from_str("host = \"git.one.org\"\nproject = \"a/b\"\nbranch = \"dev\"")
                    .unwrap(),
            ),
            ..Default::default()
        });
        assert_ne!(base, other_host);
        assert_ne!(base, with_branch);
    }

    #[test]
    fn cache_key_with_no_options_falls_back_to_remote_resolution() {
        // No `project` option: `cache_extra` walks the cwd git remote, which here is a GitHub
        // repo, so the gitlab.com lookup yields nothing and the key still resolves cleanly.
        let key = GitlabPipelineStatus.cache_key(&FetchContext::default());
        assert!(key.starts_with("gitlab_pipeline_status-"));
    }

    #[tokio::test]
    async fn fetch_rejects_unknown_option_keys_before_network_request() {
        let err = GitlabPipelineStatus
            .fetch(&FetchContext {
                options: Some(toml::from_str("bogus = 1").unwrap()),
                timeout: Duration::from_secs(1),
                ..Default::default()
            })
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            FetchError::Failed(m) if m.contains("invalid options")
        ));
    }

    #[tokio::test]
    async fn fetch_rejects_invalid_host_before_network_request() {
        let err = GitlabPipelineStatus
            .fetch(&FetchContext {
                options: Some(toml::from_str("host = \"https://evil.example\"").unwrap()),
                timeout: Duration::from_secs(1),
                ..Default::default()
            })
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            FetchError::Failed(m) if m.contains("invalid gitlab host")
        ));
    }

    #[tokio::test]
    async fn fetch_rejects_invalid_project_before_network_request() {
        let err = GitlabPipelineStatus
            .fetch(&FetchContext {
                options: Some(toml::from_str("project = \"not a path\"").unwrap()),
                timeout: Duration::from_secs(1),
                ..Default::default()
            })
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            FetchError::Failed(m) if m.contains("invalid project option")
        ));
    }
}