worktree-cleanup

module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: Apache-2.0

README

worktree-cleanup

ci OpenSSF Scorecard

Remove git worktrees whose GitHub pull request or GitLab merge request is merged or closed. A worktree is removed only when the forge proves its HEAD commit is preserved, and never while it holds uncommitted, untracked, or non-disposable ignored files.

What it does

worktree-cleanup scans the linked worktrees of git repositories and removes the ones whose work the forge has preserved: a worktree is removed only when GitHub or GitLab proves that its HEAD commit is contained in a merged or closed pull request or merge request, or in the project's default branch. The main worktree is never touched.

Guarantees:

  • Dry run by default. Nothing is removed unless pruning is enabled, by --prune, WORKTREE_CLEANUP_PRUNE=true, or prune: true in the config file.
  • A worktree with uncommitted changes, untracked files, assume-unchanged or skip-worktree paths, submodules, a rebase, merge, cherry-pick, revert, or bisect in progress, or ignored files outside the disposable list is kept.
  • The worktree holding the directory worktree-cleanup runs from is kept.
  • A worktree on a project's default branch is kept, whatever the forge proves about its HEAD.
  • git worktree remove is never run with --force, so git's own refusals (a locked worktree, for one) stand as a second check.
  • Immediately before removal, the worktree's local state is checked again: it must still be listed with the same HEAD and branch, the branch must still point at that HEAD, and every rule from locked through ignored files not disposable in How a worktree is judged must still pass. A worktree that changed is kept as changed since scan: .... The idle time and the forge are not checked again.
  • The local branch is deleted only after its worktree was removed, only if the branch still points at the commit the forge verified, and never when a forge named it as a project's default branch.
  • Any forge error keeps the worktree.

What it does not guarantee: commits reachable only from the removed worktree's reflog or from the deleted branch's reflog become unreachable and may be collected by the next git gc. The forge check covers HEAD and its ancestors, not other local-only history. See Recovery.

Install

Each release publishes a linux/amd64 and a linux/arm64 archive with worktree-cleanup at its root, a checksums.txt over them, and a cosign keyless signature of that file:

v=0.1.0 arch=amd64
curl -fsSLO "https://github.com/jhoblitt/worktree-cleanup/releases/download/v$v/worktree-cleanup_${v}_linux_$arch.tar.gz"
curl -fsSLO "https://github.com/jhoblitt/worktree-cleanup/releases/download/v$v/checksums.txt"
sha256sum --ignore-missing -c checksums.txt
tar -xzf "worktree-cleanup_${v}_linux_$arch.tar.gz" worktree-cleanup && install -m 0755 worktree-cleanup ~/bin/worktree-cleanup

Or install from source with the Go toolchain — no clone needed:

go install github.com/jhoblitt/worktree-cleanup/cmd/worktree-cleanup@latest

@latest resolves to the newest release; @main builds the newest commit, which may not be released yet.

Usage

worktree-cleanup [flags] [repo ...]

Name repositories as arguments, or set --root to scan a directory: the directory itself and each of its immediate subdirectories are checked for being a repository. With neither, the current directory is scanned that way, and finding no repository there is an error. Each worktree is reported on one row, then a summary is printed.

# dry run over the current directory's repository, or the ones directly inside it
worktree-cleanup

# dry run over every repository directly under ~/src
worktree-cleanup --root ~/src

# remove what a dry run reported, for one repository
worktree-cleanup --prune ~/src/widgets
Flags

Each flag can also be set as an environment variable or a config file key of the same name. Precedence is flags, then WORKTREE_CLEANUP_* environment variables, then the config file, then defaults.

Flag Default Meaning
--prune false Remove the worktrees found removable.
--root current directory Directory scanned for repositories; repeatable. A leading ~ is expanded. In the environment, separate several with spaces.
--min-idle 24h Keep a worktree whose git state changed more recently.
--disposable built-in list Patterns for ignored files a removable worktree may hold. Replaces the built-in list. In the environment, separate several patterns with spaces.
--concurrency 16 Worktrees decided at once, across all repositories. Whatever its value, at most 16 requests to one forge host are in flight at once, and removals within one repository run one at a time.
--format text Row format on stdout: text or json.
--config none YAML config file.
--log-level info debug, info, warn, or error. Logs go to stderr.
--log-format json json or text.

An environment variable is the flag name upper-cased, with - as _, and the prefix WORKTREE_CLEANUP_, for example WORKTREE_CLEANUP_MIN_IDLE.

Example config file, for --config:

root:
  - ~/src
  - ~/work
min-idle: 48h
disposable:
  - node_modules/
  - bin/
  - "*.test"
