Skip to main content

grp_core/common/
platform.rs

1use hyper::HeaderMap;
2use reqwest::Response;
3
4use crate::empty_notes;
5use crate::error::errors::request::Request;
6use crate::error::structs::Error;
7use crate::common::structs::Context;
8use crate::config::Config;
9use crate::platform::Platform;
10use crate::specific::{gitea, github, gitlab};
11
12impl Platform {
13    /// # Return
14    /// An _enum variant_ that matches the given &str.
15    /// 
16    /// # Error
17    /// a `grp_core::Error` of type `grp_core::ErrorType::Unsupported`.
18    pub fn matches(name: &str) -> Result<Platform, Error> {
19        let platform: Platform = match name {
20            "github" => Platform::Github,
21            "gitea" => Platform::Gitea,
22            "gitlab" => Platform::Gitlab,
23            "codeberg" => Platform::Codeberg,
24            "forgejo" => Platform::Forgejo,
25            name => {
26                return Err(Request::unsuported(name, "Platform variant", empty_notes!()));
27            }
28        };
29
30        Ok(platform)
31    }
32
33    pub(crate) fn get_auth_header<S: AsRef<str>>(&self, token: &S) -> HeaderMap {
34        let token = token.as_ref().to_string();
35        match self {
36            Platform::Github => { github::header::get_auth_header(token) }
37            Platform::Codeberg |
38            Platform::Forgejo |
39            Platform::Gitea => { gitea::header::get_auth_header(token) }
40            Platform::Gitlab => { gitlab::header::get_auth_header(token) }
41        }
42    }
43
44    pub(crate) fn get_base_url<S: AsRef<str>>(&self, endpoint: &S) -> String {
45        let endpoint = endpoint.as_ref();
46        match self {
47            Platform::Github => { format!("https://{}", endpoint) }
48            Platform::Codeberg |
49            Platform::Forgejo |
50            Platform::Gitea => { format!("https://{}/api/v1", endpoint) }
51            Platform::Gitlab => { format!("https://{}/api/v4", endpoint) }
52        }
53    }
54
55    /// this function allows to discern if the platform fails, or success 
56    /// procesing the request.
57    /// 
58    /// # Return
59    /// a `String` with the response of the platform only if the response was succesfull.
60    /// 
61    /// # Error
62    /// a `grp_core::Error` containing the detail of the error. 
63    pub async fn unwrap<T: Into<String>>(&self,
64        result: Response,
65        base_message: T,
66        config: &Config,
67        context: Context,
68    ) -> Result<String, Error> {
69        match self {
70            Platform::Github => { github::unwrap::unwrap(result, base_message.into(), config, context).await }
71            Platform::Codeberg |
72            Platform::Forgejo |
73            Platform::Gitea => { gitea::unwrap::unwrap(result, base_message.into(), config, context).await }
74            Platform::Gitlab => { gitlab::unwrap::unwrap(result, base_message.into(), config, context).await }
75        }
76    }
77}