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 `fx` 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    /// `fx 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 `fx 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 created: Option<i64>,
137    #[serde(default)]
138    pub started: Option<i64>,
139    #[serde(default)]
140    pub finished: Option<i64>,
141    #[serde(default)]
142    pub stages: Vec<Stage>,
143}
144
145impl Execution {
146    /// The branch this run is about.
147    ///
148    /// A push sets `target`; other events fall back to `source`, then to the
149    /// raw ref with its `refs/heads/` prefix trimmed.
150    pub fn branch(&self) -> Option<String> {
151        self.target
152            .clone()
153            .filter(|b| !b.is_empty())
154            .or_else(|| self.source.clone().filter(|b| !b.is_empty()))
155            .or_else(|| {
156                self.git_ref.as_deref().map(|r| {
157                    r.strip_prefix("refs/heads/")
158                        .or_else(|| r.strip_prefix("refs/tags/"))
159                        .unwrap_or(r)
160                        .to_string()
161                })
162            })
163            .filter(|b| !b.is_empty())
164    }
165
166    /// The commit subject, or the run title, whichever is there.
167    pub fn summary(&self) -> String {
168        let raw = self
169            .title
170            .clone()
171            .filter(|t| !t.trim().is_empty())
172            .or_else(|| self.message.clone())
173            .unwrap_or_default();
174        raw.lines().next().unwrap_or_default().trim().to_string()
175    }
176
177    pub fn author(&self) -> String {
178        self.author_login
179            .clone()
180            .filter(|a| !a.is_empty())
181            .or_else(|| self.author_name.clone())
182            .unwrap_or_default()
183    }
184
185    /// Every step in the run, tagged with the stage it belongs to.
186    pub fn steps(&self) -> impl Iterator<Item = (&Stage, &Step)> {
187        self.stages
188            .iter()
189            .flat_map(|stage| stage.steps.iter().map(move |step| (stage, step)))
190    }
191}
192
193/// A pipeline definition. `execution` is its latest run, present only when the
194/// list was asked for with `latest=true`.
195#[derive(Debug, Clone, Default, Serialize, Deserialize)]
196pub struct Pipeline {
197    #[serde(default)]
198    pub identifier: String,
199    #[serde(default)]
200    pub description: Option<String>,
201    #[serde(default)]
202    pub default_branch: Option<String>,
203    #[serde(default)]
204    pub disabled: Option<bool>,
205    #[serde(default)]
206    pub config_path: Option<String>,
207    #[serde(default)]
208    pub created: Option<i64>,
209    #[serde(default)]
210    pub updated: Option<i64>,
211    #[serde(default)]
212    pub execution: Option<Execution>,
213}
214
215/// One line of step output.
216#[derive(Debug, Clone, Default, Serialize, Deserialize)]
217pub struct LogLine {
218    #[serde(default)]
219    pub pos: i64,
220    #[serde(default)]
221    pub out: String,
222    #[serde(default)]
223    pub time: i64,
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use serde_json::json;
230
231    #[test]
232    fn status_classification_matches_the_documented_set() {
233        for failed in ["failure", "error", "killed"] {
234            assert!(CiStatus::from(failed).is_failed(), "{failed}");
235        }
236        // Never ran, so `--failed` must not offer to show their empty logs.
237        for not_failed in ["declined", "skipped", "success", "running", "pending"] {
238            assert!(!CiStatus::from(not_failed).is_failed(), "{not_failed}");
239        }
240        assert!(CiStatus::from("running").is_pending());
241        assert!(CiStatus::from("waiting_on_dependencies").is_pending());
242        assert!(CiStatus::from("success").is_success());
243        assert!(CiStatus::from("failure").has_run());
244        assert!(!CiStatus::from("skipped").has_run());
245    }
246
247    #[test]
248    fn an_unknown_status_survives_instead_of_failing_to_decode() {
249        let status: CiStatus = serde_json::from_str("\"quarantined\"").unwrap();
250        assert_eq!(status.as_str(), "quarantined");
251        assert!(!status.is_failed() && !status.is_success());
252        // And it round-trips back out unchanged.
253        assert_eq!(serde_json::to_string(&status).unwrap(), "\"quarantined\"");
254    }
255
256    #[test]
257    fn branch_prefers_target_then_source_then_the_ref() {
258        let mut e = Execution {
259            target: Some("main".into()),
260            source: Some("feat/x".into()),
261            git_ref: Some("refs/heads/other".into()),
262            ..Default::default()
263        };
264        assert_eq!(e.branch().as_deref(), Some("main"));
265        e.target = None;
266        assert_eq!(e.branch().as_deref(), Some("feat/x"));
267        e.source = None;
268        assert_eq!(e.branch().as_deref(), Some("other"));
269        e.git_ref = Some("refs/tags/v1.0".into());
270        assert_eq!(e.branch().as_deref(), Some("v1.0"));
271        e.git_ref = None;
272        assert_eq!(e.branch(), None);
273    }
274
275    #[test]
276    fn empty_strings_are_treated_as_absent() {
277        let e = Execution {
278            target: Some(String::new()),
279            source: Some("feat/x".into()),
280            ..Default::default()
281        };
282        assert_eq!(e.branch().as_deref(), Some("feat/x"));
283    }
284
285    #[test]
286    fn summary_takes_the_first_line_only() {
287        let e = Execution {
288            message: Some("feat: add OAuth\n\nA long body.".into()),
289            ..Default::default()
290        };
291        assert_eq!(e.summary(), "feat: add OAuth");
292    }
293
294    #[test]
295    fn steps_are_walked_with_their_stage() {
296        let execution: Execution = serde_json::from_value(json!({
297            "number": 182,
298            "status": "failure",
299            "stages": [
300                { "number": 1, "name": "build", "status": "failure", "steps": [
301                    { "number": 1, "name": "clone", "status": "success" },
302                    { "number": 2, "name": "cargo test", "status": "failure", "exit_code": 101 }
303                ]},
304                { "number": 2, "name": "deploy", "status": "skipped", "steps": [] }
305            ]
306        }))
307        .unwrap();
308
309        let all: Vec<_> = execution.steps().collect();
310        assert_eq!(all.len(), 2);
311        assert_eq!(all[1].0.name, "build");
312        assert_eq!(all[1].1.name, "cargo test");
313
314        let failed: Vec<_> = execution
315            .steps()
316            .filter(|(_, s)| s.status.is_failed())
317            .collect();
318        assert_eq!(failed.len(), 1);
319        assert_eq!(failed[0].1.exit_code, Some(101));
320    }
321
322    #[test]
323    fn a_list_response_without_stages_still_decodes() {
324        let e: Execution =
325            serde_json::from_value(json!({ "number": 1, "status": "success" })).unwrap();
326        assert!(e.stages.is_empty());
327        assert_eq!(e.steps().count(), 0);
328    }
329}