cargo_issue_lib/
lib.rs

1mod config;
2
3pub use config::{Level, Mode};
4use itertools::Itertools;
5use std::fmt::{Display, Formatter};
6
7pub const CONFIG_ENV: &str = "ISSUE_RS::Config::Mode";
8pub const IGNORE_ENV: &str = "ISSUE_RS_IGNORE";
9
10pub fn get_mode() -> Option<Mode> {
11    if let Ok(var) = std::env::var(CONFIG_ENV) {
12        serde_json::from_str(&var).expect("reading Mode from configuration")
13    } else if std::env::var(IGNORE_ENV).is_ok() {
14        Some(Mode::Noop)
15    } else {
16        Some(Default::default())
17    }
18}
19
20pub const APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
21
22#[derive(Debug, serde::Serialize, serde::Deserialize)]
23pub struct Issue {
24    pub url: String,
25}
26
27impl Display for Issue {
28    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
29        write!(f, "issue: {}", self.url)
30    }
31}
32
33// Both Github and Gitlab use the `closed_at` field to identify closed issues.
34#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
35pub struct GithubIssue {
36    pub closed_at: Option<String>,
37}
38
39impl Issue {
40    pub fn canonicalize_url(&self) -> url::Url {
41        let url = url::Url::parse(&self.url).unwrap();
42
43        if url.host_str().unwrap().contains("github") {
44            let path: String = Itertools::intersperse(url.path_segments().unwrap(), "/").collect();
45            return url::Url::parse(&format!("https://api.github.com/repos/{}", path)).unwrap();
46        }
47        unreachable!("only github public repositories are currently supported")
48    }
49
50    pub fn is_closed(&self) -> Result<bool, anyhow::Error> {
51        let client = reqwest::blocking::ClientBuilder::new()
52            .user_agent(APP_USER_AGENT)
53            .build()
54            .unwrap();
55
56        let response = client.get(self.canonicalize_url()).send()?;
57
58        if !response.status().is_success() {
59            anyhow::bail!(
60                "failed to fetch issue: {}",
61                response
62                    .text()
63                    .unwrap_or_else(|e| format!("no response found: {}", e))
64            )
65        }
66
67        let issue: GithubIssue = response.json()?;
68
69        Ok(issue.closed_at.is_some())
70    }
71}