Exit status

0 when the run completed with no error row, including a dry run that found removable worktrees. 1 when any row is an error, when a row or the summary cannot be written to stdout, or on a usage or configuration error.

Authentication

github.com is always checked and needs a gh login or a token; other hosts are contacted only if you have configured gh or glab for them.

  • GitHub: gh auth login, or set GH_TOKEN or GITHUB_TOKEN for github.com. For GitHub Enterprise Server run gh auth login --hostname <host> (or set GH_HOST); setting GH_ENTERPRISE_TOKEN alone does not make a host known. A rate-limited request waits for the limit to reset when that is at most 60 seconds away, for up to three attempts; a later reset is an error row.
  • GitLab: glab auth login, or set GITLAB_TOKEN. GITLAB_TOKEN applies only to one host: the hostname of GITLAB_HOST, or gitlab.com when that is unset. Any other host uses the token in glab's config.yml ($GLAB_CONFIG_DIR, else $XDG_CONFIG_HOME/glab-cli, else ~/.config/glab-cli). A token glab keeps in the system keyring is not read. The API is reached at https://<host>/api/v4, or where the config's api_protocol and api_host for the host say. When GITLAB_TOKEN is in use and the config sets neither for its host, the scheme and port of GITLAB_HOST are used instead: GITLAB_HOST=http://gitlab.example.com:8080 reaches http://gitlab.example.com:8080/api/v4.

Each request to GitHub or GitLab is given 60 seconds; one that takes longer fails, and the worktrees waiting on it are error rows.

A github.com remote with no token is an error row, not a skip. A remote on any other host that gh or glab is not configured for is ignored, and a worktree whose repository has no remote on a known host is kept as no forge remote.

How a worktree is judged

Only linked worktrees are considered. The rules run in this order and the first that applies decides. Local rules run first, so forge requests are made only for a worktree with nothing local to lose.

Keep reasons:

  1. locked or locked: <reason>.
  2. prunable: run git worktree prune if intended.
  3. current directory: worktree-cleanup is running from inside it.
  4. contains worktree <path>: another worktree lives inside it.
  5. uncommitted changes.
  6. untracked files.
  7. assume-unchanged/skip-worktree paths.
  8. has submodules: a .gitmodules file at the worktree root.
  9. operation in progress: a rebase, merge, cherry-pick, revert, or bisect is under way in the worktree.
  10. ignored files not disposable.
  11. active <duration> ago: newer than --min-idle, judged by the modification time of HEAD, index and logs/HEAD in the worktree's git directory.
  12. no forge remote.
  13. no reachable forge project: the forge reports every project the remotes name as not found.
  14. default branch <name>: the worktree's branch is the default branch of a project the remotes name.
  15. open PR #N or open MR !N: a pull or merge request containing HEAD is still open.
  16. A removal reason, if one applies, tried in this order:
    • merged PR #N, merged MR !N, or closed MR !N: HEAD is contained in the head of a merged pull or merge request, or of a merge request closed without merging.
    • on <branch>: HEAD is contained in the project's default branch.
    • closed PR #N: HEAD is contained in the head of a pull request closed without merging. GitHub finds those only through its search API, which allows 30 requests a minute, so they are looked for last.
  17. HEAD not on forge (never pushed?): no project holds HEAD.
  18. no merged/closed change contains HEAD: some project holds HEAD but none of the above applied.

A worktree that cannot be inspected, or whose forge query fails, is an error row and is kept.

Reading the output

