Compare commits

...
36 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
dasemu 425980e27f Merge pull request #8 from Dasemu/development
Development
2026-11-17 13:45:38 +01:00
dasemu 206130df98 Merge pull request #7 from Dasemu/claude/funny-planck-2b88wj
feat(daemon): prune worktrees merged through a pull request
2026-11-16 22:46:15 +01:00
Claude e9ac627863 feat(daemon): prune worktrees merged through a pull request
The daemon asks the forge (GitHub, Gitea/Forgejo) which pull requests were
merged and removes the local worktree and branch of each merged head that
holds no local work. Squash/rebase merges and head branches kept on the
forge are covered; regenerable ignored output (target/, node_modules...)
does not keep a worktree, any other ignored file does. The tip is kept in a
refs/sync-backup/<machine>/<stamp>/merged/<branch> ref, and materialize no
longer brings a pruned branch back unless it gets new commits.

New config: sync.prune_merged (default true) and sync.prune_disposable.
See docs/prune-merged.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011GZUAKXXztS4Hy4F4sSRkc
2026-11-16 21:41:56 +00:00
dasemu d281c91c30 Merge pull request #6 from Dasemu/development
Development
2026-11-16 22:25:28 +01:00
dasemu 8cb87d9a37 Merge pull request #5 from Dasemu/docs/two-pc-run
docs: record the real two-PC run
2026-11-16 22:24:46 +01:00
dasemuandClaude Opus 5.5 ca8a2986dc docs: record the real two-PC run
Snapshot from Dasemu-PC reached Dasemu-LT as refs/sync-remote/Dasemu-PC/main.
Also logs the install on the second machine and two open questions
(systemd PATH for tea/gh, leftover extensions.worktreeConfig).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:23:31 +01:00
dasemu a5c7cc307b Merge pull request #4 from Dasemu/feat/purge-deleted-remotes
feat(daemon): move repos deleted on their forge to Purged/
2026-11-16 22:22:46 +01:00
dasemuandClaude Opus 5.5 d1d1fa29f3 feat(daemon): move repos deleted on their forge to Purged/
When a fetch fails with a not-found error, the daemon asks the forge:
a 404 for a repo owned by the token's account (or an `owners` org),
with a working token, still confirmed 10 min later, moves the repo to
root/<sync.purged_dir>/<group>/<repo> (default "Purged"), where it is
no longer synced. Never deleted; worktree links repaired; skipped while
busy or with a git operation in progress.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:22:31 +01:00
dasemu 9340a436d5 Merge pull request #3 from Dasemu/fix/daemon-detect-inplace-migration
fix(daemon): never block the sync loop on a prompt or a stuck git call
2026-11-16 22:00:06 +01:00
dasemuandClaude Opus 5.5 4c355b28ef fix(daemon): never block the sync loop on a prompt or a stuck git call
The daemon inherited the desktop session's SSH_ASKPASS (ksshaskpass), so
an ssh passphrase/host-key prompt opened a dialog nobody answered, and
git had no time limit: the single sync loop stalled for 1.5 h and repos
migrated meanwhile were never picked up.

- groved sets a non-interactive git env (no terminal/askpass prompts,
  HTTP low-speed abort) and leaves the ssh command to the user/repo.
- Git calls get an optional wall-clock limit (daemon: 900 s); on expiry
  the whole process group (git, ssh, helpers) is killed.
- Secret Service lookups time out like the forge CLIs (locked keyring).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:59:44 +01:00
dasemu d414862dec Merge pull request #2 from Dasemu/development
Development
2026-11-16 21:42:55 +01:00
dasemu 5f33bb9327 Merge pull request #1 from Dasemu/docs/github-primary
docs: GitHub is the primary remote
2026-11-16 21:37:06 +01:00
dasemuandClaude Opus 5.5 41e7c785af docs: GitHub is the primary remote, Gitea a pull mirror
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:36:27 +01:00
44 changed files with 4786 additions and 167 deletions

No files matched your search

