Compare commits

..
23 Commits
Author SHA1 Message Date
github-actions[bot] 8c6d1a3fbf chore(release): v0.1.2 [skip ci] 2026-11-25 15:39:57 +00:00
dasemu d5b5df0e2a Merge pull request #18 from Dasemu/claude/zen-mccarthy-6s8ncd
fix(gui): keep an autostarted window from opening during login
2026-11-25 16:39:48 +01:00
Claude a5a1ad1bb4 ci: install fontconfig headers for the Slint GUI build
The GUI crate links fontconfig (via Slint); the runner image lacks the
-dev package, so the first CI run since Actions was enabled failed in
yeslogic-fontconfig-sys's build script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011GZUAGhGYoiLvmfXweQnDY
2026-11-25 14:36:52 +00:00
Claude 6b294e80d9 fix(gui): keep an autostarted window from opening during login
On Plasma Wayland an autostarted grove-gui could end up with a task bar
entry that shows nothing (window mapped while the compositor starts).

- A --hidden start waits for the StatusNotifier watcher instead of opening
  the window when the tray is not up yet (ksni assume_sni_available)
- Show requests from other launches in the first 20 s after a --hidden start
  (session restore) are ignored and logged
- Every window show is logged with its reason; the session type at start

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011GZUAGhGYoiLvmfXweQnDY
2026-11-25 14:35:02 +00:00
github-actions[bot] f46bd305a6 chore(release): v0.1.1 [skip ci] 2026-11-25 14:33:46 +00:00
dasemu f21a60f4be Merge pull request #17 from Dasemu/fix/desktop-exec-absolute-path
fix(gui): launch grove-gui by absolute path from desktop files
2026-11-25 15:33:32 +01:00
dasemuandClaude Opus 5.5 96e2d9585e fix(gui): launch grove-gui by absolute path from desktop files
Desktop sessions (KDE Plasma on Fedora) often lack ~/.local/bin in PATH, so
Exec=grove-gui never started a source install from the menu or at login.
The Start-at-login toggle now writes the running binary's absolute path, and
the README documents a source install whose menu entry does the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:32:55 +01:00
dasemu 31c8d5b4f7 Merge pull request #16 from Dasemu/claude/zen-mccarthy-6s8ncd
feat: manage namespaces/providers and open worktrees in editors
2026-11-25 15:08:03 +01:00
Claude 39d241ee2b test(core): skip the locked-rollback test where permissions are not enforced
Root ignores directory permissions, so the partial-rollback case cannot be set
up there (cloud containers run tests as root).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011GZUAGhGYoiLvmfXweQnDY
2026-11-25 04:56:36 +00:00
Claude f201611510 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011GZUAGhGYoiLvmfXweQnDY
2026-11-25 04:54:41 +00:00
dasemu 8c902e85b7 Merge pull request #15 from Dasemu/development
Release: development into main
2026-11-18 03:28:49 +01:00
dasemu 80ff449f74 Merge pull request #14 from Dasemu/fix/ignored-conflicts-real-files
fix(core): only existing files count as ignored conflicts
2026-11-17 17:26:47 +01:00
dasemuandClaude Opus 5.5 7ed5675a00 fix(core): only existing files count as ignored conflicts
A whole ignored directory (e.g. .claude/) made every incoming file under it a
'would overwrite ignored local files' conflict, even when the file did not
exist locally, so such branches never fast-forwarded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:26:20 +01:00
dasemu 933ad65cf0 Merge pull request #13 from Dasemu/fix/fair-dispatch
fix(daemon): dispatch due repos longest-waiting first
2026-11-17 17:04:20 +01:00
dasemuandClaude Opus 5.5 51450ffa5e fix(daemon): dispatch due repos longest-waiting first
With the worker pool, a full pass every fetch_interval_s re-marked every repo
due 'now' and dispatch went by path, so when a cycle took longer than the
interval the repos late in the alphabet never got a pass (52 of 80 on a real
machine). Keep the earlier due time and dispatch by it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:03:51 +01:00
dasemu 380fff5395 Merge pull request #12 from Dasemu/fix/purge-confirm-slow-passes
fix(daemon): keep purge confirmations across slow pass cycles
2026-11-17 16:19:31 +01:00
dasemuandClaude Opus 5.5 d73f0c9463 fix(daemon): keep purge confirmations across slow pass cycles
A gap of more than 20 min between two confirmations reset the wait, but a
cycle over ~80 repos took ~25 min, so no deletion was ever confirmed.
Only a gap over 6 h starts over now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:19:04 +01:00
dasemu 0f83e9d30b Merge pull request #11 from Dasemu/feat/parallel-sync
feat(daemon): run sync passes on a worker pool
2026-11-17 16:03:10 +01:00
dasemuandClaude Opus 5.5 f16438fa02 feat(daemon): run sync passes on a worker pool
The loop thread schedules and sync.workers threads (default 4) run passes,
so a slow or hanging fetch no longer holds up every other repo. A repo never
has two passes at once; passes go only to idle workers, so pause and backoff
behave as before. Visibility and merged-PR caches are shared without holding
locks across forge requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:02:41 +01:00
dasemu 6e5bee1a95 Merge pull request #10 from Dasemu/feat/prune-merged-without-pr
feat(daemon): prune branches merged without a PR, protect long-lived ones
2026-11-17 15:31:19 +01:00
dasemuandClaude Opus 5.5 a1646bccb7 feat(daemon): prune branches merged without a PR, protect long-lived ones
- Prune a worktree whose pushed tip a merge commit brought into the default
  branch (not on its first-parent history), with no forge needed.
- Never prune or keep from materializing main/master/development/... plus
  sync.prune_protected; this also stops a development->main PR pruning
  development.
- Follow repos transferred or renamed on the forge when listing merged PRs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:29:26 +01:00
dasemu c7899bcdc0 Merge pull request #9 from Dasemu/fix/purge-gitea-ssh-not-found
fix(daemon): recognise Gitea SSH "Cannot find repository" for purge
2026-11-17 15:15:58 +01:00
dasemuandClaude Opus 5.5 2772635ff9 fix(daemon): treat Gitea SSH "Cannot find repository" as a purge hint
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:15:15 +01:00
37 changed files with 3032 additions and 228 deletions

No files matched your search