Text format, one row per worktree, always six tab-separated fields: action, reason, path, branch, head (the full SHA of the worktree's HEAD), and the pull or merge request URL. A field with nothing to say is left empty rather than dropped, so a detached worktree has an empty branch and a row without a URL ends in a tab. A blocking: line lists the paths behind a keep reason: up to ten for uncommitted, untracked, and skip-flagged paths, and every non-disposable entry for ignored files not disposable.

would-remove	merged PR #12	/work/widgets-fix-parser	fix-parser	4f1c2a9e8b7d6c5f4e3d2c1b0a9f8e7d6c5b4a39	https://github.example.com/acme/widgets/pull/12
would-remove	on main	/work/widgets-old-release	old-release	9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b	
keep	open PR #15	/work/widgets-new-cache	new-cache	c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2	https://github.example.com/acme/widgets/pull/15
keep	ignored files not disposable	/work/widgets-wip	wip	0e1d2c3b4a5f6e7d8c9b0a1f2e3d4c5b6a7f8e9d	
  blocking: .env
keep	active 12m ago	/work/widgets-hotfix	hotfix	5b6a7f8e9d0e1d2c3b4a5f6e7d8c9b0a1f2e3d4c	
summary: removed=0 would-remove=2 keep=3 error=0

Actions are removed, would-remove (dry run), keep, and error. When a worktree was removed but its branch could not be deleted, the reason ends in ; branch kept: <why>.

Rows are printed as worktrees are decided, many at once, so their order differs from run to run; the summary always comes last.

With --format json, each row is one JSON object (action, reason, repo, path, branch, head, and change_url and blocking when set), followed by a final {"summary": {...}} object.

Tuning the disposable list

Ignored files are allowed in a removable worktree only if they match a disposable pattern; the others are listed after blocking:. To allow what you see there, add a pattern and rerun. Patterns are read like .gitignore lines with one difference: a pattern ending in / matches only directories, and any other pattern matches only files, so *.out covers cover.out but neither a directory sim.out/ nor anything inside it. git lists an ignored directory as one entry without its contents, so only a pattern written for a directory lets one go. A directory pattern covers everything beneath a directory it matches, because git lists the contents instead when only they are ignored, as in a cache directory that carries its own .gitignore: .ruff_cache/ covers .ruff_cache/CACHEDIR.TAG. A pattern containing a / elsewhere is anchored at the worktree root, and any other pattern matches an entry's last path segment at any depth. Setting --disposable replaces the built-in list, which is:

_output/  .cache/  __pycache__/  *.pyc  *.test  *.out
node_modules/  bin/  dist/  .build*/  target/

An empty list makes every ignored file block removal.

Recovery

Removal deletes the worktree directory and its local branch, whose commits the forge holds. GitHub keeps refs/pull/<N>/head for a pull request, so git fetch origin pull/<N>/head retrieves the commits and git switch -c <name> FETCH_HEAD makes a branch of them. GitLab keeps a merge request's commits retrievable: take the removed worktree's head SHA from its row, the fifth field of a text row or head in --format json output, and create a branch from it in the web UI or with the API's branch endpoint. A worktree removed because HEAD was on the default branch needs no recovery.

Commits held only in a reflog, as noted above, may be lost.

Development

Commit messages follow Conventional Commits; commitlint enforces this on every pull request. Every GitHub Action is pinned to a commit SHA: run pinact run after editing a workflow and actionlint before committing it. Where a Makefile is present, make check is the local gate, make tools installs the pinned linter, and that pin lives in the Makefile.

License

Apache-2.0

Directories

Path Synopsis
cmd
worktree-cleanup command
Command worktree-cleanup: Remove git worktrees whose GitHub PR or GitLab MR is merged or closed
Command worktree-cleanup: Remove git worktrees whose GitHub PR or GitLab MR is merged or closed
internal
cleanup
Package cleanup decides, for each linked worktree of a repository, whether it can be removed, and removes it when asked to.
Package cleanup decides, for each linked worktree of a repository, whether it can be removed, and removes it when asked to.
cleanup/cleanupfakes
Code generated by counterfeiter.
Code generated by counterfeiter.
cli
Package cli builds the worktree-cleanup command tree.
Package cli builds the worktree-cleanup command tree.
forge
Package forge defines the forge-neutral vocabulary shared by the GitHub and GitLab clients and the cleanup engine: which project a remote names, and which pull or merge requests a commit belongs to.
Package forge defines the forge-neutral vocabulary shared by the GitHub and GitLab clients and the cleanup engine: which project a remote names, and which pull or merge requests a commit belongs to.
forge/github
Package github answers the cleanup engine's forge questions against the GitHub REST API: whether a project exists, its default branch, which pull requests contain a commit, and whether one commit contains another.
Package github answers the cleanup engine's forge questions against the GitHub REST API: whether a project exists, its default branch, which pull requests contain a commit, and whether one commit contains another.
forge/gitlab
Package gitlab answers the cleanup engine's forge questions — does a project exist, which merge requests contain a commit, does one commit contain another — against the GitLab REST API, with credentials taken from the environment or glab's config file.
Package gitlab answers the cleanup engine's forge questions — does a project exist, which merge requests contain a commit, does one commit contain another — against the GitLab REST API, with credentials taken from the environment or glab's config file.
gitrepo
Package gitrepo drives the git binary to list a repository's worktrees, inspect a worktree for anything its removal would lose, and remove worktrees and branches.
Package gitrepo drives the git binary to list a repository's worktrees, inspect a worktree for anything its removal would lose, and remove worktrees and branches.
remote
Package remote turns git remote URLs into forge projects.
Package remote turns git remote URLs into forge projects.
version
Package version reports what the toolchain stamped into the binary.
Package version reports what the toolchain stamped into the binary.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL