Skip to main content

opendal_service_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 opendal_core::raw::*;
36use opendal_core::*;
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
45impl Debug for GithubBuilder {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.debug_struct("GithubBuilder")
48            .field("config", &self.config)
49            .finish_non_exhaustive()
50    }
51}
52
53impl GithubBuilder {
54    /// Set root of this backend.
55    ///
56    /// All operations will happen under this root.
57    pub fn root(mut self, root: &str) -> Self {
58        self.config.root = if root.is_empty() {
59            None
60        } else {
61            Some(root.to_string())
62        };
63
64        self
65    }
66
67    /// Github access_token.
68    ///
69    /// required.
70    pub fn token(mut self, token: &str) -> Self {
71        if !token.is_empty() {
72            self.config.token = Some(token.to_string());
73        }
74        self
75    }
76
77    /// Set Github repo owner.
78    pub fn owner(mut self, owner: &str) -> Self {
79        self.config.owner = owner.to_string();
80
81        self
82    }
83
84    /// Set Github repo name.
85    pub fn repo(mut self, repo: &str) -> Self {
86        self.config.repo = repo.to_string();
87
88        self
89    }
90}
91
92impl Builder for GithubBuilder {
93    type Config = GithubConfig;
94
95    /// Builds the backend and returns the result of GithubBackend.
96    fn build(self) -> Result<impl Access> {
97        debug!("backend build started: {:?}", &self);
98
99        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
100        debug!("backend use root {}", &root);
101
102        // Handle owner.
103        if self.config.owner.is_empty() {
104            return Err(Error::new(ErrorKind::ConfigInvalid, "owner is empty")
105                .with_operation("Builder::build")
106                .with_context("service", GITHUB_SCHEME));
107        }
108
109        debug!("backend use owner {}", &self.config.owner);
110
111        // Handle repo.
112        if self.config.repo.is_empty() {
113            return Err(Error::new(ErrorKind::ConfigInvalid, "repo is empty")
114                .with_operation("Builder::build")
115                .with_context("service", GITHUB_SCHEME));
116        }
117
118        debug!("backend use repo {}", &self.config.repo);
119
120        Ok(GithubBackend {
121            core: Arc::new(GithubCore {
122                info: {
123                    let am = AccessorInfo::default();
124                    am.set_scheme(GITHUB_SCHEME)
125                        .set_root(&root)
126                        .set_native_capability(Capability {
127                            stat: true,
128
129                            read: true,
130
131                            create_dir: true,
132
133                            write: true,
134                            write_can_empty: true,
135
136                            delete: true,
137
138                            list: true,
139                            list_with_recursive: true,
140
141                            shared: true,
142
143                            ..Default::default()
144                        });
145
146                    am.into()
147                },
148                root,
149                token: self.config.token.clone(),
150                owner: self.config.owner.clone(),
151                repo: self.config.repo.clone(),
152            }),
153        })
154    }
155}
156
157/// Backend for Github services.
158#[derive(Debug, Clone)]
159pub struct GithubBackend {
160    core: Arc<GithubCore>,
161}
162
163impl Access for GithubBackend {
164    type Reader = HttpBody;
165    type Writer = GithubWriters;
166    type Lister = oio::PageLister<GithubLister>;
167    type Deleter = oio::OneShotDeleter<GithubDeleter>;
168
169    fn info(&self) -> Arc<AccessorInfo> {
170        self.core.info.clone()
171    }
172
173    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
174        let empty_bytes = Buffer::new();
175
176        let resp = self
177            .core
178            .upload(&format!("{path}.gitkeep"), empty_bytes)
179            .await?;
180
181        let status = resp.status();
182
183        match status {
184            StatusCode::OK | StatusCode::CREATED => Ok(RpCreateDir::default()),
185            _ => Err(parse_error(resp)),
186        }
187    }
188
189    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
190        let resp = self.core.stat(path).await?;
191
192        let status = resp.status();
193
194        match status {
195            StatusCode::OK => {
196                let body = resp.into_body();
197                let resp: Entry =
198                    serde_json::from_reader(body.reader()).map_err(new_json_deserialize_error)?;
199
200                let m = if resp.type_field == "dir" {
201                    Metadata::new(EntryMode::DIR)
202                } else {
203                    Metadata::new(EntryMode::FILE)
204                        .with_content_length(resp.size)
205                        .with_etag(resp.sha)
206                };
207
208                Ok(RpStat::new(m))
209            }
210            _ => Err(parse_error(resp)),
211        }
212    }
213
214    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
215        let resp = self.core.get(path, args.range()).await?;
216
217        let status = resp.status();
218
219        match status {
220            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
221                Ok((RpRead::default(), resp.into_body()))
222            }
223            _ => {
224                let (part, mut body) = resp.into_parts();
225                let buf = body.to_buffer().await?;
226                Err(parse_error(Response::from_parts(part, buf)))
227            }
228        }
229    }
230
231    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
232        let writer = GithubWriter::new(self.core.clone(), path.to_string());
233
234        let w = oio::OneShotWriter::new(writer);
235
236        Ok((RpWrite::default(), w))
237    }
238
239    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
240        Ok((
241            RpDelete::default(),
242            oio::OneShotDeleter::new(GithubDeleter::new(self.core.clone())),
243        ))
244    }
245
246    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
247        let l = GithubLister::new(self.core.clone(), path, args.recursive());
248        Ok((RpList::default(), oio::PageLister::new(l)))
249    }
250}