feat(providers): Gitea/Forgejo and GitHub clients, token storage

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 13:19:33 +01:00
1 parent 0e77dd26d9
commit e599d48db8
9 files changed
+2392 -8

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
use crate::http::Http;
use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result};
use grove_core::config::ProviderKind;
use serde_json::{Value, json};
/// Gitea and Forgejo share the same `/api/v1`.
pub struct Gitea {
kind: ProviderKind,
http: Http,
}
impl Gitea {
pub fn new(kind: ProviderKind, url: &str, token: String) -> Self {
Gitea {
kind,
http: Http::new(
&format!("{}/api/v1", url.trim_end_matches('/')),
format!("token {token}"),
),
}
}
}
fn repo(v: &Value) -> RemoteRepo {
let s = |k: &str| v[k].as_str().unwrap_or_default().to_string();
RemoteRepo {
owner: v["owner"]["login"].as_str().unwrap_or_default().to_string(),
name: s("name"),
private: v["private"].as_bool().unwrap_or(false),
clone_url: s("clone_url"),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
impl Provider for Gitea {
fn kind(&self) -> ProviderKind {
self.kind
}
fn capabilities(&self) -> Capabilities {
Capabilities {
push_mirror: true,
orgs: true,
}
}
fn test_connection(&self) -> Result<String> {
let u = self.http.ok("GET", "/user", None)?;
u["login"]
.as_str()
.map(str::to_string)
.ok_or_else(|| Error::Other("response has no login".into()))
}
fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
let mut out = Vec::new();
for page in 1..=200 {
let v = self
.http
.ok("GET", &format!("/user/repos?limit=50&page={page}"), None)?;
let items = v.as_array().cloned().unwrap_or_default();
let n = items.len();
out.extend(items.iter().map(repo));
if n < 50 {
break;
}
}
Ok(out)
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
let path = match &new.owner {
Some(o) => format!("/orgs/{o}/repos"),
None => "/user/repos".to_string(),
};
let body = json!({"name": new.name, "private": new.private,
"description": new.description, "default_branch": "main"});
Ok(repo(&self.http.ok("POST", &path, Some(&body))?))
}
fn configure_mirror(&self, owner: &str, name: &str, spec: &MirrorSpec) -> Result<()> {
let body = json!({
"remote_address": spec.remote_url,
"remote_username": spec.remote_username,
"remote_password": spec.remote_token,
"interval": spec.interval,
"sync_on_commit": spec.sync_on_commit,
});
self.http
.ok(
"POST",
&format!("/repos/{owner}/{name}/push_mirrors"),
Some(&body),
)
.map(|_| ())
}
}
+87
View File
@@ -0,0 +1,87 @@
use crate::http::Http;
use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result};
use grove_core::config::ProviderKind;
use serde_json::{Value, json};
pub struct GitHub {
http: Http,
}
impl GitHub {
/// `url` empty means github.com; set it for GitHub Enterprise (`https://host/api/v3`) or tests.
pub fn new(url: &str, token: String) -> Self {
let base = if url.is_empty() || url == "https://github.com" {
"https://api.github.com"
} else {
url
};
GitHub {
http: Http::new(base, format!("Bearer {token}")),
}
}
}
fn repo(v: &Value) -> RemoteRepo {
RemoteRepo {
owner: v["owner"]["login"].as_str().unwrap_or_default().to_string(),
name: v["name"].as_str().unwrap_or_default().to_string(),
private: v["private"].as_bool().unwrap_or(false),
clone_url: v["clone_url"].as_str().unwrap_or_default().to_string(),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
impl Provider for GitHub {
fn kind(&self) -> ProviderKind {
ProviderKind::Github
}
fn capabilities(&self) -> Capabilities {
Capabilities {
push_mirror: false,
orgs: true,
}
}
fn test_connection(&self) -> Result<String> {
let u = self.http.ok("GET", "/user", None)?;
u["login"]
.as_str()
.map(str::to_string)
.ok_or_else(|| Error::Other("response has no login".into()))
}
fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
let mut out = Vec::new();
for page in 1..=200 {
let v = self.http.ok(
"GET",
&format!("/user/repos?per_page=100&page={page}"),
None,
)?;
let items = v.as_array().cloned().unwrap_or_default();
let n = items.len();
out.extend(items.iter().map(repo));
if n < 100 {
break;
}
}
Ok(out)
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
let path = match &new.owner {
Some(o) => format!("/orgs/{o}/repos"),
None => "/user/repos".to_string(),
};
let body =
json!({"name": new.name, "private": new.private, "description": new.description});
Ok(repo(&self.http.ok("POST", &path, Some(&body))?))
}
fn configure_mirror(&self, _: &str, _: &str, _: &MirrorSpec) -> Result<()> {
Err(Error::Unsupported(
"GitHub has no push mirrors; use a Gitea pull mirror or the daemon's branch push",
))
}
}
+63
View File
@@ -0,0 +1,63 @@
use crate::{Error, Result};
use serde_json::Value;
use std::time::Duration;
pub struct Http {
base: String,
auth: String,
agent: ureq::Agent,
}
impl Http {
pub fn new(base: &str, auth: String) -> Self {
let agent: ureq::Agent = ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(Duration::from_secs(30)))
.build()
.into();
Http {
base: base.trim_end_matches('/').to_string(),
auth,
agent,
}
}
/// Returns the status and the parsed JSON body (`Null` when empty or not JSON).
pub fn send(&self, method: &str, path: &str, body: Option<&Value>) -> Result<(u16, Value)> {
let url = format!("{}{}", self.base, path);
let net = |e: ureq::Error| Error::Network(e.to_string());
let mut resp = match (method, body) {
("GET", _) => self
.agent
.get(&url)
.header("Authorization", &self.auth)
.header("Accept", "application/json")
.call(),
("POST", Some(b)) => self
.agent
.post(&url)
.header("Authorization", &self.auth)
.header("Accept", "application/json")
.send_json(b),
_ => return Err(Error::Other(format!("unsupported request {method}"))),
}
.map_err(net)?;
let status = resp.status().as_u16();
let text = resp.body_mut().read_to_string().map_err(net)?;
let json = serde_json::from_str(&text).unwrap_or(Value::Null);
Ok((status, json))
}
/// Like [`send`], but maps non-2xx statuses to [`Error::Api`].
pub fn ok(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value> {
let (status, json) = self.send(method, path, body)?;
if (200..300).contains(&status) {
return Ok(json);
}
let message = json["message"]
.as_str()
.unwrap_or("(no message)")
.to_string();
Err(Error::Api { status, message })
}
}
+108
View File
@@ -0,0 +1,108 @@
//! Forge providers (Gitea/Forgejo, GitHub) and token storage.
//!
//! Providers only talk to the forge's REST API. Nothing here ever deletes a remote repository.
mod gitea;
mod github;
mod http;
pub mod token;
pub use gitea::Gitea;
pub use github::GitHub;
use grove_core::config::{Provider as ProviderCfg, ProviderKind};
use std::fmt;
#[derive(Debug)]
pub enum Error {
/// Transport problem (DNS, TLS, timeout...).
Network(String),
/// The forge answered with an error status.
Api {
status: u16,
message: String,
},
/// The forge cannot do what was asked (see [`Capabilities`]).
Unsupported(&'static str),
/// No token stored for the provider.
NoToken(String),
Other(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Network(m) => write!(f, "network error: {m}"),
Error::Api { status, message } => write!(f, "forge returned {status}: {message}"),
Error::Unsupported(m) => write!(f, "not supported by this forge: {m}"),
Error::NoToken(id) => write!(
f,
"no token for provider {id:?} (run `grove login {id}` or set GROVE_TOKEN_*)"
),
Error::Other(m) => f.write_str(m),
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteRepo {
pub owner: String,
pub name: String,
pub private: bool,
pub clone_url: String,
pub default_branch: String,
}
#[derive(Debug, Clone)]
pub struct NewRepo {
pub name: String,
/// Create under this organisation instead of the authenticated user.
pub owner: Option<String>,
pub private: bool,
pub description: String,
}
/// Push mirror from the primary forge to a secondary one.
#[derive(Debug, Clone)]
pub struct MirrorSpec {
pub remote_url: String,
pub remote_username: String,
pub remote_token: String,
/// Go-style duration (`8h0m0s`); `0` disables the periodic sync.
pub interval: String,
pub sync_on_commit: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capabilities {
/// The forge can push-mirror a repo to another forge by itself.
pub push_mirror: bool,
pub orgs: bool,
}
pub trait Provider {
fn kind(&self) -> ProviderKind;
fn capabilities(&self) -> Capabilities;
/// Verifies the token and returns the authenticated login.
fn test_connection(&self) -> Result<String>;
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
}
/// Builds the provider described by `cfg`, using `token`.
pub fn build(cfg: &ProviderCfg, token: String) -> Box<dyn Provider> {
match cfg.kind {
ProviderKind::Gitea | ProviderKind::Forgejo => Box::new(Gitea::new(
cfg.kind,
cfg.url.as_deref().unwrap_or_default(),
token,
)),
ProviderKind::Github => {
Box::new(GitHub::new(cfg.url.as_deref().unwrap_or_default(), token))
}
}
}
+47
View File
@@ -0,0 +1,47 @@
//! Token storage: `GROVE_TOKEN_<ID>` env var first (headless machines, tests), then the
//! desktop Secret Service. Tokens are never written to the config file.
use crate::{Error, Result};
const SERVICE: &str = "grove";
pub fn env_name(provider_id: &str) -> String {
let id: String = provider_id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_uppercase()
} else {
'_'
}
})
.collect();
format!("GROVE_TOKEN_{id}")
}
pub fn get(provider_id: &str) -> Result<String> {
if let Ok(t) = std::env::var(env_name(provider_id))
&& !t.trim().is_empty()
{
return Ok(t.trim().to_string());
}
let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?;
match e.get_password() {
Ok(t) => Ok(t),
Err(keyring::Error::NoEntry) => Err(Error::NoToken(provider_id.into())),
Err(e) => Err(Error::Other(format!("secret service: {e}"))),
}
}
pub fn set(provider_id: &str, token: &str) -> Result<()> {
keyring::Entry::new(SERVICE, provider_id)
.and_then(|e| e.set_password(token))
.map_err(|e| Error::Other(format!("secret service: {e}")))
}
pub fn delete(provider_id: &str) -> Result<()> {
match keyring::Entry::new(SERVICE, provider_id).and_then(|e| e.delete_credential()) {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(Error::Other(format!("secret service: {e}"))),
}
}