use miyabi_types::error::{MiyabiError, Result};
use octocrab::Octocrab;
#[derive(Clone)]
pub struct GitHubClient {
pub(crate) client: Octocrab,
pub(crate) owner: String,
pub(crate) repo: String,
}
impl GitHubClient {
pub fn new(
token: impl Into<String>,
owner: impl Into<String>,
repo: impl Into<String>,
) -> Result<Self> {
let client = Octocrab::builder()
.personal_token(token.into())
.build()
.map_err(|e| MiyabiError::GitHub(format!("Failed to build Octocrab client: {}", e)))?;
Ok(Self {
client,
owner: owner.into(),
repo: repo.into(),
})
}
pub fn octocrab(&self) -> &Octocrab {
&self.client
}
pub fn owner(&self) -> &str {
&self.owner
}
pub fn repo(&self) -> &str {
&self.repo
}
pub fn full_name(&self) -> String {
format!("{}/{}", self.owner, self.repo)
}
pub async fn verify_auth(&self) -> Result<String> {
let user = self
.client
.current()
.user()
.await
.map_err(|e| MiyabiError::GitHub(format!("Authentication failed: {}", e)))?;
Ok(user.login)
}
pub async fn get_repository(&self) -> Result<octocrab::models::Repository> {
self.client
.repos(&self.owner, &self.repo)
.get()
.await
.map_err(|e| {
MiyabiError::GitHub(format!(
"Failed to get repository {}/{}: {}",
self.owner, self.repo, e
))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_client_creation() {
let client = GitHubClient::new("ghp_test", "owner", "repo");
assert!(client.is_ok());
let client = client.unwrap();
assert_eq!(client.owner(), "owner");
assert_eq!(client.repo(), "repo");
assert_eq!(client.full_name(), "owner/repo");
}
#[tokio::test]
async fn test_client_cloning() {
let client = GitHubClient::new("ghp_test", "owner", "repo").unwrap();
let _cloned = client.clone();
assert_eq!(client.owner(), "owner");
}
}