feat: owner-scoped import listing, ssh protocol, robust import

- providers: list_owner_repos (org/user endpoints), ssh_url, Send+Sync
- import: parallel sides, case-insensitive/origin-based presence check,
  continue after failed clones and report them
- config: per-provider protocol (https|ssh); GUI settings, onboarding
- gui: import scan on its own thread, per-group cache, Rescan, failures

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 18:09:34 +01:00
1 parent 5aeb7b2077
commit 28e07aab56
14 files changed
+580 -119

No files matched your search

+38
View File
@@ -37,9 +37,35 @@ pub enum ProviderKind {
Github,
}
/// How local git talks to a forge: HTTPS with the API token, or SSH with the user's keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
#[default]
Https,
Ssh,
}
fn is_https(p: &Protocol) -> bool {
*p == Protocol::Https
}
impl Protocol {
pub fn as_str(self) -> &'static str {
match self {
Protocol::Https => "https",
Protocol::Ssh => "ssh",
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Provider {
pub kind: ProviderKind,
/// Transport for clone/fetch/push (`https` by default). Mirrors are server-side and always
/// use HTTPS.
#[serde(default, skip_serializing_if = "is_https")]
pub protocol: Protocol,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
@@ -485,4 +511,16 @@ mirror_to = ["gitea"]
let t = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitlab\"\n";
assert!(matches!(Config::parse(t), Err(ConfigError::Parse(_))));
}
#[test]
fn provider_protocol_defaults_to_https_and_is_validated() {
let t = |p: &str| {
format!("[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitea\"\n{p}")
};
assert_eq!(Config::parse(&t("")).unwrap().providers["p"].protocol, Protocol::Https);
let c = Config::parse(&t("protocol=\"ssh\"\n")).unwrap();
assert_eq!(c.providers["p"].protocol, Protocol::Ssh);
assert!(toml::to_string(&c).unwrap().contains("protocol = \"ssh\""));
assert!(Config::parse(&t("protocol=\"git\"\n")).is_err());
}
}
+1
View File
@@ -97,6 +97,7 @@ fn flag_spec(sub: &str) -> (&'static [&'static str], &'static [&'static str]) {
"--root",
"--provider",
"--kind",
"--protocol",
"--group",
"--config-repo",
"--url",
+71 -33
View File
@@ -126,6 +126,10 @@ struct UiState {
filter: String,
pending: Option<Vec<String>>,
picks: Rc<VecModel<Pick>>,
/// Last successful scan per import group, for the session (names still to import).
import_cache: HashMap<String, Vec<String>>,
/// The group whose scan the list on screen belongs to.
import_current: String,
toast_gen: u32,
last_groups: Vec<String>,
last_providers: Vec<String>,
@@ -142,6 +146,8 @@ thread_local! {
filter: String::new(),
pending: None,
picks: Rc::new(VecModel::default()),
import_cache: HashMap::new(),
import_current: String::new(),
toast_gen: 0,
last_groups: Vec::new(),
last_providers: Vec::new(),
@@ -499,41 +505,67 @@ fn out(ok: bool, text: String) -> Out {
}
}
fn scan(ctx: &Ctx, ui: &MainWindow, group: String) {
ui.set_import_note("Scanning…".into());
fn show_picks(ui: &MainWindow, names: Vec<String>, note: Option<String>) {
let empty = names.is_empty();
ST.with(|st| {
st.borrow().picks.set_vec(
names
.into_iter()
.map(|n| Pick {
name: n.into(),
checked: false,
})
.collect::<Vec<_>>(),
)
});
ui.set_import_scanned(true);
ui.set_import_note(match note {
Some(n) => n.into(),
None if empty => {
"Nothing to import: every remote repository is already on this machine.".into()
}
None => "".into(),
});
}
/// Lists the group's remote repos still to import. The scan runs on its own thread (never queued
/// behind status polling) and its result is cached per group; `force` rescans.
fn scan(ctx: &Ctx, ui: &MainWindow, group: String, force: bool, note: Option<String>) {
ST.with(|st| st.borrow_mut().import_current = group.clone());
ui.set_import_out(out(true, String::new()));
if !force && let Some(names) = ST.with(|st| st.borrow().import_cache.get(&group).cloned()) {
show_picks(ui, names, note);
return;
}
ui.set_import_scanning(true);
ui.set_import_note("Scanning…".into());
ST.with(|st| st.borrow().picks.set_vec(vec![]));
run_cli(
ctx,
ui,
None,
vec!["import".into(), group],
String::new(),
|ui, ok, text| {
ui.set_import_note("".into());
let (core, weak) = (ctx.core.clone(), ctx.weak.clone());
std::thread::spawn(move || {
let r = core.bridge.cli(&["import".to_string(), group.clone()], "");
let ok = r["ok"] == true;
let text = r["output"].as_str().unwrap_or("").to_string();
let _ = slint::invoke_from_event_loop(move || {
let Some(ui) = weak.upgrade() else { return };
ui.set_import_scanning(false);
if !ok {
ui.set_import_note("".into());
ui.set_import_out(out(false, text));
return;
}
let names = model::parse_import_listing(&text);
if names.is_empty() {
ui.set_import_note(
"Nothing to import: every remote repository is already on this machine.".into(),
);
}
ST.with(|st| {
st.borrow().picks.set_vec(
names
.into_iter()
.map(|n| Pick {
name: n.into(),
checked: false,
})
.collect::<Vec<_>>(),
)
st.borrow_mut()
.import_cache
.insert(group.clone(), names.clone())
});
},
);
if ST.with(|st| st.borrow().import_current == group) {
show_picks(&ui, names, note);
} else {
ui.set_import_note("".into());
}
});
});
}
fn first_or(v: &str, list: &ModelRc<SharedString>) -> String {
@@ -604,10 +636,10 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
ui.on_scan_import({
let c = ctx.clone();
move |group| {
move |group, force| {
let Some(ui) = c.weak.upgrade() else { return };
let group = model::group_name(&first_or(group.as_str(), &ui.get_groups())).to_string();
scan(&c, &ui, group);
scan(&c, &ui, group, force, None);
}
});
ui.on_pick_toggled(|i, checked| {
@@ -639,10 +671,14 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
args.extend(picked);
let c2 = c.clone();
run_cli(&c, &ui, None, args, String::new(), move |ui, ok, text| {
ui.set_import_out(out(ok, text));
if ok {
scan(&c2, ui, group);
}
ui.set_import_out(out(ok, text.clone()));
// Rescan either way: what was cloned must leave the list.
let failed = model::parse_import_failures(&text);
let note = (!failed.is_empty()).then(|| {
toast(ui, &format!("{} import(s) failed", failed.len()), true);
format!("Failed to import: {}", failed.join(", "))
});
scan(&c2, ui, group, true, note);
});
}
});
@@ -790,7 +826,7 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
ui.on_onboard({
let c = ctx.clone();
move |machine, root, kind, provider, url, group, crepo, token| {
move |machine, root, kind, protocol, provider, url, group, crepo, token| {
let Some(ui) = c.weak.upgrade() else { return };
let mut init: Vec<String> = [
"init",
@@ -802,6 +838,8 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
&provider,
"--kind",
&kind,
"--protocol",
&protocol,
"--group",
&group,
"--config-repo",
+25 -4
View File
@@ -196,6 +196,15 @@ pub fn parse_import_listing(output: &str) -> Vec<String> {
names
}
/// Repository names of the `FAILED <name>: <reason>` lines `grove import` prints per failed clone.
pub fn parse_import_failures(output: &str) -> Vec<String> {
output
.lines()
.filter_map(|l| l.strip_prefix("FAILED "))
.filter_map(|l| l.split_once(':').map(|(n, _)| n.trim().to_string()))
.collect()
}
fn names(v: Option<&Value>) -> Vec<String> {
v.and_then(Value::as_array)
.map(|a| {
@@ -288,7 +297,12 @@ pub fn settings_sections(cfg: &Value) -> Vec<Section> {
} else {
format!(" · {url}")
};
(id.clone(), format!("{}{url}", str_of(p, "kind")))
// `protocol` is how git talks to the forge; https when the key is absent.
let proto = match str_of(p, "protocol") {
"" => "https",
p => p,
};
(id.clone(), format!("{} · {proto}{url}", str_of(p, "kind")))
})
.collect()
})
@@ -405,6 +419,13 @@ mod tests {
assert!(parse_import_listing("nothing to import").is_empty());
}
#[test]
fn failed_imports_are_listed() {
let out = "imported a -> /x/a\nFAILED b: git clone failed: boom\nFAILED c: nope";
assert_eq!(parse_import_failures(out), ["b", "c"]);
assert!(parse_import_failures("imported a").is_empty());
}
#[test]
fn outputs_are_dropped_when_the_state_changes() {
let rec = |t: &str| OutRec {
@@ -453,7 +474,7 @@ mod tests {
fn settings_show_public_route_and_owners() {
let cfg = json!({
"machine": {"name": "pca"}, "root": {"path": "/w"},
"providers": {"gitea": {"kind": "gitea", "url": "https://g.example"}, "gh": {"kind": "github"}},
"providers": {"gitea": {"kind": "gitea", "protocol": "ssh", "url": "https://g.example"}, "gh": {"kind": "github"}},
"groups": [{"name": "work", "primary": "gitea", "mirror_to": ["gh"],
"owners": {"gitea": "Org", "gh": "org-gh"},
"snapshots": "none",
@@ -468,8 +489,8 @@ mod tests {
("Snapshots (default)".into(), "private-only".into())
);
// Providers come out sorted by id.
assert_eq!(s[1].1[0].1, "github");
assert_eq!(s[1].1[1].1, "gitea · https://g.example");
assert_eq!(s[1].1[0].1, "github · https");
assert_eq!(s[1].1[1].1, "gitea · ssh · https://g.example");
assert_eq!(
s[2].1[0].1,
"primary gitea · mirrors: gh · public: gh → gitea · snapshots: none · owners: gh=org-gh, gitea=Org · bare-worktrees"
+19 -6
View File
@@ -187,6 +187,8 @@ export component MainWindow inherits Window {
in property <[Section]> sections;
in property <[Pick]> picks;
in property <string> import-note;
in property <bool> import-scanning;
in property <bool> import-scanned;
in property <bool> busy;
in-out property <bool> onboarding-active: false;
in property <bool> autostart;
@@ -208,7 +210,7 @@ export component MainWindow inherits Window {
callback toggle-pause();
callback filter-changed(string);
callback create-repo(string, string, bool);
callback scan-import(string);
callback scan-import(string, bool);
callback import-selected(string);
callback pick-toggled(int, bool);
callback resolve(string, string, string);
@@ -216,7 +218,7 @@ export component MainWindow inherits Window {
callback confirm-cancel();
callback run-settings(string);
callback login(string, string);
callback onboard(string, string, string, string, string, string, string, string);
callback onboard(string, string, string, string, string, string, string, string, string);
callback view-changed(string);
callback branch-edited(string, string);
callback set-autostart(bool);
@@ -794,13 +796,16 @@ export component MainWindow inherits Window {
imp-group := ComboBox {
model: root.groups;
width: 260px;
selected(g) => {
root.scan-import(g, false);
}
}
Button {
text: "Scan remote";
enabled: !root.busy;
text: root.import-scanning ? "Scanning…" : (root.import-scanned ? "Rescan" : "Scan remote");
enabled: !root.import-scanning;
clicked => {
root.scan-import(imp-group.current-value);
root.scan-import(imp-group.current-value, true);
}
}
}
@@ -1015,6 +1020,14 @@ export component MainWindow inherits Window {
model: ["gitea", "forgejo", "github"];
}
Muted {
text: "Git transport (ssh uses your SSH keys; https uses the API token)";
}
ob-protocol := ComboBox {
model: ["https", "ssh"];
}
Muted {
text: "Provider id";
}
@@ -1063,7 +1076,7 @@ export component MainWindow inherits Window {
primary: true;
enabled: !root.busy && ob-token.text != "";
clicked => {
root.onboard(ob-machine.text, ob-root.text, ob-kind.current-value, ob-provider.text, ob-url.text, ob-group.text, ob-crepo.text, ob-token.text);
root.onboard(ob-machine.text, ob-root.text, ob-kind.current-value, ob-protocol.current-value, ob-provider.text, ob-url.text, ob-group.text, ob-crepo.text, ob-token.text);
ob-token.text = "";
}
}
+27 -12
View File
@@ -30,6 +30,7 @@ fn repo(v: &Value) -> RemoteRepo {
name: s("name"),
private: v["private"].as_bool().unwrap_or(false),
clone_url: s("clone_url"),
ssh_url: s("ssh_url"),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
@@ -67,19 +68,33 @@ impl Provider for Gitea {
}
fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
let mut out = Vec::new();
for page in 1..=200 {
let v = self
Ok(self
.http
.pages("/user/repos", 50, "limit")?
.iter()
.map(repo)
.collect())
}
fn list_owner_repos(&self, owner: &str, login: &str) -> Result<Vec<RemoteRepo>> {
let path = if owner.eq_ignore_ascii_case(login) {
"/user/repos".to_string()
} else {
format!("/orgs/{owner}/repos")
};
let items = match self.http.pages(&path, 50, "limit") {
Ok(v) => v,
// Not an organisation: another user's public repos.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => 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)
.pages(&format!("/users/{owner}/repos"), 50, "limit")?,
Err(e) => return Err(e),
};
Ok(items
.iter()
.map(repo)
.filter(|r| r.owner.eq_ignore_ascii_case(owner))
.collect())
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
+28 -15
View File
@@ -29,6 +29,7 @@ fn repo(v: &Value) -> RemoteRepo {
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(),
ssh_url: v["ssh_url"].as_str().unwrap_or_default().to_string(),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
@@ -74,21 +75,33 @@ impl Provider for GitHub {
}
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)
Ok(self
.http
.pages("/user/repos", 100, "per_page")?
.iter()
.map(repo)
.collect())
}
fn list_owner_repos(&self, owner: &str, login: &str) -> Result<Vec<RemoteRepo>> {
let path = if owner.eq_ignore_ascii_case(login) {
"/user/repos?affiliation=owner".to_string()
} else {
format!("/orgs/{owner}/repos?type=all")
};
let items = match self.http.pages(&path, 100, "per_page") {
Ok(v) => v,
// Not an organisation: another user's public repos.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => self
.http
.pages(&format!("/users/{owner}/repos"), 100, "per_page")?,
Err(e) => return Err(e),
};
Ok(items
.iter()
.map(repo)
.filter(|r| r.owner.eq_ignore_ascii_case(owner))
.collect())
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
+20
View File
@@ -60,4 +60,24 @@ impl Http {
.to_string();
Err(Error::Api { status, message })
}
/// Every item of a paginated list endpoint (`path` may already carry a query string).
pub fn pages(&self, path: &str, per_page: usize, size_param: &str) -> Result<Vec<Value>> {
let sep = if path.contains('?') { '&' } else { '?' };
let mut out = Vec::new();
for page in 1..=200 {
let v = self.ok(
"GET",
&format!("{path}{sep}{size_param}={per_page}&page={page}"),
None,
)?;
let items = v.as_array().cloned().unwrap_or_default();
let n = items.len();
out.extend(items);
if n < per_page {
break;
}
}
Ok(out)
}
}
+21 -1
View File
@@ -53,9 +53,26 @@ pub struct RemoteRepo {
pub name: String,
pub private: bool,
pub clone_url: String,
/// SSH clone URL (empty when the forge did not report one).
pub ssh_url: String,
pub default_branch: String,
}
impl RemoteRepo {
/// The URL local git should use for `protocol`.
pub fn git_url(&self, protocol: grove_core::config::Protocol) -> Result<&str> {
use grove_core::config::Protocol;
match protocol {
Protocol::Https => Ok(&self.clone_url),
Protocol::Ssh if self.ssh_url.is_empty() => Err(Error::Other(format!(
"the forge reported no SSH URL for {}/{}",
self.owner, self.name
))),
Protocol::Ssh => Ok(&self.ssh_url),
}
}
}
#[derive(Debug, Clone)]
pub struct NewRepo {
pub name: String,
@@ -99,7 +116,7 @@ pub struct PullMirrorSpec {
pub interval: String,
}
pub trait Provider {
pub trait Provider: Send + Sync {
fn kind(&self) -> ProviderKind;
fn capabilities(&self) -> Capabilities;
/// Verifies the token and returns the authenticated login.
@@ -107,6 +124,9 @@ pub trait Provider {
/// One repo's metadata (notably its visibility): `GET /repos/{owner}/{repo}`.
fn get_repo(&self, owner: &str, name: &str) -> Result<RemoteRepo>;
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
/// The repos owned by `owner` (an organisation, or the authenticated user `login`), without
/// paging through everything else the token can see.
fn list_owner_repos(&self, owner: &str, login: &str) -> 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`]).
+1
View File
@@ -161,6 +161,7 @@ mod tests {
let h = |kind, url: &str| {
host(&ProviderCfg {
kind,
protocol: Default::default(),
url: Some(url.into()),
})
};
+74
View File
@@ -301,10 +301,12 @@ fn falls_back_to_tea_and_gh_logins() {
let off = EnvGuard::set("GROVE_NO_CLI_TOKENS", "0");
let gitea = |url: &str| ProviderCfg {
kind: ProviderKind::Gitea,
protocol: Default::default(),
url: Some(url.into()),
};
let github = ProviderCfg {
kind: ProviderKind::Github,
protocol: Default::default(),
url: None,
};
let id = format!("clitok-{}", std::process::id());
@@ -368,3 +370,75 @@ fn get_repo_reports_visibility_on_both_forges() {
.private
);
}
const REPO_A: &str = r#"{"name":"a","private":false,"clone_url":"https://h/o/a.git","ssh_url":"git@h:o/a.git","default_branch":"main","owner":{"login":"Org"}}"#;
const REPO_B: &str = r#"{"name":"b","private":true,"clone_url":"https://h/me/b.git","ssh_url":"ssh://gitea@h:2222/me/b.git","default_branch":"main","owner":{"login":"me"}}"#;
const REPO_C: &str = r#"{"name":"c","private":true,"clone_url":"https://h/x/c.git","ssh_url":"","default_branch":"main","owner":{"login":"x"}}"#;
fn lines(req: &str) -> &str {
req.lines().next().unwrap()
}
#[test]
fn gitea_owner_listing_uses_the_org_endpoint_or_the_users_own() {
let org = format!("[{REPO_A}]");
let user = format!("[{REPO_B},{REPO_C}]");
let (url, rx) = mock(vec![
(200, Box::leak(org.into_boxed_str())),
(200, Box::leak(user.into_boxed_str())),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let r = g.list_owner_repos("Org", "me").unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].ssh_url, "git@h:o/a.git");
assert!(lines(&rx.recv().unwrap()).starts_with("GET /api/v1/orgs/Org/repos?limit=50&page=1 "));
// The login itself: `/user/repos`, then only its own repos (org repos it can see are dropped).
let r = g.list_owner_repos("ME", "me").unwrap();
assert_eq!(r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["b"]);
assert!(lines(&rx.recv().unwrap()).starts_with("GET /api/v1/user/repos?limit=50&page=1 "));
}
#[test]
fn github_owner_listing_scopes_the_query_and_falls_back_for_users() {
let org = format!("[{REPO_A}]");
let mine = format!("[{REPO_B}]");
let (url, rx) = mock(vec![
(200, Box::leak(org.into_boxed_str())),
(200, Box::leak(mine.into_boxed_str())),
(404, r#"{"message":"Not Found"}"#),
(200, "[]"),
]);
let g = GitHub::new(&url, "t".into());
assert_eq!(g.list_owner_repos("Org", "me").unwrap().len(), 1);
assert!(
lines(&rx.recv().unwrap()).starts_with("GET /orgs/Org/repos?type=all&per_page=100&page=1 ")
);
assert_eq!(g.list_owner_repos("me", "me").unwrap().len(), 1);
assert!(
lines(&rx.recv().unwrap())
.starts_with("GET /user/repos?affiliation=owner&per_page=100&page=1 ")
);
// Not an organisation (404): the other user's public repos.
assert!(g.list_owner_repos("someone", "me").unwrap().is_empty());
rx.recv().unwrap();
assert!(
lines(&rx.recv().unwrap()).starts_with("GET /users/someone/repos?per_page=100&page=1 ")
);
}
#[test]
fn git_url_follows_the_protocol_and_needs_an_ssh_url_for_ssh() {
use grove_core::config::Protocol;
let (url, _rx) = mock(vec![(
200,
Box::leak(format!("[{REPO_B},{REPO_C}]").into_boxed_str()),
)]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let r = g.list_repos().unwrap();
assert_eq!(r[0].git_url(Protocol::Https).unwrap(), "https://h/me/b.git");
assert_eq!(
r[0].git_url(Protocol::Ssh).unwrap(),
"ssh://gitea@h:2222/me/b.git"
);
assert!(r[1].git_url(Protocol::Ssh).is_err());
}
+10
View File
@@ -88,6 +88,9 @@ enum Cmd {
kind: String,
#[arg(long)]
url: Option<String>,
/// How git talks to the forge: https (API token) or ssh (your keys)
#[arg(long, default_value = "https")]
protocol: String,
#[arg(long, default_value = "default")]
group: String,
/// Name of the private config repo to keep the repo registry in
@@ -359,10 +362,16 @@ fn main() -> Result<()> {
provider,
kind,
url,
protocol,
group,
config_repo,
force,
} => {
let protocol = match protocol.as_str() {
"https" => grove_core::config::Protocol::Https,
"ssh" => grove_core::config::Protocol::Ssh,
p => bail!("unknown protocol {p:?} (https, ssh)"),
};
let path = cli
.config
.clone()
@@ -390,6 +399,7 @@ fn main() -> Result<()> {
provider: provider.clone(),
kind,
url: url.clone(),
protocol,
group: group.clone(),
config_repo: config_repo.clone(),
},
+219 -48
View File
@@ -2,7 +2,7 @@
use anyhow::{Context, Result, bail};
use grove_core::config::{
Config, Group, Layout, Machine, Provider as ProviderCfg, ProviderKind, Root,
Config, Group, Layout, Machine, Protocol, Provider as ProviderCfg, ProviderKind, Root,
};
use grove_core::git::Git;
use grove_core::registry::{Entry, Registry, clone_bare_layout, init_bare_layout, push_initial};
@@ -17,6 +17,7 @@ pub struct Forge {
pub token: String,
/// Git environment that authenticates HTTPS operations with the stored token.
pub git_env: Vec<(String, String)>,
pub protocol: Protocol,
}
pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
@@ -27,38 +28,60 @@ pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
let (tok, _) = token::resolve(id, pc)?;
let api = build(pc, tok.clone());
let login = api.test_connection()?;
let git_env = match pc.kind {
ProviderKind::Gitea | ProviderKind::Forgejo => vec![
("GIT_CONFIG_COUNT".into(), "1".into()),
("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()),
(
"GIT_CONFIG_VALUE_0".into(),
format!("Authorization: token {tok}"),
),
("GIT_TERMINAL_PROMPT".into(), "0".into()),
],
// GitHub git-over-HTTPS takes the token as Basic auth (any user name works).
ProviderKind::Github => vec![
("GIT_CONFIG_COUNT".into(), "1".into()),
("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()),
(
"GIT_CONFIG_VALUE_0".into(),
format!(
"Authorization: Basic {}",
base64(&format!("x-access-token:{tok}"))
let git_env = if pc.protocol == Protocol::Ssh {
// The user's SSH keys/agent authenticate; never prompt.
ssh_env()
} else {
match pc.kind {
ProviderKind::Gitea | ProviderKind::Forgejo => vec![
("GIT_CONFIG_COUNT".into(), "1".into()),
("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()),
(
"GIT_CONFIG_VALUE_0".into(),
format!("Authorization: token {tok}"),
),
),
("GIT_TERMINAL_PROMPT".into(), "0".into()),
],
("GIT_TERMINAL_PROMPT".into(), "0".into()),
],
// GitHub git-over-HTTPS takes the token as Basic auth (any user name works).
ProviderKind::Github => vec![
("GIT_CONFIG_COUNT".into(), "1".into()),
("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()),
(
"GIT_CONFIG_VALUE_0".into(),
format!(
"Authorization: Basic {}",
base64(&format!("x-access-token:{tok}"))
),
),
("GIT_TERMINAL_PROMPT".into(), "0".into()),
],
}
};
Ok(Forge {
api,
login,
token: tok,
git_env,
protocol: pc.protocol,
})
}
/// Git environment for SSH remotes: the user's keys/agent authenticate and nothing prompts.
/// `BatchMode` is only forced when the user has no ssh command of their own.
fn ssh_env() -> Vec<(String, String)> {
let mut env = vec![("GIT_TERMINAL_PROMPT".to_string(), "0".to_string())];
let custom = std::env::var_os("GIT_SSH_COMMAND").is_some()
|| std::env::var_os("GIT_SSH").is_some()
|| std::process::Command::new("git")
.args(["config", "--get", "core.sshCommand"])
.output()
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty());
if !custom {
env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into()));
}
env
}
/// The group's owner on `provider`, or `None` when that is the authenticated user itself
/// (personal repos use `/user/repos`, not the org endpoint).
fn org_owner(grp: &Group, provider: &str, login: &str) -> Option<String> {
@@ -103,6 +126,7 @@ pub struct InitArgs {
pub provider: String,
pub kind: ProviderKind,
pub url: Option<String>,
pub protocol: Protocol,
pub group: String,
pub config_repo: Option<String>,
}
@@ -119,6 +143,7 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
a.provider.clone(),
ProviderCfg {
kind: a.kind,
protocol: a.protocol,
url: a.url,
},
);
@@ -179,7 +204,8 @@ pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Re
"created {}/{} on {}",
remote.owner, remote.name, route.primary
);
let wt = init_bare_layout(&dir, &remote.clone_url)?;
let local_url = remote.git_url(primary.protocol)?.to_string();
let wt = init_bare_layout(&dir, &local_url)?;
push_initial(&dir, &primary.git_env)?;
println!("pushed initial commit; worktree {}", wt.display());
@@ -194,7 +220,7 @@ pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Re
&Entry {
group: grp.name.clone(),
name: name.into(),
url: remote.clone_url,
url: local_url,
},
)?;
Ok(wt)
@@ -256,6 +282,67 @@ fn select(repos: Vec<RemoteRepo>, owner: &str, private: Option<bool>) -> Vec<Rem
.collect()
}
/// `host/owner/name` (lowercase) of a git remote URL in https, `ssh://` or scp-like form.
fn remote_key(url: &str) -> Option<String> {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
let rest = rest.rsplit_once('@').map_or(rest, |(_, r)| r);
let (host, path) = match rest.split_once(['/', ':']) {
Some((h, p)) => (h, p),
None => return None,
};
// `host:2222/owner/repo` (ssh with a port): drop the port.
let path = match path.split_once('/') {
Some((port, p)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => p,
_ => path,
};
let path = path.trim_matches('/').trim_end_matches(".git");
let mut parts = path.rsplitn(2, '/');
let name = parts.next()?;
let owner = parts.next()?;
Some(format!("{host}/{owner}/{name}").to_lowercase())
}
/// What is already in a group directory: bare-layout repos by lowercase directory name and by
/// the owner/name their `origin` points to.
struct Local {
names: std::collections::HashSet<String>,
origins: std::collections::HashSet<String>,
}
impl Local {
fn scan(gdir: &Path) -> Local {
let mut l = Local {
names: Default::default(),
origins: Default::default(),
};
let Ok(rd) = fs::read_dir(gdir) else { return l };
for e in rd.filter_map(Result::ok) {
let bare = e.path().join(".bare");
if !bare.exists() {
continue;
}
l.names
.insert(e.file_name().to_string_lossy().to_lowercase());
if let Ok(Some(url)) = Git::new(&bare).probe(&["config", "--get", "remote.origin.url"])
&& let Some(k) = remote_key(&url)
{
l.origins.insert(k);
}
}
l
}
/// Present when a repo of that name exists (case-insensitively: forge names are, and so are
/// many file systems) or an existing repo's origin is this very remote.
fn has(&self, r: &RemoteRepo) -> bool {
self.names.contains(&r.name.to_lowercase())
|| [&r.clone_url, &r.ssh_url]
.iter()
.filter_map(|u| remote_key(u))
.any(|k| self.origins.contains(&k))
}
}
/// Lists the group's remote repos that are not on disk; clones the named ones.
pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
let grp = group(cfg, group_name)?;
@@ -268,14 +355,34 @@ pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
None => vec![(grp.primary.clone(), None)],
};
let gdir = cfg.root_path().join(&grp.name);
// Both routes of a split group are queried at the same time.
let scanned: Vec<Result<(String, Forge, Vec<RemoteRepo>)>> = std::thread::scope(|sc| {
let hs: Vec<_> = sides
.iter()
.map(|(pid, vis)| {
let grp = &grp;
sc.spawn(move || {
let f = connect(cfg, pid)?;
let owner = grp.owner(pid).unwrap_or(&f.login).to_string();
let repos = select(f.api.list_owner_repos(&owner, &f.login)?, &owner, *vis);
Ok((pid.clone(), f, repos))
})
})
.collect();
hs.into_iter()
.map(|h| {
h.join()
.unwrap_or_else(|_| Err(anyhow::anyhow!("provider scan panicked")))
})
.collect()
});
let mut forges = Vec::new();
let mut missing: Vec<(RemoteRepo, usize)> = Vec::new();
for (pid, vis) in sides {
let f = connect(cfg, &pid)?;
let owner = grp.owner(&pid).unwrap_or(&f.login).to_string();
for r in select(f.api.list_repos()?, &owner, vis) {
let here = gdir.join(&r.name).join(".bare").exists();
if !here && !missing.iter().any(|(m, _)| m.name == r.name) {
let local = Local::scan(&gdir);
for res in scanned {
let (pid, f, repos) = res?;
for r in repos {
if !local.has(&r) && !missing.iter().any(|(m, _)| m.name == r.name) {
missing.push((r, forges.len()));
}
}
@@ -295,22 +402,45 @@ pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
println!("run `grove import {group_name} <name>...` to clone them");
return Ok(());
}
// One broken repo must not stop the others: collect failures and report them at the end.
let mut failed: Vec<String> = Vec::new();
for w in wanted {
let (r, i) = missing
.iter()
.find(|(r, _)| &r.name == w)
.with_context(|| format!("{w:?} is not a remote repo missing locally"))?;
let dir = gdir.join(&r.name);
clone_bare_layout(&r.clone_url, &dir, &forges[*i].1.git_env)?;
println!("imported {} -> {}", r.name, dir.display());
register(
cfg,
&Entry {
group: grp.name.clone(),
name: r.name.clone(),
url: r.clone_url.clone(),
},
)?;
let Some((r, i)) = missing.iter().find(|(r, _)| &r.name == w) else {
println!("FAILED {w}: not a remote repo missing locally");
failed.push(w.clone());
continue;
};
let forge = &forges[*i].1;
let res = (|| -> Result<()> {
let url = r.git_url(forge.protocol)?.to_string();
let dir = gdir.join(&r.name);
if let Err(e) = clone_bare_layout(&url, &dir, &forge.git_env) {
// Leave no empty directory behind (it only goes away when nothing was cloned).
let _ = fs::remove_dir(&dir);
return Err(e.into());
}
println!("imported {} -> {}", r.name, dir.display());
register(
cfg,
&Entry {
group: grp.name.clone(),
name: r.name.clone(),
url,
},
)
})();
if let Err(e) = res {
println!("FAILED {w}: {e:#}");
failed.push(w.clone());
}
}
if !failed.is_empty() {
bail!(
"{} of {} imports failed: {}",
failed.len(),
wanted.len(),
failed.join(", ")
);
}
Ok(())
}
@@ -338,7 +468,7 @@ pub(crate) fn config_repo_open(cfg: &Config, create: bool) -> Result<(PathBuf, F
.into_iter()
.find(|r| r.name == cr.name);
let url = match exists {
Some(r) => r.clone_url,
Some(r) => r.git_url(forge.protocol)?.to_string(),
None if create => {
let r = forge.api.create_repo(&NewRepo {
name: cr.name.clone(),
@@ -346,7 +476,7 @@ pub(crate) fn config_repo_open(cfg: &Config, create: bool) -> Result<(PathBuf, F
private: true,
description: "grove configuration (managed repos, machines)".into(),
})?;
r.clone_url
r.git_url(forge.protocol)?.to_string()
}
None => bail!(
"config repo {:?} does not exist on {}",
@@ -485,10 +615,51 @@ mod tests {
name: name.into(),
private,
clone_url: format!("u/{name}.git"),
ssh_url: String::new(),
default_branch: "main".into(),
}
}
#[test]
fn remote_key_normalises_every_url_form() {
let want = Some("github.com/dasemu/synapse".to_string());
assert_eq!(remote_key("git@github.com:Dasemu/Synapse.git"), want);
assert_eq!(remote_key("https://github.com/Dasemu/Synapse.git"), want);
assert_eq!(remote_key("ssh://git@github.com/dasemu/synapse"), want);
assert_eq!(
remote_key("ssh://gitea@git.example.es:2222/dasemu/x.git").as_deref(),
Some("git.example.es/dasemu/x")
);
assert_eq!(remote_key("nonsense"), None);
}
#[test]
fn local_repos_match_by_name_or_origin_ignoring_case() {
let d = std::env::temp_dir().join(format!("grove-local-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
// `synapse` (lowercase dir) whose origin is Dasemu/Synapse; `other` with a renamed origin.
for (dir, origin) in [
("synapse", "git@github.com:Dasemu/Synapse.git"),
("renamed", "git@github.com:me/old-name.git"),
] {
let bare = d.join(dir).join(".bare");
fs::create_dir_all(&bare).unwrap();
let g = Git::new(&bare);
g.run(&["init", "-q", "--bare"]).unwrap();
g.run(&["remote", "add", "origin", origin]).unwrap();
}
let l = Local::scan(&d);
let mut syn = r("Dasemu", "Synapse", false);
syn.clone_url = "https://github.com/Dasemu/Synapse.git".into();
assert!(l.has(&syn));
// Different directory name, same origin.
let mut moved = r("me", "new-name", false);
moved.ssh_url = "git@github.com:me/old-name.git".into();
assert!(l.has(&moved));
assert!(!l.has(&r("me", "absent", false)));
let _ = fs::remove_dir_all(&d);
}
#[test]
fn base64_matches_rfc4648_vectors() {
for (i, o) in [
+26
View File
@@ -87,3 +87,29 @@ Hidden CPU against a busy daemon (8 repos, 5 s fetch interval, ~4 events/s): abo
- Side-by-side compare for `Diverged` stays in the CLI (`grove resolve --compare`).
- Only the layout and read-only views were checked visually; forms and CLI-driven flows were not
clicked through (no input injection available), only their parsing and logic are unit-tested.
## Import speed, git protocol, import robustness
- `Provider::list_owner_repos(owner, login)` lists only the owner's repos: Gitea `/orgs/{org}/repos`
or `/user/repos` (filtered by owner) for the login; GitHub `/orgs/{org}/repos?type=all` or
`/user/repos?affiliation=owner`. A 404 on the org endpoint falls back to `/users/{owner}/repos`.
The two sides of a split group are scanned in parallel threads. `grove import Darío` on the
owner's real forges: 3.5 s -> 1.3 s.
- The GUI scan runs on its own thread (not the status worker), is cached per group for the session,
and has a Rescan button. Switching groups shows the cached list; an import drops the cache.
- "Already on this machine" is case-insensitive by directory name, or when an existing bare repo's
`origin` points to the same host/owner/name (https, `ssh://` and scp-like forms).
- A failing clone no longer aborts a multi-repo import: the others continue, failures are printed
as `FAILED <name>: <reason>`, the exit status is non-zero and the GUI lists the failed names.
- Per-provider `protocol = "https" | "ssh"` (default `https`; also `grove init --protocol` and the
onboarding form). With `ssh`, `new`/`import`/`bootstrap` clone from the forge's `ssh_url`, registry
entries store that URL, and git gets no token header (only `GIT_TERMINAL_PROMPT=0`, plus
`GIT_SSH_COMMAND="ssh -o BatchMode=yes"` unless the user has their own ssh command). Mirrors stay
HTTPS with tokens (forge to forge). The Settings summary shows the protocol of each provider.
```toml
[providers.gitea]
kind = "gitea"
url = "https://git.example.com"
protocol = "ssh" # optional, default "https"
```