Skip to main content

interprex_github/
jobs.rs

1//! GitHub Actions operations owned by the jobs domain.
2//!
3//! Dispatch and cancellation use Octocrab's typed operations because their
4//! successful responses have no JSON body. Run responses are normalized into a
5//! small status and conclusion vocabularies; new GitHub values become
6//! `Unknown` rather than causing deserialization failure or silently
7//! pretending to be completed. An omitted workflow name remains absent.
8
9use async_trait::async_trait;
10use interprex::{
11    DispatchInputs, JobsProvider, ProviderError, Repository, Result, RunConclusion, RunId,
12    RunStatus, WorkflowRun,
13};
14use serde::Deserialize;
15
16use crate::{GithubProvider, client::external};
17
18#[derive(Deserialize)]
19struct GithubRun {
20    id: u64,
21    name: Option<String>,
22    head_sha: String,
23    status: String,
24    conclusion: Option<String>,
25    html_url: String,
26}
27
28fn normalize_run(value: GithubRun) -> Result<WorkflowRun> {
29    let status = match value.status.as_str() {
30        "queued" | "waiting" | "pending" => RunStatus::Queued,
31        "in_progress" | "requested" => RunStatus::InProgress,
32        "completed" => RunStatus::Completed,
33        _ => RunStatus::Unknown,
34    };
35    let conclusion = value.conclusion.map(|value| match value.as_str() {
36        "success" => RunConclusion::Success,
37        "failure" => RunConclusion::Failure,
38        "neutral" => RunConclusion::Neutral,
39        "cancelled" => RunConclusion::Cancelled,
40        "skipped" => RunConclusion::Skipped,
41        "timed_out" => RunConclusion::TimedOut,
42        "action_required" => RunConclusion::ActionRequired,
43        "stale" => RunConclusion::Stale,
44        "startup_failure" => RunConclusion::StartupFailure,
45        _ => RunConclusion::Unknown,
46    });
47    Ok(WorkflowRun {
48        id: RunId::new(value.id).map_err(|error| ProviderError::Unrepresentable {
49            provider: "github",
50            fact: error.to_string(),
51        })?,
52        workflow_name: value.name,
53        head_sha: value.head_sha,
54        status,
55        conclusion,
56        html_url: value.html_url,
57    })
58}
59
60#[async_trait]
61impl JobsProvider for GithubProvider {
62    async fn dispatch(
63        &self,
64        repository: &Repository,
65        workflow: &str,
66        git_ref: &str,
67        inputs: &DispatchInputs,
68    ) -> Result<()> {
69        self.user()?
70            .actions()
71            .create_workflow_dispatch(repository.owner(), repository.name(), workflow, git_ref)
72            .inputs(serde_json::Value::Object(
73                inputs.0.clone().into_iter().collect(),
74            ))
75            .send()
76            .await
77            .map_err(|error| external("dispatch workflow", error))?;
78        Ok(())
79    }
80
81    async fn run(&self, repository: &Repository, run_id: RunId) -> Result<WorkflowRun> {
82        let response: GithubRun = self
83            .user()?
84            .get(
85                format!("/repos/{repository}/actions/runs/{}", run_id.get()),
86                None::<&()>,
87            )
88            .await
89            .map_err(|error| {
90                crate::client::read_error(
91                    "read workflow run",
92                    format!("workflow run {} in {repository}", run_id.get()),
93                    error,
94                )
95            })?;
96        normalize_run(response)
97    }
98
99    async fn cancel_run(&self, repository: &Repository, run_id: RunId) -> Result<()> {
100        self.user()?
101            .actions()
102            .cancel_workflow_run(repository.owner(), repository.name(), run_id.get().into())
103            .await
104            .map_err(|error| external("cancel workflow run", error))?;
105        Ok(())
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::{GithubRun, normalize_run};
112    use interprex::{RunConclusion, RunStatus};
113
114    #[test]
115    fn run_fixture_normalizes_status_without_exporting_octocrab_types() {
116        let response: GithubRun =
117            serde_json::from_str(include_str!("../tests/fixtures/workflow_run.json"))
118                .expect("fixture");
119        let run = normalize_run(response).expect("normalizes");
120        assert_eq!(run.status, RunStatus::Completed);
121        assert_eq!(run.workflow_name.as_deref(), Some("quality"));
122        assert_eq!(run.conclusion, Some(RunConclusion::Success));
123    }
124
125    #[test]
126    fn omitted_name_stays_absent_and_new_conclusions_are_explicitly_unknown() {
127        let response: GithubRun = serde_json::from_str(
128            r#"{
129                "id": 123456,
130                "head_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
131                "status": "completed",
132                "conclusion": "future_value",
133                "html_url": "https://example.invalid/run"
134            }"#,
135        )
136        .expect("response");
137        let run = normalize_run(response).expect("normalizes");
138        assert_eq!(run.workflow_name, None);
139        assert_eq!(run.conclusion, Some(RunConclusion::Unknown));
140    }
141}