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    type Copier = ();
169
170    fn info(&self) -> Arc<AccessorInfo> {
171        self.core.info.clone()
172    }
173
174    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
175        let empty_bytes = Buffer::new();
176
177        let resp = self
178            .core
179            .upload(&format!("{path}.gitkeep"), empty_bytes)
180            .await?;
181
182        let status = resp.status();
183
184        match status {
185            StatusCode::OK | StatusCode::CREATED => Ok(RpCreateDir::default()),
186            _ => Err(parse_error(resp)),
187        }
188    }
189
190    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
191        let resp = self.core.stat(path).await?;
192
193        let status = resp.status();
194
195        match status {
196            StatusCode::OK => {
197                let body = resp.into_body();
198                let resp: Entry =
199                    serde_json::from_reader(body.reader()).map_err(new_json_deserialize_error)?;
200
201                let m = if resp.type_field == "dir" {
202                    Metadata::new(EntryMode::DIR)
203                } else {
204                    Metadata::new(EntryMode::FILE)
205                        .with_content_length(resp.size)
206                        .with_etag(resp.sha)
207                };
208
209                Ok(RpStat::new(m))
210            }
211            _ => Err(parse_error(resp)),
212        }
213    }
214
215    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
216        let resp = self.core.get(path, args.range()).await?;
217
218        let status = resp.status();
219
220        match status {
221            StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok((
222                RpRead::new(parse_into_metadata(path, resp.headers())?),
223                resp.into_body(),
224            )),
225            _ => {
226                let (part, mut body) = resp.into_parts();
227                let buf = body.to_buffer().await?;
228                Err(parse_error(Response::from_parts(part, buf)))
229            }
230        }
231    }
232
233    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
234        let writer = GithubWriter::new(self.core.clone(), path.to_string());
235
236        let w = oio::OneShotWriter::new(writer);
237
238        Ok((RpWrite::default(), w))
239    }
240
241    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
242        Ok((
243            RpDelete::default(),
244            oio::OneShotDeleter::new(GithubDeleter::new(self.core.clone())),
245        ))
246    }
247
248    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
249        let l = GithubLister::new(self.core.clone(), path, args.recursive());
250        Ok((RpList::default(), oio::PageLister::new(l)))
251    }
252}