From b86342b1d06d9f9a5c32ed49c5fbadc94cb781d9 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 13:23:10 +0100 Subject: [PATCH] feat: provider wizards (init, login, new, import, config repo, bootstrap) Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 2 + crates/grove-core/src/config.rs | 34 ++- crates/grove-core/src/lib.rs | 1 + crates/grove-core/src/registry.rs | 114 ++++++++ crates/grove-core/tests/registry.rs | 69 +++++ crates/grove/Cargo.toml | 2 + crates/grove/src/main.rs | 114 +++++++- crates/grove/src/workflow.rs | 389 ++++++++++++++++++++++++++++ docs/phase4.md | 52 ++++ spikes/phase4-e2e.sh | 29 +++ 10 files changed, 795 insertions(+), 11 deletions(-) create mode 100644 crates/grove-core/src/registry.rs create mode 100644 crates/grove-core/tests/registry.rs create mode 100644 crates/grove/src/workflow.rs create mode 100644 docs/phase4.md create mode 100755 spikes/phase4-e2e.sh diff --git a/Cargo.lock b/Cargo.lock index a587b8d..2d6dfa3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -712,7 +712,9 @@ dependencies = [ "clap", "grove-core", "grove-daemon", + "grove-providers", "serde_json", + "toml", ] [[package]] diff --git a/crates/grove-core/src/config.rs b/crates/grove-core/src/config.rs index f0ee5c6..70b1c91 100644 --- a/crates/grove-core/src/config.rs +++ b/crates/grove-core/src/config.rs @@ -1,11 +1,11 @@ //! `config.toml` model, loading and validation (section 6 of the plan). -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt; use std::path::{Path, PathBuf}; -#[derive(Debug, Clone, PartialEq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Config { pub machine: Machine, pub root: Root, @@ -15,20 +15,21 @@ pub struct Config { pub groups: Vec, #[serde(default)] pub sync: Sync, + #[serde(skip_serializing_if = "Option::is_none")] pub config_repo: Option, } -#[derive(Debug, Clone, PartialEq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Machine { pub name: String, } -#[derive(Debug, Clone, PartialEq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Root { pub path: String, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum ProviderKind { Gitea, @@ -36,13 +37,14 @@ pub enum ProviderKind { Github, } -#[derive(Debug, Clone, PartialEq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Provider { pub kind: ProviderKind, + #[serde(skip_serializing_if = "Option::is_none")] pub url: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub enum Layout { #[default] @@ -50,7 +52,7 @@ pub enum Layout { Plain, } -#[derive(Debug, Clone, PartialEq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Group { pub name: String, pub primary: String, @@ -62,7 +64,7 @@ pub struct Group { pub auto_materialize: bool, } -#[derive(Debug, Clone, PartialEq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Sync { #[serde(default = "default_debounce")] pub snapshot_debounce_ms: u64, @@ -82,7 +84,7 @@ impl Default for Sync { } } -#[derive(Debug, Clone, PartialEq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct ConfigRepo { pub provider: String, pub name: String, @@ -124,6 +126,18 @@ impl Config { Ok(cfg) } + /// Writes the config atomically (temp file + rename). + pub fn save(&self, path: &Path) -> Result<(), ConfigError> { + let text = toml::to_string_pretty(self).map_err(|e| ConfigError::Parse(e.to_string()))?; + let io = |e| ConfigError::Io(path.to_path_buf(), e); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(io)?; + } + let tmp = path.with_extension("toml.tmp"); + std::fs::write(&tmp, text).map_err(io)?; + std::fs::rename(&tmp, path).map_err(io) + } + pub fn load(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|e| ConfigError::Io(path.to_path_buf(), e))?; diff --git a/crates/grove-core/src/lib.rs b/crates/grove-core/src/lib.rs index d0bfa32..2b60188 100644 --- a/crates/grove-core/src/lib.rs +++ b/crates/grove-core/src/lib.rs @@ -6,6 +6,7 @@ pub mod inspect; pub mod layout; pub mod migrate; pub mod receive; +pub mod registry; pub mod snapshot; pub mod state; pub mod sync; diff --git a/crates/grove-core/src/registry.rs b/crates/grove-core/src/registry.rs new file mode 100644 index 0000000..7b5af5d --- /dev/null +++ b/crates/grove-core/src/registry.rs @@ -0,0 +1,114 @@ +//! The config repo: a private git repo holding `repos.toml` (what to materialize) and one +//! heartbeat file per machine. A fresh machine needs nothing else to rebuild its workspace. + +use crate::git::{Git, GitError}; +use crate::layout::dir_name; +use crate::receive::{ensure_fetch_refspec, materialize}; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)] +pub struct Registry { + #[serde(default)] + pub repos: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +pub struct Entry { + pub group: String, + pub name: String, + /// Clone URL on the group's primary remote. + pub url: String, +} + +impl Registry { + pub fn parse(text: &str) -> Result { + toml::from_str(text).map_err(|e| e.to_string()) + } + + pub fn to_text(&self) -> String { + toml::to_string_pretty(self).unwrap_or_default() + } + + /// Adds or updates an entry (same group + name). + pub fn upsert(&mut self, e: Entry) { + match self + .repos + .iter_mut() + .find(|x| x.group == e.group && x.name == e.name) + { + Some(x) => *x = e, + None => self.repos.push(e), + } + self.repos + .sort_by(|a, b| (&a.group, &a.name).cmp(&(&b.group, &b.name))); + } +} + +/// Creates `/.bare` as a clone of `url` and a worktree per remote branch. +/// `envs` are extra git environment variables (credentials). +pub fn clone_bare_layout( + url: &str, + dir: &Path, + envs: &[(String, String)], +) -> Result, GitError> { + fs::create_dir_all(dir)?; + let bare = dir.join(".bare"); + let mut g = Git::new(dir); + for (k, v) in envs { + g = g.with_env(k, v); + } + g.run(&["clone", "-q", "--bare", url, &bare.to_string_lossy()])?; + Git::new(&bare).run(&["config", "core.bare", "true"])?; + ensure_fetch_refspec(&bare, "origin")?; + let mut f = Git::new(&bare); + for (k, v) in envs { + f = f.with_env(k, v); + } + f.run(&["fetch", "-q", "--prune", "origin"])?; + materialize(dir, "origin") +} + +/// Creates a brand new local repo in the bare layout with an initial empty commit on `main`, +/// pointing at `url`. Nothing is pushed here. +pub fn init_bare_layout(dir: &Path, url: &str) -> Result { + fs::create_dir_all(dir)?; + let bare = dir.join(".bare"); + let g = Git::new(dir); + g.run(&[ + "init", + "-q", + "--bare", + "-b", + "main", + &bare.to_string_lossy(), + ])?; + let b = Git::new(&bare); + b.run(&["remote", "add", "origin", url])?; + ensure_fetch_refspec(&bare, "origin")?; + // `hash-object -t tree` on an empty file writes the empty tree object. + let tree = b.run(&["hash-object", "-t", "tree", "-w", "/dev/null"])?; + let commit = b + .with_env("GIT_AUTHOR_NAME", "grove") + .with_env("GIT_AUTHOR_EMAIL", "grove@localhost") + .with_env("GIT_COMMITTER_NAME", "grove") + .with_env("GIT_COMMITTER_EMAIL", "grove@localhost") + .run(&["commit-tree", &tree, "-m", "chore: initial commit"])?; + let b = Git::new(&bare); + b.run(&["update-ref", "refs/heads/main", &commit])?; + let name = dir_name("main", &[]); + let wt = dir.join(&name); + b.run(&["worktree", "add", "-q", &wt.to_string_lossy(), "main"])?; + Ok(wt) +} + +/// Pushes `main` of a freshly initialised layout and sets the upstream. +pub fn push_initial(dir: &Path, envs: &[(String, String)]) -> Result<(), GitError> { + let mut g = Git::new(dir.join(".bare")); + for (k, v) in envs { + g = g.with_env(k, v); + } + g.run(&["push", "-q", "-u", "origin", "main"])?; + Ok(()) +} diff --git a/crates/grove-core/tests/registry.rs b/crates/grove-core/tests/registry.rs new file mode 100644 index 0000000..ba1677f --- /dev/null +++ b/crates/grove-core/tests/registry.rs @@ -0,0 +1,69 @@ +mod common; +use common::*; +use grove_core::git::Git; +use grove_core::registry::*; +use std::fs; + +#[test] +fn new_repo_pushes_and_a_fresh_machine_clones_it_into_the_bare_layout() { + let base = tmpdir("reg"); + let remote = base.join("r.git"); + Git::new(&base) + .run(&[ + "init", + "-q", + "--bare", + "-b", + "main", + remote.to_str().unwrap(), + ]) + .unwrap(); + let url = remote.to_str().unwrap(); + + let a = base.join("A/g/proj"); + let wt = init_bare_layout(&a, url).unwrap(); + assert!(wt.ends_with("main") && wt.join(".git").exists()); + push_initial(&a, &[]).unwrap(); + let g = Git::new(&wt); + assert_eq!(g.run(&["status", "--porcelain"]).unwrap(), ""); + assert_eq!( + g.run(&["rev-parse", "--abbrev-ref", "@{upstream}"]) + .unwrap(), + "origin/main" + ); + + let b = base.join("B/g/proj"); + let made = clone_bare_layout(url, &b, &[]).unwrap(); + assert_eq!(made.len(), 1); + assert!(b.join("main/.git").exists() && b.join(".bare").is_dir()); + assert_eq!( + Git::new(b.join("main")) + .run(&["rev-parse", "HEAD"]) + .unwrap(), + g.run(&["rev-parse", "HEAD"]).unwrap() + ); + fs::remove_dir_all(&base).unwrap(); +} + +#[test] +fn registry_roundtrip_and_upsert() { + let mut r = Registry::default(); + r.upsert(Entry { + group: "z".into(), + name: "b".into(), + url: "u1".into(), + }); + r.upsert(Entry { + group: "a".into(), + name: "x".into(), + url: "u2".into(), + }); + r.upsert(Entry { + group: "z".into(), + name: "b".into(), + url: "u3".into(), + }); + assert_eq!(r.repos.len(), 2); + assert_eq!(r.repos[0].group, "a"); + assert_eq!(Registry::parse(&r.to_text()).unwrap(), r); +} diff --git a/crates/grove/Cargo.toml b/crates/grove/Cargo.toml index aa043ce..9f8ee39 100644 --- a/crates/grove/Cargo.toml +++ b/crates/grove/Cargo.toml @@ -9,4 +9,6 @@ anyhow = "1.0.104" clap = { version = "4.6.7", features = ["derive"] } grove-core = { version = "0.1.0", path = "../grove-core" } grove-daemon = { version = "0.1.0", path = "../grove-daemon" } +grove-providers = { version = "0.1.0", path = "../grove-providers" } serde_json = "1.0.154" +toml = "1.2.1" diff --git a/crates/grove/src/main.rs b/crates/grove/src/main.rs index ca5e2f8..f702086 100644 --- a/crates/grove/src/main.rs +++ b/crates/grove/src/main.rs @@ -1,6 +1,6 @@ use anyhow::{Context, Result, bail}; use clap::{Parser, Subcommand}; -use grove_core::config::Config; +use grove_core::config::{Config, ProviderKind}; use grove_core::git::Git; use grove_core::inspect::{state, worktrees}; use grove_core::migrate::migrate; @@ -10,6 +10,8 @@ use grove_core::sync::{Options, SyncReport, git_dir_for, sync_repo}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; +mod workflow; + #[derive(Parser)] #[command(name = "grove", about = "Keep git workspaces in sync across machines")] struct Cli { @@ -49,6 +51,42 @@ enum Cmd { }, /// Check the local setup Doctor, + /// Write a first config file for this machine + Init { + #[arg(long)] + machine: Option, + #[arg(long, default_value = "~/Workspace")] + root: String, + /// Provider id (name used in the config and for the token) + #[arg(long, default_value = "main")] + provider: String, + #[arg(long, default_value = "gitea")] + kind: String, + #[arg(long)] + url: Option, + #[arg(long, default_value = "default")] + group: String, + /// Name of the private config repo to keep the repo registry in + #[arg(long)] + config_repo: Option, + #[arg(long)] + force: bool, + }, + /// Store the API token for a provider (read from stdin, never from argv) + Login { provider: String }, + /// Create a repo on the group's primary forge and set it up locally + New { + group: String, + name: String, + #[arg(long)] + public: bool, + }, + /// List (or, with names, clone) remote repos that are not on this machine + Import { group: String, names: Vec }, + /// Create the config repo and register every repo already on disk + ConfigRepoInit, + /// Fresh machine: clone every repo listed in the config repo + Bootstrap, /// Talk to the running daemon (`groved`) Daemon { #[command(subcommand)] @@ -209,6 +247,80 @@ fn main() -> Result<()> { print_report(&rep) } Cmd::Doctor => doctor(&cli.config), + Cmd::Init { + machine, + root, + provider, + kind, + url, + group, + config_repo, + force, + } => { + let path = cli + .config + .clone() + .or_else(Config::default_path) + .context("cannot determine config path (set --config)")?; + let kind = match kind.as_str() { + "gitea" => ProviderKind::Gitea, + "forgejo" => ProviderKind::Forgejo, + "github" => ProviderKind::Github, + k => bail!("unknown provider kind {k:?} (gitea, forgejo, github)"), + }; + let machine = machine + .clone() + .or_else(|| { + std::fs::read_to_string("/etc/hostname") + .ok() + .map(|h| h.trim().to_string()) + }) + .context("cannot determine the machine name (set --machine)")?; + workflow::init( + &path, + workflow::InitArgs { + machine, + root: root.clone(), + provider: provider.clone(), + kind, + url: url.clone(), + group: group.clone(), + config_repo: config_repo.clone(), + }, + *force, + )?; + println!("wrote {}", path.display()); + println!("next: `grove login {provider}` to store the API token"); + Ok(()) + } + Cmd::Login { provider } => { + let cfg = load_config(&cli.config)?; + let mut tok = String::new(); + std::io::stdin().read_line(&mut tok)?; + let who = workflow::login(&cfg, provider, tok.trim())?; + println!("logged in to {provider} as {who}; token stored in the Secret Service"); + Ok(()) + } + Cmd::New { + group, + name, + public, + } => { + let wt = workflow::new_repo(&load_config(&cli.config)?, group, name, !public)?; + println!("ready: {}", wt.display()); + Ok(()) + } + Cmd::Import { group, names } => workflow::import(&load_config(&cli.config)?, group, names), + Cmd::ConfigRepoInit => { + let n = workflow::config_repo_init(&load_config(&cli.config)?)?; + println!("config repo up to date ({n} repos registered)"); + Ok(()) + } + Cmd::Bootstrap => { + let (done, skipped) = workflow::bootstrap(&load_config(&cli.config)?)?; + println!("bootstrap finished: {done} cloned, {skipped} already present"); + Ok(()) + } } } diff --git a/crates/grove/src/workflow.rs b/crates/grove/src/workflow.rs new file mode 100644 index 0000000..3a9701f --- /dev/null +++ b/crates/grove/src/workflow.rs @@ -0,0 +1,389 @@ +//! Onboarding, new-repo, import and bootstrap flows (Phase 4). + +use anyhow::{Context, Result, bail}; +use grove_core::config::{ + Config, Group, Layout, Machine, Provider as ProviderCfg, ProviderKind, Root, +}; +use grove_core::git::Git; +use grove_core::registry::{Entry, Registry, clone_bare_layout, init_bare_layout, push_initial}; +use grove_providers::{MirrorSpec, NewRepo, Provider, build, token}; +use std::fs; +use std::path::{Path, PathBuf}; + +pub struct Forge { + pub api: Box, + pub login: String, + /// Git environment that authenticates HTTPS operations with the stored token. + pub git_env: Vec<(String, String)>, +} + +pub fn connect(cfg: &Config, id: &str) -> Result { + let pc = cfg + .providers + .get(id) + .with_context(|| format!("provider {id:?} is not in the config"))?; + let tok = token::get(id)?; + 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 needs Basic auth; leave it to the user's credential helper. + ProviderKind::Github => vec![("GIT_TERMINAL_PROMPT".into(), "0".into())], + }; + Ok(Forge { + api, + login, + git_env, + }) +} + +fn group<'a>(cfg: &'a Config, name: &str) -> Result<&'a Group> { + cfg.groups + .iter() + .find(|g| g.name == name) + .with_context(|| format!("group {name:?} is not in the config")) +} + +fn with_env(g: Git, envs: &[(String, String)]) -> Git { + envs.iter().fold(g, |g, (k, v)| g.with_env(k, v)) +} + +pub struct InitArgs { + pub machine: String, + pub root: String, + pub provider: String, + pub kind: ProviderKind, + pub url: Option, + pub group: String, + pub config_repo: Option, +} + +pub fn init(path: &Path, a: InitArgs, force: bool) -> Result { + if path.exists() && !force { + bail!( + "{} already exists (use --force to overwrite)", + path.display() + ); + } + let mut providers = std::collections::BTreeMap::new(); + providers.insert( + a.provider.clone(), + ProviderCfg { + kind: a.kind, + url: a.url, + }, + ); + let cfg = Config { + machine: Machine { name: a.machine }, + root: Root { path: a.root }, + providers, + groups: vec![Group { + name: a.group, + primary: a.provider.clone(), + mirror_to: vec![], + layout: Layout::BareWorktrees, + auto_materialize: true, + }], + sync: Default::default(), + config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo { + provider: a.provider, + name, + }), + }; + // Validate by round-tripping through the parser before writing anything. + let text = toml::to_string_pretty(&cfg)?; + Config::parse(&text)?; + cfg.save(path)?; + Ok(cfg) +} + +pub fn login(cfg: &Config, id: &str, tok: &str) -> Result { + let pc = cfg + .providers + .get(id) + .with_context(|| format!("provider {id:?} is not in the config"))?; + let who = build(pc, tok.to_string()).test_connection()?; + // Keep the secret out of the store when the env override is in use. + token::set(id, tok)?; + Ok(who) +} + +/// Creates the remote repo, the local bare layout, the mirrors and the registry entry. +pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Result { + let grp = group(cfg, group_name)?; + let dir = cfg.root_path().join(&grp.name).join(name); + if dir.exists() { + bail!("{} already exists", dir.display()); + } + let primary = connect(cfg, &grp.primary)?; + let remote = primary.api.create_repo(&NewRepo { + name: name.into(), + owner: None, + private, + description: String::new(), + })?; + println!( + "created {}/{} on {}", + remote.owner, remote.name, grp.primary + ); + let wt = init_bare_layout(&dir, &remote.clone_url)?; + push_initial(&dir, &primary.git_env)?; + println!("pushed initial commit; worktree {}", wt.display()); + + for mid in &grp.mirror_to { + match configure_mirror(cfg, &primary, mid, &remote.owner, name, private) { + Ok(()) => println!("push mirror to {mid} configured"), + Err(e) => println!("warning: mirror to {mid} not configured: {e}"), + } + } + register( + cfg, + &Entry { + group: grp.name.clone(), + name: name.into(), + url: remote.clone_url, + }, + )?; + Ok(wt) +} + +fn configure_mirror( + cfg: &Config, + primary: &Forge, + mirror_id: &str, + owner: &str, + name: &str, + private: bool, +) -> Result<()> { + let m = connect(cfg, mirror_id)?; + let target = m.api.create_repo(&NewRepo { + name: name.into(), + owner: None, + private, + description: "Mirror managed by grove".into(), + })?; + primary.api.configure_mirror( + owner, + name, + &MirrorSpec { + remote_url: target.clone_url, + remote_username: m.login, + remote_token: token::get(mirror_id)?, + interval: "8h0m0s".into(), + sync_on_commit: true, + }, + )?; + Ok(()) +} + +/// Lists remote repos of the group's primary 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)?; + let primary = connect(cfg, &grp.primary)?; + let gdir = cfg.root_path().join(&grp.name); + let missing: Vec<_> = primary + .api + .list_repos()? + .into_iter() + .filter(|r| !gdir.join(&r.name).join(".bare").exists()) + .collect(); + if wanted.is_empty() { + println!("repos on {} not yet in {}:", grp.primary, gdir.display()); + for r in &missing { + println!( + " {}/{}{}", + r.owner, + r.name, + if r.private { " (private)" } else { "" } + ); + } + println!("run `grove import {group_name} ...` to clone them"); + return Ok(()); + } + for w in wanted { + let r = 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, &primary.git_env)?; + println!("imported {} -> {}", r.name, dir.display()); + register( + cfg, + &Entry { + group: grp.name.clone(), + name: r.name.clone(), + url: r.clone_url.clone(), + }, + )?; + } + Ok(()) +} + +// ---- config repo ------------------------------------------------------------------------- + +fn config_repo_dir() -> Result { + Ok(Config::state_dir() + .context("cannot determine state dir")? + .join("config-repo")) +} + +/// Makes sure the local clone of the config repo exists and is current. Returns its path. +fn config_repo_open(cfg: &Config, create: bool) -> Result<(PathBuf, Forge)> { + let cr = cfg + .config_repo + .as_ref() + .context("no [config_repo] in the config")?; + let forge = connect(cfg, &cr.provider)?; + let dir = config_repo_dir()?; + if !dir.join(".git").exists() { + let exists = forge + .api + .list_repos()? + .into_iter() + .find(|r| r.name == cr.name); + let url = match exists { + Some(r) => r.clone_url, + None if create => { + let r = forge.api.create_repo(&NewRepo { + name: cr.name.clone(), + owner: None, + private: true, + description: "grove configuration (managed repos, machines)".into(), + })?; + r.clone_url + } + None => bail!( + "config repo {:?} does not exist on {}", + cr.name, + cr.provider + ), + }; + fs::create_dir_all(dir.parent().unwrap())?; + let g = with_env(Git::new(dir.parent().unwrap()), &forge.git_env); + g.run(&["clone", "-q", &url, &dir.to_string_lossy()])?; + } else { + // An empty remote has nothing to pull yet. + let _ = with_env(Git::new(&dir), &forge.git_env).run(&["pull", "-q", "--ff-only"]); + } + Ok((dir, forge)) +} + +fn read_registry(dir: &Path) -> Result { + match fs::read_to_string(dir.join("repos.toml")) { + Ok(t) => Registry::parse(&t).map_err(anyhow::Error::msg), + Err(_) => Ok(Registry::default()), + } +} + +fn commit_and_push(cfg: &Config, dir: &Path, forge: &Forge, msg: &str) -> Result<()> { + let g = Git::new(dir) + .with_env("GIT_AUTHOR_NAME", "grove") + .with_env("GIT_AUTHOR_EMAIL", "grove@localhost") + .with_env("GIT_COMMITTER_NAME", "grove") + .with_env("GIT_COMMITTER_EMAIL", "grove@localhost"); + g.run(&["add", "-A"])?; + if g.run(&["status", "--porcelain"])?.is_empty() { + return Ok(()); + } + let machine = &cfg.machine.name; + g.run(&["commit", "-q", "-m", &format!("{msg} (from {machine})")])?; + let branch = g.run(&["rev-parse", "--abbrev-ref", "HEAD"])?; + with_env(g, &forge.git_env).run(&["push", "-q", "-u", "origin", &branch])?; + Ok(()) +} + +fn write_heartbeat(cfg: &Config, dir: &Path) -> Result<()> { + let m = dir.join("machines"); + fs::create_dir_all(&m)?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let body = serde_json::json!({"machine": cfg.machine.name, "last_registered": now}); + fs::write( + m.join(format!("{}.json", cfg.machine.name)), + serde_json::to_string_pretty(&body)?, + )?; + Ok(()) +} + +/// Adds a repo to the config repo, if one is configured (silently skipped otherwise). +pub fn register(cfg: &Config, e: &Entry) -> Result<()> { + if cfg.config_repo.is_none() { + return Ok(()); + } + let (dir, forge) = config_repo_open(cfg, true)?; + let mut reg = read_registry(&dir)?; + reg.upsert(e.clone()); + fs::write(dir.join("repos.toml"), reg.to_text())?; + write_heartbeat(cfg, &dir)?; + commit_and_push( + cfg, + &dir, + &forge, + &format!("register {}/{}", e.group, e.name), + ) +} + +/// First machine: creates the config repo (if needed) and registers every repo already on disk. +pub fn config_repo_init(cfg: &Config) -> Result { + let (dir, forge) = config_repo_open(cfg, true)?; + let mut reg = read_registry(&dir)?; + for grp in &cfg.groups { + let gdir = cfg.root_path().join(&grp.name); + let Ok(rd) = fs::read_dir(&gdir) else { + continue; + }; + for e in rd.filter_map(Result::ok) { + let bare = e.path().join(".bare"); + if !bare.is_dir() { + continue; + } + let Some(url) = Git::new(&bare).probe(&["config", "--get", "remote.origin.url"])? + else { + continue; + }; + reg.upsert(Entry { + group: grp.name.clone(), + name: e.file_name().to_string_lossy().into_owned(), + url, + }); + } + } + fs::write(dir.join("repos.toml"), reg.to_text())?; + write_heartbeat(cfg, &dir)?; + commit_and_push(cfg, &dir, &forge, "update registry")?; + Ok(reg.repos.len()) +} + +/// Fresh machine: materializes every repo of the config repo under the root. +pub fn bootstrap(cfg: &Config) -> Result<(usize, usize)> { + let (dir, forge) = config_repo_open(cfg, false)?; + let reg = read_registry(&dir)?; + let (mut done, mut skipped) = (0, 0); + for e in ®.repos { + let target = cfg.root_path().join(&e.group).join(&e.name); + if target.join(".bare").exists() { + skipped += 1; + continue; + } + match clone_bare_layout(&e.url, &target, &forge.git_env) { + Ok(_) => { + println!("cloned {}/{}", e.group, e.name); + done += 1; + } + Err(err) => println!("FAILED {}/{}: {err}", e.group, e.name), + } + } + write_heartbeat(cfg, &dir)?; + commit_and_push(cfg, &dir, &forge, "machine heartbeat")?; + Ok((done, skipped)) +} diff --git a/docs/phase4.md b/docs/phase4.md new file mode 100644 index 0000000..114c123 --- /dev/null +++ b/docs/phase4.md @@ -0,0 +1,52 @@ +# Phase 4: providers and wizards + +Crate `grove-providers`: `Provider` trait with Gitea/Forgejo (`/api/v1`) and GitHub clients over +`ureq`, plus token storage. The CLI (`crates/grove/src/workflow.rs`) composes them. + +## Tokens + +`GROVE_TOKEN_` (id upper-cased, non-alphanumerics to `_`) wins; otherwise the desktop Secret +Service via `keyring` (service `grove`, user = provider id). Tokens are never written to the config +file. `grove login ` reads the token from stdin (never argv), checks it against the forge and +stores it. HTTPS git operations of the wizards authenticate through `http.extraHeader` set in the +process environment only (Gitea/Forgejo); for GitHub they use the user's credential helper. + +## Commands + +| Command | What it does | +|---|---| +| `grove init` | Writes a first `config.toml` (machine, root, one provider, one group, optional config repo) | +| `grove login ` | Stores the API token after verifying it | +| `grove new [--public]` | Creates the repo on the group's primary forge, the local bare+worktree layout, an initial commit, pushes, configures push mirrors, registers it in the config repo | +| `grove import [names...]` | Lists remote repos not on this machine; with names, clones them into the layout | +| `grove config-repo-init` | Creates the private config repo and registers every repo already on disk | +| `grove bootstrap` | Fresh machine: clones every repo in the config repo under the root | + +## Config repo + +A private repo (name from `[config_repo]`) holding `repos.toml` (`group`, `name`, `url` per repo) and +`machines/.json` (written only when the registry changes, so no commit noise). The local +clone lives in `/config-repo`. It is created on the first registration if missing. + +## Mirrors + +Gitea/Forgejo: the primary creates a push mirror via `POST /repos/{o}/{r}/push_mirrors` +(`sync_on_commit`, 8 h interval) to a repo created on the mirror provider. GitHub has no push +mirrors: `configure_mirror` reports `Unsupported` and `new` warns. The daemon-side fallback (push +branches and tags only, never `refs/sync/*`) is **not implemented**. + +## Validation + +- Unit/mock tests: `crates/grove-providers/tests/api.rs` (requests, auth headers, error mapping, + org endpoint, no-push-mirror on GitHub, env token override), `grove-core/tests/registry.rs` + (bare layout creation, push, clone into layout, registry round trip). +- End to end against a local Forgejo 11: `spikes/phase4-e2e.sh` (new x2, config repo, a second + machine rebuilds the workspace with `login` env token + `bootstrap`). Passed; repos cleaned up. +- Also exercised there: `import` (list, clone, unknown name rejected), invalid token rejected (401). + +## Not done / not verified + +- Mirror creation against a real forge pair (only the API call shape is mock-tested). +- Secret Service storage on a real desktop session (the sandbox has none; env override used). +- GitHub provider against github.com (mock only). GitHub git auth relies on the credential helper. +- Deleting remote repos is deliberately not implemented. diff --git a/spikes/phase4-e2e.sh b/spikes/phase4-e2e.sh new file mode 100755 index 0000000..9e9f792 --- /dev/null +++ b/spikes/phase4-e2e.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Phase 4 end-to-end check against a throwaway Forgejo on localhost:3300 (spikes/forgejo-up.sh): +# new repo -> config repo -> a fresh machine rebuilds the workspace with `grove bootstrap`. +set -euo pipefail +G=${GROVE_BIN:-target/debug/grove} +G=$(realpath "$G") +W=$(mktemp -d) +api() { curl -fs -u spike:spike-pass-123 "$@"; } +cleanup() { + for r in alpha beta grove-config; do api -X DELETE "localhost:3300/api/v1/repos/spike/$r" >/dev/null || true; done + rm -rf "$W" +} +trap cleanup EXIT +TOK=$(api -H 'Content-Type: application/json' -X POST localhost:3300/api/v1/users/spike/tokens \ + -d "{\"name\":\"e2e$RANDOM\",\"scopes\":[\"all\"]}" | sed -E 's/.*"sha1":"([^"]+)".*/\1/') +export GROVE_TOKEN_MAIN=$TOK +machine() { # name + export XDG_CONFIG_HOME=$W/$1/cfg XDG_STATE_HOME=$W/$1/state + "$G" init --machine "$1" --root "$W/$1/ws" --provider main --kind gitea \ + --url http://localhost:3300 --group work --config-repo grove-config >/dev/null +} +machine pca +"$G" new work alpha +"$G" new work beta --public +"$G" config-repo-init +machine pcb +"$G" bootstrap +test -d "$W/pcb/ws/work/alpha/main" && test -d "$W/pcb/ws/work/beta/main" +echo "OK: fresh machine pcb has both repos"