mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-27 07:46:13 +00:00
feat(providers): Gitea/Forgejo and GitHub clients, token storage
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0e77dd26d9
commit
e599d48db8
9 files changed
+2392
-8
No files matched your search
Generated
+1791
-7
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = ["crates/grove-core", "crates/grove", "crates/grove-daemon"]
|
members = ["crates/grove-core", "crates/grove", "crates/grove-daemon", "crates/grove-providers"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[package]
|
||||||
|
name = "grove-providers"
|
||||||
|
description = "Forge providers (Gitea/Forgejo, GitHub) and token storage for grove"
|
||||||
|
edition.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
grove-core = { version = "0.1.0", path = "../grove-core" }
|
||||||
|
keyring = "4.2.0"
|
||||||
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
serde_json = "1.0.154"
|
||||||
|
ureq = { version = "3", features = ["json"] }
|
||||||
@@ -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(|_| ())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
use grove_core::config::ProviderKind;
|
||||||
|
use grove_providers::{Error, GitHub, Gitea, MirrorSpec, NewRepo, Provider, token};
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use std::sync::mpsc;
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
/// Serves the scripted `(status, body)` replies in order, one connection each, and reports
|
||||||
|
/// every raw request it received.
|
||||||
|
fn mock(replies: Vec<(u16, &'static str)>) -> (String, mpsc::Receiver<String>) {
|
||||||
|
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let url = format!("http://{}", l.local_addr().unwrap());
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
thread::spawn(move || {
|
||||||
|
for (status, body) in replies {
|
||||||
|
let (mut s, _) = l.accept().unwrap();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let mut chunk = [0u8; 4096];
|
||||||
|
loop {
|
||||||
|
let n = s.read(&mut chunk).unwrap();
|
||||||
|
buf.extend_from_slice(&chunk[..n]);
|
||||||
|
let text = String::from_utf8_lossy(&buf).to_string();
|
||||||
|
if let Some(h) = text.find("\r\n\r\n") {
|
||||||
|
let len = text[..h]
|
||||||
|
.lines()
|
||||||
|
.find_map(|l| {
|
||||||
|
l.to_ascii_lowercase()
|
||||||
|
.strip_prefix("content-length:")
|
||||||
|
.map(|v| v.trim().parse::<usize>().unwrap())
|
||||||
|
})
|
||||||
|
.unwrap_or(0);
|
||||||
|
if buf.len() >= h + 4 + len {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.send(String::from_utf8_lossy(&buf).to_string()).unwrap();
|
||||||
|
let resp = format!(
|
||||||
|
"HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
);
|
||||||
|
s.write_all(resp.as_bytes()).unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
(url, rx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body(req: &str) -> serde_json::Value {
|
||||||
|
serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gitea_connection_list_create_and_mirror() {
|
||||||
|
let (url, rx) = mock(vec![
|
||||||
|
(200, r#"{"login":"dasemu"}"#),
|
||||||
|
(
|
||||||
|
200,
|
||||||
|
r#"[{"name":"a","private":true,"clone_url":"u/a.git","default_branch":"main","owner":{"login":"dasemu"}}]"#,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
201,
|
||||||
|
r#"{"name":"n","private":true,"clone_url":"u/n.git","default_branch":"main","owner":{"login":"dasemu"}}"#,
|
||||||
|
),
|
||||||
|
(200, "{}"),
|
||||||
|
]);
|
||||||
|
let g = Gitea::new(ProviderKind::Gitea, &url, "secret".into());
|
||||||
|
assert_eq!(g.test_connection().unwrap(), "dasemu");
|
||||||
|
let first = rx.recv().unwrap();
|
||||||
|
assert!(first.starts_with("GET /api/v1/user "), "{first}");
|
||||||
|
assert!(first.to_lowercase().contains("authorization: token secret"));
|
||||||
|
|
||||||
|
let repos = g.list_repos().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(repos.len(), repos[0].name.as_str(), repos[0].private),
|
||||||
|
(1, "a", true)
|
||||||
|
);
|
||||||
|
|
||||||
|
let r = g
|
||||||
|
.create_repo(&NewRepo {
|
||||||
|
name: "n".into(),
|
||||||
|
owner: None,
|
||||||
|
private: true,
|
||||||
|
description: "d".into(),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.clone_url, "u/n.git");
|
||||||
|
rx.recv().unwrap();
|
||||||
|
let create = rx.recv().unwrap();
|
||||||
|
assert!(create.starts_with("POST /api/v1/user/repos "), "{create}");
|
||||||
|
assert_eq!(body(&create)["private"], true);
|
||||||
|
|
||||||
|
g.configure_mirror(
|
||||||
|
"dasemu",
|
||||||
|
"n",
|
||||||
|
&MirrorSpec {
|
||||||
|
remote_url: "https://github.com/x/n.git".into(),
|
||||||
|
remote_username: "x".into(),
|
||||||
|
remote_token: "t".into(),
|
||||||
|
interval: "8h0m0s".into(),
|
||||||
|
sync_on_commit: true,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let m = rx.recv().unwrap();
|
||||||
|
assert!(
|
||||||
|
m.starts_with("POST /api/v1/repos/dasemu/n/push_mirrors "),
|
||||||
|
"{m}"
|
||||||
|
);
|
||||||
|
assert_eq!(body(&m)["sync_on_commit"], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gitea_org_create_uses_org_endpoint_and_api_errors_carry_status() {
|
||||||
|
let (url, rx) = mock(vec![
|
||||||
|
(409, r#"{"message":"repository already exists"}"#),
|
||||||
|
(401, r#"{"message":"bad token"}"#),
|
||||||
|
]);
|
||||||
|
let g = Gitea::new(ProviderKind::Forgejo, &url, "t".into());
|
||||||
|
let e = g
|
||||||
|
.create_repo(&NewRepo {
|
||||||
|
name: "n".into(),
|
||||||
|
owner: Some("org".into()),
|
||||||
|
private: false,
|
||||||
|
description: String::new(),
|
||||||
|
})
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(e, Error::Api { status: 409, .. }), "{e}");
|
||||||
|
assert!(
|
||||||
|
rx.recv()
|
||||||
|
.unwrap()
|
||||||
|
.starts_with("POST /api/v1/orgs/org/repos ")
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
g.test_connection().unwrap_err(),
|
||||||
|
Error::Api { status: 401, .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn github_uses_bearer_and_has_no_push_mirror() {
|
||||||
|
let (url, rx) = mock(vec![(200, r#"{"login":"me"}"#)]);
|
||||||
|
let g = GitHub::new(&url, "tok".into());
|
||||||
|
assert_eq!(g.test_connection().unwrap(), "me");
|
||||||
|
assert!(
|
||||||
|
rx.recv()
|
||||||
|
.unwrap()
|
||||||
|
.to_lowercase()
|
||||||
|
.contains("authorization: bearer tok")
|
||||||
|
);
|
||||||
|
assert!(!g.capabilities().push_mirror);
|
||||||
|
let e = g
|
||||||
|
.configure_mirror(
|
||||||
|
"o",
|
||||||
|
"r",
|
||||||
|
&MirrorSpec {
|
||||||
|
remote_url: String::new(),
|
||||||
|
remote_username: String::new(),
|
||||||
|
remote_token: String::new(),
|
||||||
|
interval: String::new(),
|
||||||
|
sync_on_commit: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(e, Error::Unsupported(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unreachable_forge_is_a_network_error() {
|
||||||
|
let g = Gitea::new(ProviderKind::Gitea, "http://127.0.0.1:1", "t".into());
|
||||||
|
assert!(matches!(
|
||||||
|
g.test_connection().unwrap_err(),
|
||||||
|
Error::Network(_)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn env_var_overrides_the_keyring() {
|
||||||
|
assert_eq!(token::env_name("gitea-main"), "GROVE_TOKEN_GITEA_MAIN");
|
||||||
|
// SAFETY: tests in this binary that touch this variable run in this single test.
|
||||||
|
unsafe { std::env::set_var("GROVE_TOKEN_ENV_TEST", " abc ") };
|
||||||
|
assert_eq!(token::get("env-test").unwrap(), "abc");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user