use std::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;
use bytes::Buf;
use http::Response;
use http::StatusCode;
use log::debug;
use super::core::Entry;
use super::core::GithubCore;
use super::error::parse_error;
use super::lister::GithubLister;
use super::writer::GithubWriter;
use super::writer::GithubWriters;
use crate::raw::*;
use crate::services::GithubConfig;
use crate::*;
impl Configurator for GithubConfig {
type Builder = GithubBuilder;
fn into_builder(self) -> Self::Builder {
GithubBuilder {
config: self,
http_client: None,
}
}
}
#[doc = include_str!("docs.md")]
#[derive(Default)]
pub struct GithubBuilder {
config: GithubConfig,
http_client: Option<HttpClient>,
}
impl Debug for GithubBuilder {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("GithubBuilder");
d.field("config", &self.config);
d.finish_non_exhaustive()
}
}
impl GithubBuilder {
pub fn root(mut self, root: &str) -> Self {
self.config.root = if root.is_empty() {
None
} else {
Some(root.to_string())
};
self
}
pub fn token(mut self, token: &str) -> Self {
if !token.is_empty() {
self.config.token = Some(token.to_string());
}
self
}
pub fn owner(mut self, owner: &str) -> Self {
self.config.owner = owner.to_string();
self
}
pub fn repo(mut self, repo: &str) -> Self {
self.config.repo = repo.to_string();
self
}
pub fn http_client(mut self, client: HttpClient) -> Self {
self.http_client = Some(client);
self
}
}
impl Builder for GithubBuilder {
const SCHEME: Scheme = Scheme::Github;
type Config = GithubConfig;
fn build(self) -> Result<impl Access> {
debug!("backend build started: {:?}", &self);
let root = normalize_root(&self.config.root.clone().unwrap_or_default());
debug!("backend use root {}", &root);
if self.config.owner.is_empty() {
return Err(Error::new(ErrorKind::ConfigInvalid, "owner is empty")
.with_operation("Builder::build")
.with_context("service", Scheme::Github));
}
debug!("backend use owner {}", &self.config.owner);
if self.config.repo.is_empty() {
return Err(Error::new(ErrorKind::ConfigInvalid, "repo is empty")
.with_operation("Builder::build")
.with_context("service", Scheme::Github));
}
debug!("backend use repo {}", &self.config.repo);
let client = if let Some(client) = self.http_client {
client
} else {
HttpClient::new().map_err(|err| {
err.with_operation("Builder::build")
.with_context("service", Scheme::Github)
})?
};
Ok(GithubBackend {
core: Arc::new(GithubCore {
root,
token: self.config.token.clone(),
owner: self.config.owner.clone(),
repo: self.config.repo.clone(),
client,
}),
})
}
}
#[derive(Debug, Clone)]
pub struct GithubBackend {
core: Arc<GithubCore>,
}
impl Access for GithubBackend {
type Reader = HttpBody;
type Writer = GithubWriters;
type Lister = oio::PageLister<GithubLister>;
type BlockingReader = ();
type BlockingWriter = ();
type BlockingLister = ();
fn info(&self) -> Arc<AccessorInfo> {
let mut am = AccessorInfo::default();
am.set_scheme(Scheme::Github)
.set_root(&self.core.root)
.set_native_capability(Capability {
stat: true,
read: true,
create_dir: true,
write: true,
write_can_empty: true,
delete: true,
list: true,
list_with_recursive: true,
shared: true,
..Default::default()
});
am.into()
}
async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
let empty_bytes = Buffer::new();
let resp = self
.core
.upload(&format!("{}.gitkeep", path), empty_bytes)
.await?;
let status = resp.status();
match status {
StatusCode::OK | StatusCode::CREATED => Ok(RpCreateDir::default()),
_ => Err(parse_error(resp)),
}
}
async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
let resp = self.core.stat(path).await?;
let status = resp.status();
match status {
StatusCode::OK => {
let body = resp.into_body();
let resp: Entry =
serde_json::from_reader(body.reader()).map_err(new_json_deserialize_error)?;
let m = if resp.type_field == "dir" {
Metadata::new(EntryMode::DIR)
} else {
Metadata::new(EntryMode::FILE)
.with_content_length(resp.size)
.with_etag(resp.sha)
};
Ok(RpStat::new(m))
}
_ => Err(parse_error(resp)),
}
}
async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
let resp = self.core.get(path, args.range()).await?;
let status = resp.status();
match status {
StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
Ok((RpRead::default(), resp.into_body()))
}
_ => {
let (part, mut body) = resp.into_parts();
let buf = body.to_buffer().await?;
Err(parse_error(Response::from_parts(part, buf)))
}
}
}
async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
let writer = GithubWriter::new(self.core.clone(), path.to_string());
let w = oio::OneShotWriter::new(writer);
Ok((RpWrite::default(), w))
}
async fn delete(&self, path: &str, _: OpDelete) -> Result<RpDelete> {
match self.core.delete(path).await {
Ok(_) => Ok(RpDelete::default()),
Err(err) => Err(err),
}
}
async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
let l = GithubLister::new(self.core.clone(), path, args.recursive());
Ok((RpList::default(), oio::PageLister::new(l)))
}
}