|
| 1 | +//! `gitlab_pipeline_status` — current pipeline state for a GitLab project as a single badge, |
| 2 | +//! optional text line, or `Entries` rollup (status / branch / sha / duration). Uses |
| 3 | +//! `/api/v4/projects/{id}/pipelines?per_page=1[&ref=<branch>]`. |
| 4 | +
|
| 5 | +use async_trait::async_trait; |
| 6 | +use serde::Deserialize; |
| 7 | + |
| 8 | +use crate::options::OptionSchema; |
| 9 | +use crate::payload::{BadgeData, Body, EntriesData, Entry, Payload, Status, TextData}; |
| 10 | +use crate::render::Shape; |
| 11 | +use crate::samples; |
| 12 | + |
| 13 | +use super::super::{FetchContext, FetchError, Fetcher, Safety}; |
| 14 | +use super::client::{default_host, rest_get}; |
| 15 | +use super::common::{ProjectPath, cache_key, parse_options, payload, resolve_project}; |
| 16 | +use super::my_mrs::resolve_host; |
| 17 | + |
| 18 | +const SHAPES: &[Shape] = &[Shape::Badge, Shape::Text, Shape::Entries]; |
| 19 | + |
| 20 | +const OPTION_SCHEMAS: &[OptionSchema] = &[ |
| 21 | + OptionSchema { |
| 22 | + name: "host", |
| 23 | + type_hint: "hostname", |
| 24 | + required: false, |
| 25 | + default: Some("gitlab.com"), |
| 26 | + description: "GitLab instance host. Use this for self-hosted GitLab.", |
| 27 | + }, |
| 28 | + OptionSchema { |
| 29 | + name: "project", |
| 30 | + type_hint: "\"group/name\" or \"group/sub/name\"", |
| 31 | + required: false, |
| 32 | + default: Some("git remote of cwd"), |
| 33 | + description: "Project to query. Falls back to the current directory's GitLab remote.", |
| 34 | + }, |
| 35 | + OptionSchema { |
| 36 | + name: "branch", |
| 37 | + type_hint: "string", |
| 38 | + required: false, |
| 39 | + default: None, |
| 40 | + description: "Branch (ref) to filter the latest pipeline by. Omit for the most recent pipeline on any branch.", |
| 41 | + }, |
| 42 | +]; |
| 43 | + |
| 44 | +pub struct GitlabPipelineStatus; |
| 45 | + |
| 46 | +#[derive(Debug, Default, Deserialize)] |
| 47 | +#[serde(deny_unknown_fields)] |
| 48 | +pub struct Options { |
| 49 | + #[serde(default)] |
| 50 | + pub host: Option<String>, |
| 51 | + #[serde(default)] |
| 52 | + pub project: Option<String>, |
| 53 | + #[serde(default)] |
| 54 | + pub branch: Option<String>, |
| 55 | +} |
| 56 | + |
| 57 | +#[async_trait] |
| 58 | +impl Fetcher for GitlabPipelineStatus { |
| 59 | + fn name(&self) -> &str { |
| 60 | + "gitlab_pipeline_status" |
| 61 | + } |
| 62 | + fn safety(&self) -> Safety { |
| 63 | + Safety::Safe |
| 64 | + } |
| 65 | + fn description(&self) -> &'static str { |
| 66 | + "Latest CI pipeline run for a GitLab project as a pass/fail badge, short text line, or status rollup." |
| 67 | + } |
| 68 | + fn refresh_interval(&self) -> u64 { |
| 69 | + 60 * 5 |
| 70 | + } |
| 71 | + fn shapes(&self) -> &[Shape] { |
| 72 | + SHAPES |
| 73 | + } |
| 74 | + fn default_shape(&self) -> Shape { |
| 75 | + Shape::Badge |
| 76 | + } |
| 77 | + fn option_schemas(&self) -> &[OptionSchema] { |
| 78 | + OPTION_SCHEMAS |
| 79 | + } |
| 80 | + fn cache_key(&self, ctx: &FetchContext) -> String { |
| 81 | + cache_key(self.name(), ctx, &cache_extra(ctx)) |
| 82 | + } |
| 83 | + fn sample_body(&self, shape: Shape) -> Option<Body> { |
| 84 | + Some(match shape { |
| 85 | + Shape::Badge => samples::badge(Status::Ok, "main · passing"), |
| 86 | + Shape::Text => samples::text("main · passing"), |
| 87 | + Shape::Entries => Body::Entries(EntriesData { |
| 88 | + items: vec![ |
| 89 | + entry("status", Some(Status::Ok), "passing"), |
| 90 | + entry("branch", None, "main"), |
| 91 | + entry("sha", None, "abc123de"), |
| 92 | + entry("duration", None, "3m 12s"), |
| 93 | + ], |
| 94 | + }), |
| 95 | + _ => return None, |
| 96 | + }) |
| 97 | + } |
| 98 | + async fn fetch(&self, ctx: &FetchContext) -> Result<Payload, FetchError> { |
| 99 | + let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?; |
| 100 | + let host = resolve_host(opts.host.as_deref())?; |
| 101 | + let project = resolve_project(opts.project.as_deref(), &host)?; |
| 102 | + let mut path = format!("/projects/{}/pipelines?per_page=1", project.encoded()); |
| 103 | + if let Some(branch) = opts.branch.as_deref() { |
| 104 | + path.push_str(&format!("&ref={branch}")); |
| 105 | + } |
| 106 | + let pipelines: Vec<Pipeline> = rest_get(&host, &path).await?; |
| 107 | + let shape = ctx.shape.unwrap_or(Shape::Badge); |
| 108 | + let Some(latest) = pipelines.into_iter().next() else { |
| 109 | + return Ok(payload(Body::Badge(BadgeData { |
| 110 | + status: Status::Warn, |
| 111 | + label: "no runs".into(), |
| 112 | + }))); |
| 113 | + }; |
| 114 | + Ok(payload(render_body(&latest, shape))) |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +#[derive(Debug, Deserialize)] |
| 119 | +struct Pipeline { |
| 120 | + #[serde(default)] |
| 121 | + status: String, |
| 122 | + #[serde(default, rename = "ref")] |
| 123 | + branch: Option<String>, |
| 124 | + #[serde(default)] |
| 125 | + sha: Option<String>, |
| 126 | + #[serde(default)] |
| 127 | + duration: Option<u64>, |
| 128 | +} |
| 129 | + |
| 130 | +fn render_body(p: &Pipeline, shape: Shape) -> Body { |
| 131 | + let (status, label_word) = classify(&p.status); |
| 132 | + let branch = p.branch.as_deref().unwrap_or("?"); |
| 133 | + match shape { |
| 134 | + Shape::Text => Body::Text(TextData { |
| 135 | + value: format!("{branch} · {label_word}"), |
| 136 | + }), |
| 137 | + Shape::Entries => Body::Entries(EntriesData { |
| 138 | + items: vec![ |
| 139 | + entry("status", Some(status), label_word), |
| 140 | + entry("branch", None, branch), |
| 141 | + entry("sha", None, &short_sha(p.sha.as_deref())), |
| 142 | + entry("duration", None, &format_duration(p.duration)), |
| 143 | + ], |
| 144 | + }), |
| 145 | + _ => Body::Badge(BadgeData { |
| 146 | + status, |
| 147 | + label: format!("{branch} · {label_word}"), |
| 148 | + }), |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +fn classify(raw: &str) -> (Status, &'static str) { |
| 153 | + match raw { |
| 154 | + "success" => (Status::Ok, "passing"), |
| 155 | + "failed" => (Status::Error, "failing"), |
| 156 | + "canceled" => (Status::Warn, "cancelled"), |
| 157 | + "skipped" => (Status::Warn, "skipped"), |
| 158 | + "manual" => (Status::Warn, "manual"), |
| 159 | + "running" | "pending" | "created" | "waiting_for_resource" | "preparing" => { |
| 160 | + (Status::Warn, "running") |
| 161 | + } |
| 162 | + _ => (Status::Warn, "unknown"), |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +fn entry(key: &str, status: Option<Status>, value: &str) -> Entry { |
| 167 | + Entry { |
| 168 | + key: key.into(), |
| 169 | + value: Some(value.into()), |
| 170 | + status, |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +fn short_sha(sha: Option<&str>) -> String { |
| 175 | + sha.unwrap_or("?").chars().take(8).collect::<String>() |
| 176 | +} |
| 177 | + |
| 178 | +fn format_duration(seconds: Option<u64>) -> String { |
| 179 | + let Some(s) = seconds else { |
| 180 | + return "?".into(); |
| 181 | + }; |
| 182 | + let m = s / 60; |
| 183 | + let r = s % 60; |
| 184 | + if m == 0 { |
| 185 | + format!("{r}s") |
| 186 | + } else { |
| 187 | + format!("{m}m {r:02}s") |
| 188 | + } |
| 189 | +} |
| 190 | + |
| 191 | +fn cache_extra(ctx: &FetchContext) -> String { |
| 192 | + let host = ctx |
| 193 | + .options |
| 194 | + .as_ref() |
| 195 | + .and_then(|v| v.get("host")) |
| 196 | + .and_then(|v| v.as_str()) |
| 197 | + .unwrap_or(default_host()) |
| 198 | + .to_string(); |
| 199 | + let project = ctx |
| 200 | + .options |
| 201 | + .as_ref() |
| 202 | + .and_then(|v| v.get("project")) |
| 203 | + .and_then(|v| v.as_str()) |
| 204 | + .map(String::from) |
| 205 | + .or_else(|| { |
| 206 | + resolve_project(None, &host) |
| 207 | + .ok() |
| 208 | + .map(|p: ProjectPath| p.as_str().to_string()) |
| 209 | + }) |
| 210 | + .unwrap_or_default(); |
| 211 | + let branch = ctx |
| 212 | + .options |
| 213 | + .as_ref() |
| 214 | + .and_then(|v| v.get("branch")) |
| 215 | + .and_then(|v| v.as_str()) |
| 216 | + .unwrap_or(""); |
| 217 | + format!("{host}|{project}|{branch}") |
| 218 | +} |
| 219 | + |
| 220 | +#[cfg(test)] |
| 221 | +mod tests { |
| 222 | + use super::*; |
| 223 | + |
| 224 | + fn pipeline(status: &str) -> Pipeline { |
| 225 | + Pipeline { |
| 226 | + status: status.into(), |
| 227 | + branch: Some("main".into()), |
| 228 | + sha: Some("abc123def456".into()), |
| 229 | + duration: Some(192), |
| 230 | + } |
| 231 | + } |
| 232 | + |
| 233 | + #[test] |
| 234 | + fn options_deserialize_all_fields() { |
| 235 | + let opts: Options = |
| 236 | + toml::from_str("host = \"git.example.org\"\nproject = \"g/p\"\nbranch = \"main\"") |
| 237 | + .unwrap(); |
| 238 | + assert_eq!(opts.host.as_deref(), Some("git.example.org")); |
| 239 | + assert_eq!(opts.project.as_deref(), Some("g/p")); |
| 240 | + assert_eq!(opts.branch.as_deref(), Some("main")); |
| 241 | + assert!(toml::from_str::<Options>("bogus = 1").is_err()); |
| 242 | + } |
| 243 | + |
| 244 | + #[test] |
| 245 | + fn shapes_table_lists_the_three_supported_variants() { |
| 246 | + let fetcher = GitlabPipelineStatus; |
| 247 | + assert_eq!( |
| 248 | + fetcher.shapes(), |
| 249 | + &[Shape::Badge, Shape::Text, Shape::Entries] |
| 250 | + ); |
| 251 | + assert_eq!(fetcher.default_shape(), Shape::Badge); |
| 252 | + } |
| 253 | + |
| 254 | + #[test] |
| 255 | + fn classify_maps_each_documented_state() { |
| 256 | + for (raw, expected) in [ |
| 257 | + ("success", Status::Ok), |
| 258 | + ("failed", Status::Error), |
| 259 | + ("canceled", Status::Warn), |
| 260 | + ("skipped", Status::Warn), |
| 261 | + ("manual", Status::Warn), |
| 262 | + ("running", Status::Warn), |
| 263 | + ("pending", Status::Warn), |
| 264 | + ("created", Status::Warn), |
| 265 | + ("waiting_for_resource", Status::Warn), |
| 266 | + ("preparing", Status::Warn), |
| 267 | + ("totally_unknown", Status::Warn), |
| 268 | + ] { |
| 269 | + assert_eq!(classify(raw).0, expected, "raw={raw}"); |
| 270 | + } |
| 271 | + } |
| 272 | + |
| 273 | + #[test] |
| 274 | + fn render_badge_uses_branch_and_label_word() { |
| 275 | + let Body::Badge(b) = render_body(&pipeline("success"), Shape::Badge) else { |
| 276 | + panic!("expected badge"); |
| 277 | + }; |
| 278 | + assert_eq!(b.status, Status::Ok); |
| 279 | + assert_eq!(b.label, "main · passing"); |
| 280 | + } |
| 281 | + |
| 282 | + #[test] |
| 283 | + fn render_text_falls_back_to_question_mark_for_missing_branch() { |
| 284 | + let mut p = pipeline("success"); |
| 285 | + p.branch = None; |
| 286 | + let Body::Text(t) = render_body(&p, Shape::Text) else { |
| 287 | + panic!("expected text"); |
| 288 | + }; |
| 289 | + assert_eq!(t.value, "? · passing"); |
| 290 | + } |
| 291 | + |
| 292 | + #[test] |
| 293 | + fn render_entries_carries_status_branch_sha_duration() { |
| 294 | + let Body::Entries(e) = render_body(&pipeline("failed"), Shape::Entries) else { |
| 295 | + panic!("expected entries"); |
| 296 | + }; |
| 297 | + assert_eq!(e.items[0].key, "status"); |
| 298 | + assert_eq!(e.items[0].status, Some(Status::Error)); |
| 299 | + assert_eq!(e.items[0].value.as_deref(), Some("failing")); |
| 300 | + assert_eq!(e.items[2].value.as_deref(), Some("abc123de")); |
| 301 | + assert_eq!(e.items[3].value.as_deref(), Some("3m 12s")); |
| 302 | + } |
| 303 | + |
| 304 | + #[test] |
| 305 | + fn short_sha_truncates_long_hexes_and_falls_back() { |
| 306 | + assert_eq!(short_sha(Some("abcdef1234567890")), "abcdef12"); |
| 307 | + assert_eq!(short_sha(None), "?"); |
| 308 | + } |
| 309 | + |
| 310 | + #[test] |
| 311 | + fn format_duration_renders_seconds_only_or_minutes_seconds() { |
| 312 | + assert_eq!(format_duration(Some(45)), "45s"); |
| 313 | + assert_eq!(format_duration(Some(192)), "3m 12s"); |
| 314 | + assert_eq!(format_duration(Some(60)), "1m 00s"); |
| 315 | + assert_eq!(format_duration(None), "?"); |
| 316 | + } |
| 317 | + |
| 318 | + #[test] |
| 319 | + fn sample_entries_carries_the_four_rollup_rows() { |
| 320 | + let Some(Body::Entries(e)) = GitlabPipelineStatus.sample_body(Shape::Entries) else { |
| 321 | + panic!("expected entries"); |
| 322 | + }; |
| 323 | + let keys: Vec<&str> = e.items.iter().map(|i| i.key.as_str()).collect(); |
| 324 | + assert_eq!(keys, vec!["status", "branch", "sha", "duration"]); |
| 325 | + } |
| 326 | +} |
0 commit comments