opendal/services/github/
backend.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;
19use std::sync::Arc;
20
21use bytes::Buf;
22use http::Response;
23use http::StatusCode;
24use log::debug;
25
26use super::GITHUB_SCHEME;
27use super::config::GithubConfig;
28use super::core::Entry;
29use super::core::GithubCore;
30use super::deleter::GithubDeleter;
31use super::error::parse_error;
32use super::lister::GithubLister;
33use super::writer::GithubWriter;
34use super::writer::GithubWriters;
35use crate::raw::*;
36use crate::*;
37
38/// [github contents](https://docs.github.com/en/rest/repos/contents?apiVersion=2022-11-28#create-or-update-file-contents) services support.
39#[doc = include_str!("docs.md")]
40#[derive(Default)]
41pub struct GithubBuilder {
42    pub(super) config: GithubConfig,
43
44    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
45    pub(super) http_client: Option<HttpClient>,
46}
47
48impl Debug for GithubBuilder {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.debug_struct("GithubBuilder")
51            .field("config", &self.config)
52            .finish_non_exhaustive()
53    }
54}
55
56impl GithubBuilder {
57    /// Set root of this backend.
58    ///
59    /// All operations will happen under this root.
60    pub fn root(mut self, root: &str) -> Self {
61        self.config.root = if root.is_empty() {
62            None
63        } else {
64            Some(root.to_string())
65        };
66
67        self
68    }
69
70    /// Github access_token.
71    ///
72    /// required.
73    pub fn token(mut self, token: &str) -> Self {
74        if !token.is_empty() {
75            self.config.token = Some(token.to_string());
76        }
77        self
78    }
79
80    /// Set Github repo owner.
81    pub fn owner(mut self, owner: &str) -> Self {
82        self.config.owner = owner.to_string();
83
84        self
85    }
86
87    /// Set Github repo name.
88    pub fn repo(mut self, repo: &str) -> Self {
89        self.config.repo = repo.to_string();
90
91        self
92    }
93
94    /// Specify the http client that used by this service.
95    ///
96    /// # Notes
97    ///
98    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
99    /// during minor updates.
100    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
101    #[allow(deprecated)]
102    pub fn http_client(mut self, client: HttpClient) -> Self {
103        self.http_client = Some(client);
104        self
105    }
106}
107
108impl Builder for GithubBuilder {
109    type Config = GithubConfig;
110
111    /// Builds the backend and returns the result of GithubBackend.
112    fn build(self) -> Result<impl Access> {
113        debug!("backend build started: {:?}", &self);
114
115        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
116        debug!("backend use root {}", &root);
117
118        // Handle owner.
119        if self.config.owner.is_empty() {
120            return Err(Error::new(ErrorKind::ConfigInvalid, "owner is empty")
121                .with_operation("Builder::build")
122                .with_context("service", GITHUB_SCHEME));
123        }
124
125        debug!("backend use owner {}", &self.config.owner);
126
127        // Handle repo.
128        if self.config.repo.is_empty() {
129            return Err(Error::new(ErrorKind::ConfigInvalid, "repo is empty")
130                .with_operation("Builder::build")
131                .with_context("service", GITHUB_SCHEME));
132        }
133
134        debug!("backend use repo {}", &self.config.repo);
135
136        Ok(GithubBackend {
137            core: Arc::new(GithubCore {
138                info: {
139                    let am = AccessorInfo::default();
140                    am.set_scheme(GITHUB_SCHEME)
141                        .set_root(&root)
142                        .set_native_capability(Capability {
143                            stat: true,
144
145                            read: true,
146
147                            create_dir: true,
148
149                            write: true,
150                            write_can_empty: true,
151
152                            delete: true,
153
154                            list: true,
155                            list_with_recursive: true,
156
157                            shared: true,
158
159                            ..Default::default()
160                        });
161
162                    // allow deprecated api here for compatibility
163                    #[allow(deprecated)]
164                    if let Some(client) = self.http_client {
165                        am.update_http_client(|_| client);
166                    }
167
168                    am.into()
169                },
170                root,
171                token: self.config.token.clone(),
172                owner: self.config.owner.clone(),
173                repo: self.config.repo.clone(),
174            }),
175        })
176    }
177}
178
179/// Backend for Github services.
180#[derive(Debug, Clone)]
181pub struct GithubBackend {
182    core: Arc<GithubCore>,
183}
184
185impl Access for GithubBackend {
186    type Reader = HttpBody;
187    type Writer = GithubWriters;
188    type Lister = oio::PageLister<GithubLister>;
189    type Deleter = oio::OneShotDeleter<GithubDeleter>;
190
191    fn info(&self) -> Arc<AccessorInfo> {
192        self.core.info.clone()
193    }
194
195    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
196        let empty_bytes = Buffer::new();
197
198        let resp = self
199            .core
200            .upload(&format!("{path}.gitkeep"), empty_bytes)
201            .await?;
202
203        let status = resp.status();
204
205        match status {
206            StatusCode::OK | StatusCode::CREATED => Ok(RpCreateDir::default()),
207            _ => Err(parse_error(resp)),
208        }
209    }
210
211    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
212        let resp = self.core.stat(path).await?;
213
214        let status = resp.status();
215
216        match status {
217            StatusCode::OK => {
218                let body = resp.into_body();
219                let resp: Entry =
220                    serde_json::from_reader(body.reader()).map_err(new_json_deserialize_error)?;
221
222                let m = if resp.type_field == "dir" {
223                    Metadata::new(EntryMode::DIR)
224                } else {
225                    Metadata::new(EntryMode::FILE)
226                        .with_content_length(resp.size)
227                        .with_etag(resp.sha)
228                };
229
230                Ok(RpStat::new(m))
231            }
232            _ => Err(parse_error(resp)),
233        }
234    }
235
236    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
237        let resp = self.core.get(path, args.range()).await?;
238
239        let status = resp.status();
240
241        match status {
242            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
243                Ok((RpRead::default(), resp.into_body()))
244            }
245            _ => {
246                let (part, mut body) = resp.into_parts();
247                let buf = body.to_buffer().await?;
248                Err(parse_error(Response::from_parts(part, buf)))
249            }
250        }
251    }
252
253    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
254        let writer = GithubWriter::new(self.core.clone(), path.to_string());
255
256        let w = oio::OneShotWriter::new(writer);
257
258        Ok((RpWrite::default(), w))
259    }
260
261    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
262        Ok((
263            RpDelete::default(),
264            oio::OneShotDeleter::new(GithubDeleter::new(self.core.clone())),
265        ))
266    }
267
268    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
269        let l = GithubLister::new(self.core.clone(), path, args.recursive());
270        Ok((RpList::default(), oio::PageLister::new(l)))
271    }
272}