mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 15:26:09 +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
@@ -2,4 +2,5 @@
|
|||||||
# Headless override (CI, servers without a Secret Service): GROVE_TOKEN_<ID>, where <ID> is the provider
|
# Headless override (CI, servers without a Secret Service): GROVE_TOKEN_<ID>, where <ID> is the provider
|
||||||
# id upper-cased with non-alphanumerics replaced by `_`. Example for a provider called "home":
|
# id upper-cased with non-alphanumerics replaced by `_`. Example for a provider called "home":
|
||||||
# GROVE_TOKEN_HOME=
|
# GROVE_TOKEN_HOME=
|
||||||
|
# GROVE_NO_CLI_TOKENS=1 # do not fall back to the tokens of `tea` (Gitea/Forgejo) and `gh` (GitHub)
|
||||||
# GROVE_BIN= # GUI shell only: path of the grove CLI (default: `grove` from PATH)
|
# GROVE_BIN= # GUI shell only: path of the grove CLI (default: `grove` from PATH)
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
use crate::http::Http;
|
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 grove_core::config::ProviderKind;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
@@ -40,6 +42,7 @@ impl Provider for Gitea {
|
|||||||
fn capabilities(&self) -> Capabilities {
|
fn capabilities(&self) -> Capabilities {
|
||||||
Capabilities {
|
Capabilities {
|
||||||
push_mirror: true,
|
push_mirror: true,
|
||||||
|
pull_mirror: true,
|
||||||
orgs: true,
|
orgs: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,4 +97,28 @@ impl Provider for Gitea {
|
|||||||
)
|
)
|
||||||
.map(|_| ())
|
.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::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 grove_core::config::ProviderKind;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
@@ -39,6 +41,7 @@ impl Provider for GitHub {
|
|||||||
fn capabilities(&self) -> Capabilities {
|
fn capabilities(&self) -> Capabilities {
|
||||||
Capabilities {
|
Capabilities {
|
||||||
push_mirror: false,
|
push_mirror: false,
|
||||||
|
pull_mirror: false,
|
||||||
orgs: true,
|
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",
|
"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::Unsupported(m) => write!(f, "not supported by this forge: {m}"),
|
||||||
Error::NoToken(id) => write!(
|
Error::NoToken(id) => write!(
|
||||||
f,
|
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),
|
Error::Other(m) => f.write_str(m),
|
||||||
}
|
}
|
||||||
@@ -80,9 +80,25 @@ pub struct MirrorSpec {
|
|||||||
pub struct Capabilities {
|
pub struct Capabilities {
|
||||||
/// The forge can push-mirror a repo to another forge by itself.
|
/// The forge can push-mirror a repo to another forge by itself.
|
||||||
pub push_mirror: bool,
|
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,
|
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 {
|
pub trait Provider {
|
||||||
fn kind(&self) -> ProviderKind;
|
fn kind(&self) -> ProviderKind;
|
||||||
fn capabilities(&self) -> Capabilities;
|
fn capabilities(&self) -> Capabilities;
|
||||||
@@ -91,6 +107,8 @@ pub trait Provider {
|
|||||||
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
|
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
|
||||||
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
|
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
|
||||||
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
|
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`.
|
/// 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
|
//! 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 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";
|
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<()> {
|
pub fn set(provider_id: &str, token: &str) -> Result<()> {
|
||||||
keyring::Entry::new(SERVICE, provider_id)
|
keyring::Entry::new(SERVICE, provider_id)
|
||||||
.and_then(|e| e.set_password(token))
|
.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}"))),
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use grove_core::config::ProviderKind;
|
use grove_core::config::ProviderKind;
|
||||||
use grove_providers::{Error, GitHub, Gitea, MirrorSpec, NewRepo, Provider, token};
|
use grove_providers::{Error, GitHub, Gitea, MirrorSpec, NewRepo, Provider, PullMirrorSpec, token};
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
@@ -48,6 +48,33 @@ fn mock(replies: Vec<(u16, &'static str)>) -> (String, mpsc::Receiver<String>) {
|
|||||||
(url, rx)
|
(url, rx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serialises the tests that change process-wide env vars.
|
||||||
|
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||||
|
|
||||||
|
/// Restores an env var on drop, also when an assertion panics.
|
||||||
|
struct EnvGuard(&'static str, Option<std::ffi::OsString>);
|
||||||
|
|
||||||
|
impl EnvGuard {
|
||||||
|
fn set(k: &'static str, v: impl AsRef<std::ffi::OsStr>) -> Self {
|
||||||
|
let g = EnvGuard(k, std::env::var_os(k));
|
||||||
|
// SAFETY: callers hold ENV_LOCK; no other test reads these variables.
|
||||||
|
unsafe { std::env::set_var(k, v) };
|
||||||
|
g
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for EnvGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// SAFETY: as in `set`.
|
||||||
|
unsafe {
|
||||||
|
match &self.1 {
|
||||||
|
Some(v) => std::env::set_var(self.0, v),
|
||||||
|
None => std::env::remove_var(self.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn body(req: &str) -> serde_json::Value {
|
fn body(req: &str) -> serde_json::Value {
|
||||||
serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap()
|
serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap()
|
||||||
}
|
}
|
||||||
@@ -179,7 +206,115 @@ fn unreachable_forge_is_a_network_error() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn env_var_overrides_the_keyring() {
|
fn env_var_overrides_the_keyring() {
|
||||||
assert_eq!(token::env_name("gitea-main"), "GROVE_TOKEN_GITEA_MAIN");
|
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.
|
let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
unsafe { std::env::set_var("GROVE_TOKEN_ENV_TEST", " abc ") };
|
let _g = EnvGuard::set("GROVE_TOKEN_ENV_TEST", " abc ");
|
||||||
assert_eq!(token::get("env-test").unwrap(), "abc");
|
assert_eq!(token::get("env-test").unwrap(), "abc");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gitea_pull_mirror_sends_credentials_only_for_private_sources() {
|
||||||
|
let reply = r#"{"name":"m","private":false,"clone_url":"u/m.git","owner":{"login":"Org"}}"#;
|
||||||
|
let (url, rx) = mock(vec![(201, reply), (201, reply)]);
|
||||||
|
let g = Gitea::new(ProviderKind::Gitea, &url, "secret".into());
|
||||||
|
let mut spec = PullMirrorSpec {
|
||||||
|
name: "m".into(),
|
||||||
|
owner: Some("Org".into()),
|
||||||
|
private: false,
|
||||||
|
source_url: "https://github.com/o/m.git".into(),
|
||||||
|
source_auth: None,
|
||||||
|
interval: "8h0m0s".into(),
|
||||||
|
};
|
||||||
|
assert_eq!(g.create_pull_mirror(&spec).unwrap().owner, "Org");
|
||||||
|
let req = rx.recv().unwrap();
|
||||||
|
assert!(req.starts_with("POST /api/v1/repos/migrate "), "{req}");
|
||||||
|
let b = body(&req);
|
||||||
|
assert_eq!(b["clone_addr"], "https://github.com/o/m.git");
|
||||||
|
assert_eq!(
|
||||||
|
(b["mirror"].as_bool(), b["repo_owner"].as_str()),
|
||||||
|
(Some(true), Some("Org"))
|
||||||
|
);
|
||||||
|
assert!(b.get("auth_password").is_none(), "{b}");
|
||||||
|
|
||||||
|
spec.private = true;
|
||||||
|
spec.owner = None;
|
||||||
|
spec.source_auth = Some(("me".into(), "ghtok".into()));
|
||||||
|
g.create_pull_mirror(&spec).unwrap();
|
||||||
|
let b = body(&rx.recv().unwrap());
|
||||||
|
assert_eq!(
|
||||||
|
(b["auth_username"].as_str(), b["auth_password"].as_str()),
|
||||||
|
(Some("me"), Some("ghtok"))
|
||||||
|
);
|
||||||
|
assert!(b.get("repo_owner").is_none(), "{b}");
|
||||||
|
assert_eq!(b["private"], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn github_cannot_pull_mirror() {
|
||||||
|
let g = GitHub::new("http://127.0.0.1:9", "t".into());
|
||||||
|
assert!(!g.capabilities().pull_mirror);
|
||||||
|
let spec = PullMirrorSpec {
|
||||||
|
name: "m".into(),
|
||||||
|
owner: None,
|
||||||
|
private: false,
|
||||||
|
source_url: "x".into(),
|
||||||
|
source_auth: None,
|
||||||
|
interval: "8h0m0s".into(),
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
g.create_pull_mirror(&spec),
|
||||||
|
Err(Error::Unsupported(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes PATH and GROVE_NO_CLI_TOKENS under ENV_LOCK; both are restored on drop.
|
||||||
|
#[test]
|
||||||
|
fn falls_back_to_tea_and_gh_logins() {
|
||||||
|
use grove_core::config::Provider as ProviderCfg;
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let dir = std::env::temp_dir().join(format!(
|
||||||
|
"grove-clitok-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_nanos()
|
||||||
|
));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
// tea's credential helper answers only for its host; gh echoes the host it was asked for.
|
||||||
|
let scripts = [
|
||||||
|
(
|
||||||
|
"tea",
|
||||||
|
"#!/bin/sh\nin=\"\"; while IFS= read -r l; do in=\"$in $l\"; done\ncase \"$in\" in *host=git.example.com*) printf 'protocol=https\\nhost=git.example.com\\nusername=u\\npassword=teatok\\n';; *) exit 1;; esac\n",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"gh",
|
||||||
|
"#!/bin/sh\n[ \"$4\" = github.com ] && echo ' ghtok ' || exit 1\n",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (name, body) in scripts {
|
||||||
|
let p = dir.join(name);
|
||||||
|
std::fs::write(&p, body).unwrap();
|
||||||
|
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
}
|
||||||
|
let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let _path = EnvGuard::set("PATH", &dir);
|
||||||
|
let off = EnvGuard::set("GROVE_NO_CLI_TOKENS", "0");
|
||||||
|
let gitea = |url: &str| ProviderCfg {
|
||||||
|
kind: ProviderKind::Gitea,
|
||||||
|
url: Some(url.into()),
|
||||||
|
};
|
||||||
|
let github = ProviderCfg {
|
||||||
|
kind: ProviderKind::Github,
|
||||||
|
url: None,
|
||||||
|
};
|
||||||
|
let id = format!("clitok-{}", std::process::id());
|
||||||
|
let got = token::resolve(&id, &gitea("https://git.example.com/")).unwrap();
|
||||||
|
assert_eq!(got, ("teatok".to_string(), token::Source::Tea));
|
||||||
|
assert!(token::resolve(&id, &gitea("https://other.example.com")).is_err());
|
||||||
|
let got = token::resolve(&id, &github).unwrap();
|
||||||
|
assert_eq!(got, ("ghtok".to_string(), token::Source::Gh));
|
||||||
|
drop(off);
|
||||||
|
let _off = EnvGuard::set("GROVE_NO_CLI_TOKENS", "1");
|
||||||
|
assert!(token::resolve(&id, &github).is_err());
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
Reference in new issue
Block a user