+3
View File
@@ -11,6 +11,9 @@ jobs:
- uses: actions/checkout@v4
- name: Shell syntax
run: for f in spikes/*.sh; do bash -n "$f"; done
- name: System libraries for the GUI (Slint needs fontconfig headers)
if: hashFiles('Cargo.toml') != ''
run: sudo apt-get update -qq && sudo apt-get install -y -qq libfontconfig-dev
- name: Rust (once a Cargo workspace exists)
if: hashFiles('Cargo.toml') != ''
run: |
+2 -1
View File
@@ -6,6 +6,7 @@ uncommitted work, via snapshot refs (`refs/sync/<machine>/<branch>`) 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.
+17
View File
@@ -3,6 +3,23 @@
Keeps your git repos in sync across machines without manual commit/push/pull, including
work in progress. Early stage (Phase 1: core library and CLI). See `docs/` for details.
## Install from source
```bash
cargo install --locked --root ~/.local --path crates/grove
cargo install --locked --root ~/.local --path crates/grove-daemon
cargo install --locked --root ~/.local --path crates/grove-gui
install -Dm644 contrib/groved.service ~/.config/systemd/user/groved.service
systemctl --user enable --now groved
# Menu entry: desktop sessions often lack ~/.local/bin in PATH, so use the absolute path.
sed "s|^Exec=grove-gui|Exec=$HOME/.local/bin/grove-gui|" contrib/grove.desktop \
> ~/.local/share/applications/grove.desktop
install -Dm644 assets/grove.png ~/.local/share/icons/hicolor/64x64/apps/grove.png
```
Start-at-login is a toggle in the app's Settings. A `.deb` is also available
(`cargo deb -p grove`, see `docs/phase7.md`).
## License
MIT, see `LICENSE`.
+1 -1
View File
@@ -1 +1 @@
0.1.0
0.1.2
+141 -1
View File
@@ -17,6 +17,45 @@ pub struct Config {
pub sync: Sync,
#[serde(skip_serializing_if = "Option::is_none")]
pub config_repo: Option<ConfigRepo>,
/// 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<String>,
/// 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<Vec<String>>,
/// Own launchers; one named like a built-in replaces it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub launchers: Vec<Launcher>,
}
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<String>,
/// Program and arguments; `{path}` is replaced by the worktree path. The process also
/// starts in the worktree.
pub command: Vec<String>,
/// 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)]
@@ -167,6 +206,23 @@ pub struct Sync {
/// regenerable build output and dependency caches. Any other ignored file keeps it.
#[serde(default = "default_disposable")]
pub prune_disposable: Vec<String>,
/// Extra branches never pruned, on top of the built-in long-lived ones
/// (`prune::default_protected`) and the default branch. See [`Sync::protected_branches`].
#[serde(default)]
pub prune_protected: Vec<String>,
/// How many repos the daemon syncs at the same time (1 to 32). A repo never has two
/// passes at once.
#[serde(default = "default_workers")]
pub workers: usize,
}
impl Sync {
/// Branches never pruned: the built-in long-lived ones plus `prune_protected`.
pub fn protected_branches(&self) -> Vec<String> {
let mut all = crate::prune::default_protected();
all.extend(self.prune_protected.iter().cloned());
all
}
}
impl Default for Sync {
@@ -180,6 +236,8 @@ impl Default for Sync {
purged_dir: default_purged_dir(),
prune_merged: true,
prune_disposable: default_disposable(),
prune_protected: Vec::new(),
workers: default_workers(),
}
}
}
@@ -193,6 +251,9 @@ pub struct ConfigRepo {
fn yes() -> bool {
true
}
fn default_workers() -> usize {
4
}
fn default_debounce() -> u64 {
2000
}
@@ -333,6 +394,12 @@ impl Config {
));
}
}
if !(1..=32).contains(&self.sync.workers) {
return bad(format!(
"sync.workers = {} must be between 1 and 32",
self.sync.workers
));
}
if let Some(d) = self
.sync
.prune_disposable
@@ -396,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),
@@ -457,10 +555,19 @@ name = "grove-config"
let c = Config::parse(base).unwrap();
assert!(c.sync.prune_merged);
assert!(c.sync.prune_disposable.iter().any(|d| d == "target"));
assert!(
c.sync
.protected_branches()
.iter()
.any(|b| b == "development")
);
let own = format!("{base}[sync]\nprune_merged=false\nprune_disposable=[\"out\"]\n");
let c = Config::parse(&own).unwrap();
assert!(!c.sync.prune_merged);
assert_eq!(c.sync.prune_disposable, vec!["out".to_string()]);
let t = format!("{base}[sync]\nprune_protected=[\"release\"]\n");
let p = Config::parse(&t).unwrap().sync.protected_branches();
assert!(p.iter().any(|b| b == "release") && p.iter().any(|b| b == "main"));
for bad in ["\"\"", "\"a/b\"", "\"..\""] {
let t = format!("{base}[sync]\nprune_disposable=[{bad}]\n");
assert!(Config::parse(&t).is_err(), "{bad}");
@@ -614,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| {
+585
View File
@@ -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<String>,
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<PathBuf>;
fn env(&self, key: &str) -> Option<String>;
}
/// 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<PathBuf> {
find_program(program)
}
fn env(&self, key: &str) -> Option<String> {
std::env::var(key).ok().filter(|v| !v.trim().is_empty())
}
}
pub fn find_program(program: &str) -> Option<PathBuf> {
if program.contains('/') {
let p = expand_home(program);
return is_executable(&p).then_some(p);
}
let mut dirs: Vec<PathBuf> = 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<Resolved> {
let mut out: Vec<Resolved> = 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<Vec<String>, 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::<Vec<_>>()
};
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<Vec<String>, String> {
let p = path.to_string_lossy();
let sub = |a: &String| a.replace("{path}", &p);
let cmd: Vec<String> = l.command.iter().map(sub).collect();
if !l.terminal {
return Ok(cmd);
}
let mut t: Vec<String> = 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<PathBuf, String> {
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/<group>/<name>` across all groups: an exact match, else a case-insensitive one.
fn find_repo(cfg: &Config, root: &Path, name: &str) -> Result<PathBuf, String> {
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<String> = 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<PathBuf, String> {
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<PathBuf> {
self.progs
.contains(&p)
.then(|| PathBuf::from("/bin").join(p))
}
fn env(&self, k: &str) -> Option<String> {
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());
}
}
+1
View File
@@ -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;
+104 -26
View File
@@ -1,11 +1,18 @@
//! Removing worktrees whose work was merged through a pull request on the forge.
//! Removing worktrees whose work is already merged.
//!
//! The forge (not git ancestry) says what was merged: squash and rebase merges leave no
//! ancestry, and a branch freshly created from the default branch is an ancestor of it too.
//! A worktree is removed only when its branch is the head of a merged pull request, its tip is
//! that head (or an ancestor of it), and it holds no local work: no uncommitted or untracked
//! files, no ignored files other than regenerable ones (`sync.prune_disposable`), no git
//! operation in progress. The tip is kept under a backup ref before anything is removed.
//! A branch counts as merged when either
//! - it is the head of a pull request merged on the forge and its tip is that head (or an
//! ancestor of it): squash and rebase merges leave no ancestry, so the forge has to say so; or
//! - it was merged without a pull request: its tip was pushed (`<remote>/<branch>` points at it),
//! is a strict ancestor of `<remote>/<default>` and is not on its first-parent history (a
//! merge commit brought it in). A branch created from the default branch with no commits of
//! its own is on that history, so it never counts; neither does a fast-forward merge.
//!
//! Branches named in `sync.prune_protected` (long-lived ones such as `development`) and the
//! default branch are never pruned. A worktree is removed only when it holds no local work: no
//! uncommitted or untracked files, no ignored files other than regenerable ones
//! (`sync.prune_disposable`), no git operation in progress. The tip is kept under a backup ref
//! before anything is removed.
use crate::git::{Git, GitError};
use crate::inspect::worktrees;
@@ -27,18 +34,42 @@ pub enum Pruned {
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
Removed {
branch: String,
pr: u64,
/// The merged pull request; `None` when merged into the default branch without one.
pr: Option<u64>,
path: PathBuf,
backup_ref: String,
},
/// Merged, but the worktree holds something that is not on the forge: kept.
Kept {
branch: String,
pr: u64,
pr: Option<u64>,
why: String,
},
}
/// How a pruned branch was merged, for messages ("merged in PR #3").
pub fn merged_how(pr: Option<u64>) -> String {
match pr {
Some(n) => format!("merged in PR #{n}"),
None => "merged into the default branch".into(),
}
}
/// Long-lived branches that are never pruned; `sync.prune_protected` adds to them.
pub fn default_protected() -> Vec<String> {
[
"main",
"master",
"development",
"develop",
"dev",
"staging",
"production",
]
.map(String::from)
.to_vec()
}
/// Backup-ref kind of a pruned branch (`refs/sync-backup/<machine>/<stamp>/merged/<branch>`).
const KIND: &str = "merged";
@@ -94,19 +125,54 @@ fn is_ancestor(g: &Git, a: &str, b: &str) -> bool {
matches!(g.probe(&["merge-base", "--is-ancestor", a, b]), Ok(Some(_)))
}
/// Removes the worktrees of the bare-layout repo at `root` whose branch was merged on the forge
/// (see the module docs). Only worktrees inside `root` are touched, never the one of the
/// default branch (`.bare`'s HEAD).
fn resolve(g: &Git, r: &str) -> Option<String> {
g.probe(&["rev-parse", "-q", "--verify", &format!("{r}^{{commit}}")])
.ok()
.flatten()
}
/// Merged without a pull request: `tip` was pushed as `<remote>/<branch>`, is a strict ancestor
/// of `<remote>/<default>` and is not on its first-parent history (a merge commit brought it).
fn merged_by_ancestry(g: &Git, remote: &str, default: &str, branch: &str, tip: &str) -> bool {
let Some(base) = resolve(g, &format!("refs/remotes/{remote}/{default}")) else {
return false;
};
resolve(g, &format!("refs/remotes/{remote}/{branch}")).as_deref() == Some(tip)
&& base != tip
&& is_ancestor(g, tip, &base)
&& !on_first_parent_chain(g, tip, &base)
}
/// True when `tip` is on the first-parent history of `base`: the default branch passed through
/// it. That is a branch created from the default branch with no commits of its own (or merged
/// by fast-forward, which the PR path still covers), so ancestry says nothing about a merge.
fn on_first_parent_chain(g: &Git, tip: &str, base: &str) -> bool {
// On error, assume it is (never prune on doubt).
g.run(&["rev-list", "--first-parent", base])
.map_or(true, |l| l.lines().any(|c| c == tip))
}
/// What to prune and what to keep.
pub struct Rules<'a> {
/// Remote whose default branch and branches the ancestry rule compares against.
pub remote: &'a str,
/// Heads of pull requests merged on the forge (may be empty: unknown).
pub merged: &'a [MergedHead],
/// Ignored file/directory names that do not count as local work.
pub disposable: &'a [String],
/// Branch names never pruned.
pub protected: &'a [String],
}
/// Removes the worktrees of the bare-layout repo at `root` whose branch is already merged (see
/// the module docs). Only worktrees inside `root` are touched, never the one of the default
/// branch (`.bare`'s HEAD) nor protected branches.
pub fn prune_merged(
root: &Path,
merged: &[MergedHead],
disposable: &[String],
rules: &Rules,
machine: &str,
stamp: &str,
) -> Result<Vec<Pruned>, GitError> {
if merged.is_empty() {
return Ok(vec![]);
}
let bare = root.join(".bare");
let g = Git::new(&bare);
let default = g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?;
@@ -116,27 +182,37 @@ pub fn prune_merged(
let Some(branch) = wt.branch.as_deref() else {
continue;
};
if default.as_deref() == Some(branch) || !wt.path.starts_with(&canonical_root) {
if default.as_deref() == Some(branch)
|| rules.protected.iter().any(|p| p == branch)
|| !wt.path.starts_with(&canonical_root)
{
continue;
}
let Ok(tip) = g.run(&["rev-parse", &format!("refs/heads/{branch}")]) else {
continue;
};
// The newest merged PR of this branch whose head contains the local tip.
let Some(pr) = merged
// The newest merged PR of this branch whose head contains the local tip, else a merge
// without a PR.
let pr = rules
.merged
.iter()
.filter(|m| m.branch == branch)
.find(|m| m.sha == tip || is_ancestor(&g, &tip, &m.sha))
else {
.map(|m| m.number);
if pr.is_none()
&& !default
.as_deref()
.is_some_and(|d| merged_by_ancestry(&g, rules.remote, d, branch, &tip))
{
continue;
};
}
if !wt.path.is_dir() {
continue;
}
if let Some(why) = local_work(&wt.path, disposable)? {
if let Some(why) = local_work(&wt.path, rules.disposable)? {
out.push(Pruned::Kept {
branch: branch.to_string(),
pr: pr.number,
pr,
why,
});
continue;
@@ -148,7 +224,7 @@ pub fn prune_merged(
g.run(&["branch", "-D", branch])?;
out.push(Pruned::Removed {
branch: branch.to_string(),
pr: pr.number,
pr,
path: wt.path.clone(),
backup_ref: bref,
});
@@ -158,11 +234,12 @@ pub fn prune_merged(
/// Branches `materialize` must not bring back: the remote tip is the head of a merged PR, or
/// the tip this machine pruned (its `merged/<branch>` backup ref). New commits pushed to the
/// branch after the merge make it materialize again.
/// branch after the merge make it materialize again. Protected branches are never settled.
pub fn settled_branches(
bare: &Path,
remote: &str,
merged: &[MergedHead],
protected: &[String],
machine: &str,
) -> Result<Vec<String>, GitError> {
let g = Git::new(bare);
@@ -186,6 +263,7 @@ pub fn settled_branches(
.lines()
.filter_map(|l| l.split_once(' '))
.filter_map(|(sha, r)| Some((sha, r.strip_prefix(&prefix)?)))
.filter(|(_, b)| !protected.iter().any(|p| p == b))
.filter(|(sha, b)| {
merged.iter().any(|m| m.branch == *b && m.sha == *sha)
|| pruned.iter().any(|(s, pb)| pb == b && s == sha)
+17
View File
@@ -45,6 +45,7 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
"-z",
])?;
let ignored: Vec<&str> = ignored.split('\0').filter(|p| !p.is_empty()).collect();
let top = std::path::PathBuf::from(g.run(&["rev-parse", "--show-toplevel"])?);
Ok(added
.into_iter()
.filter(|a| {
@@ -52,10 +53,26 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
.iter()
.any(|i| a == i || (i.ends_with('/') && a.starts_with(i)))
})
// An ignored directory (`.claude/`) only covers the path: there is something to
// overwrite only if the file, or a file where one of its parent directories goes, exists.
.filter(|a| occupied(&top, a))
.map(String::from)
.collect())
}
/// True when writing `rel` under `top` would replace something on disk: the path itself
/// exists, or one of its parents exists as something other than a directory.
fn occupied(top: &Path, rel: &str) -> bool {
let path = top.join(rel);
if path.symlink_metadata().is_ok() {
return true;
}
path.ancestors()
.skip(1)
.take_while(|p| p.starts_with(top) && *p != top)
.any(|p| p.symlink_metadata().is_ok_and(|m| !m.is_dir()))
}
fn current_branch(g: &Git) -> Result<String, GitError> {
g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD".into()))
+7
View File
@@ -225,6 +225,13 @@ mod tests {
fs::write(locked.join("f"), "x").unwrap();
fs::write(d.join(crate::busy::BUSY), "1 1\n").unwrap();
fs::set_permissions(&locked, fs::Permissions::from_mode(0o500)).unwrap();
// Root (e.g. a CI container) ignores directory permissions, so nothing can be locked
// and the partial-rollback path is unreachable: the test has nothing to check there.
if fs::write(locked.join("probe"), "x").is_ok() {
eprintln!("skipped: directory permissions are not enforced (running as root?)");
fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap();
return;
}
rollback_clone(&d);
assert!(d.join(".grove-stage").exists());
assert!(
+4 -1
View File
@@ -47,7 +47,10 @@ fn temp_index_path() -> PathBuf {
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
std::env::temp_dir().join(format!("grove-index-{}-{nanos}", std::process::id()))
// A counter too: daemon workers snapshot several repos at once.
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::env::temp_dir().join(format!("grove-index-{}-{nanos}-{n}", std::process::id()))
}
/// Tree of everything in the worktree (tracked changes and untracked files, not ignored ones),
+14 -4
View File
@@ -4,7 +4,7 @@
use crate::git::{Git, GitError};
use crate::inspect::{facts, state, worktrees};
use crate::prune::{MergedHead, Pruned, prune_merged, settled_branches};
use crate::prune::{MergedHead, Pruned, Rules, prune_merged, settled_branches};
use crate::receive::{
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
materialize_except, push_snapshot, receive,
@@ -32,6 +32,10 @@ pub struct Options {
pub merged: Vec<MergedHead>,
/// Names of ignored files/directories that do not count as local work when pruning.
pub disposable: Vec<String>,
/// Prune worktrees of merged branches (bare layout only, see `prune`).
pub prune: bool,
/// Branch names never pruned.
pub protected: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
@@ -82,14 +86,20 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
}
}
if bare_layout && rep.fetch_error.is_none() && !o.offline {
match prune_merged(path, &o.merged, &o.disposable, &o.machine, &o.stamp) {
if bare_layout && o.prune && rep.fetch_error.is_none() && !o.offline {
let rules = Rules {
remote: &o.remote,
merged: &o.merged,
disposable: &o.disposable,
protected: &o.protected,
};
match prune_merged(path, &rules, &o.machine, &o.stamp) {
Ok(p) => rep.pruned = p,
Err(e) => rep.fetch_error = Some(format!("prune merged: {e}")),
}
}
if bare_layout && o.materialize && rep.fetch_error.is_none() {
let skip = settled_branches(&gitdir, &o.remote, &o.merged, &o.machine);
let skip = settled_branches(&gitdir, &o.remote, &o.merged, &o.protected, &o.machine);
match skip.and_then(|skip| materialize_except(path, &o.remote, &skip)) {
Ok(m) => rep.materialized = m,
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
+78 -4
View File
@@ -2,7 +2,7 @@ mod common;
use common::*;
use grove_core::git::Git;
use grove_core::migrate::migrate;
use grove_core::prune::{MergedHead, Pruned, prune_merged};
use grove_core::prune::{MergedHead, Pruned, Rules, default_protected, prune_merged};
use grove_core::sync::{Options, sync_repo};
use std::fs;
use std::path::{Path, PathBuf};
@@ -58,6 +58,8 @@ fn opts(stamp: &str, merged: Vec<MergedHead>) -> Options {
push_snapshots: false,
merged,
disposable: vec!["target".into()],
prune: true,
protected: default_protected(),
}
}
@@ -119,7 +121,7 @@ fn a_squash_merged_worktree_is_removed_and_not_brought_back() {
else {
panic!("{:?}", rep.pruned);
};
assert_eq!((branch.as_str(), *pr), ("feat/x", 7));
assert_eq!((branch.as_str(), *pr), ("feat/x", Some(7)));
assert!(!wt.exists() && !has_branch(&w.root, "feat/x"));
let bare = Git::new(w.root.join(".bare"));
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
@@ -215,10 +217,82 @@ fn an_older_tip_is_pruned_but_the_default_branch_and_outside_worktrees_never_are
head(5, "main", &main_tip),
head(6, "o", &tip_o),
];
let pruned = prune_merged(&w.root, &merged, &[], "me", "t").unwrap();
let rules = Rules {
remote: "origin",
merged: &merged,
disposable: &[],
protected: &[],
};
let pruned = prune_merged(&w.root, &rules, "me", "t").unwrap();
assert!(
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: 4, .. }] if branch == "f"),
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: Some(4), .. }] if branch == "f"),
"{pruned:?}"
);
assert!(w.root.join("main").exists() && ext.exists());
}
#[test]
fn a_branch_merged_without_a_pr_is_removed_but_protected_and_fresh_ones_are_not() {
let w = world();
let tip = push_branch(&w, "feat/ff");
push_branch(&w, "development");
push_branch(&w, "wip");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
// A branch at the default branch's tip has nothing of its own yet.
w.dev.run(&["push", "-q", "origin", "main:fresh"]).unwrap();
// Merged into main without a pull request (no forge answer at all), with `development`
// (long-lived, protected); `wip` is not merged.
for b in ["feat/ff", "development"] {
w.dev
.run(&["merge", "-q", "--no-ff", "-m", "m", b])
.unwrap();
}
w.dev.run(&["push", "-q", "origin", "main"]).unwrap();
w.dev.run(&["push", "-q", "origin", "main:fresh2"]).unwrap();
let rep = sync_repo(&w.root, &opts("s2", vec![])).unwrap();
assert!(rep.fetch_error.is_none(), "{:?}", rep.fetch_error);
let [
Pruned::Removed {
branch,
pr: None,
backup_ref,
..
},
] = rep.pruned.as_slice()
else {
panic!("{:?}", rep.pruned);
};
assert_eq!(branch, "feat/ff");
let bare = Git::new(w.root.join(".bare"));
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
assert!(!w.root.join("feat-ff").exists() && !has_branch(&w.root, "feat/ff"));
for d in ["development", "wip", "fresh2"] {
assert!(w.root.join(d).exists(), "{d}");
}
// `feat/ff` stays on the remote and is not materialized again. `fresh` (materialized in
// s2) has no commits of its own: main's first-parent history passed through its tip, so it
// is not taken for a merge although main moved past it.
let rep = sync_repo(&w.root, &opts("s3", vec![])).unwrap();
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
assert!(!w.root.join("feat-ff").exists());
assert!(w.root.join("fresh").exists() && w.root.join("fresh2").exists());
}
#[test]
fn a_protected_branch_is_kept_even_as_the_head_of_a_merged_pr() {
let w = world();
let tip = push_branch(&w, "development");
squash_merge(&w, "development");
// Not materialized yet: a merged PR head must not keep a protected branch away.
let rep = sync_repo(&w.root, &opts("s1", vec![head(9, "development", &tip)])).unwrap();
assert!(
w.root.join("development").exists(),
"{:?}",
rep.materialized
);
let rep = sync_repo(&w.root, &opts("s2", vec![head(9, "development", &tip)])).unwrap();
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
assert!(w.root.join("development").exists());
}
+48
View File
@@ -353,6 +353,52 @@ fn fast_forward_declines_instead_of_overwriting_local_ignored_file() {
);
}
#[test]
fn files_new_in_an_ignored_directory_do_not_block_a_fast_forward() {
let w = world();
commit(&w.g1, "tool/settings.json", "{}\n");
w.g1.run(&["push", "-q"]).unwrap();
// The whole directory is ignored and exists locally, but not the incoming file.
fs::write(w.d2.join(".git/info/exclude"), "tool/\n").unwrap();
fs::create_dir_all(w.d2.join("tool/cache")).unwrap();
fs::write(w.d2.join("tool/cache/x"), "local\n").unwrap();
fetch(&w.d2, REMOTE).unwrap();
assert!(
matches!(
receive(&w.d2, "m2", "t").unwrap(),
Received::FastForwarded { .. }
),
"nothing local would be overwritten"
);
assert_eq!(
fs::read_to_string(w.d2.join("tool/settings.json")).unwrap(),
"{}\n"
);
assert_eq!(
fs::read_to_string(w.d2.join("tool/cache/x")).unwrap(),
"local\n"
);
}
#[test]
fn an_existing_file_in_an_ignored_directory_still_blocks_a_fast_forward() {
let w = world();
commit(&w.g1, "tool/settings.json", "theirs\n");
w.g1.run(&["push", "-q"]).unwrap();
fs::write(w.d2.join(".git/info/exclude"), "tool/\n").unwrap();
fs::create_dir_all(w.d2.join("tool")).unwrap();
fs::write(w.d2.join("tool/settings.json"), "mine\n").unwrap();
fetch(&w.d2, REMOTE).unwrap();
assert!(matches!(
receive(&w.d2, "m2", "t").unwrap(),
Received::Declined(_)
));
assert_eq!(
fs::read_to_string(w.d2.join("tool/settings.json")).unwrap(),
"mine\n"
);
}
#[test]
fn snapshot_apply_declines_instead_of_overwriting_local_ignored_file() {
let w = world();
@@ -388,6 +434,8 @@ fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
push_snapshots: true,
merged: vec![],
disposable: vec![],
prune: false,
protected: vec![],
};
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
commit(&w.g1, "z.txt", "z\n");
+2
View File
@@ -18,6 +18,8 @@ fn opts(machine: &str, stamp: &str) -> Options {
push_snapshots: true,
merged: vec![],
disposable: vec![],
prune: false,
protected: vec![],
}
}
+183 -57
View File
@@ -1,6 +1,7 @@
//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything
//! the watcher missed, failures back off exponentially. One worker thread runs the sync passes,
//! so passes never overlap.
//! the watcher missed, failures back off exponentially. The loop thread schedules; a pool of
//! `sync.workers` threads runs the passes, several repos at once but never two passes of the
//! same repo.
use crate::activity::{Activity, now_secs};
use crate::discover::{discover, group_of, is_ready, subdirs};
@@ -9,7 +10,7 @@ use crate::merged::{MergedCache, has_candidates};
use crate::purge;
use crate::visibility::{RealForge, Visibility, snapshot_gate};
use grove_core::config::Config;
use grove_core::prune::Pruned;
use grove_core::prune::{Pruned, merged_how};
use grove_core::receive::Received;
use grove_core::sync::{Options, sync_repo};
use notify::{EventKind, RecursiveMode, Watcher};
@@ -99,9 +100,72 @@ pub enum Msg {
Rescan,
/// Sync one repo (or all) as soon as possible.
SyncNow(Option<PathBuf>),
/// A worker finished a pass: consecutive failures (0 = success), and whether it was offline.
Done {
repo: PathBuf,
failures: u32,
offline: bool,
},
Shutdown,
}
/// One pass for a worker to run.
struct Job {
repo: PathBuf,
offline: bool,
}
/// Starts `n` threads that run passes from `jobs` and report each one as [`Msg::Done`].
fn spawn_workers(
n: usize,
jobs: Receiver<Job>,
cfg: &Arc<Config>,
st: &Arc<Settings>,
visibility: &Arc<Visibility>,
forge: &Arc<ForgeMemory>,
ctx: &Ctx,
) -> Vec<JoinHandle<()>> {
let jobs = Arc::new(Mutex::new(jobs));
(0..n)
.map(|_| {
let (jobs, cfg, st, visibility, forge, ctx) = (
jobs.clone(),
cfg.clone(),
st.clone(),
visibility.clone(),
forge.clone(),
ctx.clone(),
);
std::thread::spawn(move || {
loop {
// The lock is held only while waiting for the next job.
let job = jobs.lock().unwrap().recv();
let Ok(Job { repo, offline }) = job else {
break;
};
// A panicking pass must still report back, or its repo is never synced again.
let failures = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
pass(&repo, &cfg, &st, &visibility, offline, &forge, &ctx)
}))
.unwrap_or_else(|_| {
ctx.activity.log(
"error",
Some(&repo.display().to_string()),
"sync pass panicked; retried with backoff",
);
1
});
let _ = ctx.tx.send(Msg::Done {
repo,
failures,
offline,
});
}
})
})
.collect()
}
#[derive(Clone)]
pub struct Ctx {
pub shared: Arc<Mutex<Shared>>,
@@ -337,6 +401,7 @@ fn rescan(
root: &Path,
groups: &[String],
watch: &mut Watch,
running: &HashSet<PathBuf>,
ctx: &Ctx,
) -> (Vec<PathBuf>, Vec<PathBuf>) {
// Shallow watches first, then discover: a `.bare` created in a child between the two steps
@@ -353,8 +418,16 @@ fn rescan(
}
}
watch.sync(&wanted, false, ctx);
let d = discover(root, groups);
let found = d.managed;
let mut d = discover(root, groups);
// A repo whose pass is running may hold `.grove-busy` (purge) for a moment: it is judged
// when the pass reports back, not now.
d.stalled.retain(|r| !running.contains(r));
let mut found = d.managed;
for r in running {
if !found.contains(r) && r.is_dir() {
found.push(r.clone());
}
}
for r in &d.stalled {
if watch.warned_stalled.insert(r.clone()) {
ctx.activity.log(
@@ -409,7 +482,26 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
let root = cfg.root_path();
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
let mut visibility = Visibility::load(st.visibility_cache.clone());
let cfg = Arc::new(cfg);
let st = Arc::new(st);
let visibility = Arc::new(Visibility::load(st.visibility_cache.clone()));
// Deletions being confirmed and merged pull requests, per repo.
let forge = Arc::new(ForgeMemory::default());
let (jobs, job_rx) = channel::<Job>();
let workers = spawn_workers(
cfg.sync.workers.max(1),
job_rx,
&cfg,
&st,
&visibility,
&forge,
&ctx,
);
// Repos a worker is running a pass for: never scheduled twice.
let mut running: HashSet<PathBuf> = HashSet::new();
// Repos whose `sync` was requested while their pass ran: that pass's failure sets no backoff.
let mut sync_asked: HashSet<PathBuf> = HashSet::new();
let pool = cfg.sync.workers.max(1);
let mut watch = make_watch(
ctx.tx.clone(),
cfg.sync.ignore_extra.clone(),
@@ -417,7 +509,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
groups.clone(),
&ctx,
);
rescan(&root, &groups, &mut watch, &ctx);
rescan(&root, &groups, &mut watch, &running, &ctx);
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
@@ -429,14 +521,16 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let mut next_full = Instant::now();
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
let mut rescan_at: Option<Instant> = None;
// Deletions being confirmed and merged pull requests, per repo.
let mut forge = ForgeMemory::default();
loop {
'main: loop {
let now = Instant::now();
// With every worker busy nothing can start before a `Done` arrives: due repos must not
// shorten the wait (that would spin).
let idle = running.len() < pool;
let wake = due_at
.values()
.copied()
.iter()
.filter(|(r, _)| idle && !running.contains(*r))
.map(|(_, t)| *t)
.chain([next_full])
.chain(rescan_at)
.min()
@@ -467,19 +561,44 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
}
Ok(Msg::SyncNow(Some(r))) => {
backoff_until.remove(&r);
if running.contains(&r) {
sync_asked.insert(r.clone());
}
due_at.insert(r, Instant::now());
}
Ok(Msg::SyncNow(None)) => {
backoff_until.clear();
sync_asked.extend(running.iter().cloned());
next_full = Instant::now();
}
Ok(Msg::Done {
repo,
failures,
offline,
}) => {
running.remove(&repo);
let asked = sync_asked.remove(&repo);
if !is_ready(&repo) {
// It vanished mid-pass (or was purged): whatever the pass reported is moot.
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
} else if !offline {
if failures == 0 || asked {
backoff_until.remove(&repo);
} else {
let wait = Duration::from_secs(5u64.saturating_mul(1 << failures.min(6)))
.min(MAX_BACKOFF);
backoff_until.insert(repo, Instant::now() + wait);
}
}
}
Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
}
// Discovery also runs while paused so the status stays current; only syncing stops.
if rescan_at.is_some_and(|t| t <= Instant::now()) {
rescan_at = None;
let (found, added) = rescan(&root, &groups, &mut watch, &ctx);
let (found, added) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
for r in added {
due_at.insert(r, Instant::now());
@@ -491,20 +610,31 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let now = Instant::now();
if now >= next_full {
// Safety net for events the watcher missed (one `read_dir` per group).
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
// A repo still waiting keeps its earlier due time, so it is not overtaken.
for r in found {
due_at.insert(r, now);
due_at
.entry(r)
.and_modify(|t| *t = (*t).min(now))
.or_insert(now);
}
next_full = now + fetch_every;
}
let mut due: Vec<PathBuf> = due_at
// A repo whose pass is running stays due and is dispatched when that pass is done.
// Longest waiting first: with more due repos than workers, the order decides who waits.
let mut due: Vec<(Instant, PathBuf)> = due_at
.iter()
.filter(|(_, t)| **t <= now)
.map(|(r, _)| r.clone())
.filter(|(r, t)| **t <= now && !running.contains(*r))
.map(|(r, t)| (*t, r.clone()))
.collect();
due.sort();
for r in due {
for (_, r) in due {
// Only as many passes as idle workers: the rest stay due, so pause stops them and
// `offline` is decided when a pass really starts.
if running.len() >= pool {
break;
}
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
due_at.remove(&r);
continue;
@@ -513,35 +643,24 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
first_at.remove(&r);
if !is_ready(&r) {
// Removed or migrated away since the last discovery: drop it, no error.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
continue;
}
// While backing off after a failure, still snapshot local work (no network needed);
// the network is retried at the first pass after the backoff expires.
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &mut forge, &ctx);
if !is_ready(&r) {
// It vanished mid-pass: whatever the pass reported is moot.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
continue;
}
if offline {
continue;
}
if failures == 0 {
backoff_until.remove(&r);
} else {
let wait =
Duration::from_secs(5u64.saturating_mul(1 << failures.min(6))).min(MAX_BACKOFF);
backoff_until.insert(r, Instant::now() + wait);
}
if ctx.shared.lock().unwrap().paused {
break;
running.insert(r.clone());
if jobs.send(Job { repo: r, offline }).is_err() {
break 'main;
}
}
}
// Workers finish the pass they are running; nothing is cut short.
drop(jobs);
for w in workers {
let _ = w.join();
}
ctx.activity.log("stop", None, "daemon stopped");
}
@@ -557,11 +676,12 @@ fn forget_removed(
backoff_until.retain(|r, _| found.contains(r));
}
/// What the daemon remembers between passes about each repo's forge (in memory only).
/// What the daemon remembers between passes about each repo's forge (in memory only), shared
/// by the workers.
#[derive(Default)]
struct ForgeMemory {
/// Repos whose forge first confirmed their deletion at this time (see `purge`).
gone_since: HashMap<PathBuf, (u64, u64)>,
gone_since: Mutex<HashMap<PathBuf, (u64, u64)>>,
/// Merged pull requests per repo (see `merged`).
merged: MergedCache,
}
@@ -571,9 +691,9 @@ fn pass(
repo: &Path,
cfg: &Config,
st: &Settings,
visibility: &mut Visibility,
visibility: &Visibility,
offline: bool,
forge: &mut ForgeMemory,
forge: &ForgeMemory,
ctx: &Ctx,
) -> u32 {
let ForgeMemory { gone_since, merged } = forge;
@@ -632,6 +752,8 @@ fn pass(
push_snapshots,
merged: merged_heads,
disposable: cfg.sync.prune_disposable.clone(),
prune: cfg.sync.prune_merged,
protected: cfg.sync.protected_branches(),
};
let result = sync_repo(repo, &opts);
if !offline && purge_if_gone(repo, cfg, st, &result, gone_since, ctx) {
@@ -713,12 +835,13 @@ fn pass(
"pruned_merged",
Some(&name),
format!(
"{branch}: merged in PR #{pr}; removed {} (tip kept in {backup_ref})",
"{branch}: {}; removed {} (tip kept in {backup_ref})",
merged_how(*pr),
path.display()
),
),
Pruned::Kept { branch, pr, why } => {
kept.push(format!("{branch}: merged in PR #{pr} but kept: {why}"))
kept.push(format!("{branch}: {} but kept: {why}", merged_how(*pr)))
}
}
}
@@ -763,7 +886,7 @@ fn purge_if_gone(
cfg: &Config,
st: &Settings,
result: &Result<grove_core::sync::SyncReport, grove_core::git::GitError>,
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>,
ctx: &Ctx,
) -> bool {
let name = repo.display().to_string();
@@ -773,14 +896,14 @@ fn purge_if_gone(
};
if !hint || cfg.sync.purged_dir.is_empty() {
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
gone_since.remove(repo);
gone_since.lock().unwrap().remove(repo);
}
return false;
}
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
Ok(true) => {}
Ok(false) => {
gone_since.remove(repo);
gone_since.lock().unwrap().remove(repo);
return false;
}
// Cannot tell (network, token): keep whatever was confirmed before.
@@ -788,13 +911,16 @@ fn purge_if_gone(
}
let now = now_secs();
let window = purge::CONFIRM_AFTER_SECS;
let entry = gone_since.entry(repo.to_path_buf()).or_insert((now, now));
if now.saturating_sub(entry.1) > 2 * window {
// Stale: start over.
*entry = (now, now);
}
entry.1 = now;
let first = entry.0;
let first = {
let mut map = gone_since.lock().unwrap();
let entry = map.entry(repo.to_path_buf()).or_insert((now, now));
if now.saturating_sub(entry.1) > purge::STALE_AFTER_SECS {
// Stale: start over.
*entry = (now, now);
}
entry.1 = now;
entry.0
};
if first == now {
ctx.activity.log(
"purge_pending",
@@ -813,8 +939,8 @@ fn purge_if_gone(
else {
return false;
};
let gone = |ctx: &Ctx, gone_since: &mut HashMap<PathBuf, (u64, u64)>| {
gone_since.remove(repo);
let gone = |ctx: &Ctx, gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>| {
gone_since.lock().unwrap().remove(repo);
ctx.shared.lock().unwrap().repos.remove(repo);
};
match purge::move_repo(repo, &dest) {
+29 -18
View File
@@ -12,6 +12,7 @@ use grove_core::inspect::worktrees;
use grove_core::prune::MergedHead;
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// How long a forge answer is reused.
@@ -37,8 +38,8 @@ impl PullSource for RealForge {
name: &str,
) -> Result<Vec<MergedHead>, String> {
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
let pulls = grove_providers::build(pc, token)
.merged_pulls(owner, name)
let forge = grove_providers::build(pc, token);
let pulls = grove_providers::merged_pulls_following_moves(forge.as_ref(), owner, name)
.map_err(|e| e.to_string())?;
Ok(pulls
.into_iter()
@@ -91,10 +92,11 @@ struct Entry {
noted: BTreeSet<String>,
}
/// Per-repo forge answers and notes, held by the daemon loop (in memory only).
/// Per-repo forge answers and notes (in memory only), shared by the daemon's sync workers. The
/// lock is never held across a forge request.
#[derive(Default)]
pub struct MergedCache {
entries: HashMap<PathBuf, Entry>,
entries: Mutex<HashMap<PathBuf, Entry>>,
}
/// Result of [`MergedCache::heads`].
@@ -107,25 +109,31 @@ pub struct Heads {
impl MergedCache {
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
pub fn heads(
&mut self,
&self,
cfg: &Config,
repo: &Path,
remote: &str,
src: &dyn PullSource,
now: Instant,
) -> Heads {
let e = self.entries.entry(repo.to_path_buf()).or_default();
if e.checked
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
{
return Heads {
heads: e.heads.clone(),
new_error: None,
};
let mut entries = self.entries.lock().unwrap();
let e = entries.entry(repo.to_path_buf()).or_default();
if e.checked
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
{
return Heads {
heads: e.heads.clone(),
new_error: None,
};
}
e.checked = Some(now);
}
e.checked = Some(now);
let answer = lookup(cfg, repo, remote, src);
let mut entries = self.entries.lock().unwrap();
let e = entries.entry(repo.to_path_buf()).or_default();
let mut new_error = None;
match lookup(cfg, repo, remote, src) {
match answer {
Ok(h) => {
e.heads = h;
e.error = None;
@@ -145,8 +153,9 @@ impl MergedCache {
/// Of the "kept" notes of this pass, those not logged yet for `repo`. Notes that no longer
/// apply are forgotten, so they are logged again if they come back.
pub fn new_notes(&mut self, repo: &Path, notes: Vec<String>) -> Vec<String> {
let e = self.entries.entry(repo.to_path_buf()).or_default();
pub fn new_notes(&self, repo: &Path, notes: Vec<String>) -> Vec<String> {
let mut entries = self.entries.lock().unwrap();
let e = entries.entry(repo.to_path_buf()).or_default();
let now: BTreeSet<String> = notes.into_iter().collect();
let fresh = now.difference(&e.noted).cloned().collect();
e.noted = now;
@@ -156,6 +165,8 @@ impl MergedCache {
/// The last answer for `repo`, without asking the forge (offline passes).
pub fn cached(&self, repo: &Path) -> Vec<MergedHead> {
self.entries
.lock()
.unwrap()
.get(repo)
.map(|e| e.heads.clone())
.unwrap_or_default()
@@ -217,7 +228,7 @@ mod tests {
asked: RefCell::new(vec![]),
answer: RefCell::new(Ok(vec![head(1)])),
};
let mut c = MergedCache::default();
let c = MergedCache::default();
let t0 = Instant::now();
assert_eq!(c.heads(&cfg, &repo, "origin", &f, t0).heads, vec![head(1)]);
assert_eq!(f.asked.borrow().as_slice(), ["gitea:Org/r"]);
@@ -235,7 +246,7 @@ mod tests {
#[test]
fn notes_are_reported_once_while_they_hold() {
let mut c = MergedCache::default();
let c = MergedCache::default();
let r = Path::new("/r");
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
assert!(c.new_notes(r, vec!["a".into()]).is_empty());
+9
View File
@@ -14,6 +14,10 @@ use std::path::{Path, PathBuf};
/// How long a remote deletion must keep being confirmed before the repo is moved.
pub const CONFIRM_AFTER_SECS: u64 = 600;
/// A confirmation older than this (no check in between, e.g. the forge was unreachable) no
/// longer counts and the wait starts over. Much longer than the time between two passes of
/// one repo, which can exceed 20 minutes with many repos.
pub const STALE_AFTER_SECS: u64 = 6 * 3600;
/// Fetch failures that may mean the remote repo is gone (only a hint; see [`confirmed_gone`]).
pub fn looks_gone(fetch_error: &str) -> bool {
@@ -22,6 +26,7 @@ pub fn looks_gone(fetch_error: &str) -> bool {
"not found",
"does not appear to be a git repository",
"does not exist",
"cannot find repository", // Gitea/Forgejo over SSH
"error: 404",
]
.iter()
@@ -183,6 +188,10 @@ mod tests {
assert!(looks_gone(
"fatal: 'x.git' does not appear to be a git repository"
));
assert!(looks_gone(
"git fetch -q --prune origin failed (Some(128)): error:\nerror: Cannot find \
repository: dasemu/x\nerror:\nfatal: Could not read from remote repository."
));
assert!(!looks_gone(
"ssh: connect to host h port 22: Connection timed out"
));
+70 -58
View File
@@ -15,6 +15,7 @@ use grove_core::sync::git_dir_for;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
/// How long a "private" answer is trusted (a repo can be made public at any time).
pub const PRIVATE_TTL: u64 = 3600;
@@ -223,10 +224,16 @@ impl Entry {
}
}
/// Visibility cache. Owned by the daemon's single worker thread.
/// Visibility cache, shared by the daemon's sync workers. The lock is never held across a
/// forge request, so lookups for different repos run in parallel.
#[derive(Debug, Default)]
pub struct Visibility {
path: Option<PathBuf>,
state: Mutex<Cache>,
}
#[derive(Debug, Default)]
struct Cache {
entries: BTreeMap<String, Entry>,
failed: HashMap<String, (u64, String)>,
logins: HashMap<String, String>,
@@ -242,12 +249,14 @@ impl Visibility {
.unwrap_or_default();
Visibility {
path,
entries,
..Visibility::default()
state: Mutex::new(Cache {
entries,
..Cache::default()
}),
}
}
fn save(&self) {
fn save(&self, entries: &BTreeMap<String, Entry>) {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let Some(path) = &self.path else { return };
@@ -256,7 +265,7 @@ impl Visibility {
}
let tmp = path.with_extension("json.tmp");
let _ = std::fs::remove_file(&tmp);
let Ok(text) = serde_json::to_string_pretty(&self.entries) else {
let Ok(text) = serde_json::to_string_pretty(entries) else {
return;
};
let written = std::fs::OpenOptions::new()
@@ -272,7 +281,7 @@ impl Visibility {
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
fn seen(
&mut self,
&self,
pid: &str,
pc: &ProviderCfg,
owner: &str,
@@ -282,34 +291,39 @@ impl Visibility {
) -> Result<Seen, String> {
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
if let Some(e) = self.entries.get(&key)
&& e.fresh(now)
{
return Ok(e.seen);
let c = self.state.lock().unwrap();
if let Some(e) = c.entries.get(&key)
&& e.fresh(now)
{
return Ok(e.seen);
}
if let Some((at, why)) = c.failed.get(&key)
&& at.saturating_sub(0) <= now
&& now - at < RETRY
{
return Err(why.clone());
}
}
if let Some((at, why)) = self.failed.get(&key)
&& at.saturating_sub(0) <= now
&& now - at < RETRY
{
return Err(why.clone());
}
match forge.seen(pid, pc, owner, name) {
let answer = forge.seen(pid, pc, owner, name);
let mut c = self.state.lock().unwrap();
match answer {
Ok(seen) => {
self.failed.remove(&key);
self.entries.insert(key, Entry { seen, checked: now });
self.save();
c.failed.remove(&key);
c.entries.insert(key, Entry { seen, checked: now });
self.save(&c.entries);
Ok(seen)
}
Err(why) => {
let why = format!("lookup on {pid:?} failed: {why}");
self.failed.insert(key, (now, why.clone()));
c.failed.insert(key, (now, why.clone()));
Err(why)
}
}
}
/// Visibility of the repo behind one push URL.
pub fn check_url(&mut self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
pub fn check_url(&self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
let Some(id) = parse_remote(url) else {
return Verdict::Unknown("push URL not understood".into());
};
@@ -327,7 +341,7 @@ impl Visibility {
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
fn check_mirror(
&mut self,
&self,
cfg: &Config,
group: &str,
pid: &str,
@@ -346,16 +360,20 @@ impl Visibility {
.and_then(|g| g.owner(pid))
{
Some(o) => o.to_string(),
None => match self.logins.get(pid) {
Some(l) => l.clone(),
None => {
let l = forge
.login(pid, pc)
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
self.logins.insert(pid.to_string(), l.clone());
l
None => {
let known = self.state.lock().unwrap().logins.get(pid).cloned();
match known {
Some(l) => l,
None => {
let l = forge
.login(pid, pc)
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
let mut c = self.state.lock().unwrap();
c.logins.insert(pid.to_string(), l.clone());
l
}
}
},
}
};
match self.seen(pid, pc, &owner, name, now, forge) {
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
@@ -395,7 +413,7 @@ pub fn snapshot_gate(
cfg: &Config,
repo: &Path,
remote: &str,
vis: &mut Visibility,
vis: &Visibility,
now: u64,
forge: &dyn Forge,
) -> Result<(), String> {
@@ -559,7 +577,7 @@ owners = { github = "gh-org" }
.unwrap();
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
assert!(e.contains("several"));
let mut v = Visibility::default();
let v = Visibility::default();
let fake = Fake::default().with("o/r", Ok(Seen::Private));
assert!(matches!(
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
@@ -571,7 +589,7 @@ owners = { github = "gh-org" }
#[test]
fn unknown_visibility_is_public_and_withholds_snapshots() {
let c = cfg();
let mut v = Visibility::default();
let v = Visibility::default();
let boom = Fake::default();
for url in [
"https://gitlab.com/o/r.git",
@@ -608,7 +626,7 @@ owners = { github = "gh-org" }
#[test]
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
let c = cfg();
let mut v = Visibility::default();
let v = Visibility::default();
let f = Fake::default().with("o/r", Ok(Seen::Private));
let url = "https://github.com/o/r";
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
@@ -654,7 +672,7 @@ owners = { github = "gh-org" }
#[test]
fn cache_keys_include_provider_and_are_case_normalised() {
let c = cfg();
let mut v = Visibility::default();
let v = Visibility::default();
let f = Fake::default().with("o/r", Ok(Seen::Private));
v.check_url(&c, "https://github.com/O/R.git", 0, &f);
v.check_url(&c, "git@github.com:o/r", 0, &f);
@@ -676,7 +694,7 @@ owners = { github = "gh-org" }
let file = dir.join("visibility.json");
let c = cfg();
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
let mut v = Visibility::load(Some(file.clone()));
let v = Visibility::load(Some(file.clone()));
assert_eq!(
v.check_url(&c, "https://github.com/o/r", 50, &f),
Verdict::Public
@@ -684,7 +702,7 @@ owners = { github = "gh-org" }
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let never = Fake::default();
let mut again = Visibility::load(Some(file));
let again = Visibility::load(Some(file));
assert_eq!(
again.check_url(&c, "https://github.com/o/r", 60, &never),
Verdict::Public
@@ -721,22 +739,16 @@ owners = { github = "gh-org" }
let f = Fake::default()
.with("o/r", Ok(Seen::Private))
.with("o/open", Ok(Seen::NotPrivate));
let mut v = Visibility::default();
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
let v = Visibility::default();
let gate = |repo: &Path, v: &Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
let ok = "https://git.example.com:3000/o/r.git";
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok());
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err());
assert!(
gate(
&mk(&base, "all", &["https://unknown.example/o/r"], &[]),
&mut v
)
.is_ok()
);
assert!(gate(&mk(&base, "priv", &[ok], &[]), &v).is_ok());
assert!(gate(&mk(&base, "off", &[ok], &[]), &v).is_err());
assert!(gate(&mk(&base, "all", &["https://unknown.example/o/r"], &[]), &v).is_ok());
// Fetch URL private, but the push goes to a public repo (pushurl).
let e = gate(
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
&mut v,
&v,
);
assert!(e.is_err());
// Private-only without any remote: unknown, withheld.
@@ -744,7 +756,7 @@ owners = { github = "gh-org" }
std::fs::create_dir_all(&bare).unwrap();
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
assert!(
gate(&base.join("priv/none"), &mut v)
gate(&base.join("priv/none"), &v)
.unwrap_err()
.contains("unknown")
);
@@ -760,24 +772,24 @@ owners = { github = "gh-org" }
let f = Fake::default()
.with("o/r", Ok(Seen::Private))
.with("o/open", Ok(Seen::NotPrivate));
let mut v = Visibility::default();
let v = Visibility::default();
let ok = "https://git.example.com:3000/o/r.git";
let open = "https://github.com/o/open";
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
assert!(snapshot_gate(&c, &both, "origin", &mut v, 0, &f).is_ok());
assert!(snapshot_gate(&c, &both, "origin", &v, 0, &f).is_ok());
std::fs::remove_dir_all(base.join("priv")).unwrap();
let leaky = mk(&base, "priv", &[ok, open], &[]);
let e = snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).unwrap_err();
let e = snapshot_gate(&c, &leaky, "origin", &v, 0, &f).unwrap_err();
assert!(e.contains("public"), "{e}");
// pushInsteadOf rewrites the push URL to a public repo.
let g = Git::new(leaky.join(".bare"));
g.run(&["remote", "set-url", "--delete", "origin", open])
.unwrap();
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_ok());
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_ok());
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
.unwrap();
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_err());
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_err());
std::fs::remove_dir_all(&base).unwrap();
}
@@ -789,8 +801,8 @@ owners = { github = "gh-org" }
let _ = std::fs::remove_dir_all(&base);
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
let gate = |f: &Fake| {
let mut v = Visibility::default();
snapshot_gate(&c, &repo, "origin", &mut v, 0, f)
let v = Visibility::default();
snapshot_gate(&c, &repo, "origin", &v, 0, f)
};
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
// No mirror (404): fine. Mirror owner comes from `owners`.
+66
View File
@@ -768,3 +768,69 @@ fn clone_appears_only_when_complete() {
assert!(seen, "cloned repo never managed");
d.shutdown();
}
#[test]
fn a_hanging_fetch_does_not_hold_up_other_repos() {
let w = world("workers", &["pca"]);
// `a-slow` sorts first, so its pass is dispatched first; its fetch hangs for 15 s.
let slow = w.base.join("pca/g/a-slow");
bare_layout(&slow, &w.remote);
let bare = slow.join(".bare");
git(
&bare,
&["remote", "set-url", "origin", "ssh://hang.invalid/x.git"],
);
git(&bare, &["config", "core.sshCommand", "sleep 15; false"]);
let mut cfg = config(&w, "pca", 200, 60);
cfg.sync.workers = 2;
let started = Instant::now();
let d = Daemon::start(cfg, settings(&w, "pca")).unwrap();
fs::write(w.base.join("pca/g/repo/main/new.txt"), "x\n").unwrap();
wait_until("snapshot of the other repo pushed", 10, || {
!git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).is_empty()
});
assert!(started.elapsed() < Duration::from_secs(12));
d.shutdown();
}
#[test]
fn every_repo_gets_a_pass_when_a_cycle_takes_longer_than_the_interval() {
let w = world("fair", &["pca"]);
// Four repos sorting before `g/repo` whose fetch takes 1.5 s each: with one worker a cycle
// takes ~6 s against a 1 s interval.
for n in ["a", "b", "c", "d"] {
let r = w.base.join(format!("pca/g/{n}"));
bare_layout(&r, &w.remote);
git(
&r.join(".bare"),
&[
"config",
"remote.origin.uploadpack",
"sleep 1.5; git-upload-pack",
],
);
}
let mut cfg = config(&w, "pca", 200, 1);
cfg.sync.workers = 1;
let d = Daemon::start(cfg, settings(&w, "pca")).unwrap();
let sock = w.base.join("pca.sock");
let last = |s: &serde_json::Value, name: &str| {
s["repos"]
.as_array()
.unwrap()
.iter()
.find(|r| r["path"].as_str().unwrap().ends_with(&format!("/g/{name}")))
.and_then(|r| r["last_sync"].as_u64())
};
// `repo` keeps getting passes: it is not starved by the slow ones (before, sorted dispatch
// gave every new cycle to `a`..`d` again and `repo` never ran).
let mut seen = Vec::new();
wait_until("two passes of the last repo", 45, || {
let t = last(&status(&sock), "repo");
if t.is_some() && seen.last() != Some(&t) {
seen.push(t);
}
seen.len() >= 2
});
d.shutdown();
}
+45 -2
View File
@@ -16,6 +16,29 @@ pub fn file(config_home: &Path) -> PathBuf {
config_home.join("autostart").join("grove.desktop")
}
/// The autostart file, its `Exec` pointing at `exe` (this binary) by absolute path: desktop
/// sessions often lack `~/.local/bin` (where `cargo install --root ~/.local` puts it) in `PATH`,
/// and then a bare `grove-gui` never starts. Without a usable path the bare name is kept.
fn desktop_text(exe: Option<&Path>) -> String {
let Some(exe) = exe.filter(|e| e.is_absolute()).and_then(|e| e.to_str()) else {
return DESKTOP.to_string();
};
// Desktop Entry spec: quote arguments with reserved characters, escaping `"`, `` ` ``, `$`, `\`.
let exe = if exe.contains(|c: char| " \t\n\"'\\><~|&;$*?#()`".contains(c)) {
let esc: String = exe
.chars()
.flat_map(|c| match c {
'"' | '`' | '$' | '\\' => vec!['\\', c],
c => vec![c],
})
.collect();
format!("\"{esc}\"")
} else {
exe.to_string()
};
DESKTOP.replace("Exec=grove-gui", &format!("Exec={exe}"))
}
pub fn is_enabled(config_home: &Path) -> bool {
file(config_home).exists()
}
@@ -26,7 +49,8 @@ pub fn set(config_home: &Path, on: bool) -> std::io::Result<()> {
if let Some(d) = f.parent() {
std::fs::create_dir_all(d)?;
}
std::fs::write(&f, DESKTOP)
let exe = std::env::current_exe().ok();
std::fs::write(&f, desktop_text(exe.as_deref()))
} else {
match std::fs::remove_file(&f) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
@@ -47,10 +71,29 @@ mod tests {
set(&d, true).unwrap();
assert!(is_enabled(&d));
let text = std::fs::read_to_string(file(&d)).unwrap();
assert!(text.contains("Exec=grove-gui --hidden"));
let exe = std::env::current_exe().unwrap();
assert!(
text.contains(&format!("Exec={} --hidden", exe.display())) || text.contains("Exec=\"")
);
set(&d, false).unwrap();
assert!(!is_enabled(&d));
set(&d, false).unwrap(); // already off: fine
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn exec_uses_the_absolute_binary_path_quoted_when_needed() {
let t = desktop_text(Some(Path::new("/home/u/.local/bin/grove-gui")));
assert!(
t.contains("Exec=/home/u/.local/bin/grove-gui --hidden"),
"{t}"
);
let t = desktop_text(Some(Path::new("/opt/my apps/grove-gui")));
assert!(
t.contains("Exec=\"/opt/my apps/grove-gui\" --hidden"),
"{t}"
);
let t = desktop_text(None);
assert!(t.contains("Exec=grove-gui --hidden"), "{t}");
}
}
+122 -1
View File
@@ -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<PathBuf> {
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<PathBuf, String> {
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<PathBuf> {
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]
+168 -15
View File
@@ -47,6 +47,8 @@ struct Snapshot {
status: Option<Value>,
log: Vec<Value>,
config: Option<Value>,
/// 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<String>,
last_providers: Vec<String>,
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<Section> = 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<Launch> = 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();
}
});
}
@@ -467,7 +489,12 @@ fn toast(ui: &MainWindow, msg: &str, bad: bool) {
});
}
fn show_window(ui: &MainWindow, core: &Core) {
/// Shows (or re-maps) the window. `why` goes to the diagnostics log.
fn show_window(ui: &MainWindow, core: &Core, why: &str) {
log::line(&format!(
"showing the window ({why}; visible before: {})",
ui.window().is_visible()
));
// Slint exposes no xdg-activation, so an already visible window is raised by re-mapping it:
// a fresh toplevel is what the compositor focuses.
if core.visible.load(Ordering::SeqCst) && ui.window().is_visible() {
@@ -539,6 +566,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<String>, 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 +779,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 +806,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 +1036,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<String> = 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 +1320,7 @@ fn worker(
status,
log,
config: core.bridge.config_json(),
launchers: core.bridge.launchers(),
alerts,
};
let w = weak.clone();
@@ -1283,6 +1404,11 @@ fn run() -> Result<()> {
return Ok(());
}
let hidden = args.iter().any(|a| a == "--hidden");
let started = Instant::now();
log::line(&format!(
"session type: {}",
std::env::var("XDG_SESSION_TYPE").unwrap_or_else(|_| "unknown".into())
));
let inst_path = arg("--instance-socket")
.map(PathBuf::from)
.unwrap_or_else(instance::default_socket_path);
@@ -1297,15 +1423,25 @@ fn run() -> Result<()> {
{
let (late, pending) = (late.clone(), pending_show.clone());
std::thread::spawn(move || {
instance::serve(listener, move || match late.lock().unwrap().clone() {
Some(c) => {
let _ = slint::invoke_from_event_loop(move || {
if let Some(ui) = c.weak.upgrade() {
show_window(&ui, &c.core);
}
});
instance::serve(listener, move || {
let age = started.elapsed();
if !model::accept_instance_show(hidden, age) {
log::line(&format!(
"ignored a show request from another launch {:.1} s after a --hidden start (session restore?)",
age.as_secs_f32()
));
return;
}
match late.lock().unwrap().clone() {
Some(c) => {
let _ = slint::invoke_from_event_loop(move || {
if let Some(ui) = c.weak.upgrade() {
show_window(&ui, &c.core, "another launch asked");
}
});
}
None => pending.store(true, Ordering::SeqCst),
}
None => pending.store(true, Ordering::SeqCst),
})
});
}
@@ -1356,7 +1492,7 @@ fn run() -> Result<()> {
let c = ctx.clone();
let _ = slint::invoke_from_event_loop(move || {
if let Some(ui) = c.weak.upgrade() {
show_window(&ui, &c.core);
show_window(&ui, &c.core, "tray");
}
});
}
@@ -1371,7 +1507,8 @@ fn run() -> Result<()> {
}
})
};
let tray = match tray::spawn(on_action.clone()) {
// Autostart runs before Plasma's tray is ready: wait for it instead of opening the window.
let tray = match tray::spawn(on_action.clone(), hidden) {
Ok(h) => {
core.tray_ok.store(true, Ordering::SeqCst);
Some(h)
@@ -1400,7 +1537,13 @@ fn run() -> Result<()> {
let (c, w) = (core.clone(), ui.as_weak());
let respawn = on_action.clone();
std::thread::spawn(move || {
worker(c, rx, tray, move || tray::spawn(respawn.clone()).ok(), w)
worker(
c,
rx,
tray,
move || tray::spawn(respawn.clone(), true).ok(),
w,
)
});
}
{
@@ -1409,9 +1552,19 @@ fn run() -> Result<()> {
}
*late.lock().unwrap() = Some(ctx.clone());
if !hidden || pending_show.load(Ordering::SeqCst) || !core.tray_ok.load(Ordering::SeqCst) {
show_window(&ui, &core);
let why = if !hidden {
Some("started without --hidden")
} else if pending_show.load(Ordering::SeqCst) {
Some("another launch asked during start-up")
} else if !core.tray_ok.load(Ordering::SeqCst) {
Some("no tray")
} else {
None
};
if let Some(why) = why {
show_window(&ui, &core, why);
} else {
log::line("started hidden in the tray");
core.wake();
}
let r = slint::run_event_loop_until_quit();
+108
View File
@@ -336,6 +336,63 @@ pub fn group_name(entry: &str) -> &str {
entry.split(" → ").next().unwrap_or(entry)
}
/// After a `--hidden` start (autostart at login), show requests from other launches are ignored
/// for this long: they come from the desktop's session restore, and a window mapped while the
/// compositor is still starting shows up in the task bar but never on screen.
pub const LOGIN_GRACE: std::time::Duration = std::time::Duration::from_secs(20);
/// Whether a show request from another launch, `since_start` after this one started, is honoured.
pub fn accept_instance_show(hidden_start: bool, since_start: std::time::Duration) -> bool {
!hidden_start || since_start >= LOGIN_GRACE
}
/// 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<String> {
let mut a: Vec<String> = 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 +558,55 @@ mod tests {
assert_eq!(s[3].1[0].1, "grove-config on gitea");
assert_eq!(group_name("work → gitea"), "work");
}
#[test]
fn early_show_requests_are_ignored_only_after_a_hidden_start() {
use std::time::Duration;
assert!(accept_instance_show(false, Duration::ZERO));
assert!(!accept_instance_show(true, Duration::from_secs(3)));
assert!(accept_instance_show(true, LOGIN_GRACE));
assert!(accept_instance_show(true, Duration::from_secs(600)));
}
#[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());
}
}
+19 -2
View File
@@ -22,12 +22,18 @@ pub struct GroveTray {
pub type TrayHandle = Handle<GroveTray>;
/// Starts the tray service. Fails when there is no D-Bus session.
pub fn spawn(on_action: Arc<dyn Fn(Action) + Send + Sync>) -> Result<TrayHandle, ksni::Error> {
/// Starts the tray service. Fails when there is no D-Bus session. With `wait_for_host` a
/// missing StatusNotifier watcher/host is not an error: the item registers as soon as the
/// desktop's tray comes up (an autostarted app usually runs before Plasma's tray is ready).
pub fn spawn(
on_action: Arc<dyn Fn(Action) + Send + Sync>,
wait_for_host: bool,
) -> Result<TrayHandle, ksni::Error> {
GroveTray {
agg: Aggregate::default(),
on_action,
}
.assume_sni_available(wait_for_host)
.spawn()
}
@@ -48,6 +54,17 @@ impl ksni::Tray for GroveTray {
"grove".into()
}
fn watcher_online(&self) {
crate::log::line("tray: StatusNotifier watcher is online; icon registered");
}
fn watcher_offline(&self, reason: ksni::OfflineReason) -> bool {
crate::log::line(&format!(
"tray: StatusNotifier watcher offline ({reason:?}); waiting for it"
));
true
}
fn title(&self) -> String {
"Grove".into()
}
+305 -8
View File
@@ -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 <string> import-note;
@@ -209,6 +220,7 @@ export component MainWindow inherits Window {
in property <Repo> detail;
in property <bool> detail-found;
in-out property <string> selected-path;
property <string> prov-url-text;
in property <Out> new-out;
in property <Out> import-out;
in property <Out> 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;
+24
View File
@@ -158,6 +158,30 @@ pub trait Provider: Send + Sync {
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>>;
}
/// [`Provider::merged_pulls`] that also finds a repo transferred or renamed on the forge: `origin`
/// may still name the old place, which git and the repo endpoint follow by redirect but the
/// pulls endpoint does not. On failure the repo is looked up and, if its current owner/name
/// differ, its pulls are listed under those.
pub fn merged_pulls_following_moves(
p: &dyn Provider,
owner: &str,
name: &str,
) -> Result<Vec<MergedPull>> {
let err = match p.merged_pulls(owner, name) {
Ok(pulls) => return Ok(pulls),
Err(e) => e,
};
match p.get_repo(owner, name) {
Ok(r)
if !r.owner.is_empty()
&& !(r.owner.eq_ignore_ascii_case(owner) && r.name.eq_ignore_ascii_case(name)) =>
{
p.merged_pulls(&r.owner, &r.name)
}
_ => Err(err),
}
}
/// Builds the provider described by `cfg`, using `token`.
pub fn build(cfg: &ProviderCfg, token: String) -> Box<dyn Provider> {
match cfg.kind {
+36
View File
@@ -526,3 +526,39 @@ fn merged_pulls_keep_only_merged_same_repo_heads() {
Error::Api { status: 404, .. }
));
}
#[test]
fn merged_pulls_follow_a_transferred_repo() {
let pulls = r#"[{"number":4,"merged":true,"head":{"ref":"f","sha":"fff","repo":{"full_name":"Org/r"}},"base":{"repo":{"full_name":"Org/r"}}}]"#;
let (url, rx) = mock(vec![
(404, r#"{"message":"not found"}"#),
(
200,
r#"{"name":"r","owner":{"login":"Org"},"private":true}"#,
),
(200, pulls),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let got = grove_providers::merged_pulls_following_moves(&g, "me", "r").unwrap();
assert_eq!(got.iter().map(|p| p.number).collect::<Vec<_>>(), vec![4]);
let asked: Vec<String> = rx
.try_iter()
.map(|l| l.lines().next().unwrap().to_string())
.collect();
assert!(asked[1].starts_with("GET /api/v1/repos/me/r "), "{asked:?}");
assert!(
asked[2].starts_with("GET /api/v1/repos/Org/r/pulls?"),
"{asked:?}"
);
// Not moved: the original error stands.
let (url, _rx) = mock(vec![
(404, r#"{"message":"not found"}"#),
(404, r#"{"message":"not found"}"#),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
assert!(matches!(
grove_providers::merged_pulls_following_moves(&g, "me", "gone").unwrap_err(),
Error::Api { status: 404, .. }
));
}
+277 -16
View File
@@ -1,10 +1,10 @@
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;
use grove_core::prune::Pruned;
use grove_core::prune::{Pruned, merged_how};
use grove_core::receive::{Applied, Archived, Received};
use grove_core::resolve::{Choice, resolve};
use grove_core::snapshot::{Outcome, take};
@@ -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<String>,
},
/// 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<String>,
/// 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 `<root>/<name>` 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<String> },
@@ -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<String>,
/// 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<String>,
/// Public repos go to this provider instead (then --primary is for private ones)
#[arg(long, value_name = "PROVIDER")]
public_primary: Option<String>,
/// Mirrors of public repos (repeatable; needs --public-primary)
#[arg(long = "public-mirror-to", value_name = "PROVIDER")]
public_mirror_to: Vec<String>,
/// WIP snapshot policy for this namespace: private-only, all, none
#[arg(long)]
snapshots: Option<String>,
/// 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<String>,
/// 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<PathBuf>) -> Result<PathBuf> {
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<PathBuf>, 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<PathBuf>, 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 {
@@ -377,6 +620,8 @@ fn main() -> Result<()> {
push_snapshots: true,
merged,
disposable: cfg.sync.prune_disposable.clone(),
prune: cfg.sync.prune_merged,
protected: cfg.sync.protected_branches(),
},
)?;
print_report(&rep)
@@ -393,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(|| {
@@ -449,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)?)?;
@@ -531,11 +791,12 @@ fn print_report(rep: &SyncReport) -> Result<()> {
path,
backup_ref,
} => println!(
"pruned {branch}: merged in PR #{pr}, removed {} (backup {backup_ref})",
"pruned {branch}: {}, removed {} (backup {backup_ref})",
merged_how(*pr),
path.display()
),
Pruned::Kept { branch, pr, why } => {
println!("kept {branch}: merged in PR #{pr} but {why}")
println!("kept {branch}: {} but {why}", merged_how(*pr))
}
}
}
+362
View File
@@ -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<String>,
/// `PROVIDER=OWNER`, or a bare `OWNER` for the primary provider.
pub owners: Vec<String>,
pub public_primary: Option<String>,
pub public_mirror_to: Vec<String>,
pub snapshots: Option<SnapshotPolicy>,
pub no_materialize: bool,
}
pub fn parse_kind(k: &str) -> Result<ProviderKind> {
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<Protocol> {
Ok(match p {
"https" => Protocol::Https,
"ssh" => Protocol::Ssh,
p => bail!("unknown protocol {p:?} (https, ssh)"),
})
}
pub fn parse_snapshots(s: &str) -> Result<SnapshotPolicy> {
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 `<path>.bak` and writes the new one.
pub fn save(cfg: &Config, path: &Path) -> Result<PathBuf> {
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<String> {
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<String> = 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<String> {
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());
}
}
+1
View File
@@ -182,6 +182,7 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
public: None,
}],
sync: Default::default(),
open: Default::default(),
config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo {
provider: a.provider,
name,
+2
View File
@@ -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/<machine>/<branch>` 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 <worktree>`. 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.
+13 -2
View File
@@ -17,8 +17,19 @@ is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only de
cannot starve snapshots.
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
snapshots, materialize/archive). Also what catches missed events.
- **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass;
it finds nothing to do and ends the chain.
- **Worker pool**: the loop thread only schedules; `sync.workers` threads (default 4, 1 to 32) run
the passes, so a slow or hanging fetch of one repo no longer holds up the others. A repo never
has two passes at once: one that becomes due while its pass runs is dispatched when it ends.
Events that arrive during a pass queue another pass; it finds nothing to do and ends the chain.
Due repos are dispatched longest-waiting first, and a full pass never moves an earlier due
time later, so when a cycle takes longer than `fetch_interval_s` every repo still gets its
turn (dispatching by path starved the repos late in the alphabet).
Passes are handed out only to idle workers, so the rest stay due: pause stops them, and whether
a pass runs offline (backoff) is decided when it starts. A `sync` request for a repo whose pass
is running is not undone by that pass failing. A panicking pass is logged and counts as a
failure. Rediscovery does not drop or flag (stalled) a repo while its pass runs.
The visibility and merged-PR caches are shared and never locked across a forge request.
Shutdown and pause let running passes finish. `workers = 1` is the old sequential behaviour.
- **Failures** (network, auth, git errors) back off exponentially per repo: 10 s, 20 s, ... capped at
5 min, and are logged as `error`. `sync` over IPC clears the backoff. While backing off, changes
are still snapshotted locally (an offline pass); only the network is retried after the backoff.
+4 -3
View File
@@ -127,10 +127,11 @@ A managed repo whose remote was deleted is moved out of the synced tree, never d
purged_dir = "Purged" # default; "" disables the move
```
- Trigger: a fetch fails with a "not found"-style error. That is only a hint: the forge serving
- Trigger: a fetch fails with a "not found"-style error (also Gitea's SSH "Cannot find repository"). That is only a hint: the forge serving
`origin` must then answer 404 while the same token works (`test_connection`), and still do so
`purge::CONFIRM_AFTER_SECS` (10 min) after the first confirmation (a gap of more than twice
that starts over). A working fetch, or the forge seeing the repo again, clears it. Network or
`purge::CONFIRM_AFTER_SECS` (10 min) after the first confirmation (a gap of more than
`STALE_AFTER_SECS`, 6 h, between two confirmations starts over: a pass over many repos can take
longer than 20 min, so a shorter gap never let a deletion be confirmed). A working fetch, or the forge seeing the repo again, clears it. Network or
token errors change nothing.
- Only repos owned by the token's account, or by an organisation named in some group's `owners`
for that provider, are ever moved: someone else's repo turning private or revoking access looks
+25 -1
View File
@@ -54,7 +54,8 @@ grove-gui --view settings # start on a view (activity, new, im
`grove` is looked up next to the `grove-gui` binary, then in `PATH`. Packaging: `.deb` installs
`grove-gui`, `contrib/grove.desktop`, `assets/grove.png` and a copy of the autostart file under
`/usr/share/grove/`. Autostart is opt-in: Settings has a "Start Grove at login" toggle that writes or
removes `~/.config/autostart/grove.desktop`. The deb recommends `libnotify-bin` (`notify-send`). Dev builds need no system Qt: Slint is built with the `winit` backend (Wayland and
removes `~/.config/autostart/grove.desktop`; its `Exec` is the running binary's absolute path,
because desktop sessions often lack `~/.local/bin` in `PATH` (a source install from the README). The deb recommends `libnotify-bin` (`notify-send`). Dev builds need no system Qt: Slint is built with the `winit` backend (Wayland and
X11 loaded at runtime) and the software renderer.
## Dependencies
@@ -155,3 +156,26 @@ tray errors and restarts, panics with a backtrace (from any thread) and why the
repeated page, not on a short page. For a user that is not the login, GitHub/Gitea listing uses
`/user/repos` (collaborator repos included) and says when `/orgs/{owner}` is a 404.
- The GUI hands `grove add` the canonical path it validated.
## Autostart at login (Plasma Wayland)
Seen on Plasma 6 / Wayland: after an autostart (`grove-gui --hidden`) the window had a task bar
entry, but clicking it showed nothing; opening it from the tray worked (that path hides and
re-shows the window). A window mapped while the compositor is still starting ends up in that
state. Two ways it got shown at login, both handled now:
- No tray yet: Plasma's StatusNotifier watcher/host can come up after autostart, and a failed tray
start used to fall back to opening the window. A `--hidden` start now registers the tray item
with ksni's `assume_sni_available`: it waits for the watcher and registers when it appears
(`tray: StatusNotifier watcher …` lines in the log). Without a D-Bus session at all the window
still opens, as before. The tray respawn after a lost D-Bus connection also waits.
- Session restore: the desktop relaunches `grove-gui` (no `--hidden`) at login, which asks the
running instance to show its window. During the first 20 s after a `--hidden` start
(`model::LOGIN_GRACE`) such requests are ignored and logged. The tray's "Open Grove" is never
ignored.
Every time the window is shown, `grove-gui.log` records why (start without `--hidden`, another
launch, tray, no tray) and whether it was visible before; the session type is logged at start.
Checked under Xvfb with a private D-Bus session and no tray host (starts hidden, an early second
launch is ignored, a later one opens the window). The watcher appearing later was not simulated,
and the original symptom was not reproduced here (no Plasma).
+114
View File
@@ -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 `<root>/<name>` 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: <root>/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 `<root>/<name>`. `--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 <worktree>` |
| `vscode` | `code`, `codium`, `code-oss` | `code <worktree>` |
| `claude` | `claude` | in a terminal, started in the worktree |
| `claude-desktop` | `claude-desktop` | `claude-desktop <worktree>` (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 <launcher>" 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.
+26 -7
View File
@@ -1,10 +1,11 @@
# Pruning worktrees merged through a pull request
# Pruning merged worktrees
Worktrees of branches that were pushed, reviewed in a pull request and merged used to stay
forever: `archive_gone` only removes a worktree when its remote branch is deleted, the forge
often keeps the head branch, squash and rebase merges leave no ancestry for git to see, and a
Rust/Node worktree always holds ignored build output that kept it "dirty". The daemon now asks
the forge which pull requests were merged and removes those worktrees itself.
the forge which pull requests were merged and removes those worktrees itself. Branches merged
into the default branch without a pull request (merged locally and pushed) are removed too.
## Config
@@ -14,9 +15,15 @@ prune_merged = true # default
prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".pytest_cache",
".mypy_cache", ".ruff_cache", ".tox", ".gradle", ".next", ".nuxt", ".svelte-kit", ".turbo",
".parcel-cache", "dist", "build", "out", "coverage", ".cache"] # default
prune_protected = [] # default; extra branch names never pruned
```
- `prune_merged = false` turns the feature off.
- `prune_protected`: extra branch names (exact, no globs) never pruned nor kept from being
materialized, added to the built-in `main`, `master`, `development`, `develop`, `dev`,
`staging`, `production` (a `development` -> `main` PR has `development` as its head). The
default branch (`.bare`'s HEAD) never is either. Other long-lived branches (`release/1.2`,
`hotfix/x`) merged back with no new commits are pruned like any other: list them here.
- `prune_disposable`: names (not paths, not globs) of ignored files/directories that are
regenerable and may go with a pruned worktree. Entries must be plain names.
@@ -26,19 +33,29 @@ prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".
requests (GitHub: 100, `merged_at` set; Gitea/Forgejo: 50, `merged: true`), keeping only those
whose head repo is the base repo: fork PRs reuse branch names freely. The repo is found from
`origin`'s fetch URL, matched to a configured provider like the visibility check (`phase6.md`),
with the token from `token::resolve`.
with the token from `token::resolve`. When that fails, the repo is looked up and, if the forge
reports another owner/name (transferred or renamed: git and the repo endpoint follow the old
`origin` by redirect, the pulls endpoint does not), its pulls are listed under the current one.
Without a pull request, a branch counts as merged when its tip was pushed
(`origin/<branch>` points at it), is a strict ancestor of `origin/<default>` and is not on its
first-parent history, i.e. a merge commit brought it in. This needs no forge. A branch created
from the default branch with no commits of its own is on that history and is never pruned this
way; neither is a fast-forward merge (only the PR path catches those).
## When a worktree is removed
All of these must hold (`grove_core::prune::prune_merged`):
1. The repo is bare layout, the fetch of this pass worked, and the pass is not offline.
2. The worktree is on a branch that is not `.bare`'s HEAD (the default branch), and it lives
2. The worktree is on a branch that is not `.bare`'s HEAD (the default branch) nor in
`prune_protected`, and it lives
inside the repo directory (`root/<group>/<repo>/...`, so nested ones such as
`main/.claude/worktrees/x` count). Linked worktrees elsewhere are the user's and are never
touched.
3. A merged PR has that branch as head and its head commit equals the local tip, or contains it
(the PR got more commits from another machine before the merge).
(the PR got more commits from another machine before the merge); or, without a PR, the
ancestry rule above holds.
4. No local work: no staged, modified or untracked file, no git operation in progress
(`index.lock`, rebase, merge, cherry-pick, revert, bisect), and no ignored entry whose name
is not in `prune_disposable` (`.env` keeps it, `target/` does not).
@@ -66,10 +83,12 @@ branch after the merge are new work: the worktree is materialized again.
error changes).
- Offline passes (backoff) prune nothing, but still use the last answer to keep pruned branches
from being materialized.
- Activity log: `pruned_merged` (removed, with the PR, path and backup ref) and `prune_kept`.
- The ancestry rule runs on every online pass, also when the forge lookup fails.
- Activity log: `pruned_merged` (removed, with the PR or "merged into the default branch", path
and backup ref) and `prune_kept`.
`grove sync <path>` does the same in one shot (no cache) and prints `pruned ...` / `kept ...`
lines; a failed lookup is a warning and prunes nothing.
lines; a failed lookup is a warning, and only the ancestry rule applies.
## Validation