use std::fmt::Debug;
use serde::Deserialize;
use serde::Serialize;
use super::GITHUB_SCHEME;
use super::backend::GithubBuilder;
use opendal_core::{Configurator, Error, ErrorKind, OperatorUri, Result};
#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(default)]
#[non_exhaustive]
pub struct GithubConfig {
pub root: Option<String>,
pub token: Option<String>,
pub owner: String,
pub repo: String,
}
impl Debug for GithubConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GithubConfig")
.field("root", &self.root)
.field("owner", &self.owner)
.field("repo", &self.repo)
.finish_non_exhaustive()
}
}
impl Configurator for GithubConfig {
type Builder = GithubBuilder;
fn from_uri(uri: &OperatorUri) -> Result<Self> {
let owner = uri.name().ok_or_else(|| {
Error::new(ErrorKind::ConfigInvalid, "uri host must contain owner")
.with_context("service", GITHUB_SCHEME)
})?;
let raw_path = uri.root().ok_or_else(|| {
Error::new(ErrorKind::ConfigInvalid, "uri path must contain repository")
.with_context("service", GITHUB_SCHEME)
})?;
let (repo, remainder) = match raw_path.split_once('/') {
Some((repo, rest)) => (repo, Some(rest)),
None => (raw_path, None),
};
if repo.is_empty() {
return Err(
Error::new(ErrorKind::ConfigInvalid, "repository name is required")
.with_context("service", GITHUB_SCHEME),
);
}
let mut map = uri.options().clone();
map.insert("owner".to_string(), owner.to_string());
map.insert("repo".to_string(), repo.to_string());
if let Some(rest) = remainder
&& !rest.is_empty()
{
map.insert("root".to_string(), rest.to_string());
}
Self::from_iter(map)
}
fn into_builder(self) -> Self::Builder {
GithubBuilder { config: self }
}
}
#[cfg(test)]
mod tests {
use super::*;
use opendal_core::Configurator;
use opendal_core::OperatorUri;
#[test]
fn from_uri_sets_owner_repo_and_root() {
let uri = OperatorUri::new(
"github://apache/opendal/src/services",
Vec::<(String, String)>::new(),
)
.unwrap();
let cfg = GithubConfig::from_uri(&uri).unwrap();
assert_eq!(cfg.owner, "apache".to_string());
assert_eq!(cfg.repo, "opendal".to_string());
assert_eq!(cfg.root.as_deref(), Some("src/services"));
}
#[test]
fn from_uri_requires_repository() {
let uri = OperatorUri::new("github://apache", Vec::<(String, String)>::new()).unwrap();
assert!(GithubConfig::from_uri(&uri).is_err());
}
}