opendal/services/github/
backend.rs1use 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#[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 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 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 pub fn owner(mut self, owner: &str) -> Self {
82 self.config.owner = owner.to_string();
83
84 self
85 }
86
87 pub fn repo(mut self, repo: &str) -> Self {
89 self.config.repo = repo.to_string();
90
91 self
92 }
93
94 #[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 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 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 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)]
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#[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}