From f2016115101b5c2d02971af7e6927265229105e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 04:54:41 +0000 Subject: [PATCH] feat: manage namespaces/providers and open worktrees in editors - grove group add|remove|list and grove provider add|remove|list edit config.toml (validated first, previous file kept as config.toml.bak) - grove open [group/]repo[@branch] launches Zed, VS Code, Claude Code (in a terminal) or Claude Desktop; [open] config for defaults, terminal and own launchers; grove new --open - GUI: provider/namespace forms and removal in Settings, Open buttons on repos and worktrees, open-after-create on New repository - docs/phase8.md, DECISIONS 10-11 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011GZUAGhGYoiLvmfXweQnDY --- CLAUDE.md | 3 +- crates/grove-core/src/config.rs | 105 +++++- crates/grove-core/src/launch.rs | 585 ++++++++++++++++++++++++++++++++ crates/grove-core/src/lib.rs | 1 + crates/grove-gui/src/bridge.rs | 123 ++++++- crates/grove-gui/src/main.rs | 118 ++++++- crates/grove-gui/src/model.rs | 89 +++++ crates/grove-gui/ui/app.slint | 313 ++++++++++++++++- crates/grove/src/main.rs | 284 +++++++++++++++- crates/grove/src/namespace.rs | 362 ++++++++++++++++++++ crates/grove/src/workflow.rs | 1 + docs/DECISIONS.md | 2 + docs/phase8.md | 114 +++++++ 13 files changed, 2075 insertions(+), 25 deletions(-) create mode 100644 crates/grove-core/src/launch.rs create mode 100644 crates/grove/src/namespace.rs create mode 100644 docs/phase8.md diff --git a/CLAUDE.md b/CLAUDE.md index 26d2e58..fb77ee0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,6 +6,7 @@ uncommitted work, via snapshot refs (`refs/sync//`) on a primar Rust workspace: `grove-core`, `grove` (CLI), `grove-daemon` (`groved`), `grove-providers` (Gitea/Forgejo/GitHub), `grove-gui` (native Slint desktop app with a ksni tray, `docs/phase7.md`). Phases 0-7 are implemented; the real two-PC run passed (`docs/two-pc-run.md`). Worktrees merged through a PR on the forge are pruned by the daemon (`docs/prune-merged.md`). +Namespaces/providers are edited with `grove group|provider` and worktrees opened in editors with `grove open` (`docs/phase8.md`). Do not start new work before the previous results are written to `docs/`. ## Commands @@ -18,7 +19,7 @@ Do not start new work before the previous results are written to `docs/`. - Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh` ## Architecture -See `docs/` (`phase0-spike.md` ... `phase7.md`, `two-pc-run.md`, `prune-merged.md`, `DECISIONS.md`). Git is the storage layer; shell out to +See `docs/` (`phase0-spike.md` ... `phase7.md`, `phase8.md`, `two-pc-run.md`, `prune-merged.md`, `DECISIONS.md`). Git is the storage layer; shell out to system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the user's branch or index. diff --git a/crates/grove-core/src/config.rs b/crates/grove-core/src/config.rs index 684928c..bbb5385 100644 --- a/crates/grove-core/src/config.rs +++ b/crates/grove-core/src/config.rs @@ -17,6 +17,45 @@ pub struct Config { pub sync: Sync, #[serde(skip_serializing_if = "Option::is_none")] pub config_repo: Option, + /// How `grove open` launches editors and tools on a worktree (machine-local). + #[serde(default, skip_serializing_if = "Open::is_empty")] + pub open: Open, +} + +/// `[open]`: editors and tools a worktree can be opened with (see `crate::launch`). +#[derive(Debug, Clone, PartialEq, Default, Deserialize, Serialize)] +pub struct Open { + /// Launcher used when none is named (default: the first available one). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default: Option, + /// Terminal command prefix for terminal launchers, e.g. `["kitty", "--directory", "{path}"]`. + /// The launcher's command is appended. Default: `$TERMINAL`, then the first known terminal + /// found. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub terminal: Option>, + /// Own launchers; one named like a built-in replaces it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub launchers: Vec, +} + +impl Open { + pub fn is_empty(&self) -> bool { + *self == Open::default() + } +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Launcher { + pub name: String, + /// Shown in the GUI (default: the name). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + /// Program and arguments; `{path}` is replaced by the worktree path. The process also + /// starts in the worktree. + pub command: Vec, + /// Run the command inside a terminal (for command-line tools such as `claude`). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub terminal: bool, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] @@ -424,11 +463,42 @@ impl Config { { return bad(format!("config_repo: unknown provider {:?}", c.provider)); } + let mut seen = std::collections::BTreeSet::new(); + for l in &self.open.launchers { + if !is_plain_name(&l.name) { + return bad(format!( + "open.launchers: name {:?} must use only letters, digits, '-' or '_'", + l.name + )); + } + if !seen.insert(l.name.as_str()) { + return bad(format!("open.launchers: {:?} is defined twice", l.name)); + } + if l.command.first().is_none_or(|p| p.trim().is_empty()) { + return bad(format!("open.launchers: {:?} has no command", l.name)); + } + } + if let Some(d) = &self.open.default + && !seen.contains(d.as_str()) + && !crate::launch::BUILTIN.iter().any(|b| b.name == d) + { + return bad(format!("open.default: unknown launcher {d:?}")); + } + if self.open.terminal.as_ref().is_some_and(|t| t.is_empty()) { + return bad("open.terminal must not be empty".into()); + } Ok(()) } } -fn expand_home(p: &str) -> PathBuf { +/// Letters, digits, `-` and `_` only (and not empty): safe as a ref part, id or file name. +pub fn is_plain_name(s: &str) -> bool { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +pub fn expand_home(p: &str) -> PathBuf { match (p.strip_prefix("~/"), std::env::var_os("HOME")) { (Some(rest), Some(home)) => PathBuf::from(home).join(rest), _ if p == "~" => std::env::var_os("HOME").map_or_else(|| PathBuf::from(p), PathBuf::from), @@ -651,6 +721,39 @@ mirror_to = ["gitea"] assert!(matches!(Config::parse(t), Err(ConfigError::Parse(_)))); } + #[test] + fn open_section_round_trips_and_is_validated() { + let base = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n"; + let c = Config::parse(base).unwrap(); + assert!(c.open.is_empty()); + assert!(!toml::to_string(&c).unwrap().contains("[open]")); + let t = format!( + "{base}[open]\ndefault=\"nvim\"\nterminal=[\"foot\"]\n\ + [[open.launchers]]\nname=\"nvim\"\ncommand=[\"nvim\",\".\"]\nterminal=true\n" + ); + let c = Config::parse(&t).unwrap(); + assert_eq!(c.open.launchers[0].command, ["nvim", "."]); + assert!(c.open.launchers[0].terminal); + assert_eq!(Config::parse(&toml::to_string(&c).unwrap()).unwrap(), c); + // A built-in can be the default without being redefined. + assert!(Config::parse(&format!("{base}[open]\ndefault=\"zed\"\n")).is_ok()); + for bad in [ + "[open]\ndefault=\"nope\"\n", + "[open]\nterminal=[]\n", + "[[open.launchers]]\nname=\"a b\"\ncommand=[\"x\"]\n", + "[[open.launchers]]\nname=\"a\"\ncommand=[]\n", + "[[open.launchers]]\nname=\"a\"\ncommand=[\"x\"]\n[[open.launchers]]\nname=\"a\"\ncommand=[\"y\"]\n", + ] { + assert!( + matches!( + Config::parse(&format!("{base}{bad}")), + Err(ConfigError::Invalid(_)) + ), + "{bad}" + ); + } + } + #[test] fn provider_protocol_defaults_to_https_and_is_validated() { let t = |p: &str| { diff --git a/crates/grove-core/src/launch.rs b/crates/grove-core/src/launch.rs new file mode 100644 index 0000000..5240ac3 --- /dev/null +++ b/crates/grove-core/src/launch.rs @@ -0,0 +1,585 @@ +//! Opening a worktree in an editor or tool (`grove open`): the launcher table, terminal +//! detection, target resolution and a detached spawn. No sync logic lives here. + +use crate::config::{Config, Open, expand_home}; +use crate::git::Git; +use crate::inspect::worktrees; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +/// A launcher grove knows without configuration. +pub struct Builtin { + pub name: &'static str, + pub label: &'static str, + /// Candidate programs; the first one found wins (distributions rename some of them). + pub programs: &'static [&'static str], + pub args: &'static [&'static str], + pub terminal: bool, +} + +pub const BUILTIN: &[Builtin] = &[ + Builtin { + name: "zed", + label: "Zed", + programs: &["zed", "zeditor", "zedit"], + args: &["{path}"], + terminal: false, + }, + Builtin { + name: "vscode", + label: "VS Code", + programs: &["code", "codium", "code-oss"], + args: &["{path}"], + terminal: false, + }, + Builtin { + name: "claude", + label: "Claude Code", + programs: &["claude"], + args: &[], + terminal: true, + }, + Builtin { + name: "claude-desktop", + label: "Claude Desktop", + programs: &["claude-desktop"], + args: &["{path}"], + terminal: false, + }, +]; + +/// Known terminals and the arguments that run a command in `{path}` (the command follows). +const TERMINALS: &[(&str, &[&str])] = &[ + ("kitty", &["--directory", "{path}"]), + ("ghostty", &["--working-directory={path}", "-e"]), + ("alacritty", &["--working-directory", "{path}", "-e"]), + ("foot", &["--working-directory={path}"]), + ("wezterm", &["start", "--cwd", "{path}", "--"]), + ("konsole", &["--workdir", "{path}", "-e"]), + ( + "ptyxis", + &["--new-window", "--working-directory={path}", "--"], + ), + ("gnome-terminal", &["--working-directory={path}", "--"]), + ("xfce4-terminal", &["--working-directory={path}", "-x"]), + ("xterm", &["-e"]), +]; + +/// A launcher as resolved on this machine. +#[derive(Debug, Clone, PartialEq)] +pub struct Resolved { + pub name: String, + pub label: String, + /// Program (absolute when found) and arguments, `{path}` not yet substituted. + pub command: Vec, + pub terminal: bool, + /// The program was found. + pub available: bool, +} + +/// Program lookup and environment, injectable for tests. +pub trait Finder { + fn find(&self, program: &str) -> Option; + fn env(&self, key: &str) -> Option; +} + +/// The real machine: `PATH` plus the user-level install directories a desktop session's `PATH` +/// often lacks (`~/.local/bin`, `~/.claude/local`, `~/.cargo/bin`). +pub struct System; + +impl Finder for System { + fn find(&self, program: &str) -> Option { + find_program(program) + } + fn env(&self, key: &str) -> Option { + std::env::var(key).ok().filter(|v| !v.trim().is_empty()) + } +} + +pub fn find_program(program: &str) -> Option { + if program.contains('/') { + let p = expand_home(program); + return is_executable(&p).then_some(p); + } + let mut dirs: Vec = std::env::var_os("PATH") + .map(|p| std::env::split_paths(&p).collect()) + .unwrap_or_default(); + if let Some(h) = std::env::var_os("HOME") { + let h = PathBuf::from(h); + dirs.extend([ + h.join(".local/bin"), + h.join(".claude/local"), + h.join(".cargo/bin"), + ]); + } + dirs.into_iter() + .map(|d| d.join(program)) + .find(|c| is_executable(c)) +} + +fn is_executable(p: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + p.metadata() + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) +} + +/// Every launcher: the configured ones first (in config order), then the built-ins they do not +/// replace. +pub fn launchers(open: &Open, f: &dyn Finder) -> Vec { + let mut out: Vec = open + .launchers + .iter() + .map(|l| { + let found = f.find(&l.command[0]); + let mut command = l.command.clone(); + if let Some(p) = &found { + command[0] = p.to_string_lossy().into_owned(); + } + Resolved { + name: l.name.clone(), + label: l.label.clone().unwrap_or_else(|| l.name.clone()), + command, + terminal: l.terminal, + available: found.is_some(), + } + }) + .collect(); + for b in BUILTIN { + if out.iter().any(|r| r.name == b.name) { + continue; + } + let found = b.programs.iter().find_map(|p| f.find(p)); + let program = found.as_ref().map_or(b.programs[0].to_string(), |p| { + p.to_string_lossy().into_owned() + }); + out.push(Resolved { + name: b.name.into(), + label: b.label.into(), + command: std::iter::once(program) + .chain(b.args.iter().map(|a| a.to_string())) + .collect(), + terminal: b.terminal, + available: found.is_some(), + }); + } + out +} + +/// The launcher named `name`, or the default one: `open.default`, else the first available. +pub fn pick<'a>( + all: &'a [Resolved], + open: &Open, + name: Option<&str>, +) -> Result<&'a Resolved, String> { + let wanted = name.or(open.default.as_deref()); + let l = match wanted { + Some(n) => all.iter().find(|l| l.name == n).ok_or_else(|| { + let names: Vec<&str> = all.iter().map(|l| l.name.as_str()).collect(); + format!("unknown launcher {n:?} (known: {})", names.join(", ")) + })?, + None => all.iter().find(|l| l.available).ok_or( + "no editor or tool found (install zed, code or claude, or add [[open.launchers]])", + )?, + }; + if !l.available { + let tried = BUILTIN + .iter() + .find(|b| b.name == l.name && l.command[0] == b.programs[0]) + .map_or_else(|| l.command[0].clone(), |b| b.programs.join(", ")); + return Err(format!( + "{} is not installed (looked for {tried} in PATH, ~/.local/bin, ~/.claude/local, ~/.cargo/bin)", + l.label + )); + } + Ok(l) +} + +/// The terminal prefix for terminal launchers (`{path}` not yet substituted). +pub fn terminal(open: &Open, f: &dyn Finder) -> Result, String> { + if let Some(t) = &open.terminal { + return Ok(t.clone()); + } + let known = |prog: &str, base: &str| { + let args = TERMINALS + .iter() + .find(|(n, _)| *n == base) + .map_or(&["-e"][..], |(_, a)| a); + std::iter::once(prog.to_string()) + .chain(args.iter().map(|a| a.to_string())) + .collect::>() + }; + if let Some(t) = f.env("TERMINAL") { + let prog = t.split_whitespace().next().unwrap_or_default().to_string(); + if let Some(p) = f.find(&prog) { + let base = Path::new(&prog) + .file_name() + .map(|b| b.to_string_lossy().into_owned()) + .unwrap_or_default(); + return Ok(known(&p.to_string_lossy(), &base)); + } + } + TERMINALS + .iter() + .find_map(|(n, _)| f.find(n).map(|p| known(&p.to_string_lossy(), n))) + .ok_or_else(|| "no terminal found: set $TERMINAL or open.terminal in config.toml".into()) +} + +/// The full command line that opens `path` with `l`. +pub fn argv(l: &Resolved, path: &Path, open: &Open, f: &dyn Finder) -> Result, String> { + let p = path.to_string_lossy(); + let sub = |a: &String| a.replace("{path}", &p); + let cmd: Vec = l.command.iter().map(sub).collect(); + if !l.terminal { + return Ok(cmd); + } + let mut t: Vec = terminal(open, f)?.iter().map(sub).collect(); + t.extend(cmd); + Ok(t) +} + +/// Starts `argv` in `cwd`, detached (own process group, no stdio), so it outlives grove. A +/// program that fails within half a second (bad arguments, missing display) is reported. +pub fn spawn(argv: &[String], cwd: &Path) -> Result<(), String> { + use std::os::unix::process::CommandExt; + let (prog, args) = argv.split_first().ok_or("empty command")?; + let mut child = Command::new(prog) + .args(args) + .current_dir(cwd) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .process_group(0) + .spawn() + .map_err(|e| format!("cannot start {prog}: {e}"))?; + let until = Instant::now() + Duration::from_millis(500); + while Instant::now() < until { + match child.try_wait() { + Ok(Some(st)) if !st.success() => return Err(format!("{prog} exited with {st}")), + Ok(Some(_)) => return Ok(()), + Ok(None) => std::thread::sleep(Duration::from_millis(50)), + Err(e) => return Err(format!("{prog}: {e}")), + } + } + Ok(()) +} + +/// The directory `target` names: a path (a worktree, or a bare-layout repo whose default-branch +/// worktree is picked), or `[group/]repo[@branch]` under the root. +pub fn resolve_target(cfg: &Config, target: &str) -> Result { + let as_path = expand_home(target); + if as_path.exists() { + let dir = as_path + .canonicalize() + .map_err(|e| format!("{}: {e}", as_path.display()))?; + if !dir.is_dir() { + return Err(format!("{} is not a directory", dir.display())); + } + return if dir.join(".bare").is_dir() { + pick_worktree(&dir, None) + } else { + Ok(dir) + }; + } + let (name, branch) = match target.rsplit_once('@') { + Some((n, b)) if !b.is_empty() => (n, Some(b)), + _ => (target, None), + }; + let root = cfg.root_path(); + let dir = match name.split_once('/') { + Some((g, r)) => { + let d = root.join(g).join(r); + if !is_plain(g) || !is_plain(r) || !d.is_dir() { + return Err(format!("no repository {name:?} under {}", root.display())); + } + d + } + None => find_repo(cfg, &root, name)?, + }; + if dir.join(".bare").is_dir() { + pick_worktree(&dir, branch) + } else if let Some(b) = branch { + Err(format!( + "{} is not in the bare layout, so it has no worktree for {b:?}", + dir.display() + )) + } else { + Ok(dir) + } +} + +fn is_plain(s: &str) -> bool { + !s.is_empty() && !s.starts_with('.') && !s.contains(['/', '\\']) +} + +/// `root//` across all groups: an exact match, else a case-insensitive one. +fn find_repo(cfg: &Config, root: &Path, name: &str) -> Result { + if !is_plain(name) { + return Err(format!("{name:?} is not a repository name or path")); + } + let mut exact = Vec::new(); + let mut loose = Vec::new(); + for g in &cfg.groups { + let Ok(rd) = std::fs::read_dir(root.join(&g.name)) else { + continue; + }; + for e in rd.flatten() { + let n = e.file_name().to_string_lossy().into_owned(); + if !e.path().is_dir() || n.starts_with('.') { + continue; + } + if n == name { + exact.push((g.name.clone(), e.path())); + } else if n.eq_ignore_ascii_case(name) { + loose.push((g.name.clone(), e.path())); + } + } + } + let hits = if exact.is_empty() { loose } else { exact }; + match hits.len() { + 0 => Err(format!( + "no repository {name:?} in any group under {}", + root.display() + )), + 1 => Ok(hits.into_iter().next().map(|(_, p)| p).unwrap_or_default()), + _ => { + let names: Vec = hits + .iter() + .map(|(g, p)| { + format!( + "{g}/{}", + p.file_name().unwrap_or_default().to_string_lossy() + ) + }) + .collect(); + Err(format!( + "{name:?} is ambiguous: {} (use group/repo)", + names.join(", ") + )) + } + } +} + +/// The worktree of `branch` in the bare-layout repo `dir`; without a branch the default +/// branch's (`origin/HEAD`, then `main`, `master`), else the first one, else `dir` itself. +pub fn pick_worktree(dir: &Path, branch: Option<&str>) -> Result { + let bare = dir.join(".bare"); + let wts: Vec<_> = worktrees(&bare) + .map_err(|e| e.to_string())? + .into_iter() + .filter(|w| w.path.is_dir()) + .collect(); + if let Some(b) = branch { + return wts + .iter() + .find(|w| w.branch.as_deref() == Some(b)) + .map(|w| w.path.clone()) + .ok_or_else(|| { + let have: Vec<&str> = wts.iter().filter_map(|w| w.branch.as_deref()).collect(); + format!( + "{} has no worktree for branch {b:?} (have: {})", + dir.display(), + have.join(", ") + ) + }); + } + let head = Git::new(&bare) + .probe(&["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) + .ok() + .flatten() + .and_then(|h| h.strip_prefix("origin/").map(str::to_string)); + let by = |b: &str| wts.iter().find(|w| w.branch.as_deref() == Some(b)); + Ok(head + .as_deref() + .and_then(by) + .or_else(|| by("main")) + .or_else(|| by("master")) + .or(wts.first()) + .map_or_else(|| dir.to_path_buf(), |w| w.path.clone())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Launcher; + use std::collections::HashMap; + + struct Fake { + progs: Vec<&'static str>, + env: HashMap<&'static str, &'static str>, + } + + impl Finder for Fake { + fn find(&self, p: &str) -> Option { + self.progs + .contains(&p) + .then(|| PathBuf::from("/bin").join(p)) + } + fn env(&self, k: &str) -> Option { + self.env.get(k).map(|v| v.to_string()) + } + } + + fn fake(progs: &[&'static str]) -> Fake { + Fake { + progs: progs.to_vec(), + env: HashMap::new(), + } + } + + #[test] + fn builtins_resolve_to_the_first_program_found() { + let all = launchers(&Open::default(), &fake(&["zeditor", "claude", "kitty"])); + let zed = all.iter().find(|l| l.name == "zed").unwrap(); + assert!(zed.available); + assert_eq!(zed.command, ["/bin/zeditor", "{path}"]); + let code = all.iter().find(|l| l.name == "vscode").unwrap(); + assert!(!code.available); + let p = Path::new("/w/repo/main"); + let open = Open::default(); + let f = fake(&["zeditor", "claude", "kitty"]); + assert_eq!( + argv(zed, p, &open, &f).unwrap(), + ["/bin/zeditor", "/w/repo/main"] + ); + let claude = pick(&all, &open, Some("claude")).unwrap(); + assert_eq!( + argv(claude, p, &open, &f).unwrap(), + ["/bin/kitty", "--directory", "/w/repo/main", "/bin/claude"] + ); + let e = pick(&all, &open, Some("vscode")).unwrap_err(); + assert!(e.contains("code, codium"), "{e}"); + assert!( + pick(&all, &open, Some("emacs")) + .unwrap_err() + .contains("unknown") + ); + // No name, no default: the first available. + assert_eq!(pick(&all, &open, None).unwrap().name, "zed"); + assert!(pick(&launchers(&open, &fake(&[])), &open, None).is_err()); + } + + #[test] + fn configured_launchers_replace_builtins_and_set_the_default() { + let open = Open { + default: Some("claude".into()), + terminal: Some(vec![ + "myterm".into(), + "-d".into(), + "{path}".into(), + "--".into(), + ]), + launchers: vec![ + Launcher { + name: "nvim".into(), + label: Some("Neovim".into()), + command: vec!["nvim".into(), ".".into()], + terminal: true, + }, + Launcher { + name: "zed".into(), + label: None, + command: vec!["/opt/zed/bin/zed".into(), "-n".into(), "{path}".into()], + terminal: false, + }, + ], + }; + let f = fake(&["nvim", "claude"]); + let all = launchers(&open, &f); + assert_eq!(all[0].label, "Neovim"); + assert_eq!(all.iter().filter(|l| l.name == "zed").count(), 1); + assert!(!all[1].available); + assert_eq!(pick(&all, &open, None).unwrap().name, "claude"); + let nvim = pick(&all, &open, Some("nvim")).unwrap(); + assert_eq!( + argv(nvim, Path::new("/r"), &open, &f).unwrap(), + ["myterm", "-d", "/r", "--", "/bin/nvim", "."] + ); + } + + #[test] + fn terminal_prefers_env_then_known_list() { + let mut f = fake(&["foot", "alacritty"]); + let open = Open::default(); + assert_eq!(terminal(&open, &f).unwrap()[0], "/bin/alacritty"); + f.env.insert("TERMINAL", "foot"); + assert_eq!( + terminal(&open, &f).unwrap(), + ["/bin/foot", "--working-directory={path}"] + ); + f.progs.push("myterm"); + f.env.insert("TERMINAL", "myterm"); + assert_eq!(terminal(&open, &f).unwrap(), ["/bin/myterm", "-e"]); + assert!(terminal(&open, &fake(&[])).is_err()); + } + + fn git(dir: &Path, args: &[&str]) { + Git::new(dir).run(args).unwrap(); + } + + #[test] + fn targets_resolve_to_worktrees() { + let tmp = crate::test_tmp::TempDir::new("launch"); + let root = tmp.path().canonicalize().unwrap(); + // work/app: bare layout with main and feat worktrees, origin/HEAD -> main. + let app = root.join("work/app"); + std::fs::create_dir_all(&app).unwrap(); + let wt = crate::registry::init_bare_layout(&app, "https://example.invalid/x.git").unwrap(); + let bare = app.join(".bare"); + git(&bare, &["update-ref", "refs/remotes/origin/main", "main"]); + git( + &bare, + &[ + "symbolic-ref", + "refs/remotes/origin/HEAD", + "refs/remotes/origin/main", + ], + ); + git(&bare, &["branch", "feat", "main"]); + let feat = app.join("feat"); + git( + &bare, + &["worktree", "add", "-q", &feat.to_string_lossy(), "feat"], + ); + // home/notes: a plain directory; other/App: a case-insensitive clash with work/app. + std::fs::create_dir_all(root.join("home/notes")).unwrap(); + let cfg = Config::parse(&format!( + "[machine]\nname=\"m\"\n[root]\npath=\"{}\"\n[providers.p]\nkind=\"gitea\"\n\ + [[groups]]\nname=\"work\"\nprimary=\"p\"\n[[groups]]\nname=\"home\"\nprimary=\"p\"\n\ + [[groups]]\nname=\"other\"\nprimary=\"p\"\n", + root.display() + )) + .unwrap(); + let wt = wt.canonicalize().unwrap(); + let feat = feat.canonicalize().unwrap(); + let r = |t: &str| resolve_target(&cfg, t); + assert_eq!(r("app").unwrap(), wt); + assert_eq!(r("work/app").unwrap(), wt); + assert_eq!(r("APP").unwrap(), wt); + assert_eq!(r("app@feat").unwrap(), feat); + assert_eq!(r(&app.to_string_lossy()).unwrap(), wt); + assert_eq!(r(&feat.to_string_lossy()).unwrap(), feat); + assert_eq!(r("notes").unwrap(), root.join("home/notes")); + assert!(r("app@nope").unwrap_err().contains("have: ")); + assert!(r("notes@main").is_err()); + assert!(r("missing").is_err()); + assert!(r("work/../home").is_err()); + std::fs::create_dir_all(root.join("other/App")).unwrap(); + assert_eq!(r("app").unwrap(), wt, "an exact match wins"); + std::fs::create_dir_all(root.join("other/app")).unwrap(); + assert!(r("app").unwrap_err().contains("ambiguous")); + } + + #[test] + fn spawn_reports_early_failures() { + let tmp = crate::test_tmp::TempDir::new("spawn"); + assert!(spawn(&["true".into()], tmp.path()).is_ok()); + assert!( + spawn(&["false".into()], tmp.path()) + .unwrap_err() + .contains("exited") + ); + assert!(spawn(&["/nonexistent/x".into()], tmp.path()).is_err()); + assert!(spawn(&[], tmp.path()).is_err()); + } +} diff --git a/crates/grove-core/src/lib.rs b/crates/grove-core/src/lib.rs index f5475d4..4a03112 100644 --- a/crates/grove-core/src/lib.rs +++ b/crates/grove-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod busy; pub mod config; pub mod git; pub mod inspect; +pub mod launch; pub mod layout; pub mod migrate; pub mod prune; diff --git a/crates/grove-gui/src/bridge.rs b/crates/grove-gui/src/bridge.rs index cb6897c..e03ab08 100644 --- a/crates/grove-gui/src/bridge.rs +++ b/crates/grove-gui/src/bridge.rs @@ -18,6 +18,9 @@ const ALLOWED: &[&str] = &[ "secrets", "sync", "status", + "group", + "provider", + "open", ]; pub struct Bridge { @@ -53,6 +56,17 @@ impl Bridge { Err(e) => return json!({"ok": false, "output": format!("rejected: {e}")}), } } + // `open` only for a directory under the workspace root, in canonical form. + if sub == "open" { + let checked_path = self + .loaded_config() + .ok_or_else(|| "no readable configuration".to_string()) + .and_then(|cfg| check_open_path(&cfg, Path::new(&args[1]))); + match checked_path { + Ok(canon) => checked[1] = canon.to_string_lossy().into_owned(), + Err(e) => return json!({"ok": false, "output": format!("rejected: {e}")}), + } + } let args = &checked[..]; let mut cmd = Command::new(&self.grove_bin); if let Some(c) = &self.config { @@ -106,6 +120,26 @@ impl Bridge { check_migrate_path(&cfg, Path::new(path)) } + /// Installed launchers (name, label) for "Open in" buttons, the default one first. + pub fn launchers(&self) -> Vec<(String, String)> { + use grove_core::launch::{System, launchers, pick}; + let Some(cfg) = self.loaded_config() else { + return Vec::new(); + }; + let all = launchers(&cfg.open, &System); + let default = pick(&all, &cfg.open, None).ok().map(|l| l.name.clone()); + let mut out: Vec<(String, String)> = all + .into_iter() + .filter(|l| l.available) + .map(|l| (l.name, l.label)) + .collect(); + if let Some(i) = out.iter().position(|(n, _)| Some(n) == default.as_ref()) { + let d = out.remove(i); + out.insert(0, d); + } + out + } + /// Where `grove add` writes its safety backup. pub fn backup_dir() -> Option { grove_core::config::Config::state_dir().map(|d| d.join("backups")) @@ -135,7 +169,20 @@ fn flag_spec(sub: &str) -> (&'static [&'static str], &'static [&'static str]) { "--url", ], ), - "new" => (&["--public"], &[]), + "new" => (&["--public"], &["--open"]), + "open" => (&[], &["--with"]), + "group" => ( + &["--replace", "--no-materialize"], + &[ + "--primary", + "--mirror-to", + "--owner", + "--public-primary", + "--public-mirror-to", + "--snapshots", + ], + ), + "provider" => (&["--replace"], &["--kind", "--url", "--protocol"]), "resolve" => (&["--take-remote", "--keep-local"], &["--save-as"]), _ => (&[], &[]), } @@ -159,11 +206,22 @@ pub fn validate(args: &[String]) -> Result<(), String> { } } else if sub == "secrets" && i == 0 && !["init", "pull", "rekey"].contains(&a.as_str()) { return Err(format!("secrets {a:?} is not allowed from the GUI")); + } else if (sub == "group" || sub == "provider") + && i == 0 + && !["add", "remove"].contains(&a.as_str()) + { + return Err(format!("{sub} {a:?} is not allowed from the GUI")); } } if sub == "secrets" && args.len() != 2 { return Err("secrets takes exactly one action".into()); } + if (sub == "group" || sub == "provider") && args.len() < 3 { + return Err(format!("{sub} needs an action and a name")); + } + if sub == "open" && args.get(1).is_none_or(|p| p.starts_with('-')) { + return Err("open needs a path first".into()); + } Ok(()) } @@ -192,6 +250,27 @@ pub fn check_migrate_path( } } +/// A directory the GUI may open in an editor: an existing directory inside the workspace root. +pub fn check_open_path(cfg: &grove_core::config::Config, path: &Path) -> Result { + let canon = path + .canonicalize() + .map_err(|e| format!("{}: {e}", path.display()))?; + if !canon.is_dir() { + return Err(format!("{} is not a directory", path.display())); + } + let root = cfg.root_path(); + let root = root.canonicalize().unwrap_or(root); + if canon.starts_with(&root) && canon != root { + Ok(canon) + } else { + Err(format!( + "{} is not inside {}", + path.display(), + root.display() + )) + } +} + fn grove_core_default_config() -> Option { let base = std::env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) @@ -215,6 +294,48 @@ mod tests { assert!(v(&["resolve", "/p", "--save-as", "b", "--take-remote"]).is_ok()); assert!(v(&["new", "g", "n", "--public"]).is_ok()); assert!(v(&["secrets", "pull"]).is_ok()); + assert!(v(&["group", "list"]).is_err()); + assert!(v(&["group", "add"]).is_err()); + assert!(v(&["group", "add", "g", "--primary", "p", "--force"]).is_err()); + assert!( + v(&[ + "group", + "add", + "g", + "--primary", + "p", + "--mirror-to", + "q", + "--replace" + ]) + .is_ok() + ); + assert!(v(&["provider", "remove", "p"]).is_ok()); + assert!(v(&["provider", "add", "p", "--url", "--kind"]).is_err()); + assert!(v(&["open", "/p", "--with", "zed"]).is_ok()); + assert!(v(&["open", "/p", "--print"]).is_err()); + assert!(v(&["open", "--with", "zed"]).is_err()); + assert!(v(&["new", "g", "n", "--open", "zed"]).is_ok()); + } + + #[test] + fn open_path_must_be_inside_the_root() { + let tmp = crate::test_tmp::TempDir::new("grove-open"); + let base = tmp.path().canonicalize().unwrap(); + std::fs::create_dir_all(base.join("ws/work/app/main")).unwrap(); + std::fs::create_dir_all(base.join("elsewhere")).unwrap(); + let cfg = grove_core::config::Config::parse(&format!( + "[machine]\nname=\"m\"\n[root]\npath=\"{}/ws\"\n", + base.display() + )) + .unwrap(); + assert_eq!( + check_open_path(&cfg, &base.join("ws/work/app/../app/main")).unwrap(), + base.join("ws/work/app/main") + ); + for bad in ["ws", "elsewhere", "ws/work/../../elsewhere", "ws/none"] { + assert!(check_open_path(&cfg, &base.join(bad)).is_err(), "{bad}"); + } } #[test] diff --git a/crates/grove-gui/src/main.rs b/crates/grove-gui/src/main.rs index 4c24ae2..a1682c1 100644 --- a/crates/grove-gui/src/main.rs +++ b/crates/grove-gui/src/main.rs @@ -47,6 +47,8 @@ struct Snapshot { status: Option, log: Vec, config: Option, + /// Installed launchers (name, label), the default one first. + launchers: Vec<(String, String)>, alerts: Vec<(String, String)>, } @@ -141,6 +143,7 @@ struct UiState { toast_gen: u32, last_groups: Vec, last_providers: Vec, + last_launchers: Vec<(String, String)>, } thread_local! { @@ -161,6 +164,7 @@ thread_local! { import_current: String::new(), toast_gen: 0, last_groups: Vec::new(), + last_launchers: Vec::new(), last_providers: Vec::new(), }); } @@ -428,6 +432,9 @@ fn render(ui: &MainWindow) { } if providers != st.last_providers { ui.set_providers(str_model(&providers)); + let mut mirrors = vec!["No mirror".to_string()]; + mirrors.extend(providers.iter().cloned()); + ui.set_mirror_choices(str_model(&mirrors)); st.last_providers = providers; } let secs: Vec
= model::settings_sections(cfg) @@ -446,6 +453,21 @@ fn render(ui: &MainWindow) { .collect(); ui.set_sections(ModelRc::from(Rc::new(VecModel::from(secs)))); } + if snap.launchers != st.last_launchers { + let rows: Vec = snap + .launchers + .iter() + .map(|(n, l)| Launch { + name: n.into(), + label: l.into(), + }) + .collect(); + ui.set_launchers(ModelRc::from(Rc::new(VecModel::from(rows)))); + let mut choices = vec!["Don't open".to_string()]; + choices.extend(snap.launchers.iter().map(|(_, l)| format!("Open in {l}"))); + ui.set_open_choices(str_model(&choices)); + st.last_launchers = snap.launchers.clone(); + } }); } @@ -539,6 +561,15 @@ fn run_cli( }); } +/// A config-editing command from Settings: output below the forms, a toast either way. +fn run_settings_cli(ctx: &Ctx, ui: &MainWindow, args: Vec, done_msg: &'static str) { + run_cli(ctx, ui, None, args, String::new(), move |ui, ok, text| { + let first = text.lines().next().unwrap_or("").to_string(); + toast(ui, if ok { done_msg } else { &first }, !ok); + ui.set_settings_out(out(ok, text)); + }); +} + fn out(ok: bool, text: String) -> Out { Out { ok, @@ -743,13 +774,23 @@ fn wire(ui: &MainWindow, ctx: &Ctx) { ui.on_create_repo({ let c = ctx.clone(); - move |group, name, public| { + move |group, name, public, open| { let Some(ui) = c.weak.upgrade() else { return }; let group = model::group_name(&first_or(group.as_str(), &ui.get_groups())).to_string(); let mut args = vec!["new".to_string(), group, name.trim().to_string()]; if public { args.push("--public".into()); } + let launcher = ST.with(|st| { + st.borrow() + .last_launchers + .iter() + .find(|(_, l)| format!("Open in {l}") == open.as_str()) + .map(|(n, _)| n.clone()) + }); + if let Some(n) = launcher { + args.extend(["--open".into(), n]); + } ui.set_new_out(out(true, String::new())); run_cli(&c, &ui, None, args, String::new(), |ui, ok, text| { ui.set_new_out(out(ok, text)); @@ -760,6 +801,23 @@ fn wire(ui: &MainWindow, ctx: &Ctx) { } }); + ui.on_open_in({ + let c = ctx.clone(); + move |path, launcher| { + let Some(ui) = c.weak.upgrade() else { return }; + let args = vec![ + "open".to_string(), + path.to_string(), + "--with".into(), + launcher.to_string(), + ]; + run_cli(&c, &ui, None, args, String::new(), |ui, ok, text| { + let first = text.lines().last().unwrap_or("").to_string(); + toast(ui, &first, !ok); + }); + } + }); + ui.on_scan_import({ let c = ctx.clone(); move |group, force| { @@ -973,6 +1031,63 @@ fn wire(ui: &MainWindow, ctx: &Ctx) { }); } }); + ui.on_add_provider({ + let c = ctx.clone(); + move |id, kind, url, protocol, replace| { + let Some(ui) = c.weak.upgrade() else { return }; + let mut args: Vec = vec![ + "provider".into(), + "add".into(), + id.trim().to_string(), + "--kind".into(), + kind.to_string(), + "--protocol".into(), + protocol.to_string(), + ]; + if !url.trim().is_empty() { + args.extend(["--url".into(), url.trim().to_string()]); + } + if replace { + args.push("--replace".into()); + } + run_settings_cli(&c, &ui, args, "Provider saved"); + } + }); + ui.on_remove_provider({ + let c = ctx.clone(); + move |id| { + let Some(ui) = c.weak.upgrade() else { return }; + let args = vec!["provider".into(), "remove".into(), id.to_string()]; + run_settings_cli(&c, &ui, args, "Provider removed"); + } + }); + ui.on_add_group({ + let c = ctx.clone(); + move |name, primary, mirror, owner, mirror_owner, snapshots, replace| { + let Some(ui) = c.weak.upgrade() else { return }; + let primary = first_or(primary.as_str(), &ui.get_providers()); + let args = model::group_add_args(&model::GroupForm { + name: name.to_string(), + primary, + mirror: mirror.to_string(), + owner: owner.to_string(), + mirror_owner: mirror_owner.to_string(), + snapshots: snapshots.to_string(), + replace, + }); + run_settings_cli(&c, &ui, args, "Namespace saved"); + } + }); + ui.on_remove_group({ + let c = ctx.clone(); + move |label| { + let Some(ui) = c.weak.upgrade() else { return }; + let name = model::group_name(&first_or(label.as_str(), &ui.get_groups())).to_string(); + let args = vec!["group".into(), "remove".into(), name]; + run_settings_cli(&c, &ui, args, "Namespace removed"); + } + }); + ui.on_login({ let c = ctx.clone(); move |provider, token| { @@ -1200,6 +1315,7 @@ fn worker( status, log, config: core.bridge.config_json(), + launchers: core.bridge.launchers(), alerts, }; let w = weak.clone(); diff --git a/crates/grove-gui/src/model.rs b/crates/grove-gui/src/model.rs index 82f1ef1..8bf2e51 100644 --- a/crates/grove-gui/src/model.rs +++ b/crates/grove-gui/src/model.rs @@ -336,6 +336,53 @@ pub fn group_name(entry: &str) -> &str { entry.split(" → ").next().unwrap_or(entry) } +/// What the "Add or change a namespace" form holds. +pub struct GroupForm { + pub name: String, + pub primary: String, + /// Empty: no mirror. + pub mirror: String, + pub owner: String, + pub mirror_owner: String, + /// "default" leaves the global policy in force. + pub snapshots: String, + pub replace: bool, +} + +/// `grove group add ...` for the namespace form. +pub fn group_add_args(f: &GroupForm) -> Vec { + let mut a: Vec = vec![ + "group".into(), + "add".into(), + f.name.trim().to_string(), + "--primary".into(), + f.primary.clone(), + ]; + let mirror = f.mirror.trim(); + if !mirror.is_empty() { + a.extend(["--mirror-to".into(), mirror.to_string()]); + } + if !f.owner.trim().is_empty() { + a.extend([ + "--owner".into(), + format!("{}={}", f.primary, f.owner.trim()), + ]); + } + if !mirror.is_empty() && !f.mirror_owner.trim().is_empty() { + a.extend([ + "--owner".into(), + format!("{mirror}={}", f.mirror_owner.trim()), + ]); + } + if !f.snapshots.is_empty() && f.snapshots != "default" { + a.extend(["--snapshots".into(), f.snapshots.clone()]); + } + if f.replace { + a.push("--replace".into()); + } + a +} + #[cfg(test)] mod tests { use super::*; @@ -501,4 +548,46 @@ mod tests { assert_eq!(s[3].1[0].1, "grove-config on gitea"); assert_eq!(group_name("work → gitea"), "work"); } + + #[test] + fn group_form_becomes_group_add_args() { + let mut f = GroupForm { + name: " oss ".into(), + primary: "gh".into(), + mirror: String::new(), + owner: String::new(), + mirror_owner: "ignored without a mirror".into(), + snapshots: "default".into(), + replace: false, + }; + assert_eq!( + group_add_args(&f), + ["group", "add", "oss", "--primary", "gh"] + ); + f.mirror = "gitea".into(); + f.owner = "Zenvairo".into(); + f.mirror_owner = "Org".into(); + f.snapshots = "none".into(); + f.replace = true; + assert_eq!( + group_add_args(&f), + [ + "group", + "add", + "oss", + "--primary", + "gh", + "--mirror-to", + "gitea", + "--owner", + "gh=Zenvairo", + "--owner", + "gitea=Org", + "--snapshots", + "none", + "--replace" + ] + ); + assert!(crate::bridge::validate(&group_add_args(&f)).is_ok()); + } } diff --git a/crates/grove-gui/ui/app.slint b/crates/grove-gui/ui/app.slint index 4a387a3..18ce875 100644 --- a/crates/grove-gui/ui/app.slint +++ b/crates/grove-gui/ui/app.slint @@ -52,6 +52,11 @@ export struct MigRow { msg: string, } +export struct Launch { + name: string, + label: string, +} + export struct Out { text: string, ok: bool, @@ -195,6 +200,12 @@ export component MainWindow inherits Window { in property <[LogRow]> log; in property <[string]> groups; in property <[string]> providers; + // "No mirror" followed by the providers. + in property <[string]> mirror-choices; + // Installed editors/tools, the default one first. + in property <[Launch]> launchers; + // "Don't open" followed by the launcher labels. + in property <[string]> open-choices; in property <[Section]> sections; in property <[Pick]> picks; in property import-note; @@ -209,6 +220,7 @@ export component MainWindow inherits Window { in property detail; in property detail-found; in-out property selected-path; + property prov-url-text; in property new-out; in property import-out; in property settings-out; @@ -220,7 +232,12 @@ export component MainWindow inherits Window { callback sync-all(); callback toggle-pause(); callback filter-changed(string); - callback create-repo(string, string, bool); + callback create-repo(string, string, bool, string); + callback open-in(string, string); + callback add-provider(string, string, string, string, bool); + callback remove-provider(string); + callback add-group(string, string, string, string, string, string, bool); + callback remove-group(string); callback scan-import(string, bool); callback import-selected(string); callback pick-toggled(int, bool); @@ -491,6 +508,13 @@ export component MainWindow inherits Window { for r in root.repos: Rectangle { height: rcard.preferred-height; + // Below the card, so the card's own buttons get their clicks. + TouchArea { + clicked => { + root.open-repo(r.path); + } + } + rcard := Card { HorizontalLayout { spacing: 12px; @@ -553,15 +577,20 @@ export component MainWindow inherits Window { font-size: 11px; } } - } - } - - TouchArea { - clicked => { - root.open-repo(r.path); + if root.launchers.length > 0: VerticalLayout { + alignment: center; + Button { + text: "Open"; + accessible-label: "Open in " + root.launchers[0].label; + clicked => { + root.open-in(r.path, root.launchers[0].name); + } + } } } + + } } } } @@ -650,6 +679,22 @@ export component MainWindow inherits Window { text: w.plan; } + if w.path != "" && root.launchers.length > 0: HorizontalLayout { + spacing: 8px; + alignment: start; + Muted { + text: "Open in"; + vertical-alignment: center; + } + + for l in root.launchers: Button { + text: l.label; + clicked => { + root.open-in(w.path, l.name); + } + } + } + if w.state == "diverged": diverged := VerticalLayout { spacing: 8px; alignment: start; @@ -831,6 +876,14 @@ export component MainWindow inherits Window { text: "Public repository"; } + Muted { + text: "Afterwards"; + } + + new-open := ComboBox { + model: root.open-choices; + } + HorizontalLayout { alignment: start; Button { @@ -838,7 +891,7 @@ export component MainWindow inherits Window { primary: true; enabled: !root.busy && new-name.text != ""; clicked => { - root.create-repo(new-group.current-value, new-name.text, new-public.checked); + root.create-repo(new-group.current-value, new-name.text, new-public.checked, new-open.current-value); } } } @@ -1009,6 +1062,250 @@ export component MainWindow inherits Window { } } + Text { + text: "Add or change a provider"; + font-size: 16px; + font-weight: 700; + } + + Card { + HorizontalLayout { + spacing: 8px; + VerticalLayout { + spacing: 4px; + horizontal-stretch: 1; + Muted { + text: "Id"; + } + + prov-id := LineEdit { + placeholder-text: "gitea, gh, work-forge…"; + accessible-label: "Provider id"; + } + } + + VerticalLayout { + spacing: 4px; + min-width: 150px; + horizontal-stretch: 0; + Muted { + text: "Kind"; + } + + prov-kind := ComboBox { + model: ["gitea", "forgejo", "github"]; + } + } + + VerticalLayout { + spacing: 4px; + min-width: 130px; + horizontal-stretch: 0; + Muted { + text: "Git over"; + } + + prov-proto := ComboBox { + model: ["https", "ssh"]; + } + } + } + + if prov-kind.current-value != "github": VerticalLayout { + spacing: 4px; + Muted { + text: "URL"; + } + + prov-url := LineEdit { + placeholder-text: "https://git.example.com"; + accessible-label: "Provider URL"; + edited(t) => { + root.prov-url-text = t; + } + } + } + HorizontalLayout { + spacing: 8px; + alignment: start; + prov-replace := CheckBox { + text: "Replace an existing provider with this id"; + } + + Button { + text: "Save provider"; + primary: true; + enabled: !root.busy && prov-id.text != "" && (prov-kind.current-value == "github" || root.prov-url-text != ""); + clicked => { + root.add-provider(prov-id.text, prov-kind.current-value, prov-kind.current-value == "github" ? "" : root.prov-url-text, prov-proto.current-value, prov-replace.checked); + } + } + } + + Muted { + text: "Then sign in to it below (a token from `tea`/`gh` is used when present)."; + font-size: 11px; + } + } + + Text { + text: "Add or change a namespace"; + font-size: 16px; + font-weight: 700; + } + + Card { + Muted { + text: "A namespace is a directory under the workspace root whose repos live on one forge, optionally mirrored to another."; + font-size: 11px; + } + + HorizontalLayout { + spacing: 8px; + VerticalLayout { + spacing: 4px; + Muted { + text: "Name"; + } + + grp-name := LineEdit { + placeholder-text: "work, personal, clients…"; + accessible-label: "Namespace name"; + } + } + + VerticalLayout { + spacing: 4px; + width: 170px; + Muted { + text: "Snapshots"; + } + + grp-snap := ComboBox { + model: ["default", "private-only", "all", "none"]; + } + } + } + + HorizontalLayout { + spacing: 8px; + VerticalLayout { + spacing: 4px; + Muted { + text: "Primary (repos are created here)"; + } + + grp-primary := ComboBox { + model: root.providers; + } + } + + VerticalLayout { + spacing: 4px; + Muted { + text: "Owner there (empty: your account)"; + } + + grp-owner := LineEdit { + placeholder-text: "account or organisation"; + accessible-label: "Owner on the primary provider"; + } + } + } + + HorizontalLayout { + spacing: 8px; + VerticalLayout { + spacing: 4px; + Muted { + text: "Mirror to"; + } + + grp-mirror := ComboBox { + model: root.mirror-choices; + } + } + + VerticalLayout { + spacing: 4px; + Muted { + text: "Owner on the mirror"; + } + + grp-mowner := LineEdit { + enabled: grp-mirror.current-index > 0; + placeholder-text: "account or organisation"; + accessible-label: "Owner on the mirror provider"; + } + } + } + + HorizontalLayout { + spacing: 8px; + alignment: start; + grp-replace := CheckBox { + text: "Replace an existing namespace with this name"; + } + + Button { + text: "Save namespace"; + primary: true; + enabled: !root.busy && grp-name.text != ""; + clicked => { + root.add-group(grp-name.text, grp-primary.current-value, grp-mirror.current-index > 0 ? grp-mirror.current-value : "", grp-owner.text, grp-mirror.current-index > 0 ? grp-mowner.text : "", grp-snap.current-value, grp-replace.checked); + } + } + } + + Muted { + text: "Public repos can take a different route (`grove group add --public-primary`); that is CLI only. The daemon picks up changes after `systemctl --user restart groved`."; + font-size: 11px; + } + } + + Text { + text: "Remove"; + font-size: 16px; + font-weight: 700; + } + + Card { + HorizontalLayout { + spacing: 8px; + rm-group := ComboBox { + model: root.groups; + } + + Button { + text: "Remove namespace"; + enabled: !root.busy && root.groups.length > 0; + clicked => { + root.remove-group(rm-group.current-value); + } + } + } + + HorizontalLayout { + spacing: 8px; + rm-prov := ComboBox { + model: root.providers; + } + + Button { + text: "Remove provider"; + enabled: !root.busy && root.providers.length > 0; + clicked => { + root.remove-provider(rm-prov.current-value); + } + } + } + + Muted { + text: "Removing a namespace only edits config.toml: its directory and repos stay on disk and stop syncing. A provider still used by a namespace cannot be removed. The previous config is kept as config.toml.bak."; + font-size: 11px; + } + } + Text { text: "Sign in to a provider"; font-size: 16px; diff --git a/crates/grove/src/main.rs b/crates/grove/src/main.rs index 0c0e436..9c5d7a2 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, ProviderKind}; +use grove_core::config::Config; use grove_core::git::Git; use grove_core::inspect::{state, worktrees}; use grove_core::migrate::migrate; @@ -13,6 +13,7 @@ use grove_core::sync::{Options, SyncReport, git_dir_for, sync_repo}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; +mod namespace; mod secrets; #[cfg(test)] #[path = "../../../test-support/tmp.rs"] @@ -111,6 +112,34 @@ enum Cmd { name: String, #[arg(long)] public: bool, + /// Open the new worktree afterwards (with LAUNCHER, or the default one) + #[arg(long, value_name = "LAUNCHER", num_args = 0..=1, default_missing_value = "")] + open: Option, + }, + /// Open a worktree in an editor or tool (Zed, VS Code, Claude Code, ...) + Open { + /// A path, or `[group/]repo[@branch]` under the root (default: the current directory) + #[arg(default_value = ".")] + target: String, + /// Launcher name (see --list; default: `open.default`, else the first installed) + #[arg(long = "with", short = 'w', value_name = "LAUNCHER")] + with: Option, + /// List the launchers and whether they are installed + #[arg(long)] + list: bool, + /// Print the command instead of running it + #[arg(long)] + print: bool, + }, + /// Manage namespaces: the groups of repos under `/` and where they live + Group { + #[command(subcommand)] + action: GroupCmd, + }, + /// Manage forge accounts (Gitea, Forgejo, GitHub) + Provider { + #[command(subcommand)] + action: ProviderCmd, }, /// List (or, with names, clone) remote repos that are not on this machine Import { group: String, names: Vec }, @@ -130,6 +159,66 @@ enum Cmd { }, } +#[derive(Subcommand)] +enum GroupCmd { + /// List the namespaces + List, + /// Add a namespace (or change one with --replace) and create its directory + Add { + name: String, + /// Provider the repos are created on + #[arg(long)] + primary: String, + /// Provider(s) the repos are mirrored to (repeatable) + #[arg(long = "mirror-to", value_name = "PROVIDER")] + mirror_to: Vec, + /// Owning account or organisation: `PROVIDER=OWNER`, or `OWNER` for the primary + /// (repeatable; default: your own account) + #[arg(long = "owner", value_name = "[PROVIDER=]OWNER")] + owners: Vec, + /// Public repos go to this provider instead (then --primary is for private ones) + #[arg(long, value_name = "PROVIDER")] + public_primary: Option, + /// Mirrors of public repos (repeatable; needs --public-primary) + #[arg(long = "public-mirror-to", value_name = "PROVIDER")] + public_mirror_to: Vec, + /// WIP snapshot policy for this namespace: private-only, all, none + #[arg(long)] + snapshots: Option, + /// Do not create worktrees for new remote branches automatically + #[arg(long)] + no_materialize: bool, + /// Replace an existing namespace of that name + #[arg(long)] + replace: bool, + }, + /// Remove a namespace from the config (its directory and repos stay on disk, unsynced) + Remove { name: String }, +} + +#[derive(Subcommand)] +enum ProviderCmd { + /// List the providers + List, + /// Add a provider (or change one with --replace); then `grove login ID` + Add { + id: String, + /// gitea, forgejo or github + #[arg(long)] + kind: String, + /// Base URL (required for gitea/forgejo) + #[arg(long)] + url: Option, + /// How git talks to it: https (API token) or ssh (your keys) + #[arg(long, default_value = "https")] + protocol: String, + #[arg(long)] + replace: bool, + }, + /// Remove a provider no namespace uses + Remove { id: String }, +} + #[derive(Subcommand)] enum SecretsCmd { /// Create this machine's age key and publish the public half @@ -260,6 +349,160 @@ fn daemon(action: &DaemonCmd) -> Result<()> { Ok(()) } +/// Opens `dir` with the launcher `with` (or the default one); `print` only shows the command. +fn open_dir(cfg: &Config, dir: &Path, with: Option<&str>, print: bool) -> Result<()> { + use grove_core::launch::{System, argv, launchers, pick, spawn}; + let all = launchers(&cfg.open, &System); + let l = pick(&all, &cfg.open, with).map_err(anyhow::Error::msg)?; + let cmd = argv(l, dir, &cfg.open, &System).map_err(anyhow::Error::msg)?; + if print { + println!("{}", cmd.join(" ")); + return Ok(()); + } + spawn(&cmd, dir).map_err(anyhow::Error::msg)?; + println!("opened {} in {}", dir.display(), l.label); + Ok(()) +} + +fn list_launchers(cfg: &Config) -> Result<()> { + let all = grove_core::launch::launchers(&cfg.open, &grove_core::launch::System); + let default = grove_core::launch::pick(&all, &cfg.open, None) + .ok() + .map(|l| l.name.clone()); + for l in &all { + println!( + "{} {:<16} {:<16} {}{}", + if Some(&l.name) == default.as_ref() { + "*" + } else { + " " + }, + l.name, + l.label, + if l.available { + l.command[0].as_str() + } else { + "(not installed)" + }, + if l.terminal { " [terminal]" } else { "" } + ); + } + Ok(()) +} + +fn config_path(arg: &Option) -> Result { + arg.clone() + .or_else(Config::default_path) + .context("cannot determine config path (set --config)") +} + +/// Saves an edited config and says what to do next. +fn save_edited(cfg: &Config, path: &Path) -> Result<()> { + let bak = namespace::save(cfg, path)?; + println!( + "saved {} (previous version: {})", + path.display(), + bak.display() + ); + if grove_daemon::ipc::default_socket_path().exists() { + println!("restart the daemon to apply it: systemctl --user restart groved"); + } + Ok(()) +} + +fn group_cmd(arg: &Option, action: &GroupCmd) -> Result<()> { + let path = config_path(arg)?; + let mut cfg = load_config(arg)?; + match action { + GroupCmd::List => { + for l in namespace::describe_groups(&cfg) { + println!("{l}"); + } + Ok(()) + } + GroupCmd::Add { + name, + primary, + mirror_to, + owners, + public_primary, + public_mirror_to, + snapshots, + no_materialize, + replace, + } => { + let snapshots = snapshots + .as_deref() + .map(namespace::parse_snapshots) + .transpose()?; + namespace::add_group( + &mut cfg, + namespace::GroupArgs { + name: name.clone(), + primary: primary.clone(), + mirror_to: mirror_to.clone(), + owners: owners.clone(), + public_primary: public_primary.clone(), + public_mirror_to: public_mirror_to.clone(), + snapshots, + no_materialize: *no_materialize, + }, + *replace, + )?; + save_edited(&cfg, &path)?; + let dir = cfg.root_path().join(name); + std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; + println!("namespace {name}: {}", dir.display()); + Ok(()) + } + GroupCmd::Remove { name } => { + namespace::remove_group(&mut cfg, name)?; + save_edited(&cfg, &path)?; + println!( + "removed namespace {name}; {} stays on disk and is no longer synced", + cfg.root_path().join(name).display() + ); + Ok(()) + } + } +} + +fn provider_cmd(arg: &Option, action: &ProviderCmd) -> Result<()> { + let path = config_path(arg)?; + let mut cfg = load_config(arg)?; + match action { + ProviderCmd::List => { + for l in namespace::describe_providers(&cfg) { + println!("{l}"); + } + Ok(()) + } + ProviderCmd::Add { + id, + kind, + url, + protocol, + replace, + } => { + let p = grove_core::config::Provider { + kind: namespace::parse_kind(kind)?, + protocol: namespace::parse_protocol(protocol)?, + url: url.clone().filter(|u| !u.is_empty()), + }; + namespace::add_provider(&mut cfg, id, p, *replace)?; + save_edited(&cfg, &path)?; + println!("next: `grove login {id}` (tokens from `tea`/`gh` are used if present)"); + Ok(()) + } + ProviderCmd::Remove { id } => { + namespace::remove_provider(&mut cfg, id)?; + save_edited(&cfg, &path)?; + println!("removed provider {id} (its stored token stays in the keyring)"); + Ok(()) + } + } +} + fn main() -> Result<()> { let cli = Cli::parse(); match &cli.cmd { @@ -395,22 +638,13 @@ fn main() -> Result<()> { 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 protocol = namespace::parse_protocol(protocol)?; 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 kind = namespace::parse_kind(kind)?; let machine = machine .clone() .or_else(|| { @@ -451,11 +685,35 @@ fn main() -> Result<()> { group, name, public, + open, } => { - let wt = workflow::new_repo(&load_config(&cli.config)?, group, name, !public)?; + let cfg = load_config(&cli.config)?; + let wt = workflow::new_repo(&cfg, group, name, !public)?; println!("ready: {}", wt.display()); + if let Some(with) = open { + let with = (!with.is_empty()).then_some(with.as_str()); + if let Err(e) = open_dir(&cfg, &wt, with, false) { + println!("warning: not opened: {e:#}"); + } + } Ok(()) } + Cmd::Open { + target, + with, + list, + print, + } => { + let cfg = load_config(&cli.config)?; + if *list { + return list_launchers(&cfg); + } + let dir = + grove_core::launch::resolve_target(&cfg, target).map_err(anyhow::Error::msg)?; + open_dir(&cfg, &dir, with.as_deref(), *print) + } + Cmd::Group { action } => group_cmd(&cli.config, action), + Cmd::Provider { action } => provider_cmd(&cli.config, action), Cmd::Import { group, names } => workflow::import(&load_config(&cli.config)?, group, names), Cmd::ConfigRepoInit => { let n = workflow::config_repo_init(&load_config(&cli.config)?)?; diff --git a/crates/grove/src/namespace.rs b/crates/grove/src/namespace.rs new file mode 100644 index 0000000..f9b5293 --- /dev/null +++ b/crates/grove/src/namespace.rs @@ -0,0 +1,362 @@ +//! Editing namespaces (`[[groups]]`) and providers in `config.toml` from the CLI and GUI, so +//! nobody has to hand-edit TOML. Every change is validated before anything is written, and the +//! previous file is kept as `config.toml.bak` (the TOML writer drops comments). + +use anyhow::{Context, Result, bail}; +use grove_core::config::{ + Config, Group, Layout, Protocol, Provider, ProviderKind, Route, SnapshotPolicy, is_plain_name, +}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +pub struct GroupArgs { + pub name: String, + pub primary: String, + pub mirror_to: Vec, + /// `PROVIDER=OWNER`, or a bare `OWNER` for the primary provider. + pub owners: Vec, + pub public_primary: Option, + pub public_mirror_to: Vec, + pub snapshots: Option, + pub no_materialize: bool, +} + +pub fn parse_kind(k: &str) -> Result { + Ok(match k { + "gitea" => ProviderKind::Gitea, + "forgejo" => ProviderKind::Forgejo, + "github" => ProviderKind::Github, + k => bail!("unknown provider kind {k:?} (gitea, forgejo, github)"), + }) +} + +pub fn parse_protocol(p: &str) -> Result { + Ok(match p { + "https" => Protocol::Https, + "ssh" => Protocol::Ssh, + p => bail!("unknown protocol {p:?} (https, ssh)"), + }) +} + +pub fn parse_snapshots(s: &str) -> Result { + Ok(match s { + "private-only" => SnapshotPolicy::PrivateOnly, + "all" => SnapshotPolicy::All, + "none" => SnapshotPolicy::None, + s => bail!("unknown snapshot policy {s:?} (private-only, all, none)"), + }) +} + +fn kind_str(k: ProviderKind) -> &'static str { + match k { + ProviderKind::Gitea => "gitea", + ProviderKind::Forgejo => "forgejo", + ProviderKind::Github => "github", + } +} + +/// Adds the namespace `a.name` (or replaces it with `replace`, keeping its layout). +pub fn add_group(cfg: &mut Config, a: GroupArgs, replace: bool) -> Result<()> { + let existing = cfg.groups.iter().position(|g| g.name == a.name); + if existing.is_some() && !replace { + bail!( + "namespace {:?} already exists (use --replace to change it)", + a.name + ); + } + let mut owners = BTreeMap::new(); + for o in &a.owners { + let (p, who) = o + .split_once('=') + .map_or((a.primary.as_str(), o.as_str()), |(p, w)| (p, w)); + owners.insert(p.trim().to_string(), who.trim().to_string()); + } + let public = a.public_primary.map(|primary| Route { + primary, + mirror_to: a.public_mirror_to.clone(), + }); + if public.is_none() && !a.public_mirror_to.is_empty() { + bail!("--public-mirror-to needs --public-primary"); + } + let g = Group { + name: a.name, + primary: a.primary, + mirror_to: a.mirror_to, + layout: existing.map_or(Layout::BareWorktrees, |i| cfg.groups[i].layout), + auto_materialize: !a.no_materialize, + snapshots: a.snapshots, + owners, + public, + }; + match existing { + Some(i) => cfg.groups[i] = g, + None => cfg.groups.push(g), + } + Ok(()) +} + +pub fn remove_group(cfg: &mut Config, name: &str) -> Result<()> { + let before = cfg.groups.len(); + cfg.groups.retain(|g| g.name != name); + if cfg.groups.len() == before { + bail!("no namespace {name:?}"); + } + Ok(()) +} + +pub fn add_provider(cfg: &mut Config, id: &str, p: Provider, replace: bool) -> Result<()> { + if !is_plain_name(id) { + bail!("provider id {id:?} must use only letters, digits, '-' or '_'"); + } + if p.kind != ProviderKind::Github && p.url.as_deref().is_none_or(str::is_empty) { + bail!("a {} provider needs --url", kind_str(p.kind)); + } + if let Some(u) = &p.url + && !u.starts_with("https://") + && !u.starts_with("http://") + { + bail!("--url must start with https:// (got {u:?})"); + } + if cfg.providers.contains_key(id) && !replace { + bail!("provider {id:?} already exists (use --replace to change it)"); + } + cfg.providers.insert(id.to_string(), p); + Ok(()) +} + +/// Removes a provider no namespace or the config repo still uses. +pub fn remove_provider(cfg: &mut Config, id: &str) -> Result<()> { + if !cfg.providers.contains_key(id) { + bail!("no provider {id:?}"); + } + let users: Vec<&str> = cfg + .groups + .iter() + .filter(|g| { + let routes = [Some(g.route(true)), g.public.clone()]; + routes + .iter() + .flatten() + .any(|r| r.primary == id || r.mirror_to.iter().any(|m| m == id)) + || g.owners.contains_key(id) + }) + .map(|g| g.name.as_str()) + .collect(); + if !users.is_empty() { + bail!( + "provider {id:?} is used by namespace(s) {}; change or remove them first", + users.join(", ") + ); + } + if cfg.config_repo.as_ref().is_some_and(|c| c.provider == id) { + bail!("provider {id:?} holds the config repo; it cannot be removed"); + } + cfg.providers.remove(id); + Ok(()) +} + +/// Validates `cfg`, keeps the current file as `.bak` and writes the new one. +pub fn save(cfg: &Config, path: &Path) -> Result { + let text = toml::to_string_pretty(cfg)?; + Config::parse(&text)?; + let bak = path.with_extension("toml.bak"); + if path.exists() { + std::fs::copy(path, &bak).with_context(|| format!("backing up {}", path.display()))?; + } + cfg.save(path)?; + Ok(bak) +} + +/// One line per namespace: `name primary -> mirrors [public: ...] owners`. +pub fn describe_groups(cfg: &Config) -> Vec { + cfg.groups + .iter() + .map(|g| { + let mut s = format!("{:<16} {}", g.name, route_str(&g.route(true))); + if let Some(p) = &g.public { + s.push_str(&format!(" public: {}", route_str(p))); + } + if !g.owners.is_empty() { + let o: Vec = g.owners.iter().map(|(p, w)| format!("{p}={w}")).collect(); + s.push_str(&format!(" owners: {}", o.join(","))); + } + if let Some(sp) = g.snapshots { + let name = match sp { + SnapshotPolicy::PrivateOnly => "private-only", + SnapshotPolicy::All => "all", + SnapshotPolicy::None => "none", + }; + s.push_str(&format!(" snapshots: {name}")); + } + s + }) + .collect() +} + +fn route_str(r: &Route) -> String { + if r.mirror_to.is_empty() { + r.primary.clone() + } else { + format!("{} -> {}", r.primary, r.mirror_to.join(", ")) + } +} + +pub fn describe_providers(cfg: &Config) -> Vec { + cfg.providers + .iter() + .map(|(id, p)| { + format!( + "{id:<16} {:<8} {:<6} {}", + kind_str(p.kind), + p.protocol.as_str(), + p.url.as_deref().unwrap_or("https://github.com") + ) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg() -> Config { + Config::parse( + "[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\ + [providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n\ + [providers.gh]\nkind=\"github\"\n\ + [[groups]]\nname=\"work\"\nprimary=\"gitea\"\nlayout=\"plain\"\n", + ) + .unwrap() + } + + fn args(name: &str, primary: &str) -> GroupArgs { + GroupArgs { + name: name.into(), + primary: primary.into(), + mirror_to: vec![], + owners: vec![], + public_primary: None, + public_mirror_to: vec![], + snapshots: None, + no_materialize: false, + } + } + + fn valid(c: &Config) -> bool { + Config::parse(&toml::to_string_pretty(c).unwrap()).is_ok() + } + + #[test] + fn add_group_with_mirror_owners_and_public_route() { + let mut c = cfg(); + let mut a = args("oss", "gitea"); + a.mirror_to = vec!["gh".into()]; + a.owners = vec!["Zenvairo".into(), "gh=zenvairo-gh".into()]; + a.public_primary = Some("gh".into()); + a.public_mirror_to = vec!["gitea".into()]; + a.snapshots = Some(SnapshotPolicy::None); + add_group(&mut c, a, false).unwrap(); + assert!(valid(&c)); + let g = &c.groups[1]; + assert_eq!(g.owner("gitea"), Some("Zenvairo")); + assert_eq!(g.owner("gh"), Some("zenvairo-gh")); + assert_eq!(g.route(false).primary, "gh"); + assert_eq!(c.snapshot_policy("oss"), SnapshotPolicy::None); + let lines = describe_groups(&c); + assert!(lines[1].contains("gitea -> gh") && lines[1].contains("public: gh -> gitea")); + } + + #[test] + fn replacing_a_group_needs_the_flag_and_keeps_its_layout() { + let mut c = cfg(); + assert!(add_group(&mut c, args("work", "gh"), false).is_err()); + add_group(&mut c, args("work", "gh"), true).unwrap(); + assert_eq!(c.groups.len(), 1); + assert_eq!(c.groups[0].primary, "gh"); + assert_eq!(c.groups[0].layout, Layout::Plain); + let mut bad = args("x", "gitea"); + bad.public_mirror_to = vec!["gh".into()]; + assert!(add_group(&mut c, bad, false).is_err()); + // Unknown providers are caught by validation before saving. + add_group(&mut c, args("y", "nope"), false).unwrap(); + assert!(!valid(&c)); + } + + #[test] + fn providers_in_use_cannot_be_removed() { + let mut c = cfg(); + assert!( + remove_provider(&mut c, "gitea") + .unwrap_err() + .to_string() + .contains("work") + ); + remove_provider(&mut c, "gh").unwrap(); + assert!(remove_provider(&mut c, "gh").is_err()); + remove_group(&mut c, "work").unwrap(); + assert!(remove_group(&mut c, "work").is_err()); + remove_provider(&mut c, "gitea").unwrap(); + assert!(valid(&c)); + } + + #[test] + fn add_provider_checks_id_url_and_duplicates() { + let mut c = cfg(); + let p = |kind, url: Option<&str>| Provider { + kind, + protocol: Protocol::Ssh, + url: url.map(String::from), + }; + assert!(add_provider(&mut c, "a b", p(ProviderKind::Github, None), false).is_err()); + assert!(add_provider(&mut c, "fj", p(ProviderKind::Forgejo, None), false).is_err()); + assert!( + add_provider(&mut c, "fj", p(ProviderKind::Forgejo, Some("git.x")), false).is_err() + ); + add_provider( + &mut c, + "fj", + p(ProviderKind::Forgejo, Some("https://git.x")), + false, + ) + .unwrap(); + assert!(add_provider(&mut c, "fj", p(ProviderKind::Github, None), false).is_err()); + add_provider(&mut c, "fj", p(ProviderKind::Github, None), true).unwrap(); + assert!(valid(&c)); + assert!( + describe_providers(&c) + .iter() + .any(|l| l.starts_with("fj") && l.contains("ssh")) + ); + } + + #[test] + fn save_keeps_a_backup() { + let tmp = crate::test_tmp::TempDir::new("ns-save"); + let path = tmp.path().join("config.toml"); + std::fs::write( + &path, + "# my comment\n[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n", + ) + .unwrap(); + let mut c = Config::load(&path).unwrap(); + c.providers.insert( + "gh".into(), + Provider { + kind: ProviderKind::Github, + protocol: Protocol::Https, + url: None, + }, + ); + let bak = save(&c, &path).unwrap(); + assert!( + std::fs::read_to_string(bak) + .unwrap() + .contains("# my comment") + ); + assert_eq!(Config::load(&path).unwrap(), c); + // An invalid config is never written. + add_group(&mut c, args("g", "nope"), false).unwrap(); + assert!(save(&c, &path).is_err()); + assert!(Config::load(&path).unwrap().groups.is_empty()); + } +} diff --git a/crates/grove/src/workflow.rs b/crates/grove/src/workflow.rs index c9b47f9..f5830f2 100644 --- a/crates/grove/src/workflow.rs +++ b/crates/grove/src/workflow.rs @@ -182,6 +182,7 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result { public: None, }], sync: Default::default(), + open: Default::default(), config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo { provider: a.provider, name, diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 0245235..1892901 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -9,3 +9,5 @@ 7. Open: `grove add` refuses `extensions.worktreeConfig = true` even when no `config.worktree` exists. Claude Code worktrees leave that flag behind. Options: accept it when no per-worktree config file exists (and sparse checkout is off), or keep refusing and print the exact `git config --unset` hint. 8. Merged worktrees are pruned (`prune-merged.md`), but the PR's head branch is left on the forge and this machine's `refs/sync//` snapshot ref stays there too. Open: should grove delete either once the PR is merged (the forge's "delete branch after merge" covers the first)? 9. Open: a branch recreated under the name of a fast-forward-merged PR before the default branch moves has the PR head as tip and is pruned at once if clean (nothing is lost; a backup ref is kept). Options: accept it, or require the worktree to be older than the merge. +10. Open: `groved` reads `config.toml` only at start, so namespaces/providers added with `grove group|provider add` (or the GUI) need `systemctl --user restart groved`. Options: an IPC `reload` command the CLI/GUI calls after saving, or watching the file. Also open: config edits rewrite the file without comments (backup in `config.toml.bak`); `toml_edit` would keep them but is not an approved dependency. +11. Open: the `claude-desktop` built-in launcher runs `claude-desktop `. Whether the Linux Claude desktop app accepts a folder (and opens Claude Code there) is unverified; override it with `[[open.launchers]] name = "claude-desktop"` once the real command is known. diff --git a/docs/phase8.md b/docs/phase8.md new file mode 100644 index 0000000..4da3e82 --- /dev/null +++ b/docs/phase8.md @@ -0,0 +1,114 @@ +# Phase 8: personal workflow (namespaces, providers, open in editor) + +Goal: run the daily steps from grove itself, without hand-editing `config.toml`. You set up +namespaces and forges, create or clone repos, and open a worktree in Zed, VS Code, Claude Code +or Claude Desktop. Creating repos (`grove new`), cloning existing ones (`grove import`) and +bootstrapping a fresh machine (`grove bootstrap`) existed already (Phase 4). This phase adds the +pieces around them. + +## Namespaces and providers + +A namespace is a `[[groups]]` entry: a directory `/` whose repos are created on one +provider (`primary`), optionally mirrored to others (`mirror_to`), owned by an account or +organisation (`owners`), with a snapshot policy and an optional public route. + +```bash +grove provider add gitea --kind gitea --url https://git.example.com --protocol ssh +grove provider add gh --kind github +grove login gh # token on stdin (or picked up from `gh`/`tea`) +grove group add work --primary gitea --mirror-to gh --owner Zenvairo --owner gh=zenvairo-gh +grove group add oss --primary gh --snapshots none +grove group add work --primary gh --replace # change an existing one +grove group list ; grove provider list +grove group remove oss # config only: /oss stays on disk, unsynced +grove provider remove gh # refused while a namespace or the config repo uses it +``` + +- `--owner OWNER` without `PROVIDER=` applies to the primary provider. +- `--public-primary` / `--public-mirror-to` set the public route (CLI only, not in the GUI form). +- `group add` creates `/`. `--replace` keeps the namespace's `layout`. +- Every edit is checked by the config parser before anything is written. The previous file is kept + as `config.toml.bak`. The TOML writer drops comments and writes every `[sync]` default out + explicitly (as `grove init` already did). +- The daemon reads the config only at start. When its socket exists the CLI reminds you to run + `systemctl --user restart groved`. Hot reload is open (DECISIONS 10). + +GUI (Settings): "Add or change a provider" (id, kind, URL, git over https/ssh, replace), +"Add or change a namespace" (name, snapshots, primary and owner, mirror and owner on the mirror, +replace), and "Remove" (namespace, provider). Each runs the CLI command above. The output appears +at the bottom of Settings, and a toast reports the result. + +## Opening a worktree: `grove open` + +```bash +grove open # the current directory, default launcher +grove open app # repo "app" in any namespace (exact name, else case-insensitive) +grove open work/app@feat -w claude +grove open ~/Workspace/work/app --with vscode +grove open --list # launchers, * = default, and whether they are installed +grove open app --print # show the command, do not run it +grove new work tool --open # create, then open with the default launcher (--open zed: that one) +``` + +A bare-layout repo resolves to the worktree of the default branch (`origin/HEAD`, then `main`, +`master`, then the first worktree). `@branch` picks another worktree. A plain directory opens as is. +Ambiguous names (the same repo name in two namespaces) are refused with the candidates listed. + +Built-in launchers (the first program found wins; lookup is `PATH` plus `~/.local/bin`, +`~/.claude/local` and `~/.cargo/bin`, which desktop sessions often lack): + +| name | programs | runs | +|---|---|---| +| `zed` | `zed`, `zeditor`, `zedit` | `zed ` | +| `vscode` | `code`, `codium`, `code-oss` | `code ` | +| `claude` | `claude` | in a terminal, started in the worktree | +| `claude-desktop` | `claude-desktop` | `claude-desktop ` (unverified, see DECISIONS 11) | + +Terminal for `claude` (and any `terminal = true` launcher): `open.terminal` if set, else `$TERMINAL`, +else the first of kitty, ghostty, alacritty, foot, wezterm, konsole, ptyxis, gnome-terminal, +xfce4-terminal, xterm. Each known terminal gets the arguments that start the command in the +worktree. The process is started detached (own process group, no stdio) with the worktree as its +working directory. A program that exits with an error within 0.5 s is reported. + +Own launchers and defaults (machine-local, in `config.toml`): + +```toml +[open] +default = "zed" # else the first installed one +terminal = ["kitty", "--directory", "{path}"] # the command is appended + +[[open.launchers]] +name = "nvim" +label = "Neovim" +command = ["nvim", "."] +terminal = true + +[[open.launchers]] # same name as a built-in: replaces it +name = "claude-desktop" +command = ["/opt/Claude/claude-desktop", "{path}"] +``` + +GUI: each repo row on Repositories has an "Open" button (the default launcher, default-branch +worktree). Each worktree in the repository view has "Open in " buttons, for installed +launchers only. New repository has an "Afterwards: Open in …" choice. The GUI runs `grove open` +only for a directory inside the workspace root, passed in canonical form, and only with `--with`. + +## Checks + +- Unit tests: config `[open]` parsing and validation, launcher resolution and terminal choice + (fake finder), target resolution on a real bare layout (`launch.rs`), detached spawn error + reporting, namespace/provider editing and save with backup (`namespace.rs`), GUI form → args + and bridge allow-list (`model.rs`, `bridge.rs`). +- CLI run by hand on a throwaway config: provider/group add, list, remove (in-use refusal), + `open --list`, `--print`, launch, missing launcher. +- GUI screenshots under Xvfb (Settings forms, repository view buttons, repo list Open, New + repository). As in Phase 7, the forms were not clicked through (no input injection). +- Not tried on a real desktop: actual Zed/VS Code/Claude launches and each terminal's argument + form (kitty, foot, alacritty and konsole forms are from their documentation). + +## Not done (next steps) + +- Repo templates for `grove new` (README, .gitignore, CLAUDE.md…); the initial commit is still + empty. +- Daemon hot reload of the config (DECISIONS 10). +- Editing a namespace's public route from the GUI.