Skip to main content

gitfox_client/models/
pipeline.rs

1use serde::{Deserialize, Serialize};
2
3/// A CI status.
4///
5/// Deliberately a string rather than an enum. GitFox's set today is `blocked`,
6/// `declined`, `error`, `failure`, `killed`, `pending`, `running`, `skipped`,
7/// `success` and `waiting_on_dependencies`, but a CI system grows states over
8/// time; a closed enum would either lose the server's exact word or fail to
9/// decode. Everything `gf` needs is classification, and that is what the
10/// predicates below provide.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
12#[serde(transparent)]
13pub struct CiStatus(pub String);
14
15impl CiStatus {
16    pub fn as_str(&self) -> &str {
17        &self.0
18    }
19
20    /// Something went wrong and there is likely a log worth reading.
21    ///
22    /// `declined` and `skipped` are excluded on purpose: they never ran, so
23    /// `gf pipeline logs --failed` would only show empty output for them.
24    pub fn is_failed(&self) -> bool {
25        matches!(self.0.as_str(), "failure" | "error" | "killed")
26    }
27
28    pub fn is_success(&self) -> bool {
29        self.0 == "success"
30    }
31
32    /// Still going, or waiting to.
33    pub fn is_pending(&self) -> bool {
34        matches!(
35            self.0.as_str(),
36            "running" | "pending" | "blocked" | "waiting_on_dependencies"
37        )
38    }
39
40    /// Ran to some conclusion, so it may have produced output.
41    pub fn has_run(&self) -> bool {
42        !matches!(
43            self.0.as_str(),
44            "pending" | "skipped" | "blocked" | "waiting_on_dependencies"
45        )
46    }
47}
48
49impl std::fmt::Display for CiStatus {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.write_str(&self.0)
52    }
53}
54
55impl From<&str> for CiStatus {
56    fn from(value: &str) -> Self {
57        Self(value.to_string())
58    }
59}
60
61/// One step of a stage — the unit logs are addressed by.
62#[derive(Debug, Clone, Default, Serialize, Deserialize)]
63pub struct Step {
64    #[serde(default)]
65    pub number: i64,
66    #[serde(default)]
67    pub name: String,
68    #[serde(default)]
69    pub status: CiStatus,
70    #[serde(default)]
71    pub error: Option<String>,
72    #[serde(default)]
73    pub exit_code: Option<i64>,
74    #[serde(default)]
75    pub started: Option<i64>,
76    #[serde(default)]
77    pub stopped: Option<i64>,
78}
79
80#[derive(Debug, Clone, Default, Serialize, Deserialize)]
81pub struct Stage {
82    #[serde(default)]
83    pub number: i64,
84    #[serde(default)]
85    pub name: String,
86    #[serde(default)]
87    pub status: CiStatus,
88    #[serde(default)]
89    pub error: Option<String>,
90    #[serde(default)]
91    pub exit_code: Option<i64>,
92    #[serde(default)]
93    pub started: Option<i64>,
94    #[serde(default)]
95    pub stopped: Option<i64>,
96    #[serde(default)]
97    pub steps: Vec<Step>,
98}
99
100/// One run of a pipeline.
101///
102/// `stages` is populated by the single-execution endpoint and empty in list
103/// responses, which is why `gf pipeline logs` fetches the execution before it
104/// can find anything to fetch logs for.
105#[derive(Debug, Clone, Default, Serialize, Deserialize)]
106pub struct Execution {
107    #[serde(default)]
108    pub number: u64,
109    #[serde(default)]
110    pub status: CiStatus,
111    #[serde(default)]
112    pub title: Option<String>,
113    #[serde(default)]
114    pub message: Option<String>,
115    #[serde(default)]
116    pub author_login: Option<String>,
117    #[serde(default)]
118    pub author_name: Option<String>,
119    #[serde(default)]
120    pub event: Option<String>,
121    #[serde(default)]
122    pub source: Option<String>,
123    #[serde(default)]
124    pub target: Option<String>,
125    #[serde(default, rename = "ref")]
126    pub git_ref: Option<String>,
127    #[serde(default)]
128    pub after: Option<String>,
129    #[serde(default)]
130    pub error: Option<String>,
131    #[serde(default)]
132    pub link: Option<String>,
133    #[serde(default)]
134    pub pipeline_uid: Option<String>,
135    #[serde(default)]
136    pub pipeline_id: Option<i64>,
137    /// What caused the run: `@hook`, a user, `@cron`.
138    #[serde(default)]
139    pub trigger: Option<String>,
140    /// How many times this run has been retried.
141    #[serde(default)]
142    pub retry_count: Option<i64>,
143    #[serde(default)]
144    pub created: Option<i64>,
145    #[serde(default)]
146    pub started: Option<i64>,
147    #[serde(default)]
148    pub finished: Option<i64>,
149    #[serde(default)]
150    pub updated: Option<i64>,
151    #[serde(default)]
152    pub stages: Vec<Stage>,
153}
154
155impl Execution {
156    /// The branch this run is about.
157    ///
158    /// A push sets `target`; other events fall back to `source`, then to the
159    /// raw ref with its `refs/heads/` prefix trimmed.
160    pub fn branch(&self) -> Option<String> {
161        self.target
162            .clone()
163            .filter(|b| !b.is_empty())
164            .or_else(|| self.source.clone().filter(|b| !b.is_empty()))
165            .or_else(|| {
166                self.git_ref.as_deref().map(|r| {
167                    r.strip_prefix("refs/heads/")
168                        .or_else(|| r.strip_prefix("refs/tags/"))
169                        .unwrap_or(r)
170                        .to_string()
171                })
172            })
173            .filter(|b| !b.is_empty())
174    }
175
176    /// The commit subject, or the run title, whichever is there.
177    pub fn summary(&self) -> String {
178        let raw = self
179            .title
180            .clone()
181            .filter(|t| !t.trim().is_empty())
182            .or_else(|| self.message.clone())
183            .unwrap_or_default();
184        raw.lines().next().unwrap_or_default().trim().to_string()
185    }
186
187    pub fn author(&self) -> String {
188        self.author_login
189            .clone()
190            .filter(|a| !a.is_empty())
191            .or_else(|| self.author_name.clone())
192            .unwrap_or_default()
193    }
194
195    /// Every step in the run, tagged with the stage it belongs to.
196    pub fn steps(&self) -> impl Iterator<Item = (&Stage, &Step)> {
197        self.stages
198            .iter()
199            .flat_map(|stage| stage.steps.iter().map(move |step| (stage, step)))
200    }
201}
202
203/// A pipeline definition. `execution` is its latest run, present only when the
204/// list was asked for with `latest=true`.
205#[derive(Debug, Clone, Default, Serialize, Deserialize)]
206pub struct Pipeline {
207    #[serde(default)]
208    pub id: Option<i64>,
209    #[serde(default)]
210    pub identifier: String,
211    #[serde(default)]
212    pub description: Option<String>,
213    #[serde(default)]
214    pub default_branch: Option<String>,
215    #[serde(default)]
216    pub disabled: Option<bool>,
217    #[serde(default)]
218    pub config_path: Option<String>,
219    #[serde(default)]
220    pub created: Option<i64>,
221    #[serde(default)]
222    pub updated: Option<i64>,
223    #[serde(default)]
224    pub execution: Option<Execution>,
225}
226
227/// One line of step output.
228#[derive(Debug, Clone, Default, Serialize, Deserialize)]
229pub struct LogLine {
230    #[serde(default)]
231    pub pos: i64,
232    #[serde(default)]
233    pub out: String,
234    #[serde(default)]
235    pub time: i64,
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use serde_json::json;
242
243    #[test]
244    fn status_classification_matches_the_documented_set() {
245        for failed in ["failure", "error", "killed"] {
246            assert!(CiStatus::from(failed).is_failed(), "{failed}");
247        }
248        // Never ran, so `--failed` must not offer to show their empty logs.
249        for not_failed in ["declined", "skipped", "success", "running", "pending"] {
250            assert!(!CiStatus::from(not_failed).is_failed(), "{not_failed}");
251        }
252        assert!(CiStatus::from("running").is_pending());
253        assert!(CiStatus::from("waiting_on_dependencies").is_pending());
254        assert!(CiStatus::from("success").is_success());
255        assert!(CiStatus::from("failure").has_run());
256        assert!(!CiStatus::from("skipped").has_run());
257    }
258
259    #[test]
260    fn an_unknown_status_survives_instead_of_failing_to_decode() {
261        let status: CiStatus = serde_json::from_str("\"quarantined\"").unwrap();
262        assert_eq!(status.as_str(), "quarantined");
263        assert!(!status.is_failed() && !status.is_success());
264        // And it round-trips back out unchanged.
265        assert_eq!(serde_json::to_string(&status).unwrap(), "\"quarantined\"");
266    }
267
268    #[test]
269    fn branch_prefers_target_then_source_then_the_ref() {
270        let mut e = Execution {
271            target: Some("main".into()),
272            source: Some("feat/x".into()),
273            git_ref: Some("refs/heads/other".into()),
274            ..Default::default()
275        };
276        assert_eq!(e.branch().as_deref(), Some("main"));
277        e.target = None;
278        assert_eq!(e.branch().as_deref(), Some("feat/x"));
279        e.source = None;
280        assert_eq!(e.branch().as_deref(), Some("other"));
281        e.git_ref = Some("refs/tags/v1.0".into());
282        assert_eq!(e.branch().as_deref(), Some("v1.0"));
283        e.git_ref = None;
284        assert_eq!(e.branch(), None);
285    }
286
287    #[test]
288    fn empty_strings_are_treated_as_absent() {
289        let e = Execution {
290            target: Some(String::new()),
291            source: Some("feat/x".into()),
292            ..Default::default()
293        };
294        assert_eq!(e.branch().as_deref(), Some("feat/x"));
295    }
296
297    #[test]
298    fn summary_takes_the_first_line_only() {
299        let e = Execution {
300            message: Some("feat: add OAuth\n\nA long body.".into()),
301            ..Default::default()
302        };
303        assert_eq!(e.summary(), "feat: add OAuth");
304    }
305
306    #[test]
307    fn steps_are_walked_with_their_stage() {
308        let execution: Execution = serde_json::from_value(json!({
309            "number": 182,
310            "status": "failure",
311            "stages": [
312                { "number": 1, "name": "build", "status": "failure", "steps": [
313                    { "number": 1, "name": "clone", "status": "success" },
314                    { "number": 2, "name": "cargo test", "status": "failure", "exit_code": 101 }
315                ]},
316                { "number": 2, "name": "deploy", "status": "skipped", "steps": [] }
317            ]
318        }))
319        .unwrap();
320
321        let all: Vec<_> = execution.steps().collect();
322        assert_eq!(all.len(), 2);
323        assert_eq!(all[1].0.name, "build");
324        assert_eq!(all[1].1.name, "cargo test");
325
326        let failed: Vec<_> = execution
327            .steps()
328            .filter(|(_, s)| s.status.is_failed())
329            .collect();
330        assert_eq!(failed.len(), 1);
331        assert_eq!(failed[0].1.exit_code, Some(101));
332    }
333
334    #[test]
335    fn a_list_response_without_stages_still_decodes() {
336        let e: Execution =
337            serde_json::from_value(json!({ "number": 1, "status": "success" })).unwrap();
338        assert!(e.stages.is_empty());
339        assert_eq!(e.steps().count(), 0);
340    }
341}