mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
feat(providers): pull mirrors on Gitea and tea/gh token fallback
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
251bfe3685
commit
e2631e7ab7
6 files changed
+337
-7
No files matched your search
@@ -1,5 +1,7 @@
|
||||
use crate::http::Http;
|
||||
use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result};
|
||||
use crate::{
|
||||
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result,
|
||||
};
|
||||
use grove_core::config::ProviderKind;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -40,6 +42,7 @@ impl Provider for Gitea {
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities {
|
||||
push_mirror: true,
|
||||
pull_mirror: true,
|
||||
orgs: true,
|
||||
}
|
||||
}
|
||||
@@ -94,4 +97,28 @@ impl Provider for Gitea {
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo> {
|
||||
let mut body = json!({
|
||||
"clone_addr": spec.source_url,
|
||||
"repo_name": spec.name,
|
||||
"mirror": true,
|
||||
"mirror_interval": spec.interval,
|
||||
"private": spec.private,
|
||||
"service": "git",
|
||||
"description": "Mirror managed by grove",
|
||||
});
|
||||
if let Some(o) = &spec.owner {
|
||||
body["repo_owner"] = json!(o);
|
||||
}
|
||||
if let Some((user, token)) = &spec.source_auth {
|
||||
body["auth_username"] = json!(user);
|
||||
body["auth_password"] = json!(token);
|
||||
}
|
||||
Ok(repo(&self.http.ok(
|
||||
"POST",
|
||||
"/repos/migrate",
|
||||
Some(&body),
|
||||
)?))
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::http::Http;
|
||||
use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result};
|
||||
use crate::{
|
||||
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result,
|
||||
};
|
||||
use grove_core::config::ProviderKind;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -39,6 +41,7 @@ impl Provider for GitHub {
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities {
|
||||
push_mirror: false,
|
||||
pull_mirror: false,
|
||||
orgs: true,
|
||||
}
|
||||
}
|
||||
@@ -84,4 +87,10 @@ impl Provider for GitHub {
|
||||
"GitHub has no push mirrors; use a Gitea pull mirror or the daemon's branch push",
|
||||
))
|
||||
}
|
||||
|
||||
fn create_pull_mirror(&self, _: &PullMirrorSpec) -> Result<RemoteRepo> {
|
||||
Err(Error::Unsupported(
|
||||
"GitHub cannot pull-mirror another forge",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ impl fmt::Display for Error {
|
||||
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_*)"
|
||||
"no token for provider {id:?} (log in with `tea`/`gh`, run `grove login {id}` or set GROVE_TOKEN_*)"
|
||||
),
|
||||
Error::Other(m) => f.write_str(m),
|
||||
}
|
||||
@@ -80,9 +80,25 @@ pub struct MirrorSpec {
|
||||
pub struct Capabilities {
|
||||
/// The forge can push-mirror a repo to another forge by itself.
|
||||
pub push_mirror: bool,
|
||||
/// The forge can create a repo that pulls (mirrors) another forge's repo on a schedule.
|
||||
pub pull_mirror: bool,
|
||||
pub orgs: bool,
|
||||
}
|
||||
|
||||
/// A repo on this forge that mirrors `source_url` (another forge) by pulling it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PullMirrorSpec {
|
||||
pub name: String,
|
||||
/// Create under this organisation instead of the authenticated user.
|
||||
pub owner: Option<String>,
|
||||
pub private: bool,
|
||||
pub source_url: String,
|
||||
/// Credentials for a private source; `None` for a public one (nothing is stored).
|
||||
pub source_auth: Option<(String, String)>,
|
||||
/// Go-style duration (`8h0m0s`).
|
||||
pub interval: String,
|
||||
}
|
||||
|
||||
pub trait Provider {
|
||||
fn kind(&self) -> ProviderKind;
|
||||
fn capabilities(&self) -> Capabilities;
|
||||
@@ -91,6 +107,8 @@ pub trait Provider {
|
||||
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<()>;
|
||||
/// Creates a pull mirror (see [`Capabilities::pull_mirror`]).
|
||||
fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo>;
|
||||
}
|
||||
|
||||
/// Builds the provider described by `cfg`, using `token`.
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
//! Token storage: `GROVE_TOKEN_<ID>` env var first (headless machines, tests), then the
|
||||
//! desktop Secret Service. Tokens are never written to the config file.
|
||||
//! desktop Secret Service, then the login of the forge's own CLI (`tea`, `gh`) if present.
|
||||
//! Tokens are never written to the config file.
|
||||
|
||||
use crate::{Error, Result};
|
||||
use grove_core::config::{Provider as ProviderCfg, ProviderKind};
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const SERVICE: &str = "grove";
|
||||
|
||||
@@ -33,6 +38,107 @@ pub fn get(provider_id: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a token came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Source {
|
||||
Grove,
|
||||
Tea,
|
||||
Gh,
|
||||
}
|
||||
|
||||
/// [`get`], falling back to the forge CLI's own login (`tea` for Gitea/Forgejo, `gh` for
|
||||
/// GitHub) when grove has no token of its own. Set `GROVE_NO_CLI_TOKENS=1` to disable it.
|
||||
pub fn resolve(provider_id: &str, cfg: &ProviderCfg) -> Result<(String, Source)> {
|
||||
let own = match get(provider_id) {
|
||||
Ok(t) => return Ok((t, Source::Grove)),
|
||||
Err(e) => e,
|
||||
};
|
||||
if std::env::var_os("GROVE_NO_CLI_TOKENS").is_some_and(|v| !v.is_empty() && v != "0") {
|
||||
return Err(own);
|
||||
}
|
||||
let host = host(cfg);
|
||||
let found = match cfg.kind {
|
||||
ProviderKind::Gitea | ProviderKind::Forgejo => host
|
||||
.as_deref()
|
||||
.and_then(tea_token)
|
||||
.map(|t| (t, Source::Tea)),
|
||||
ProviderKind::Github => {
|
||||
gh_token(host.as_deref().unwrap_or("github.com")).map(|t| (t, Source::Gh))
|
||||
}
|
||||
};
|
||||
// Report grove's own error (no token / Secret Service down) when the CLIs have nothing.
|
||||
found.ok_or(own)
|
||||
}
|
||||
|
||||
/// Host (with port) of the provider URL, without user info. For GitHub a leading `api.` is
|
||||
/// dropped so Enterprise API URLs map to the host `gh` knows. `None` when no URL is configured.
|
||||
fn host(cfg: &ProviderCfg) -> Option<String> {
|
||||
let url = cfg.url.as_deref()?.trim();
|
||||
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
||||
let h = rest.split(['/', '?', '#']).next()?.trim();
|
||||
let h = h.rsplit_once('@').map_or(h, |(_, h)| h);
|
||||
let h = match cfg.kind {
|
||||
ProviderKind::Github => h.strip_prefix("api.").unwrap_or(h),
|
||||
_ => h,
|
||||
};
|
||||
(!h.is_empty()).then(|| h.to_string())
|
||||
}
|
||||
|
||||
/// How long a forge CLI may take to answer (it may be waiting on a keyring unlock prompt).
|
||||
const CLI_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
fn run(cmd: &str, args: &[&str], stdin: Option<&str>) -> Option<String> {
|
||||
let mut child = Command::new(cmd)
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let wrote = match (stdin, child.stdin.take()) {
|
||||
(Some(input), Some(mut w)) => w.write_all(input.as_bytes()).is_ok(),
|
||||
_ => true, // dropping the handle closes stdin
|
||||
};
|
||||
// Outputs are a few bytes, so the pipe cannot fill up while we poll.
|
||||
let deadline = Instant::now() + CLI_TIMEOUT;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(s)) => break Some(s),
|
||||
Ok(None) if wrote && Instant::now() < deadline => {
|
||||
std::thread::sleep(Duration::from_millis(20))
|
||||
}
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
}
|
||||
}?;
|
||||
let mut out = String::new();
|
||||
child.stdout.take()?.read_to_string(&mut out).ok()?;
|
||||
status.success().then_some(out)
|
||||
}
|
||||
|
||||
/// Asks tea's git credential helper, which matches the host against tea's logins.
|
||||
fn tea_token(host: &str) -> Option<String> {
|
||||
let out = run(
|
||||
"tea",
|
||||
&["login", "helper", "get"],
|
||||
Some(&format!("protocol=https\nhost={host}\n\n")),
|
||||
)?;
|
||||
out.lines()
|
||||
.find_map(|l| l.strip_prefix("password="))
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
fn gh_token(host: &str) -> Option<String> {
|
||||
let t = run("gh", &["auth", "token", "--hostname", host], None)?;
|
||||
let t = t.trim();
|
||||
(!t.is_empty()).then(|| t.to_string())
|
||||
}
|
||||
|
||||
pub fn set(provider_id: &str, token: &str) -> Result<()> {
|
||||
keyring::Entry::new(SERVICE, provider_id)
|
||||
.and_then(|e| e.set_password(token))
|
||||
@@ -45,3 +151,37 @@ pub fn delete(provider_id: &str) -> Result<()> {
|
||||
Err(e) => Err(Error::Other(format!("secret service: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn host_strips_scheme_path_userinfo_and_github_api_prefix() {
|
||||
let h = |kind, url: &str| {
|
||||
host(&ProviderCfg {
|
||||
kind,
|
||||
url: Some(url.into()),
|
||||
})
|
||||
};
|
||||
let g = ProviderKind::Gitea;
|
||||
assert_eq!(
|
||||
h(g, "https://git.example.com/").as_deref(),
|
||||
Some("git.example.com")
|
||||
);
|
||||
assert_eq!(
|
||||
h(g, "https://u@git.example.com:3000/x").as_deref(),
|
||||
Some("git.example.com:3000")
|
||||
);
|
||||
assert_eq!(
|
||||
h(g, "https://api.example.com").as_deref(),
|
||||
Some("api.example.com")
|
||||
);
|
||||
let gh = ProviderKind::Github;
|
||||
assert_eq!(
|
||||
h(gh, "https://api.ghe.corp/api/v3").as_deref(),
|
||||
Some("ghe.corp")
|
||||
);
|
||||
assert_eq!(h(gh, "").as_deref(), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user