+3
View File
@@ -11,6 +11,9 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Shell syntax - name: Shell syntax
run: for f in spikes/*.sh; do bash -n "$f"; done 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) - name: Rust (once a Cargo workspace exists)
if: hashFiles('Cargo.toml') != '' if: hashFiles('Cargo.toml') != ''
run: | run: |
+6 -4
View File
@@ -4,7 +4,9 @@
Linux tool that keeps chosen git repos continuously in sync across machines, including Linux tool that keeps chosen git repos continuously in sync across machines, including
uncommitted work, via snapshot refs (`refs/sync/<machine>/<branch>`) on a primary remote. uncommitted work, via snapshot refs (`refs/sync/<machine>/<branch>`) on a primary remote.
Rust workspace: `grove-core`, `grove` (CLI), `grove-daemon` (`groved`), `grove-providers` (Gitea/Forgejo/GitHub), 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 is still pending. `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/`. Do not start new work before the previous results are written to `docs/`.
## Commands ## Commands
@@ -17,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` - Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh`
## Architecture ## Architecture
See `docs/` (`phase0-spike.md` ... `phase7.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 system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the
user's branch or index. user's branch or index.
@@ -28,8 +30,8 @@ user's branch or index.
- The daemon manages only bare-layout repos at `root/<group>/<repo>` and pushes WIP snapshots only to private repos by default (`sync.snapshots`, per-group override); see `docs/phase6.md`. - The daemon manages only bare-layout repos at `root/<group>/<repo>` and pushes WIP snapshots only to private repos by default (`sync.snapshots`, per-group override); see `docs/phase6.md`.
## Workflow quirks ## Workflow quirks
- Remote: Gitea `git.zenvairo.es`, owner `dasemu` (section `Darío`), CLI `tea`. SSH (port 22) - Remote: public GitHub `Dasemu/Grove` over SSH, CLI `gh`; PRs target `development` there.
is unreachable from the dev machine; use HTTPS with `git -c credential.helper='!tea login helper'`. `git.zenvairo.es/dasemu/Grove` is a read-only pull mirror of it (never push to it).
- In zsh, aliases like `g`/`gg` shadow shell functions; use unusual function names in scripts. - In zsh, aliases like `g`/`gg` shadow shell functions; use unusual function names in scripts.
- Throwaway repos created on the real Gitea for tests must be deleted afterwards. - Throwaway repos created on the real Gitea for tests must be deleted afterwards.
+17
View File
@@ -3,6 +3,23 @@
Keeps your git repos in sync across machines without manual commit/push/pull, including 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. 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 ## License
MIT, see `LICENSE`. MIT, see `LICENSE`.
+1 -1
View File
@@ -1 +1 @@
0.1.0 0.1.2
+243 -1
View File
@@ -17,6 +17,45 @@ pub struct Config {
pub sync: Sync, pub sync: Sync,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub config_repo: Option<ConfigRepo>, 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)] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
@@ -155,6 +194,35 @@ pub struct Sync {
/// Default snapshot push policy; a group can override it. /// Default snapshot push policy; a group can override it.
#[serde(default)] #[serde(default)]
pub snapshots: SnapshotPolicy, pub snapshots: SnapshotPolicy,
/// Directory under the root that repos deleted on their forge are moved to (and so stop
/// syncing). Empty disables the move.
#[serde(default = "default_purged_dir")]
pub purged_dir: String,
/// Remove worktrees whose branch was merged through a pull request on the forge (when they
/// hold no local work).
#[serde(default = "yes")]
pub prune_merged: bool,
/// Ignored files/directories (matched by name) that may be deleted with a pruned worktree:
/// 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 { impl Default for Sync {
@@ -165,6 +233,11 @@ impl Default for Sync {
ignore_extra: Vec::new(), ignore_extra: Vec::new(),
max_file_mb: default_max_file_mb(), max_file_mb: default_max_file_mb(),
snapshots: SnapshotPolicy::default(), snapshots: SnapshotPolicy::default(),
purged_dir: default_purged_dir(),
prune_merged: true,
prune_disposable: default_disposable(),
prune_protected: Vec::new(),
workers: default_workers(),
} }
} }
} }
@@ -178,12 +251,45 @@ pub struct ConfigRepo {
fn yes() -> bool { fn yes() -> bool {
true true
} }
fn default_workers() -> usize {
4
}
fn default_debounce() -> u64 { fn default_debounce() -> u64 {
2000 2000
} }
fn default_max_file_mb() -> u64 { fn default_max_file_mb() -> u64 {
50 50
} }
fn default_purged_dir() -> String {
"Purged".into()
}
fn default_disposable() -> Vec<String> {
[
"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",
]
.into_iter()
.map(String::from)
.collect()
}
fn default_fetch() -> u64 { fn default_fetch() -> u64 {
60 60
} }
@@ -275,6 +381,35 @@ impl Config {
"machine.name {n:?} must be non-empty and use only letters, digits, '-' or '_'" "machine.name {n:?} must be non-empty and use only letters, digits, '-' or '_'"
)); ));
} }
let pd = &self.sync.purged_dir;
if !pd.is_empty() {
if pd.starts_with('.') || pd.contains(['/', '\\']) {
return bad(format!(
"sync.purged_dir {pd:?} must be a plain directory name"
));
}
if self.groups.iter().any(|g| &g.name == pd) {
return bad(format!(
"sync.purged_dir {pd:?} is also a group: purged repos would keep syncing"
));
}
}
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
.iter()
.find(|d| d.is_empty() || *d == "." || *d == ".." || d.contains(['/', '\\']))
{
return bad(format!(
"sync.prune_disposable entry {d:?} must be a plain file or directory name"
));
}
for g in &self.groups { for g in &self.groups {
// Group names are directory names under the root. // Group names are directory names under the root.
if g.name.is_empty() || g.name.starts_with('.') || g.name.contains(['/', '\\']) { if g.name.is_empty() || g.name.starts_with('.') || g.name.contains(['/', '\\']) {
@@ -328,11 +463,42 @@ impl Config {
{ {
return bad(format!("config_repo: unknown provider {:?}", c.provider)); 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(()) 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")) { match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
(Some(rest), Some(home)) => PathBuf::from(home).join(rest), (Some(rest), Some(home)) => PathBuf::from(home).join(rest),
_ if p == "~" => std::env::var_os("HOME").map_or_else(|| PathBuf::from(p), PathBuf::from), _ if p == "~" => std::env::var_os("HOME").map_or_else(|| PathBuf::from(p), PathBuf::from),
@@ -383,6 +549,49 @@ name = "grove-config"
assert_eq!(c.root_path(), PathBuf::from("/x")); assert_eq!(c.root_path(), PathBuf::from("/x"));
} }
#[test]
fn prune_merged_defaults_on_and_disposable_names_are_plain() {
let base = "[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n";
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}");
}
}
#[test]
fn purged_dir_defaults_and_must_not_be_a_group() {
let base = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"github\"\n";
assert_eq!(Config::parse(base).unwrap().sync.purged_dir, "Purged");
let off = format!("{base}[sync]\npurged_dir=\"\"\n");
assert_eq!(Config::parse(&off).unwrap().sync.purged_dir, "");
for bad in [
format!("{base}[sync]\npurged_dir=\"a/b\"\n"),
format!("{base}[sync]\npurged_dir=\".x\"\n"),
format!("{base}[[groups]]\nname=\"Purged\"\nprimary=\"p\"\n"),
] {
assert!(
matches!(Config::parse(&bad), Err(ConfigError::Invalid(_))),
"{bad}"
);
}
}
#[test] #[test]
fn rejects_unsafe_machine_name() { fn rejects_unsafe_machine_name() {
for n in ["", "a/b", "a b", "a..b"] { for n in ["", "a/b", "a b", "a..b"] {
@@ -512,6 +721,39 @@ mirror_to = ["gitea"]
assert!(matches!(Config::parse(t), Err(ConfigError::Parse(_)))); 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] #[test]
fn provider_protocol_defaults_to_https_and_is_validated() { fn provider_protocol_defaults_to_https_and_is_validated() {
let t = |p: &str| { let t = |p: &str| {
+129 -3
View File
@@ -4,7 +4,74 @@ use std::ffi::OsStr;
use std::fmt; use std::fmt;
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
/// Wall-clock limit for one git invocation in seconds; 0 (the default) means none.
static TIMEOUT_SECS: AtomicU64 = AtomicU64::new(0);
/// Sets a wall-clock limit for every git invocation of this process (0 disables it). Meant for
/// the daemon, whose single sync loop must never block forever on a stuck fetch, hook or helper.
pub fn set_timeout(secs: u64) {
TIMEOUT_SECS.store(secs, Ordering::Relaxed);
}
/// Runs `cmd`, killing it (and its process group: ssh, helpers) when it outlives the limit.
fn output(cmd: Command, args: &[String]) -> Result<Output, GitError> {
output_within(cmd, args, TIMEOUT_SECS.load(Ordering::Relaxed))
}
fn output_within(mut cmd: Command, args: &[String], secs: u64) -> Result<Output, GitError> {
if secs == 0 {
return Ok(cmd.output()?);
}
use std::io::Read;
use std::os::unix::process::CommandExt;
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0);
let mut child = cmd.spawn()?;
let reader = |mut r: Box<dyn Read + Send>| {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = r.read_to_end(&mut buf);
let _ = tx.send(buf);
});
rx
};
let out_rx = reader(Box::new(child.stdout.take().expect("piped")));
let err_rx = reader(Box::new(child.stderr.take().expect("piped")));
let deadline = Instant::now() + Duration::from_secs(secs);
let mut nap = Duration::from_millis(1);
let status = loop {
if let Some(st) = child.try_wait()? {
break st;
}
if Instant::now() >= deadline {
let _ = Command::new("kill")
.args(["-KILL", "--", &format!("-{}", child.id())])
.status();
let _ = child.kill();
let _ = child.wait();
return Err(GitError::Other(format!(
"git {} timed out after {secs} s and was killed",
args.join(" ")
)));
}
std::thread::sleep(nap);
nap = (nap * 2).min(Duration::from_millis(100));
};
// A lingering ssh master (ControlPersist) may keep the pipes open after git exits.
let grace = Duration::from_secs(2);
Ok(Output {
status,
stdout: out_rx.recv_timeout(grace).unwrap_or_default(),
stderr: err_rx.recv_timeout(grace).unwrap_or_default(),
})
}
#[derive(Debug)] #[derive(Debug)]
pub enum GitError { pub enum GitError {
@@ -37,6 +104,10 @@ impl From<io::Error> for GitError {
} }
} }
fn owned(args: &[&str]) -> Vec<String> {
args.iter().map(|s| s.to_string()).collect()
}
/// A git invocation context: a working directory plus extra environment. /// A git invocation context: a working directory plus extra environment.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Git { pub struct Git {
@@ -73,7 +144,7 @@ impl Git {
/// Run git, returning trimmed stdout. Any non-zero exit is an error. /// Run git, returning trimmed stdout. Any non-zero exit is an error.
pub fn run(&self, args: &[&str]) -> Result<String, GitError> { pub fn run(&self, args: &[&str]) -> Result<String, GitError> {
let out = self.command(args).output()?; let out = output(self.command(args), &owned(args))?;
if out.status.success() { if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else { } else {
@@ -87,7 +158,7 @@ impl Git {
/// Run git; a non-zero exit yields `None` (for probes like `rev-parse --verify`). /// Run git; a non-zero exit yields `None` (for probes like `rev-parse --verify`).
pub fn probe(&self, args: &[&str]) -> Result<Option<String>, GitError> { pub fn probe(&self, args: &[&str]) -> Result<Option<String>, GitError> {
let out = self.command(args).output()?; let out = output(self.command(args), &owned(args))?;
if out.status.success() { if out.status.success() {
Ok(Some( Ok(Some(
String::from_utf8_lossy(&out.stdout).trim().to_string(), String::from_utf8_lossy(&out.stdout).trim().to_string(),
@@ -97,3 +168,58 @@ impl Git {
} }
} }
} }
/// Environment that keeps unattended git from ever waiting on a person: no terminal or askpass
/// prompts (a desktop `SSH_ASKPASS` such as ksshaskpass would otherwise open a dialog and block
/// forever), and stalled HTTP transfers abort. The ssh command is left alone so a user's (or a
/// repo's) `core.sshCommand` keeps working; wall-clock limits come from [`set_timeout`].
pub fn noninteractive_env() -> Vec<(String, String)> {
[
("GIT_TERMINAL_PROMPT", "0"),
("GIT_ASKPASS", "true"),
("SSH_ASKPASS_REQUIRE", "never"),
("GIT_HTTP_LOW_SPEED_LIMIT", "1000"),
("GIT_HTTP_LOW_SPEED_TIME", "60"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
/// Whether the user configured their own ssh command for git (env or `core.sshCommand`).
pub fn has_custom_ssh() -> bool {
std::env::var_os("GIT_SSH_COMMAND").is_some()
|| std::env::var_os("GIT_SSH").is_some()
|| std::process::Command::new("git")
.args(["config", "--get", "core.sshCommand"])
.output()
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty())
}
#[cfg(test)]
mod env_tests {
use super::*;
#[test]
fn unattended_git_never_prompts_and_leaves_the_ssh_command_alone() {
let env = noninteractive_env();
let get = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
assert_eq!(get("GIT_TERMINAL_PROMPT"), Some("0"));
assert_eq!(get("SSH_ASKPASS_REQUIRE"), Some("never"));
assert_eq!(get("GIT_SSH_COMMAND"), None);
}
#[test]
fn a_git_call_over_the_limit_is_killed() {
// A hook-like stall: `git -c alias.x='!sleep 30' x`. The global limit is not touched, so
// tests running in parallel are unaffected.
let args = owned(&["-c", "alias.zzsleep=!sleep 30", "zzsleep"]);
let t = Instant::now();
let r = output_within(Git::new(".").command(&args), &args, 1);
assert!(r.unwrap_err().to_string().contains("timed out"));
assert!(t.elapsed() < Duration::from_secs(10));
let v = owned(&["--version"]);
let out = output_within(Git::new(".").command(&v), &v, 5).unwrap();
assert!(String::from_utf8_lossy(&out.stdout).starts_with("git version"));
}
}
+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());
}
}
+2
View File
@@ -8,8 +8,10 @@ pub mod busy;
pub mod config; pub mod config;
pub mod git; pub mod git;
pub mod inspect; pub mod inspect;
pub mod launch;
pub mod layout; pub mod layout;
pub mod migrate; pub mod migrate;
pub mod prune;
pub mod receive; pub mod receive;
pub mod registry; pub mod registry;
pub mod resolve; pub mod resolve;
+273
View File
@@ -0,0 +1,273 @@
//! Removing worktrees whose work is already merged.
//!
//! 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;
use crate::receive::backup_ref;
use std::path::{Path, PathBuf};
/// The head of a pull request merged on the forge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergedHead {
pub number: u64,
/// Branch name of the pull request's head (in the same repo; fork PRs are left out).
pub branch: String,
/// Commit the pull request's head pointed at when it was merged.
pub sha: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pruned {
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
Removed {
branch: String,
/// 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: 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";
/// An operation in progress in `worktree` that removing it would break.
pub fn operation_in_progress(worktree: &Path) -> Option<&'static str> {
let gd = Git::new(worktree)
.run(&["rev-parse", "--absolute-git-dir"])
.ok()?;
let gd = PathBuf::from(gd);
[
"index.lock",
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
]
.into_iter()
.find(|f| gd.join(f).exists())
}
/// Why `worktree` holds local work, if it does. Ignored entries whose last path component is
/// in `disposable` (build output, dependency caches) do not count.
fn local_work(worktree: &Path, disposable: &[String]) -> Result<Option<String>, GitError> {
if let Some(op) = operation_in_progress(worktree) {
return Ok(Some(format!("git operation in progress ({op})")));
}
let st = Git::new(worktree).run(&["status", "--porcelain", "--ignored", "-z"])?;
let mut kept = Vec::new();
for entry in st.split('\0').filter(|e| e.len() > 3) {
let (code, path) = entry.split_at(3);
if code != "!! " {
return Ok(Some("uncommitted or untracked changes".into()));
}
let last = path
.trim_end_matches('/')
.rsplit('/')
.next()
.unwrap_or(path);
if !disposable.iter().any(|d| d == last) {
kept.push(path.to_string());
}
}
if kept.is_empty() {
return Ok(None);
}
kept.truncate(5);
Ok(Some(format!("ignored files: {}", kept.join(", "))))
}
fn is_ancestor(g: &Git, a: &str, b: &str) -> bool {
matches!(g.probe(&["merge-base", "--is-ancestor", a, b]), Ok(Some(_)))
}
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,
rules: &Rules,
machine: &str,
stamp: &str,
) -> Result<Vec<Pruned>, GitError> {
let bare = root.join(".bare");
let g = Git::new(&bare);
let default = g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?;
let canonical_root = root.canonicalize()?;
let mut out = Vec::new();
for wt in worktrees(&bare)? {
let Some(branch) = wt.branch.as_deref() else {
continue;
};
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, 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))
.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, rules.disposable)? {
out.push(Pruned::Kept {
branch: branch.to_string(),
pr,
why,
});
continue;
}
let bref = backup_ref(machine, stamp, &format!("{KIND}/{branch}"));
g.run(&["update-ref", &bref, &tip])?;
// `--force`: the only files left are disposable ignored ones (checked above).
g.run(&["worktree", "remove", "--force", &wt.path.to_string_lossy()])?;
g.run(&["branch", "-D", branch])?;
out.push(Pruned::Removed {
branch: branch.to_string(),
pr,
path: wt.path.clone(),
backup_ref: bref,
});
}
Ok(out)
}
/// 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. 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);
let backups = g.run(&[
"for-each-ref",
"--format=%(objectname) %(refname)",
&format!("refs/sync-backup/{machine}/"),
])?;
let pruned: Vec<(&str, &str)> = backups
.lines()
.filter_map(|l| l.split_once(' '))
.filter_map(|(sha, r)| {
let rest = r.strip_prefix(&format!("refs/sync-backup/{machine}/"))?;
let (_, kind) = rest.split_once('/')?;
Some((sha, kind.strip_prefix(&format!("{KIND}/"))?))
})
.collect();
let prefix = format!("refs/remotes/{remote}/");
let tips = g.run(&["for-each-ref", "--format=%(objectname) %(refname)", &prefix])?;
Ok(tips
.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)
})
.map(|(_, b)| b.to_string())
.collect())
}
+30 -1
View File
@@ -45,6 +45,7 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
"-z", "-z",
])?; ])?;
let ignored: Vec<&str> = ignored.split('\0').filter(|p| !p.is_empty()).collect(); 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 Ok(added
.into_iter() .into_iter()
.filter(|a| { .filter(|a| {
@@ -52,10 +53,26 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
.iter() .iter()
.any(|i| a == i || (i.ends_with('/') && a.starts_with(i))) .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) .map(String::from)
.collect()) .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> { fn current_branch(g: &Git) -> Result<String, GitError> {
g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])? g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD".into())) .ok_or_else(|| GitError::Other("detached HEAD".into()))
@@ -345,6 +362,15 @@ pub fn apply_snapshot(
/// Create worktrees under `root` for remote branches that have none. Returns new paths. /// Create worktrees under `root` for remote branches that have none. Returns new paths.
pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError> { pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError> {
materialize_except(root, remote, &[])
}
/// Like [`materialize`], leaving out the branches in `skip` (e.g. merged ones that were pruned).
pub fn materialize_except(
root: &Path,
remote: &str,
skip: &[String],
) -> Result<Vec<PathBuf>, GitError> {
let bare = root.join(".bare"); let bare = root.join(".bare");
let g = Git::new(&bare); let g = Git::new(&bare);
let prefix = format!("refs/remotes/{remote}/"); let prefix = format!("refs/remotes/{remote}/");
@@ -362,7 +388,10 @@ pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError>
let Some(branch) = r.strip_prefix(&prefix) else { let Some(branch) = r.strip_prefix(&prefix) else {
continue; continue;
}; };
if branch == "HEAD" || existing_branches.iter().any(|b| b == branch) { if branch == "HEAD"
|| existing_branches.iter().any(|b| b == branch)
|| skip.iter().any(|b| b == branch)
{
continue; continue;
} }
let refs: Vec<&str> = taken.iter().map(String::as_str).collect(); let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
+7
View File
@@ -225,6 +225,13 @@ mod tests {
fs::write(locked.join("f"), "x").unwrap(); fs::write(locked.join("f"), "x").unwrap();
fs::write(d.join(crate::busy::BUSY), "1 1\n").unwrap(); fs::write(d.join(crate::busy::BUSY), "1 1\n").unwrap();
fs::set_permissions(&locked, fs::Permissions::from_mode(0o500)).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); rollback_clone(&d);
assert!(d.join(".grove-stage").exists()); assert!(d.join(".grove-stage").exists());
assert!( assert!(
+4 -1
View File
@@ -47,7 +47,10 @@ fn temp_index_path() -> PathBuf {
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos()) .map(|d| d.as_nanos())
.unwrap_or(0); .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), /// Tree of everything in the worktree (tracked changes and untracked files, not ignored ones),
+31 -3
View File
@@ -1,11 +1,13 @@
//! One full sync pass over a repo: snapshot, push, fetch, receive, apply, materialize, archive. //! One full sync pass over a repo: snapshot, push, fetch, receive, apply, materialize, archive,
//! prune merged.
//! Failures of individual steps are reported per worktree and never abort the whole pass. //! Failures of individual steps are reported per worktree and never abort the whole pass.
use crate::git::{Git, GitError}; use crate::git::{Git, GitError};
use crate::inspect::{facts, state, worktrees}; use crate::inspect::{facts, state, worktrees};
use crate::prune::{MergedHead, Pruned, Rules, prune_merged, settled_branches};
use crate::receive::{ use crate::receive::{
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots, Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
materialize, push_snapshot, receive, materialize_except, push_snapshot, receive,
}; };
use crate::snapshot::{Outcome, ref_name, take}; use crate::snapshot::{Outcome, ref_name, take};
use crate::state::State; use crate::state::State;
@@ -24,6 +26,16 @@ pub struct Options {
/// repo, or `snapshots = "none"`) no `refs/sync/<machine>/*` ref is created or pushed; /// repo, or `snapshots = "none"`) no `refs/sync/<machine>/*` ref is created or pushed;
/// fetching, fast-forwarding and applying other machines' snapshots are unaffected. /// fetching, fast-forwarding and applying other machines' snapshots are unaffected.
pub push_snapshots: bool, pub push_snapshots: bool,
/// Heads of pull requests merged on the forge (empty: unknown or pruning disabled).
/// Worktrees of those branches without local work are removed (bare layout only), and
/// `materialize` does not bring them back.
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)] #[derive(Debug, Clone, PartialEq)]
@@ -44,6 +56,7 @@ pub struct SyncReport {
pub fetch_error: Option<String>, pub fetch_error: Option<String>,
pub materialized: Vec<PathBuf>, pub materialized: Vec<PathBuf>,
pub archived: Vec<Archived>, pub archived: Vec<Archived>,
pub pruned: Vec<Pruned>,
pub worktrees: Vec<WorktreeReport>, pub worktrees: Vec<WorktreeReport>,
} }
@@ -72,7 +85,22 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
Ok(a) => rep.archived = a, Ok(a) => rep.archived = a,
Err(e) => rep.fetch_error = Some(format!("archive: {e}")), Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
} }
match materialize(path, &o.remote) { }
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.protected, &o.machine);
match skip.and_then(|skip| materialize_except(path, &o.remote, &skip)) {
Ok(m) => rep.materialized = m, Ok(m) => rep.materialized = m,
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")), Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
} }
+298
View File
@@ -0,0 +1,298 @@
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::migrate::migrate;
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};
struct World {
_tmp: tmp::TempDir,
base: PathBuf,
/// Another machine's plain clone (plays the forge user who merges).
dev: Git,
/// This machine's bare-layout repo.
root: PathBuf,
}
fn world() -> World {
let tmp = tmpdir("prune");
let base = tmp.to_path_buf();
let remote = base.join("remote.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let dev = init(&base.join("dev"));
dev.run(&["remote", "add", "origin", remote.to_str().unwrap()])
.unwrap();
commit(&dev, ".gitignore", "*.env\ntarget/\n");
dev.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
let d = base.join("me");
Git::new(&base)
.run(&["clone", "-q", remote.to_str().unwrap(), d.to_str().unwrap()])
.unwrap();
migrate(&d, "me", &base.join("bk"), "1").unwrap();
World {
_tmp: tmp,
base,
dev,
root: d.canonicalize().unwrap(),
}
}
fn opts(stamp: &str, merged: Vec<MergedHead>) -> Options {
Options {
machine: "me".into(),
stamp: stamp.into(),
remote: "origin".into(),
offline: false,
materialize: true,
push_snapshots: false,
merged,
disposable: vec!["target".into()],
prune: true,
protected: default_protected(),
}
}
/// Pushes branch `b` with one commit from `dev` and returns its tip.
fn push_branch(w: &World, b: &str) -> String {
w.dev.run(&["checkout", "-q", "-b", b, "main"]).unwrap();
commit(&w.dev, &format!("{}.txt", b.replace('/', "-")), "x\n");
w.dev.run(&["push", "-q", "-u", "origin", b]).unwrap();
let tip = w.dev.run(&["rev-parse", "HEAD"]).unwrap();
w.dev.run(&["checkout", "-q", "main"]).unwrap();
tip
}
/// A squash merge: the branch's content lands on main as a new commit (no ancestry), and the
/// head branch stays on the remote.
fn squash_merge(w: &World, b: &str) {
w.dev.run(&["merge", "-q", "--squash", b]).unwrap();
w.dev.run(&["commit", "-qm", "squash"]).unwrap();
w.dev.run(&["push", "-q", "origin", "main"]).unwrap();
}
fn head(n: u64, branch: &str, sha: &str) -> MergedHead {
MergedHead {
number: n,
branch: branch.into(),
sha: sha.into(),
}
}
fn has_branch(root: &Path, b: &str) -> bool {
Git::new(root.join(".bare"))
.probe(&["rev-parse", "-q", "--verify", &format!("refs/heads/{b}")])
.unwrap()
.is_some()
}
#[test]
fn a_squash_merged_worktree_is_removed_and_not_brought_back() {
let w = world();
let tip = push_branch(&w, "feat/x");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
let wt = w.root.join("feat-x");
assert!(wt.exists());
// Build output is regenerable: it does not keep the worktree.
fs::create_dir_all(wt.join("target/debug")).unwrap();
fs::write(wt.join("target/debug/bin"), "b").unwrap();
squash_merge(&w, "feat/x");
let rep = sync_repo(&w.root, &opts("s2", vec![head(7, "feat/x", &tip)])).unwrap();
assert!(rep.fetch_error.is_none(), "{:?}", rep.fetch_error);
let [
Pruned::Removed {
branch,
pr,
backup_ref,
..
},
] = rep.pruned.as_slice()
else {
panic!("{:?}", rep.pruned);
};
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);
assert!(rep.materialized.is_empty(), "{:?}", rep.materialized);
// The remote branch is still there; later passes (even without a forge answer) leave it.
let rep = sync_repo(&w.root, &opts("s3", vec![])).unwrap();
assert!(rep.materialized.is_empty() && !wt.exists());
// New commits on the branch after the merge are new work: it comes back.
w.dev.run(&["checkout", "-q", "feat/x"]).unwrap();
commit(&w.dev, "more.txt", "m\n");
w.dev.run(&["push", "-q", "origin", "feat/x"]).unwrap();
let rep = sync_repo(&w.root, &opts("s4", vec![head(7, "feat/x", &tip)])).unwrap();
assert_eq!(rep.materialized, vec![wt.clone()]);
assert!(rep.pruned.is_empty());
}
#[test]
fn local_work_keeps_a_merged_worktree() {
let w = world();
let tip = push_branch(&w, "a");
let tip_b = push_branch(&w, "b");
let tip_c = push_branch(&w, "c");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
fs::write(w.root.join("a/new.txt"), "untracked\n").unwrap();
fs::write(w.root.join("b/secret.env"), "ignored, not regenerable\n").unwrap();
// A local commit the merged PR does not have.
let gc = Git::new(w.root.join("c"));
gc.run(&["config", "user.email", "t@t"]).unwrap();
gc.run(&["config", "user.name", "t"]).unwrap();
commit(&gc, "local.txt", "l\n");
let merged = vec![
head(1, "a", &tip),
head(2, "b", &tip_b),
head(3, "c", &tip_c),
];
let rep = sync_repo(&w.root, &opts("s2", merged)).unwrap();
let mut kept: Vec<(String, String)> = rep
.pruned
.iter()
.map(|p| match p {
Pruned::Kept { branch, why, .. } => (branch.clone(), why.clone()),
other => panic!("{other:?}"),
})
.collect();
kept.sort();
assert_eq!(
kept,
vec![
("a".into(), "uncommitted or untracked changes".into()),
("b".into(), "ignored files: secret.env".into()),
]
);
for b in ["a", "b", "c"] {
assert!(w.root.join(b).exists() && has_branch(&w.root, b), "{b}");
}
}
#[test]
fn an_older_tip_is_pruned_but_the_default_branch_and_outside_worktrees_never_are() {
let w = world();
let first = push_branch(&w, "f");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
// The PR got more commits (from another machine) before it was merged.
w.dev.run(&["checkout", "-q", "f"]).unwrap();
commit(&w.dev, "f2.txt", "2\n");
w.dev.run(&["push", "-q", "origin", "f"]).unwrap();
let last = w.dev.run(&["rev-parse", "HEAD"]).unwrap();
w.dev.run(&["checkout", "-q", "main"]).unwrap();
assert_ne!(first, last);
// A linked worktree outside the repo directory is the user's.
let ext = w.base.join("elsewhere");
let bare = Git::new(w.root.join(".bare"));
let tip_o = push_branch(&w, "o");
bare.run(&["fetch", "-q", "origin"]).unwrap();
bare.run(&[
"worktree",
"add",
"-q",
"-b",
"o",
ext.to_str().unwrap(),
"origin/o",
])
.unwrap();
let main_tip = bare.run(&["rev-parse", "refs/heads/main"]).unwrap();
// `prune_merged` alone: `f` is still at `first` locally (no fetch/fast-forward).
let merged = vec![
head(4, "f", &last),
head(5, "main", &main_tip),
head(6, "o", &tip_o),
];
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: 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());
}
+50
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] #[test]
fn snapshot_apply_declines_instead_of_overwriting_local_ignored_file() { fn snapshot_apply_declines_instead_of_overwriting_local_ignored_file() {
let w = world(); let w = world();
@@ -386,6 +432,10 @@ fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
offline: false, offline: false,
materialize: true, materialize: true,
push_snapshots: true, push_snapshots: true,
merged: vec![],
disposable: vec![],
prune: false,
protected: vec![],
}; };
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap(); w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
commit(&w.g1, "z.txt", "z\n"); commit(&w.g1, "z.txt", "z\n");
+4
View File
@@ -16,6 +16,10 @@ fn opts(machine: &str, stamp: &str) -> Options {
offline: false, offline: false,
materialize: true, materialize: true,
push_snapshots: true, push_snapshots: true,
merged: vec![],
disposable: vec![],
prune: false,
protected: vec![],
} }
} }
+332 -37
View File
@@ -1,12 +1,16 @@
//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything //! 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, //! the watcher missed, failures back off exponentially. The loop thread schedules; a pool of
//! so passes never overlap. //! `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::activity::{Activity, now_secs};
use crate::discover::{discover, group_of, is_ready, subdirs}; use crate::discover::{discover, group_of, is_ready, subdirs};
use crate::ipc; use crate::ipc;
use crate::merged::{MergedCache, has_candidates};
use crate::purge;
use crate::visibility::{RealForge, Visibility, snapshot_gate}; use crate::visibility::{RealForge, Visibility, snapshot_gate};
use grove_core::config::Config; use grove_core::config::Config;
use grove_core::prune::{Pruned, merged_how};
use grove_core::receive::Received; use grove_core::receive::Received;
use grove_core::sync::{Options, sync_repo}; use grove_core::sync::{Options, sync_repo};
use notify::{EventKind, RecursiveMode, Watcher}; use notify::{EventKind, RecursiveMode, Watcher};
@@ -96,9 +100,72 @@ pub enum Msg {
Rescan, Rescan,
/// Sync one repo (or all) as soon as possible. /// Sync one repo (or all) as soon as possible.
SyncNow(Option<PathBuf>), 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, 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)] #[derive(Clone)]
pub struct Ctx { pub struct Ctx {
pub shared: Arc<Mutex<Shared>>, pub shared: Arc<Mutex<Shared>>,
@@ -334,6 +401,7 @@ fn rescan(
root: &Path, root: &Path,
groups: &[String], groups: &[String],
watch: &mut Watch, watch: &mut Watch,
running: &HashSet<PathBuf>,
ctx: &Ctx, ctx: &Ctx,
) -> (Vec<PathBuf>, Vec<PathBuf>) { ) -> (Vec<PathBuf>, Vec<PathBuf>) {
// Shallow watches first, then discover: a `.bare` created in a child between the two steps // Shallow watches first, then discover: a `.bare` created in a child between the two steps
@@ -350,8 +418,16 @@ fn rescan(
} }
} }
watch.sync(&wanted, false, ctx); watch.sync(&wanted, false, ctx);
let d = discover(root, groups); let mut d = discover(root, groups);
let found = d.managed; // 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 { for r in &d.stalled {
if watch.warned_stalled.insert(r.clone()) { if watch.warned_stalled.insert(r.clone()) {
ctx.activity.log( ctx.activity.log(
@@ -406,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 fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
let root = cfg.root_path(); let root = cfg.root_path();
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect(); 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( let mut watch = make_watch(
ctx.tx.clone(), ctx.tx.clone(),
cfg.sync.ignore_extra.clone(), cfg.sync.ignore_extra.clone(),
@@ -414,7 +509,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
groups.clone(), groups.clone(),
&ctx, &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. // due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new(); let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
@@ -427,11 +522,15 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back). // When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
let mut rescan_at: Option<Instant> = None; let mut rescan_at: Option<Instant> = None;
loop { 'main: loop {
let now = Instant::now(); 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 let wake = due_at
.values() .iter()
.copied() .filter(|(r, _)| idle && !running.contains(*r))
.map(|(_, t)| *t)
.chain([next_full]) .chain([next_full])
.chain(rescan_at) .chain(rescan_at)
.min() .min()
@@ -462,19 +561,44 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
} }
Ok(Msg::SyncNow(Some(r))) => { Ok(Msg::SyncNow(Some(r))) => {
backoff_until.remove(&r); backoff_until.remove(&r);
if running.contains(&r) {
sync_asked.insert(r.clone());
}
due_at.insert(r, Instant::now()); due_at.insert(r, Instant::now());
} }
Ok(Msg::SyncNow(None)) => { Ok(Msg::SyncNow(None)) => {
backoff_until.clear(); backoff_until.clear();
sync_asked.extend(running.iter().cloned());
next_full = Instant::now(); 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, Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
} }
// Discovery also runs while paused so the status stays current; only syncing stops. // Discovery also runs while paused so the status stays current; only syncing stops.
if rescan_at.is_some_and(|t| t <= Instant::now()) { if rescan_at.is_some_and(|t| t <= Instant::now()) {
rescan_at = None; 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); forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
for r in added { for r in added {
due_at.insert(r, Instant::now()); due_at.insert(r, Instant::now());
@@ -486,20 +610,31 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let now = Instant::now(); let now = Instant::now();
if now >= next_full { if now >= next_full {
// Safety net for events the watcher missed (one `read_dir` per group). // 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); 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 { 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; 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() .iter()
.filter(|(_, t)| **t <= now) .filter(|(r, t)| **t <= now && !running.contains(*r))
.map(|(r, _)| r.clone()) .map(|(r, t)| (*t, r.clone()))
.collect(); .collect();
due.sort(); 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) { if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
due_at.remove(&r); due_at.remove(&r);
continue; continue;
@@ -508,35 +643,24 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
first_at.remove(&r); first_at.remove(&r);
if !is_ready(&r) { if !is_ready(&r) {
// Removed or migrated away since the last discovery: drop it, no error. // 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); forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
continue; continue;
} }
// While backing off after a failure, still snapshot local work (no network needed); // 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. // 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 offline = backoff_until.get(&r).is_some_and(|u| *u > now);
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &ctx); running.insert(r.clone());
if !is_ready(&r) { if jobs.send(Job { repo: r, offline }).is_err() {
// It vanished mid-pass: whatever the pass reported is moot. break 'main;
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;
} }
} }
} }
// 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"); ctx.activity.log("stop", None, "daemon stopped");
} }
@@ -552,15 +676,27 @@ fn forget_removed(
backoff_until.retain(|r, _| found.contains(r)); backoff_until.retain(|r, _| found.contains(r));
} }
/// 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: Mutex<HashMap<PathBuf, (u64, u64)>>,
/// Merged pull requests per repo (see `merged`).
merged: MergedCache,
}
/// One sync pass for `repo`; returns the number of consecutive failures (0 = success). /// One sync pass for `repo`; returns the number of consecutive failures (0 = success).
fn pass( fn pass(
repo: &Path, repo: &Path,
cfg: &Config, cfg: &Config,
st: &Settings, st: &Settings,
visibility: &mut Visibility, visibility: &Visibility,
offline: bool, offline: bool,
forge: &ForgeMemory,
ctx: &Ctx, ctx: &Ctx,
) -> u32 { ) -> u32 {
let ForgeMemory { gone_since, merged } = forge;
let name = repo.display().to_string(); let name = repo.display().to_string();
if !is_ready(repo) { if !is_ready(repo) {
// Being migrated/cloned (or gone): leave it alone, the rediscovery sorts it out. // Being migrated/cloned (or gone): leave it alone, the rediscovery sorts it out.
@@ -591,6 +727,22 @@ fn pass(
} }
allowed allowed
}; };
// Offline passes prune nothing; the last answer still keeps pruned branches away.
let merged_heads = if !cfg.sync.prune_merged || !has_candidates(repo) {
Vec::new()
} else if offline {
merged.cached(repo)
} else {
let h = merged.heads(cfg, repo, &st.remote, &RealForge, Instant::now());
if let Some(e) = h.new_error {
ctx.activity.log(
"prune_lookup_failed",
Some(&name),
format!("cannot list merged pull requests: {e}"),
);
}
h.heads
};
let opts = Options { let opts = Options {
machine: cfg.machine.name.clone(), machine: cfg.machine.name.clone(),
stamp: stamp(), stamp: stamp(),
@@ -598,8 +750,15 @@ fn pass(
offline, offline,
materialize, materialize,
push_snapshots, 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); let result = sync_repo(repo, &opts);
if !offline && purge_if_gone(repo, cfg, st, &result, gone_since, ctx) {
return 0;
}
let mut shared = ctx.shared.lock().unwrap(); let mut shared = ctx.shared.lock().unwrap();
// The repo may have been dropped by a rediscovery while the pass ran. // The repo may have been dropped by a rediscovery while the pass ran.
let Some(status) = shared.repos.get_mut(repo) else { let Some(status) = shared.repos.get_mut(repo) else {
@@ -664,6 +823,31 @@ fn pass(
for a in &rep.archived { for a in &rep.archived {
ctx.activity.log("archived", Some(&name), format!("{a:?}")); ctx.activity.log("archived", Some(&name), format!("{a:?}"));
} }
let mut kept = Vec::new();
for p in &rep.pruned {
match p {
Pruned::Removed {
branch,
pr,
path,
backup_ref,
} => ctx.activity.log(
"pruned_merged",
Some(&name),
format!(
"{branch}: {}; removed {} (tip kept in {backup_ref})",
merged_how(*pr),
path.display()
),
),
Pruned::Kept { branch, pr, why } => {
kept.push(format!("{branch}: {} but kept: {why}", merged_how(*pr)))
}
}
}
for k in merged.new_notes(repo, kept) {
ctx.activity.log("prune_kept", Some(&name), k);
}
} }
} }
if !errors.is_empty() && !is_ready(repo) { if !errors.is_empty() && !is_ready(repo) {
@@ -693,6 +877,117 @@ fn pass(
status.failures status.failures
} }
/// Moves `repo` out of the synced tree once its forge has kept confirming its deletion for
/// `purge::CONFIRM_AFTER_SECS`; returns true when it is gone from its place. A fetch that works,
/// or the forge seeing the repo, clears it; so does a gap of more than twice that interval
/// between confirmations.
fn purge_if_gone(
repo: &Path,
cfg: &Config,
st: &Settings,
result: &Result<grove_core::sync::SyncReport, grove_core::git::GitError>,
gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>,
ctx: &Ctx,
) -> bool {
let name = repo.display().to_string();
let hint = match result {
Ok(rep) => rep.fetch_error.as_deref().is_some_and(purge::looks_gone),
Err(_) => false,
};
if !hint || cfg.sync.purged_dir.is_empty() {
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
gone_since.lock().unwrap().remove(repo);
}
return false;
}
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
Ok(true) => {}
Ok(false) => {
gone_since.lock().unwrap().remove(repo);
return false;
}
// Cannot tell (network, token): keep whatever was confirmed before.
Err(_) => return false,
}
let now = now_secs();
let window = purge::CONFIRM_AFTER_SECS;
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",
Some(&name),
format!(
"the forge reports the remote repo deleted; moving it to {}/ if that still holds in {} min",
cfg.sync.purged_dir,
window / 60
),
);
}
if now.saturating_sub(first) < window {
return false;
}
let Some(dest) = purge::destination(&cfg.root_path(), &cfg.sync.purged_dir, repo, &stamp())
else {
return false;
};
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) {
Ok(moved) => {
gone(ctx, gone_since);
let mut msg = format!(
"remote repo deleted: moved to {} (no longer synced; files untouched)",
dest.display()
);
if !moved.unrepaired.is_empty() {
let list: Vec<String> = moved
.unrepaired
.iter()
.map(|p| p.display().to_string())
.collect();
msg.push_str(&format!(
"; worktrees not found, run `git worktree repair <path>` from {}/.bare once they are back: {}",
dest.display(),
list.join(", ")
));
}
ctx.activity.log("purged", Some(&name), msg);
true
}
Err(purge::MoveError::Repair(e)) => {
gone(ctx, gone_since);
ctx.activity.log(
"purged",
Some(&name),
format!(
"remote repo deleted: moved to {}, but repairing its worktree links failed ({e}); run `git worktree repair` there",
dest.display()
),
);
true
}
Err(purge::MoveError::NotMoved(e)) => {
ctx.activity.log(
"purge_failed",
Some(&name),
format!("not moved to {}: {e}", dest.display()),
);
false
}
}
}
/// Records why snapshots are withheld (or that they are pushed again), logging only changes. /// Records why snapshots are withheld (or that they are pushed again), logging only changes.
fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<String>) { fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<String>) {
let mut shared = ctx.shared.lock().unwrap(); let mut shared = ctx.shared.lock().unwrap();
+2
View File
@@ -6,6 +6,8 @@ pub mod activity;
pub mod daemon; pub mod daemon;
pub mod discover; pub mod discover;
pub mod ipc; pub mod ipc;
pub mod merged;
pub mod purge;
#[cfg(test)] #[cfg(test)]
#[path = "../../../test-support/tmp.rs"] #[path = "../../../test-support/tmp.rs"]
mod test_tmp; mod test_tmp;
+10
View File
@@ -5,6 +5,9 @@ use grove_core::config::Config;
use grove_daemon::{Daemon, Settings}; use grove_daemon::{Daemon, Settings};
use std::path::PathBuf; use std::path::PathBuf;
/// Upper bound for one git call of the daemon (a large first fetch included).
const GIT_TIMEOUT_SECS: u64 = 900;
fn main() -> Result<()> { fn main() -> Result<()> {
let mut args = std::env::args().skip(1); let mut args = std::env::args().skip(1);
let mut config: Option<PathBuf> = None; let mut config: Option<PathBuf> = None;
@@ -23,6 +26,13 @@ fn main() -> Result<()> {
.context("cannot determine config path")?; .context("cannot determine config path")?;
let cfg = Config::load(&path)?; let cfg = Config::load(&path)?;
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024); grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
// Unattended: git/ssh must never prompt (the session's SSH_ASKPASS would open a dialog and
// block every sync), and no git call may block the sync loop forever.
for (k, v) in grove_core::git::noninteractive_env() {
// SAFETY: still single-threaded; no other thread reads the environment yet.
unsafe { std::env::set_var(k, v) };
}
grove_core::git::set_timeout(GIT_TIMEOUT_SECS);
let st = Settings::standard(); let st = Settings::standard();
eprintln!( eprintln!(
"groved: machine {:?}, root {}, socket {}", "groved: machine {:?}, root {}, socket {}",
+256
View File
@@ -0,0 +1,256 @@
//! Which branches of a repo were merged through a pull request on its forge (`origin`), so
//! that their worktrees can be pruned (`grove_core::prune`).
//!
//! The daemon asks the forge at most every [`TTL`] per repo, and only for repos that have a
//! worktree on a branch other than the default one. A failed lookup keeps the last answer, so a
//! forge outage never makes `materialize` bring back worktrees that were pruned.
use crate::visibility::{RealForge, parse_remote, provider_for};
use grove_core::config::{Config, Provider as ProviderCfg};
use grove_core::git::Git;
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.
pub const TTL: Duration = Duration::from_secs(300);
/// Lists the merged pull requests of a repo on a forge.
pub trait PullSource {
fn merged(
&self,
id: &str,
pc: &ProviderCfg,
owner: &str,
name: &str,
) -> Result<Vec<MergedHead>, String>;
}
impl PullSource for RealForge {
fn merged(
&self,
id: &str,
pc: &ProviderCfg,
owner: &str,
name: &str,
) -> Result<Vec<MergedHead>, String> {
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
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()
.map(|p| MergedHead {
number: p.number,
branch: p.head_ref,
sha: p.head_sha,
})
.collect())
}
}
/// The merged pull requests of the repo at `repo` (bare layout), looked up on the forge that
/// serves its `remote` fetch URL.
pub fn lookup(
cfg: &Config,
repo: &Path,
remote: &str,
src: &dyn PullSource,
) -> Result<Vec<MergedHead>, String> {
let url = Git::new(repo.join(".bare"))
.run(&["remote", "get-url", remote])
.map_err(|e| e.to_string())?;
let id = parse_remote(&url).ok_or_else(|| format!("cannot parse remote URL {url:?}"))?;
let (pid, pc) = provider_for(cfg, &id)?;
src.merged(pid, pc, &id.owner, &id.name)
}
/// True when the repo has a worktree on a branch other than `.bare`'s HEAD: only then can
/// anything be pruned, so only then is the forge asked.
pub fn has_candidates(repo: &Path) -> bool {
let bare = repo.join(".bare");
let default = Git::new(&bare)
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])
.ok()
.flatten();
worktrees(&bare).is_ok_and(|wts| {
wts.iter()
.filter_map(|w| w.branch.as_deref())
.any(|b| Some(b) != default.as_deref())
})
}
#[derive(Default)]
struct Entry {
checked: Option<Instant>,
heads: Vec<MergedHead>,
error: Option<String>,
/// "Kept" notes already logged, so a merged worktree with local work is reported once.
noted: BTreeSet<String>,
}
/// 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: Mutex<HashMap<PathBuf, Entry>>,
}
/// Result of [`MergedCache::heads`].
pub struct Heads {
pub heads: Vec<MergedHead>,
/// A lookup error that differs from the previous one (to be logged once).
pub new_error: Option<String>,
}
impl MergedCache {
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
pub fn heads(
&self,
cfg: &Config,
repo: &Path,
remote: &str,
src: &dyn PullSource,
now: Instant,
) -> Heads {
{
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);
}
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 answer {
Ok(h) => {
e.heads = h;
e.error = None;
}
Err(err) => {
if e.error.as_deref() != Some(&err) {
new_error = Some(err.clone());
}
e.error = Some(err);
}
}
Heads {
heads: e.heads.clone(),
new_error,
}
}
/// 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(&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;
fresh
}
/// 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()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_tmp as tmp;
use std::cell::{Cell, RefCell};
struct Fake {
calls: Cell<u32>,
asked: RefCell<Vec<String>>,
answer: RefCell<Result<Vec<MergedHead>, String>>,
}
impl PullSource for Fake {
fn merged(
&self,
id: &str,
_: &ProviderCfg,
owner: &str,
name: &str,
) -> Result<Vec<MergedHead>, String> {
self.calls.set(self.calls.get() + 1);
self.asked.borrow_mut().push(format!("{id}:{owner}/{name}"));
self.answer.borrow().clone()
}
}
fn head(n: u64) -> MergedHead {
MergedHead {
number: n,
branch: format!("b{n}"),
sha: "0".repeat(40),
}
}
#[test]
fn answers_are_cached_and_kept_on_failure() {
let d = tmp::TempDir::new("merged-cache");
let repo = d.path().join("G/r");
std::fs::create_dir_all(&repo).unwrap();
let bare = repo.join(".bare");
Git::new(d.path())
.run(&["init", "-q", "--bare", bare.to_str().unwrap()])
.unwrap();
Git::new(&bare)
.run(&["remote", "add", "origin", "git@git.example.es:Org/r.git"])
.unwrap();
let cfg = Config::parse(
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n",
)
.unwrap();
let f = Fake {
calls: Cell::new(0),
asked: RefCell::new(vec![]),
answer: RefCell::new(Ok(vec![head(1)])),
};
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"]);
// Within the TTL the forge is not asked again.
c.heads(&cfg, &repo, "origin", &f, t0 + Duration::from_secs(10));
assert_eq!(f.calls.get(), 1);
// A failure keeps the last answer and is reported once.
*f.answer.borrow_mut() = Err("down".into());
let h = c.heads(&cfg, &repo, "origin", &f, t0 + TTL);
assert_eq!((h.heads, h.new_error), (vec![head(1)], Some("down".into())));
let h = c.heads(&cfg, &repo, "origin", &f, t0 + TTL * 2);
assert_eq!((h.heads, h.new_error), (vec![head(1)], None));
assert_eq!(f.calls.get(), 3);
}
#[test]
fn notes_are_reported_once_while_they_hold() {
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());
assert!(c.new_notes(r, vec![]).is_empty());
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
}
}
+387
View File
@@ -0,0 +1,387 @@
//! Repos deleted on their forge are moved out of the synced tree, never deleted locally.
//!
//! A fetch error alone never moves anything: the forge must answer 404 for a repo the token's
//! account owns (its login, or an organisation named in a group's `owners`) while that token
//! works, and must still do so [`CONFIRM_AFTER_SECS`] after the first confirmation. The repo then
//! moves to `root/<sync.purged_dir>/<group>/<repo>`, which is not a configured group, so it is no
//! longer synced; its worktree links are repaired.
use crate::visibility::{Forge, Seen, parse_remote, provider_for};
use grove_core::busy::BusyGuard;
use grove_core::config::Config;
use grove_core::git::Git;
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 {
let e = fetch_error.to_ascii_lowercase();
[
"not found",
"does not appear to be a git repository",
"does not exist",
"cannot find repository", // Gitea/Forgejo over SSH
"error: 404",
]
.iter()
.any(|p| e.contains(p))
}
/// True only when the forge serving `remote` answers 404 for a repo owned by the token's own
/// account or by an organisation the config names in some group's `owners`, while that token
/// works. A repo of someone else (made private, or access revoked) is never reported gone.
pub fn confirmed_gone(
cfg: &Config,
repo: &Path,
remote: &str,
forge: &dyn Forge,
) -> Result<bool, String> {
let url = Git::new(repo.join(".bare"))
.run(&["remote", "get-url", remote])
.map_err(|e| e.to_string())?;
let id = parse_remote(&url).ok_or_else(|| format!("cannot parse remote URL {url:?}"))?;
let (pid, pc) = provider_for(cfg, &id)?;
// A 404 from a broken or foreign token proves nothing.
let login = forge.login(pid, pc)?;
let owned = id.owner.eq_ignore_ascii_case(&login)
|| cfg.groups.iter().any(|g| {
g.owners
.get(pid)
.is_some_and(|o| o.eq_ignore_ascii_case(&id.owner))
});
if !owned {
return Ok(false);
}
Ok(forge.seen(pid, pc, &id.owner, &id.name)? == Seen::Absent)
}
/// Where `repo` (`root/<group>/<name>`) goes: `root/<purged_dir>/<group>/<name>`, with a
/// `-<stamp>` suffix when that is taken.
pub fn destination(root: &Path, purged_dir: &str, repo: &Path, stamp: &str) -> Option<PathBuf> {
let name = repo.file_name()?;
let group = repo.parent()?.file_name()?;
let dir = root.join(purged_dir).join(group);
let first = dir.join(name);
if !first.exists() {
return Some(first);
}
Some(dir.join(format!("{}-{stamp}", name.to_string_lossy())))
}
#[derive(Debug)]
pub enum MoveError {
/// Nothing was moved (busy, an operation in progress, cross-device...).
NotMoved(String),
/// The repo is at its destination, but some worktree links could not be repaired.
Repair(String),
}
/// A finished move: worktrees whose directory was missing (unmounted disk, prunable) could not
/// be repaired; `git worktree repair <path>` from the new `.bare` fixes them later.
#[derive(Debug, Default)]
pub struct Moved {
pub unrepaired: Vec<PathBuf>,
}
/// An operation in progress in some worktree (or the repo) that a move would break.
fn in_progress(repo: &Path, wts: &[PathBuf]) -> Option<String> {
if repo.join(".grove-stage").exists() {
return Some("an interrupted grove operation left .grove-stage".into());
}
for w in wts.iter().filter(|w| w.exists()) {
let Ok(gd) = Git::new(w).run(&["rev-parse", "--absolute-git-dir"]) else {
continue;
};
let gd = PathBuf::from(gd);
for f in [
"index.lock",
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
] {
if gd.join(f).exists() {
return Some(format!("{}: {f} (git operation in progress)", w.display()));
}
}
}
None
}
/// Moves the bare-layout repo to `dest` (same file system) and repairs every worktree link:
/// worktrees inside the repo move with it, linked ones elsewhere are pointed at the new `.bare`.
/// Holds `.grove-busy` while moving and refuses while a git operation is in progress.
pub fn move_repo(repo: &Path, dest: &Path) -> Result<Moved, MoveError> {
let not = |m: String| MoveError::NotMoved(m);
// git reports worktree paths resolved (symlinks followed): compare against resolved paths.
let real_repo = repo
.canonicalize()
.map_err(|e| not(format!("{}: {e}", repo.display())))?;
let bare = real_repo.join(".bare");
let list = Git::new(&bare)
.run(&["worktree", "list", "--porcelain"])
.map_err(|e| not(e.to_string()))?;
let wts: Vec<PathBuf> = list
.lines()
.filter_map(|l| l.strip_prefix("worktree "))
.map(PathBuf::from)
.filter(|p| *p != bare)
.collect();
let guard =
BusyGuard::acquire(&real_repo).map_err(|e| not(format!("repo busy (.grove-busy): {e}")))?;
if let Some(why) = in_progress(&real_repo, &wts) {
return Err(not(why));
}
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(|e| not(format!("{}: {e}", parent.display())))?;
}
// A rename never copies: across file systems it fails and the repo stays where it was.
std::fs::rename(&real_repo, dest)
.map_err(|e| not(format!("cannot move to {}: {e}", dest.display())))?;
// The marker moved with the repo: the guard's old path is gone, remove the moved one.
drop(guard);
let _ = std::fs::remove_file(dest.join(".grove-busy"));
let real_dest = dest.canonicalize().unwrap_or_else(|_| dest.to_path_buf());
let mut moved = Moved::default();
let mut repair: Vec<String> = Vec::new();
for w in &wts {
let now = match w.strip_prefix(&real_repo) {
Ok(rel) => real_dest.join(rel),
Err(_) => w.clone(),
};
if now.exists() {
repair.push(now.display().to_string());
} else {
moved.unrepaired.push(now);
}
}
if !repair.is_empty() {
let mut args = vec!["worktree", "repair"];
args.extend(repair.iter().map(String::as_str));
Git::new(real_dest.join(".bare"))
.run(&args)
.map_err(|e| MoveError::Repair(e.to_string()))?;
}
Ok(moved)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_tmp as tmp;
use grove_core::config::Provider as ProviderCfg;
use std::cell::Cell;
#[test]
fn only_not_found_style_fetch_errors_are_hints() {
assert!(looks_gone(
"git fetch failed (Some(128)): ERROR: Repository not found."
));
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"
));
assert!(!looks_gone("fatal: Authentication failed"));
}
struct Fake {
login_ok: bool,
seen: Seen,
lookups: Cell<u32>,
}
impl Forge for Fake {
fn seen(&self, _: &str, _: &ProviderCfg, _: &str, _: &str) -> Result<Seen, String> {
self.lookups.set(self.lookups.get() + 1);
Ok(self.seen)
}
fn login(&self, _: &str, _: &ProviderCfg) -> Result<String, String> {
if self.login_ok {
Ok("me".into())
} else {
Err("401".into())
}
}
}
fn git(dir: &Path, args: &[&str]) {
Git::new(dir).run(args).unwrap();
}
/// `base/root/G/r` in bare layout with a `main` worktree and a linked one outside the repo.
fn bare_repo(base: &Path) -> (PathBuf, PathBuf) {
let repo = base.join("root/G/r");
std::fs::create_dir_all(&repo).unwrap();
let bare = repo.join(".bare");
git(
base,
&["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
);
git(
&bare,
&["remote", "add", "origin", "https://git.example.es/me/r.git"],
);
let main = repo.join("main");
git(
&bare,
&[
"worktree",
"add",
"-q",
"--orphan",
"-b",
"main",
main.to_str().unwrap(),
],
);
std::fs::write(main.join("f"), "x").unwrap();
git(&main, &["add", "f"]);
git(
&main,
&[
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-qm",
"c",
],
);
let ext = base.join("elsewhere");
git(
&bare,
&["worktree", "add", "-q", "-b", "side", ext.to_str().unwrap()],
);
(repo, ext)
}
fn cfg() -> Config {
Config::parse(
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n",
)
.unwrap()
}
#[test]
fn a_404_counts_only_with_a_working_token() {
let d = tmp::TempDir::new("purge-confirm");
let (repo, _) = bare_repo(d.path());
let cfg = cfg();
let gone = |login_ok, seen| {
let f = Fake {
login_ok,
seen,
lookups: Cell::new(0),
};
confirmed_gone(&cfg, &repo, "origin", &f)
};
assert_eq!(gone(true, Seen::Absent), Ok(true));
assert_eq!(gone(true, Seen::Private), Ok(false));
assert!(gone(false, Seen::Absent).is_err());
// Someone else's repo (made private, access revoked) is never "gone".
git(
&repo.join(".bare"),
&[
"remote",
"set-url",
"origin",
"https://git.example.es/other/r.git",
],
);
let f = Fake {
login_ok: true,
seen: Seen::Absent,
lookups: Cell::new(0),
};
assert_eq!(confirmed_gone(&cfg, &repo, "origin", &f), Ok(false));
assert_eq!(f.lookups.get(), 0);
// ...unless the config names that organisation as an owner.
let org = Config::parse(
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n\
[[groups]]\nname=\"G\"\nprimary=\"gitea\"\nowners={gitea=\"Other\"}\n",
)
.unwrap();
assert_eq!(confirmed_gone(&org, &repo, "origin", &f), Ok(true));
}
#[test]
fn moving_keeps_every_worktree_working() {
let d = tmp::TempDir::new("purge-move");
let (repo, ext) = bare_repo(d.path());
let root = d.path().join("root");
let dest = destination(&root, "Purged", &repo, "1").unwrap();
assert_eq!(dest, root.join("Purged/G/r"));
move_repo(&repo, &dest).unwrap();
assert!(!repo.exists());
for wt in [dest.join("main"), ext.clone()] {
let st = Git::new(&wt).run(&["status", "--porcelain"]);
assert!(st.is_ok(), "{}: {st:?}", wt.display());
}
let list = Git::new(dest.join(".bare"))
.run(&["worktree", "list", "--porcelain"])
.unwrap();
assert!(list.contains(&dest.join("main").display().to_string()));
assert!(!list.contains("prunable"), "{list}");
// A second repo of the same name does not overwrite the first.
std::fs::create_dir_all(&repo).unwrap();
assert_eq!(
destination(&root, "Purged", &repo, "7").unwrap(),
root.join("Purged/G/r-7")
);
}
#[test]
fn moving_through_a_symlinked_root_repairs_the_worktrees() {
let d = tmp::TempDir::new("purge-symlink");
std::fs::create_dir_all(d.path().join("real")).unwrap();
std::os::unix::fs::symlink(d.path().join("real"), d.path().join("link")).unwrap();
let base = d.path().join("link");
let (repo, ext) = bare_repo(&base);
let dest = destination(&base.join("root"), "Purged", &repo, "1").unwrap();
let moved = move_repo(&repo, &dest).unwrap();
assert!(moved.unrepaired.is_empty());
for wt in [dest.join("main"), ext] {
assert!(Git::new(&wt).run(&["status"]).is_ok(), "{}", wt.display());
}
assert!(!dest.join(".grove-busy").exists());
}
#[test]
fn a_busy_repo_or_a_git_operation_in_progress_is_left_alone() {
let d = tmp::TempDir::new("purge-busy");
let (repo, _) = bare_repo(d.path());
let dest = d.path().join("root/Purged/G/r");
std::fs::write(repo.join(".grove-busy"), "1 1\n").unwrap();
assert!(matches!(
move_repo(&repo, &dest),
Err(MoveError::NotMoved(_))
));
std::fs::remove_file(repo.join(".grove-busy")).unwrap();
let gd = Git::new(repo.join("main"))
.run(&["rev-parse", "--absolute-git-dir"])
.unwrap();
std::fs::write(Path::new(&gd).join("MERGE_HEAD"), "x").unwrap();
assert!(matches!(
move_repo(&repo, &dest),
Err(MoveError::NotMoved(_))
));
assert!(repo.join(".bare").is_dir() && !dest.exists());
assert!(!repo.join(".grove-busy").exists());
}
}
+70 -58
View File
@@ -15,6 +15,7 @@ use grove_core::sync::git_dir_for;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf}; 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). /// How long a "private" answer is trusted (a repo can be made public at any time).
pub const PRIVATE_TTL: u64 = 3600; 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)] #[derive(Debug, Default)]
pub struct Visibility { pub struct Visibility {
path: Option<PathBuf>, path: Option<PathBuf>,
state: Mutex<Cache>,
}
#[derive(Debug, Default)]
struct Cache {
entries: BTreeMap<String, Entry>, entries: BTreeMap<String, Entry>,
failed: HashMap<String, (u64, String)>, failed: HashMap<String, (u64, String)>,
logins: HashMap<String, String>, logins: HashMap<String, String>,
@@ -242,12 +249,14 @@ impl Visibility {
.unwrap_or_default(); .unwrap_or_default();
Visibility { Visibility {
path, path,
entries, state: Mutex::new(Cache {
..Visibility::default() entries,
..Cache::default()
}),
} }
} }
fn save(&self) { fn save(&self, entries: &BTreeMap<String, Entry>) {
use std::io::Write; use std::io::Write;
use std::os::unix::fs::OpenOptionsExt; use std::os::unix::fs::OpenOptionsExt;
let Some(path) = &self.path else { return }; let Some(path) = &self.path else { return };
@@ -256,7 +265,7 @@ impl Visibility {
} }
let tmp = path.with_extension("json.tmp"); let tmp = path.with_extension("json.tmp");
let _ = std::fs::remove_file(&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; return;
}; };
let written = std::fs::OpenOptions::new() 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. /// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
fn seen( fn seen(
&mut self, &self,
pid: &str, pid: &str,
pc: &ProviderCfg, pc: &ProviderCfg,
owner: &str, owner: &str,
@@ -282,34 +291,39 @@ impl Visibility {
) -> Result<Seen, String> { ) -> Result<Seen, String> {
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/'); let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase(); 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) let answer = forge.seen(pid, pc, owner, name);
&& at.saturating_sub(0) <= now let mut c = self.state.lock().unwrap();
&& now - at < RETRY match answer {
{
return Err(why.clone());
}
match forge.seen(pid, pc, owner, name) {
Ok(seen) => { Ok(seen) => {
self.failed.remove(&key); c.failed.remove(&key);
self.entries.insert(key, Entry { seen, checked: now }); c.entries.insert(key, Entry { seen, checked: now });
self.save(); self.save(&c.entries);
Ok(seen) Ok(seen)
} }
Err(why) => { Err(why) => {
let why = format!("lookup on {pid:?} failed: {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) Err(why)
} }
} }
} }
/// Visibility of the repo behind one push URL. /// 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 { let Some(id) = parse_remote(url) else {
return Verdict::Unknown("push URL not understood".into()); 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. /// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
fn check_mirror( fn check_mirror(
&mut self, &self,
cfg: &Config, cfg: &Config,
group: &str, group: &str,
pid: &str, pid: &str,
@@ -346,16 +360,20 @@ impl Visibility {
.and_then(|g| g.owner(pid)) .and_then(|g| g.owner(pid))
{ {
Some(o) => o.to_string(), Some(o) => o.to_string(),
None => match self.logins.get(pid) { None => {
Some(l) => l.clone(), let known = self.state.lock().unwrap().logins.get(pid).cloned();
None => { match known {
let l = forge Some(l) => l,
.login(pid, pc) None => {
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?; let l = forge
self.logins.insert(pid.to_string(), l.clone()); .login(pid, pc)
l .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) { match self.seen(pid, pc, &owner, name, now, forge) {
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")), Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
@@ -395,7 +413,7 @@ pub fn snapshot_gate(
cfg: &Config, cfg: &Config,
repo: &Path, repo: &Path,
remote: &str, remote: &str,
vis: &mut Visibility, vis: &Visibility,
now: u64, now: u64,
forge: &dyn Forge, forge: &dyn Forge,
) -> Result<(), String> { ) -> Result<(), String> {
@@ -559,7 +577,7 @@ owners = { github = "gh-org" }
.unwrap(); .unwrap();
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err(); let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
assert!(e.contains("several")); assert!(e.contains("several"));
let mut v = Visibility::default(); let v = Visibility::default();
let fake = Fake::default().with("o/r", Ok(Seen::Private)); let fake = Fake::default().with("o/r", Ok(Seen::Private));
assert!(matches!( assert!(matches!(
v.check_url(&dup, "https://h.io/o/r", 0, &fake), v.check_url(&dup, "https://h.io/o/r", 0, &fake),
@@ -571,7 +589,7 @@ owners = { github = "gh-org" }
#[test] #[test]
fn unknown_visibility_is_public_and_withholds_snapshots() { fn unknown_visibility_is_public_and_withholds_snapshots() {
let c = cfg(); let c = cfg();
let mut v = Visibility::default(); let v = Visibility::default();
let boom = Fake::default(); let boom = Fake::default();
for url in [ for url in [
"https://gitlab.com/o/r.git", "https://gitlab.com/o/r.git",
@@ -608,7 +626,7 @@ owners = { github = "gh-org" }
#[test] #[test]
fn private_answers_expire_after_an_hour_and_failures_are_throttled() { fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
let c = cfg(); let c = cfg();
let mut v = Visibility::default(); let v = Visibility::default();
let f = Fake::default().with("o/r", Ok(Seen::Private)); let f = Fake::default().with("o/r", Ok(Seen::Private));
let url = "https://github.com/o/r"; let url = "https://github.com/o/r";
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private); assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
@@ -654,7 +672,7 @@ owners = { github = "gh-org" }
#[test] #[test]
fn cache_keys_include_provider_and_are_case_normalised() { fn cache_keys_include_provider_and_are_case_normalised() {
let c = cfg(); let c = cfg();
let mut v = Visibility::default(); let v = Visibility::default();
let f = Fake::default().with("o/r", Ok(Seen::Private)); 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, "https://github.com/O/R.git", 0, &f);
v.check_url(&c, "git@github.com:o/r", 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 file = dir.join("visibility.json");
let c = cfg(); let c = cfg();
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate)); 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!( assert_eq!(
v.check_url(&c, "https://github.com/o/r", 50, &f), v.check_url(&c, "https://github.com/o/r", 50, &f),
Verdict::Public Verdict::Public
@@ -684,7 +702,7 @@ owners = { github = "gh-org" }
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777; let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600); assert_eq!(mode, 0o600);
let never = Fake::default(); let never = Fake::default();
let mut again = Visibility::load(Some(file)); let again = Visibility::load(Some(file));
assert_eq!( assert_eq!(
again.check_url(&c, "https://github.com/o/r", 60, &never), again.check_url(&c, "https://github.com/o/r", 60, &never),
Verdict::Public Verdict::Public
@@ -721,22 +739,16 @@ owners = { github = "gh-org" }
let f = Fake::default() let f = Fake::default()
.with("o/r", Ok(Seen::Private)) .with("o/r", Ok(Seen::Private))
.with("o/open", Ok(Seen::NotPrivate)); .with("o/open", Ok(Seen::NotPrivate));
let mut v = Visibility::default(); let v = Visibility::default();
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f); let gate = |repo: &Path, v: &Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
let ok = "https://git.example.com:3000/o/r.git"; let ok = "https://git.example.com:3000/o/r.git";
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok()); assert!(gate(&mk(&base, "priv", &[ok], &[]), &v).is_ok());
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err()); assert!(gate(&mk(&base, "off", &[ok], &[]), &v).is_err());
assert!( assert!(gate(&mk(&base, "all", &["https://unknown.example/o/r"], &[]), &v).is_ok());
gate(
&mk(&base, "all", &["https://unknown.example/o/r"], &[]),
&mut v
)
.is_ok()
);
// Fetch URL private, but the push goes to a public repo (pushurl). // Fetch URL private, but the push goes to a public repo (pushurl).
let e = gate( let e = gate(
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]), &mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
&mut v, &v,
); );
assert!(e.is_err()); assert!(e.is_err());
// Private-only without any remote: unknown, withheld. // Private-only without any remote: unknown, withheld.
@@ -744,7 +756,7 @@ owners = { github = "gh-org" }
std::fs::create_dir_all(&bare).unwrap(); std::fs::create_dir_all(&bare).unwrap();
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap(); Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
assert!( assert!(
gate(&base.join("priv/none"), &mut v) gate(&base.join("priv/none"), &v)
.unwrap_err() .unwrap_err()
.contains("unknown") .contains("unknown")
); );
@@ -760,24 +772,24 @@ owners = { github = "gh-org" }
let f = Fake::default() let f = Fake::default()
.with("o/r", Ok(Seen::Private)) .with("o/r", Ok(Seen::Private))
.with("o/open", Ok(Seen::NotPrivate)); .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 ok = "https://git.example.com:3000/o/r.git";
let open = "https://github.com/o/open"; let open = "https://github.com/o/open";
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed. // Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]); 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(); std::fs::remove_dir_all(base.join("priv")).unwrap();
let leaky = mk(&base, "priv", &[ok, open], &[]); 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}"); assert!(e.contains("public"), "{e}");
// pushInsteadOf rewrites the push URL to a public repo. // pushInsteadOf rewrites the push URL to a public repo.
let g = Git::new(leaky.join(".bare")); let g = Git::new(leaky.join(".bare"));
g.run(&["remote", "set-url", "--delete", "origin", open]) g.run(&["remote", "set-url", "--delete", "origin", open])
.unwrap(); .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]) g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
.unwrap(); .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(); std::fs::remove_dir_all(&base).unwrap();
} }
@@ -789,8 +801,8 @@ owners = { github = "gh-org" }
let _ = std::fs::remove_dir_all(&base); let _ = std::fs::remove_dir_all(&base);
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]); let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
let gate = |f: &Fake| { let gate = |f: &Fake| {
let mut v = Visibility::default(); let v = Visibility::default();
snapshot_gate(&c, &repo, "origin", &mut v, 0, f) snapshot_gate(&c, &repo, "origin", &v, 0, f)
}; };
let base_f = || Fake::default().with("o/r", Ok(Seen::Private)); let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
// No mirror (404): fine. Mirror owner comes from `owners`. // 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"); assert!(seen, "cloned repo never managed");
d.shutdown(); 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") 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 { pub fn is_enabled(config_home: &Path) -> bool {
file(config_home).exists() 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() { if let Some(d) = f.parent() {
std::fs::create_dir_all(d)?; 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 { } else {
match std::fs::remove_file(&f) { match std::fs::remove_file(&f) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e), Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
@@ -47,10 +71,29 @@ mod tests {
set(&d, true).unwrap(); set(&d, true).unwrap();
assert!(is_enabled(&d)); assert!(is_enabled(&d));
let text = std::fs::read_to_string(file(&d)).unwrap(); 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(); set(&d, false).unwrap();
assert!(!is_enabled(&d)); assert!(!is_enabled(&d));
set(&d, false).unwrap(); // already off: fine set(&d, false).unwrap(); // already off: fine
let _ = std::fs::remove_dir_all(&d); 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", "secrets",
"sync", "sync",
"status", "status",
"group",
"provider",
"open",
]; ];
pub struct Bridge { pub struct Bridge {
@@ -53,6 +56,17 @@ impl Bridge {
Err(e) => return json!({"ok": false, "output": format!("rejected: {e}")}), 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 args = &checked[..];
let mut cmd = Command::new(&self.grove_bin); let mut cmd = Command::new(&self.grove_bin);
if let Some(c) = &self.config { if let Some(c) = &self.config {
@@ -106,6 +120,26 @@ impl Bridge {
check_migrate_path(&cfg, Path::new(path)) 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. /// Where `grove add` writes its safety backup.
pub fn backup_dir() -> Option<PathBuf> { pub fn backup_dir() -> Option<PathBuf> {
grove_core::config::Config::state_dir().map(|d| d.join("backups")) 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", "--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"]), "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()) { } else if sub == "secrets" && i == 0 && !["init", "pull", "rekey"].contains(&a.as_str()) {
return Err(format!("secrets {a:?} is not allowed from the GUI")); 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 { if sub == "secrets" && args.len() != 2 {
return Err("secrets takes exactly one action".into()); 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(()) 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> { fn grove_core_default_config() -> Option<PathBuf> {
let base = std::env::var_os("XDG_CONFIG_HOME") let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from) .map(PathBuf::from)
@@ -215,6 +294,48 @@ mod tests {
assert!(v(&["resolve", "/p", "--save-as", "b", "--take-remote"]).is_ok()); assert!(v(&["resolve", "/p", "--save-as", "b", "--take-remote"]).is_ok());
assert!(v(&["new", "g", "n", "--public"]).is_ok()); assert!(v(&["new", "g", "n", "--public"]).is_ok());
assert!(v(&["secrets", "pull"]).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] #[test]
+168 -15
View File
@@ -47,6 +47,8 @@ struct Snapshot {
status: Option<Value>, status: Option<Value>,
log: Vec<Value>, log: Vec<Value>,
config: Option<Value>, config: Option<Value>,
/// Installed launchers (name, label), the default one first.
launchers: Vec<(String, String)>,
alerts: Vec<(String, String)>, alerts: Vec<(String, String)>,
} }
@@ -141,6 +143,7 @@ struct UiState {
toast_gen: u32, toast_gen: u32,
last_groups: Vec<String>, last_groups: Vec<String>,
last_providers: Vec<String>, last_providers: Vec<String>,
last_launchers: Vec<(String, String)>,
} }
thread_local! { thread_local! {
@@ -161,6 +164,7 @@ thread_local! {
import_current: String::new(), import_current: String::new(),
toast_gen: 0, toast_gen: 0,
last_groups: Vec::new(), last_groups: Vec::new(),
last_launchers: Vec::new(),
last_providers: Vec::new(), last_providers: Vec::new(),
}); });
} }
@@ -428,6 +432,9 @@ fn render(ui: &MainWindow) {
} }
if providers != st.last_providers { if providers != st.last_providers {
ui.set_providers(str_model(&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; st.last_providers = providers;
} }
let secs: Vec<Section> = model::settings_sections(cfg) let secs: Vec<Section> = model::settings_sections(cfg)
@@ -446,6 +453,21 @@ fn render(ui: &MainWindow) {
.collect(); .collect();
ui.set_sections(ModelRc::from(Rc::new(VecModel::from(secs)))); 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: // Slint exposes no xdg-activation, so an already visible window is raised by re-mapping it:
// a fresh toplevel is what the compositor focuses. // a fresh toplevel is what the compositor focuses.
if core.visible.load(Ordering::SeqCst) && ui.window().is_visible() { 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 { fn out(ok: bool, text: String) -> Out {
Out { Out {
ok, ok,
@@ -743,13 +779,23 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
ui.on_create_repo({ ui.on_create_repo({
let c = ctx.clone(); let c = ctx.clone();
move |group, name, public| { move |group, name, public, open| {
let Some(ui) = c.weak.upgrade() else { return }; let Some(ui) = c.weak.upgrade() else { return };
let group = model::group_name(&first_or(group.as_str(), &ui.get_groups())).to_string(); 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()]; let mut args = vec!["new".to_string(), group, name.trim().to_string()];
if public { if public {
args.push("--public".into()); 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())); ui.set_new_out(out(true, String::new()));
run_cli(&c, &ui, None, args, String::new(), |ui, ok, text| { run_cli(&c, &ui, None, args, String::new(), |ui, ok, text| {
ui.set_new_out(out(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({ ui.on_scan_import({
let c = ctx.clone(); let c = ctx.clone();
move |group, force| { 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({ ui.on_login({
let c = ctx.clone(); let c = ctx.clone();
move |provider, token| { move |provider, token| {
@@ -1200,6 +1320,7 @@ fn worker(
status, status,
log, log,
config: core.bridge.config_json(), config: core.bridge.config_json(),
launchers: core.bridge.launchers(),
alerts, alerts,
}; };
let w = weak.clone(); let w = weak.clone();
@@ -1283,6 +1404,11 @@ fn run() -> Result<()> {
return Ok(()); return Ok(());
} }
let hidden = args.iter().any(|a| a == "--hidden"); 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") let inst_path = arg("--instance-socket")
.map(PathBuf::from) .map(PathBuf::from)
.unwrap_or_else(instance::default_socket_path); .unwrap_or_else(instance::default_socket_path);
@@ -1297,15 +1423,25 @@ fn run() -> Result<()> {
{ {
let (late, pending) = (late.clone(), pending_show.clone()); let (late, pending) = (late.clone(), pending_show.clone());
std::thread::spawn(move || { std::thread::spawn(move || {
instance::serve(listener, move || match late.lock().unwrap().clone() { instance::serve(listener, move || {
Some(c) => { let age = started.elapsed();
let _ = slint::invoke_from_event_loop(move || { if !model::accept_instance_show(hidden, age) {
if let Some(ui) = c.weak.upgrade() { log::line(&format!(
show_window(&ui, &c.core); "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 c = ctx.clone();
let _ = slint::invoke_from_event_loop(move || { let _ = slint::invoke_from_event_loop(move || {
if let Some(ui) = c.weak.upgrade() { 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) => { Ok(h) => {
core.tray_ok.store(true, Ordering::SeqCst); core.tray_ok.store(true, Ordering::SeqCst);
Some(h) Some(h)
@@ -1400,7 +1537,13 @@ fn run() -> Result<()> {
let (c, w) = (core.clone(), ui.as_weak()); let (c, w) = (core.clone(), ui.as_weak());
let respawn = on_action.clone(); let respawn = on_action.clone();
std::thread::spawn(move || { 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()); *late.lock().unwrap() = Some(ctx.clone());
if !hidden || pending_show.load(Ordering::SeqCst) || !core.tray_ok.load(Ordering::SeqCst) { let why = if !hidden {
show_window(&ui, &core); 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 { } else {
None
};
if let Some(why) = why {
show_window(&ui, &core, why);
} else {
log::line("started hidden in the tray");
core.wake(); core.wake();
} }
let r = slint::run_event_loop_until_quit(); 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) 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -501,4 +558,55 @@ mod tests {
assert_eq!(s[3].1[0].1, "grove-config on gitea"); assert_eq!(s[3].1[0].1, "grove-config on gitea");
assert_eq!(group_name("work → gitea"), "work"); 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>; pub type TrayHandle = Handle<GroveTray>;
/// Starts the tray service. Fails when there is no D-Bus session. /// Starts the tray service. Fails when there is no D-Bus session. With `wait_for_host` a
pub fn spawn(on_action: Arc<dyn Fn(Action) + Send + Sync>) -> Result<TrayHandle, ksni::Error> { /// 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 { GroveTray {
agg: Aggregate::default(), agg: Aggregate::default(),
on_action, on_action,
} }
.assume_sni_available(wait_for_host)
.spawn() .spawn()
} }
@@ -48,6 +54,17 @@ impl ksni::Tray for GroveTray {
"grove".into() "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 { fn title(&self) -> String {
"Grove".into() "Grove".into()
} }
+305 -8
View File
@@ -52,6 +52,11 @@ export struct MigRow {
msg: string, msg: string,
} }
export struct Launch {
name: string,
label: string,
}
export struct Out { export struct Out {
text: string, text: string,
ok: bool, ok: bool,
@@ -195,6 +200,12 @@ export component MainWindow inherits Window {
in property <[LogRow]> log; in property <[LogRow]> log;
in property <[string]> groups; in property <[string]> groups;
in property <[string]> providers; 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 <[Section]> sections;
in property <[Pick]> picks; in property <[Pick]> picks;
in property <string> import-note; in property <string> import-note;
@@ -209,6 +220,7 @@ export component MainWindow inherits Window {
in property <Repo> detail; in property <Repo> detail;
in property <bool> detail-found; in property <bool> detail-found;
in-out property <string> selected-path; in-out property <string> selected-path;
property <string> prov-url-text;
in property <Out> new-out; in property <Out> new-out;
in property <Out> import-out; in property <Out> import-out;
in property <Out> settings-out; in property <Out> settings-out;
@@ -220,7 +232,12 @@ export component MainWindow inherits Window {
callback sync-all(); callback sync-all();
callback toggle-pause(); callback toggle-pause();
callback filter-changed(string); 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 scan-import(string, bool);
callback import-selected(string); callback import-selected(string);
callback pick-toggled(int, bool); callback pick-toggled(int, bool);
@@ -491,6 +508,13 @@ export component MainWindow inherits Window {
for r in root.repos: Rectangle { for r in root.repos: Rectangle {
height: rcard.preferred-height; 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 { rcard := Card {
HorizontalLayout { HorizontalLayout {
spacing: 12px; spacing: 12px;
@@ -553,15 +577,20 @@ export component MainWindow inherits Window {
font-size: 11px; font-size: 11px;
} }
} }
}
} if root.launchers.length > 0: VerticalLayout {
alignment: center;
TouchArea { Button {
clicked => { text: "Open";
root.open-repo(r.path); 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; 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 { if w.state == "diverged": diverged := VerticalLayout {
spacing: 8px; spacing: 8px;
alignment: start; alignment: start;
@@ -831,6 +876,14 @@ export component MainWindow inherits Window {
text: "Public repository"; text: "Public repository";
} }
Muted {
text: "Afterwards";
}
new-open := ComboBox {
model: root.open-choices;
}
HorizontalLayout { HorizontalLayout {
alignment: start; alignment: start;
Button { Button {
@@ -838,7 +891,7 @@ export component MainWindow inherits Window {
primary: true; primary: true;
enabled: !root.busy && new-name.text != ""; enabled: !root.busy && new-name.text != "";
clicked => { 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 {
text: "Sign in to a provider"; text: "Sign in to a provider";
font-size: 16px; font-size: 16px;
+22 -1
View File
@@ -1,6 +1,7 @@
use crate::http::Http; use crate::http::Http;
use crate::{ use crate::{
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result, Capabilities, Error, MergedPull, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo,
Result, same_repo,
}; };
use grove_core::config::ProviderKind; use grove_core::config::ProviderKind;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -156,4 +157,24 @@ impl Provider for Gitea {
Some(&body), Some(&body),
)?)) )?))
} }
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>> {
let v = self.http.ok(
"GET",
&format!("/repos/{owner}/{name}/pulls?state=closed&sort=recentupdate&limit=50"),
None,
)?;
Ok(v.as_array()
.into_iter()
.flatten()
.filter(|p| p["merged"].as_bool() == Some(true) && same_repo(p))
.filter_map(|p| {
Some(MergedPull {
number: p["number"].as_u64()?,
head_ref: p["head"]["ref"].as_str()?.to_string(),
head_sha: p["head"]["sha"].as_str()?.to_string(),
})
})
.collect())
}
} }
+26 -1
View File
@@ -1,6 +1,7 @@
use crate::http::Http; use crate::http::Http;
use crate::{ use crate::{
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result, Capabilities, Error, MergedPull, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo,
Result, same_repo,
}; };
use grove_core::config::ProviderKind; use grove_core::config::ProviderKind;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -138,4 +139,28 @@ impl Provider for GitHub {
"GitHub cannot pull-mirror another forge", "GitHub cannot pull-mirror another forge",
)) ))
} }
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>> {
let v = self.http.ok(
"GET",
&format!(
"/repos/{owner}/{name}/pulls?state=closed&sort=updated&direction=desc&per_page=100"
),
None,
)?;
Ok(v.as_array()
.into_iter()
.flatten()
.filter(|p| p["merged_at"].is_string() && same_repo(p))
.filter_map(pull)
.collect())
}
}
fn pull(p: &Value) -> Option<MergedPull> {
Some(MergedPull {
number: p["number"].as_u64()?,
head_ref: p["head"]["ref"].as_str()?.to_string(),
head_sha: p["head"]["sha"].as_str()?.to_string(),
})
} }
+46
View File
@@ -119,6 +119,25 @@ pub struct PullMirrorSpec {
pub interval: String, pub interval: String,
} }
/// A pull request merged on the forge whose head branch is in the same repo.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergedPull {
pub number: u64,
pub head_ref: String,
pub head_sha: String,
}
/// Head repo of a pull request equals its base repo (fork PRs reuse branch names freely).
/// A head repo that was deleted reports `null`: not the same repo.
pub(crate) fn same_repo(pr: &serde_json::Value) -> bool {
let name = |side: &str| {
pr[side]["repo"]["full_name"]
.as_str()
.map(str::to_ascii_lowercase)
};
matches!((name("head"), name("base")), (Some(h), Some(b)) if h == b)
}
pub trait Provider: Send + Sync { pub trait Provider: Send + Sync {
fn kind(&self) -> ProviderKind; fn kind(&self) -> ProviderKind;
fn capabilities(&self) -> Capabilities; fn capabilities(&self) -> Capabilities;
@@ -134,6 +153,33 @@ pub trait Provider: Send + Sync {
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>; fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
/// Creates a pull mirror (see [`Capabilities::pull_mirror`]). /// Creates a pull mirror (see [`Capabilities::pull_mirror`]).
fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo>; fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo>;
/// The most recently updated closed pull requests (one page) that were merged, newest
/// first, leaving out those whose head is in a fork.
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`. /// Builds the provider described by `cfg`, using `token`.
+13 -4
View File
@@ -31,10 +31,19 @@ pub fn get(provider_id: &str) -> Result<String> {
return Ok(t.trim().to_string()); return Ok(t.trim().to_string());
} }
let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?; let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?;
match e.get_password() { // A locked keyring may wait on an unlock dialog: never block the caller for longer than the
Ok(t) => Ok(t), // forge CLIs get (the thread is left behind if the Secret Service never answers).
Err(keyring::Error::NoEntry) => Err(Error::NoToken(provider_id.into())), let (tx, rx) = std::sync::mpsc::channel();
Err(e) => Err(Error::Other(format!("secret service: {e}"))), std::thread::spawn(move || {
let _ = tx.send(e.get_password());
});
match rx.recv_timeout(CLI_TIMEOUT) {
Ok(Ok(t)) => Ok(t),
Ok(Err(keyring::Error::NoEntry)) => Err(Error::NoToken(provider_id.into())),
Ok(Err(e)) => Err(Error::Other(format!("secret service: {e}"))),
Err(_) => Err(Error::Other(
"secret service did not answer in time (locked keyring?)".into(),
)),
} }
} }
+81
View File
@@ -481,3 +481,84 @@ fn git_url_follows_the_protocol_and_needs_an_ssh_url_for_ssh() {
); );
assert!(r[1].git_url(Protocol::Ssh).is_err()); assert!(r[1].git_url(Protocol::Ssh).is_err());
} }
#[test]
fn merged_pulls_keep_only_merged_same_repo_heads() {
// Merged, closed without merging, merged from a fork, merged from a deleted fork.
let gitea = r#"[
{"number":3,"merged":true,"head":{"ref":"feat/a","sha":"aaa","repo":{"full_name":"O/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":2,"merged":false,"head":{"ref":"b","sha":"bbb","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":1,"merged":true,"head":{"ref":"c","sha":"ccc","repo":{"full_name":"x/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":0,"merged":true,"head":{"ref":"d","sha":"ddd","repo":null},"base":{"repo":{"full_name":"o/r"}}}
]"#;
let (url, rx) = mock(vec![(200, gitea)]);
let pulls = Gitea::new(ProviderKind::Forgejo, &url, "t".into())
.merged_pulls("o", "r")
.unwrap();
assert!(
rx.recv()
.unwrap()
.starts_with("GET /api/v1/repos/o/r/pulls?state=closed&sort=recentupdate&limit=50 ")
);
assert_eq!(pulls.len(), 1);
assert_eq!(
(
pulls[0].number,
pulls[0].head_ref.as_str(),
pulls[0].head_sha.as_str()
),
(3, "feat/a", "aaa")
);
let github = r#"[
{"number":9,"merged_at":"2026-01-01T00:00:00Z","head":{"ref":"x","sha":"999","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":8,"merged_at":null,"head":{"ref":"y","sha":"888","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}}
]"#;
let (url, rx) = mock(vec![(200, github), (404, r#"{"message":"Not Found"}"#)]);
let gh = GitHub::new(&url, "t".into());
let pulls = gh.merged_pulls("o", "r").unwrap();
assert!(rx.recv().unwrap().starts_with(
"GET /repos/o/r/pulls?state=closed&sort=updated&direction=desc&per_page=100 "
));
assert_eq!(pulls.iter().map(|p| p.number).collect::<Vec<_>>(), vec![9]);
assert!(matches!(
gh.merged_pulls("o", "gone").unwrap_err(),
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, .. }
));
}
+308 -13
View File
@@ -1,9 +1,10 @@
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use grove_core::config::{Config, ProviderKind}; use grove_core::config::Config;
use grove_core::git::Git; use grove_core::git::Git;
use grove_core::inspect::{state, worktrees}; use grove_core::inspect::{state, worktrees};
use grove_core::migrate::migrate; use grove_core::migrate::migrate;
use grove_core::prune::{Pruned, merged_how};
use grove_core::receive::{Applied, Archived, Received}; use grove_core::receive::{Applied, Archived, Received};
use grove_core::resolve::{Choice, resolve}; use grove_core::resolve::{Choice, resolve};
use grove_core::snapshot::{Outcome, take}; use grove_core::snapshot::{Outcome, take};
@@ -12,6 +13,7 @@ use grove_core::sync::{Options, SyncReport, git_dir_for, sync_repo};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
mod namespace;
mod secrets; mod secrets;
#[cfg(test)] #[cfg(test)]
#[path = "../../../test-support/tmp.rs"] #[path = "../../../test-support/tmp.rs"]
@@ -110,6 +112,34 @@ enum Cmd {
name: String, name: String,
#[arg(long)] #[arg(long)]
public: bool, 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 /// List (or, with names, clone) remote repos that are not on this machine
Import { group: String, names: Vec<String> }, Import { group: String, names: Vec<String> },
@@ -129,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)] #[derive(Subcommand)]
enum SecretsCmd { enum SecretsCmd {
/// Create this machine's age key and publish the public half /// Create this machine's age key and publish the public half
@@ -259,6 +349,160 @@ fn daemon(action: &DaemonCmd) -> Result<()> {
Ok(()) 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<()> { fn main() -> Result<()> {
let cli = Cli::parse(); let cli = Cli::parse();
match &cli.cmd { match &cli.cmd {
@@ -345,6 +589,21 @@ fn main() -> Result<()> {
Cmd::Sync { path, offline } => { Cmd::Sync { path, offline } => {
let cfg = load_config(&cli.config)?; let cfg = load_config(&cli.config)?;
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024); grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
// Merged pull requests, for pruning (bare layout only; best effort).
let merged = if *offline || !cfg.sync.prune_merged || !path.join(".bare").is_dir() {
Vec::new()
} else {
grove_daemon::merged::lookup(
&cfg,
path,
"origin",
&grove_daemon::visibility::RealForge,
)
.unwrap_or_else(|e| {
eprintln!("grove: cannot list merged pull requests: {e}");
Vec::new()
})
};
let rep = sync_repo( let rep = sync_repo(
path, path,
&Options { &Options {
@@ -359,6 +618,10 @@ fn main() -> Result<()> {
.and_then(|g| cfg.groups.iter().find(|x| x.name == g)) .and_then(|g| cfg.groups.iter().find(|x| x.name == g))
.is_none_or(|g| g.auto_materialize), .is_none_or(|g| g.auto_materialize),
push_snapshots: true, push_snapshots: true,
merged,
disposable: cfg.sync.prune_disposable.clone(),
prune: cfg.sync.prune_merged,
protected: cfg.sync.protected_branches(),
}, },
)?; )?;
print_report(&rep) print_report(&rep)
@@ -375,22 +638,13 @@ fn main() -> Result<()> {
config_repo, config_repo,
force, force,
} => { } => {
let protocol = match protocol.as_str() { let protocol = namespace::parse_protocol(protocol)?;
"https" => grove_core::config::Protocol::Https,
"ssh" => grove_core::config::Protocol::Ssh,
p => bail!("unknown protocol {p:?} (https, ssh)"),
};
let path = cli let path = cli
.config .config
.clone() .clone()
.or_else(Config::default_path) .or_else(Config::default_path)
.context("cannot determine config path (set --config)")?; .context("cannot determine config path (set --config)")?;
let kind = match kind.as_str() { let kind = namespace::parse_kind(kind)?;
"gitea" => ProviderKind::Gitea,
"forgejo" => ProviderKind::Forgejo,
"github" => ProviderKind::Github,
k => bail!("unknown provider kind {k:?} (gitea, forgejo, github)"),
};
let machine = machine let machine = machine
.clone() .clone()
.or_else(|| { .or_else(|| {
@@ -431,11 +685,35 @@ fn main() -> Result<()> {
group, group,
name, name,
public, 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()); 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(()) 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::Import { group, names } => workflow::import(&load_config(&cli.config)?, group, names),
Cmd::ConfigRepoInit => { Cmd::ConfigRepoInit => {
let n = workflow::config_repo_init(&load_config(&cli.config)?)?; let n = workflow::config_repo_init(&load_config(&cli.config)?)?;
@@ -505,6 +783,23 @@ fn print_report(rep: &SyncReport) -> Result<()> {
} }
} }
} }
for p in &rep.pruned {
match p {
Pruned::Removed {
branch,
pr,
path,
backup_ref,
} => println!(
"pruned {branch}: {}, removed {} (backup {backup_ref})",
merged_how(*pr),
path.display()
),
Pruned::Kept { branch, pr, why } => {
println!("kept {branch}: {} but {why}", merged_how(*pr))
}
}
}
for w in &rep.worktrees { for w in &rep.worktrees {
let branch = w.branch.as_deref().unwrap_or("(detached)"); let branch = w.branch.as_deref().unwrap_or("(detached)");
let mut notes = Vec::new(); let mut notes = Vec::new();
+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());
}
}
+3 -8
View File
@@ -95,14 +95,8 @@ pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
/// Git environment for SSH remotes: the user's keys/agent authenticate and nothing prompts. /// Git environment for SSH remotes: the user's keys/agent authenticate and nothing prompts.
/// `BatchMode` is only forced when the user has no ssh command of their own. /// `BatchMode` is only forced when the user has no ssh command of their own.
fn ssh_env() -> Vec<(String, String)> { fn ssh_env() -> Vec<(String, String)> {
let mut env = vec![("GIT_TERMINAL_PROMPT".to_string(), "0".to_string())]; let mut env = grove_core::git::noninteractive_env();
let custom = std::env::var_os("GIT_SSH_COMMAND").is_some() if !grove_core::git::has_custom_ssh() {
|| std::env::var_os("GIT_SSH").is_some()
|| std::process::Command::new("git")
.args(["config", "--get", "core.sshCommand"])
.output()
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty());
if !custom {
env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into())); env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into()));
} }
env env
@@ -188,6 +182,7 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
public: None, public: None,
}], }],
sync: Default::default(), sync: Default::default(),
open: Default::default(),
config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo { config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo {
provider: a.provider, provider: a.provider,
name, name,
+6
View File
@@ -5,3 +5,9 @@
3. Config: TOML for user intent (implemented); runtime state storage still open. 3. Config: TOML for user intent (implemented); runtime state storage still open.
4. License: MIT (decided). 4. License: MIT (decided).
5. Final name: Grove (decided; binary `grove`, crates `grove-core` and `grove`). 5. Final name: Grove (decided; binary `grove`, crates `grove-core` and `grove`).
6. Open: `groved` under systemd gets `PATH=/usr/local/bin:/usr/bin:/bin`, so a `tea`/`gh` in `~/.local/bin` is not found and the token lookup fails. Options: ship `Environment=PATH=%h/.local/bin:...` in `contrib/groved.service`, or resolve the helpers by absolute path (`~/.local/bin`, then `PATH`). Workaround in use: a user drop-in (see `two-pc-run.md`).
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. cannot starve snapshots.
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply - **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
snapshots, materialize/archive). Also what catches missed events. snapshots, materialize/archive). Also what catches missed events.
- **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass; - **Worker pool**: the loop thread only schedules; `sync.workers` threads (default 4, 1 to 32) run
it finds nothing to do and ends the chain. 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 - **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 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. are still snapshotted locally (an offline pass); only the network is retried after the backoff.
+33
View File
@@ -118,6 +118,39 @@ groups are only picked up then).
**Breaking change:** group names must now be plain directory names (non-empty, no `/`, no leading **Breaking change:** group names must now be plain directory names (non-empty, no `/`, no leading
`.`); a config with other names no longer loads. `.`); a config with other names no longer loads.
### Repos deleted on the forge
A managed repo whose remote was deleted is moved out of the synced tree, never deleted locally:
```toml
[sync]
purged_dir = "Purged" # default; "" disables the move
```
- 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
`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
the same as a deletion. Being removed from one of your own `owners` organisations is still
indistinguishable and moves its repos.
- Never while busy: the move holds `.grove-busy` and is skipped (`purge_failed`, retried next
pass) when `.grove-stage` exists or a worktree has a git operation in progress (`index.lock`,
rebase, merge, cherry-pick, revert, bisect).
- Action: `root/<group>/<repo>` moves to `root/<purged_dir>/<group>/<repo>` (a `-<stamp>` suffix
if taken) by `rename` (same file system only; otherwise it stays and `purge_failed` is logged),
then `git worktree repair` fixes the in-repo and linked worktrees (paths compared after
resolving symlinks). Worktrees whose directory is missing at that moment are listed in the
`purged` entry for a later `git worktree repair`. The directory is not a configured group, so
the daemon stops syncing it.
- Activity log: `purge_pending` (first confirmation), `purged` (moved, with the destination),
`purge_failed` (not moved, with the reason).
- `purged_dir` must be a plain directory name and must not also be a group.
- The confirmation state is in memory: a daemon restart restarts the 10-minute wait.
### Snapshot policy ### Snapshot policy
WIP snapshots (`refs/sync/<machine>/<branch>`) contain uncommitted work, so on a public repo anyone WIP snapshots (`refs/sync/<machine>/<branch>`) contain uncommitted work, so on a public repo anyone
+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` 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 `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 `/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. X11 loaded at runtime) and the software renderer.
## Dependencies ## 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 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. `/user/repos` (collaborator repos included) and says when `/orgs/{owner}` is a 404.
- The GUI hands `grove add` the canonical path it validated. - 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.
+111
View File
@@ -0,0 +1,111 @@
# 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. Branches merged
into the default branch without a pull request (merged locally and pushed) are removed too.
## Config
```toml
[sync]
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.
## What counts as merged
`Provider::merged_pulls(owner, repo)` lists one page of the most recently updated closed pull
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`. 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) 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); 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).
Then the tip is saved under `refs/sync-backup/<machine>/<stamp>/merged/<branch>`, the worktree
is removed (`git worktree remove --force`, needed for the disposable ignored files only) and the
local branch is deleted. Nothing on the forge changes: the remote branch, if any, stays.
A merged worktree with local work is kept and reported, once per change, as `prune_kept`
(`feat/x: merged in PR #12 but kept: ignored files: .env`).
## Not brought back by `auto_materialize`
`materialize` creates a worktree for every remote branch without one, so a pruned branch whose
head was not deleted on the forge would come back on the next pass. It now skips a remote
branch whose tip is the head of a merged PR or the tip this machine pruned (its `merged/` backup
ref), so this holds also offline or when the forge cannot be asked. New commits pushed to the
branch after the merge are new work: the worktree is materialized again.
## Daemon
- The forge is asked at most every 5 minutes per repo, and only when the repo has a worktree
on a non-default branch. The answer is in memory only.
- A failed lookup keeps the last answer and is logged once as `prune_lookup_failed` (until the
error changes).
- Offline passes (backoff) prune nothing, but still use the last answer to keep pruned branches
from being materialized.
- 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 only the ancestry rule applies.
## Validation
- `grove-core/tests/prune.rs`: squash merge with the head branch kept on the remote (pruned with
`target/` present, backup ref, not re-materialized with or without a forge answer, comes back
after a new commit), local work (untracked file, non-disposable ignored file, local commit)
keeps the worktree, an older tip contained in the PR head is pruned, the default branch and a
linked worktree outside the repo are never touched.
- `grove-providers/tests/api.rs`: request shape on both forges, only merged same-repo PRs kept
(fork and deleted-fork heads left out), API errors surface.
- `grove-daemon` `merged` unit tests: TTL cache, last answer kept on failure, error and kept
notes logged once.
- Config: defaults and validation of `prune_disposable`.
## Not verified
- Against a real GitHub or Gitea (mock-tested only).
- Only the first page of closed PRs is read: a branch merged long ago in a busy repo (more than
100 / 50 PRs closed since) is not found. `grove sync` on it does not help either; remove it by
hand.
+50
View File
@@ -0,0 +1,50 @@
# Real two-PC run
First real run on two machines, 16/11/2026: `Dasemu-LT` (laptop, already running Grove) and
`Dasemu-PC` (desktop, Fedora 44, KDE Plasma / Wayland, installed fresh from `development` at
`e6030f7`). Real forges: Gitea `git.zenvairo.es` (SSH on port 2222) and github.com, both with
`protocol = "ssh"`.
## Result
Passed. An uncommitted file in a private test repo on `Dasemu-PC` was snapshotted by the daemon
and pushed as `refs/sync/Dasemu-PC/main` (snapshot commit on top of `main`, containing only the
untracked file). On `Dasemu-LT`, after `grove import Darío <test repo>` and one daemon pass, the
snapshot showed up as `refs/sync-remote/Dasemu-PC/main`. The other direction was already visible
on real repos: `Academia-LMS` carries both `refs/sync/Dasemu-LT/feat/student-portal` and
`refs/sync/Dasemu-PC/feat/student-portal`. The throwaway repo was deleted from Gitea afterwards.
Notes:
- Right after `grove import`, the clone has no `refs/sync-remote/*` yet; they arrive with the
daemon's first pass over the new repo (up to `fetch_interval_s`, or `grove daemon sync PATH`).
- A repo created while the daemon runs is picked up (`repo_added`), but its worktree states only
appear after its first pass.
## Install on the second machine
`cargo test` passed; `grove`, `groved` and `grove-gui` installed with `cargo install --root ~/.local`.
`grove doctor` found both tokens (tea, gh). Migration of the existing `~/Hacking`:
- 14 plain clones migrated with `grove add`; 9 of them had a read-only Gitea pull mirror as
`origin` and were switched to their GitHub source (the `e6030f7` fix), Grove itself included.
- 19 missing repos cloned with `grove import`; 4 unversioned folders turned into repos with
`grove new` (2 public on GitHub with a Gitea mirror, 2 private on Gitea).
- First daemon pass: no `diverged`, 8 `dirty`, 2 `ahead`; 36 public repos report
`snapshots withheld` as intended.
## Problems found
1. **systemd PATH.** The user unit runs with `PATH=/usr/local/bin:/usr/bin:/bin`. `tea` lived in
`~/.local/bin`, so under systemd `groved` found no Gitea token (`grove doctor` run with that
PATH: `no token for provider "gitea"`). Worked around with a drop-in
`~/.config/systemd/user/groved.service.d/path.conf` setting
`Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin`. See `DECISIONS.md` (6).
2. **Leftover `extensions.worktreeConfig`.** Claude Code worktrees set
`extensions.worktreeConfig = true`; it stays after the worktrees are removed. `grove add`
refused 12 such clones ("sparse checkout / per-worktree config is not supported yet") although
none had a `config.worktree` file. Unsetting the extension (only when no `config.worktree`
exists and sparse checkout is off) let them migrate. See `DECISIONS.md` (7).
3. **Clones with a dirty linked worktree** still cannot be migrated (2 repos left as plain clones).
4. **Repos deleted on the forge after import** (2 on Gitea) make the daemon log a fetch error on
every pass. `development` now moves such repos to `Purged/` (PR #4); not part of this install.