Skip to main content

opendal_service_github/
config.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19
20use serde::Deserialize;
21use serde::Serialize;
22
23use super::GITHUB_SCHEME;
24use super::backend::GithubBuilder;
25use opendal_core::{Configurator, Error, ErrorKind, OperatorUri, Result};
26
27/// Config for GitHub services support.
28#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
29#[serde(default)]
30#[non_exhaustive]
31pub struct GithubConfig {
32    /// root of this backend.
33    ///
34    /// All operations will happen under this root.
35    pub root: Option<String>,
36    /// GitHub access_token.
37    ///
38    /// optional.
39    /// If not provided, the backend will only support read operations for public repositories.
40    /// And rate limit will be limited to 60 requests per hour.
41    pub token: Option<String>,
42    /// GitHub repo owner.
43    ///
44    /// required.
45    pub owner: String,
46    /// GitHub repo name.
47    ///
48    /// required.
49    pub repo: String,
50}
51
52impl Debug for GithubConfig {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("GithubConfig")
55            .field("root", &self.root)
56            .field("owner", &self.owner)
57            .field("repo", &self.repo)
58            .finish_non_exhaustive()
59    }
60}
61
62impl Configurator for GithubConfig {
63    type Builder = GithubBuilder;
64
65    fn from_uri(uri: &OperatorUri) -> Result<Self> {
66        let owner = uri.name().ok_or_else(|| {
67            Error::new(ErrorKind::ConfigInvalid, "uri host must contain owner")
68                .with_context("service", GITHUB_SCHEME)
69        })?;
70
71        let raw_path = uri.root().ok_or_else(|| {
72            Error::new(ErrorKind::ConfigInvalid, "uri path must contain repository")
73                .with_context("service", GITHUB_SCHEME)
74        })?;
75
76        let (repo, remainder) = match raw_path.split_once('/') {
77            Some((repo, rest)) => (repo, Some(rest)),
78            None => (raw_path, None),
79        };
80
81        if repo.is_empty() {
82            return Err(
83                Error::new(ErrorKind::ConfigInvalid, "repository name is required")
84                    .with_context("service", GITHUB_SCHEME),
85            );
86        }
87
88        let mut map = uri.options().clone();
89        map.insert("owner".to_string(), owner.to_string());
90        map.insert("repo".to_string(), repo.to_string());
91
92        if let Some(rest) = remainder
93            && !rest.is_empty()
94        {
95            map.insert("root".to_string(), rest.to_string());
96        }
97
98        Self::from_iter(map)
99    }
100
101    fn into_builder(self) -> Self::Builder {
102        GithubBuilder { config: self }
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use opendal_core::Configurator;
110    use opendal_core::OperatorUri;
111
112    #[test]
113    fn from_uri_sets_owner_repo_and_root() {
114        let uri = OperatorUri::new(
115            "github://apache/opendal/src/services",
116            Vec::<(String, String)>::new(),
117        )
118        .unwrap();
119
120        let cfg = GithubConfig::from_uri(&uri).unwrap();
121        assert_eq!(cfg.owner, "apache".to_string());
122        assert_eq!(cfg.repo, "opendal".to_string());
123        assert_eq!(cfg.root.as_deref(), Some("src/services"));
124    }
125
126    #[test]
127    fn from_uri_requires_repository() {
128        let uri = OperatorUri::new("github://apache", Vec::<(String, String)>::new()).unwrap();
129
130        assert!(GithubConfig::from_uri(&uri).is_err());
131    }
132}