Skip to main content

interprex_github/
issues.rs

1//! Issue and label operations owned by the issues domain.
2//!
3//! GitHub presents pull requests through its issues routes too, but this module
4//! intentionally models only issues and label taxonomy. Pull-request review
5//! facts remain in `code_reviews`, preventing a convenient vendor route from
6//! moving ownership between contracts.
7
8use async_trait::async_trait;
9use interprex::{
10    Issue, IssueNumber, IssuesProvider, Label, OpenClosed, ProviderError, Repository, Result,
11};
12use octocrab::Page;
13use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
14use serde::Deserialize;
15
16use crate::{GithubProvider, client::external};
17
18#[derive(Deserialize)]
19struct GithubIssue {
20    number: u64,
21    title: String,
22    body: Option<String>,
23    state: String,
24    #[serde(default)]
25    labels: Vec<GithubLabel>,
26    updated_at: chrono::DateTime<chrono::Utc>,
27    pull_request: Option<serde_json::Value>,
28}
29
30#[derive(Deserialize)]
31struct GithubLabel {
32    name: String,
33    color: String,
34    description: Option<String>,
35}
36
37impl From<GithubLabel> for Label {
38    fn from(value: GithubLabel) -> Self {
39        Self {
40            name: value.name,
41            color: value.color,
42            description: value.description,
43        }
44    }
45}
46
47fn normalize_issue(value: GithubIssue) -> Result<Issue> {
48    if value.pull_request.is_some() {
49        return Err(ProviderError::Unrepresentable {
50            provider: "github",
51            fact: "an issue-domain read addressed a pull request".to_owned(),
52        });
53    }
54    Ok(Issue {
55        number: IssueNumber::new(value.number).map_err(|error| ProviderError::Unrepresentable {
56            provider: "github",
57            fact: error.to_string(),
58        })?,
59        title: value.title,
60        body: value.body,
61        state: match value.state.as_str() {
62            "open" => OpenClosed::Open,
63            "closed" => OpenClosed::Closed,
64            other => {
65                return Err(ProviderError::Unrepresentable {
66                    provider: "github",
67                    fact: format!("unknown issue state {other}"),
68                });
69            }
70        },
71        labels: value.labels.into_iter().map(Into::into).collect(),
72        updated_at: value.updated_at,
73    })
74}
75
76#[async_trait]
77impl IssuesProvider for GithubProvider {
78    async fn issue(&self, repository: &Repository, number: IssueNumber) -> Result<Issue> {
79        let response: GithubIssue = self
80            .user()?
81            .get(
82                format!("/repos/{repository}/issues/{}", number.get()),
83                None::<&()>,
84            )
85            .await
86            .map_err(|error| {
87                crate::client::read_error(
88                    "read issue",
89                    format!("issue {} in {repository}", number.get()),
90                    error,
91                )
92            })?;
93        normalize_issue(response)
94    }
95
96    async fn labels(&self, repository: &Repository) -> Result<Vec<Label>> {
97        let page: Page<GithubLabel> = self
98            .user()?
99            .get(
100                format!("/repos/{repository}/labels"),
101                Some(&[("per_page", 100)]),
102            )
103            .await
104            .map_err(|error| external("list labels", error))?;
105        let response = self
106            .user()?
107            .all_pages(page)
108            .await
109            .map_err(|error| external("list labels", error))?;
110        Ok(response.into_iter().map(Into::into).collect())
111    }
112
113    async fn upsert_label(&self, repository: &Repository, label: &Label) -> Result<Label> {
114        let existing = self.labels(repository).await?;
115        let response: GithubLabel = if existing.iter().any(|existing| existing.name == label.name) {
116            self.user()?
117                .patch(
118                    format!(
119                        "/repos/{repository}/labels/{}",
120                        utf8_percent_encode(&label.name, NON_ALPHANUMERIC)
121                    ),
122                    Some(label),
123                )
124                .await
125                .map_err(|error| external("update label", error))?
126        } else {
127            self.user()?
128                .post(format!("/repos/{repository}/labels"), Some(label))
129                .await
130                .map_err(|error| external("create label", error))?
131        };
132        Ok(response.into())
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::{GithubIssue, normalize_issue};
139
140    #[test]
141    fn issue_fixture_normalizes_labels_and_state() {
142        let response: GithubIssue =
143            serde_json::from_str(include_str!("../tests/fixtures/issue.json")).expect("fixture");
144        let issue = normalize_issue(response).expect("normalizes");
145        assert_eq!(issue.number.get(), 11);
146        assert_eq!(issue.labels[0].name, "feature");
147    }
148
149    #[test]
150    fn unknown_issue_states_are_unrepresentable() {
151        let mut response: GithubIssue =
152            serde_json::from_str(include_str!("../tests/fixtures/issue.json")).expect("fixture");
153        response.state = "reopening".to_owned();
154        let error = normalize_issue(response).expect_err("unknown state must be unrepresentable");
155        assert!(matches!(
156            error,
157            interprex::ProviderError::Unrepresentable { fact, .. }
158                if fact.contains("unknown issue state")
159        ));
160    }
161}