Re: Bug: git worktree remove and overwritten directory
Jonathan Müller
Git List
Eric Sunshine
See Also
2020-05-20 14:22:45 UTC
On Wed, May 20, 2020 at 6:36 AM Jonathan Müller
<> wrote:
> It seems to be impossible to remove a git worktree whose location has
> been replaced by the main working tree [...]
> cd test
> git worktree add ../test2 some-branch
> cd ../
> rm -rf test2  # Remove the worktree folder
> mv test test2 # Main git repository now located where the worktree used
> to be
> Afterwards, `git worktree list` reports:
> /home/foonathan/test2  e7bb748 [master]
> /home/foonathan/test2  e7bb748 [some-branch]
> And both `git worktree remove .` and `git worktree remove ../test2`
> report an error `fatal: '../test2' is a main working tree`. I had to
> manually remove the corresponding folder from `.git/worktree` to get rid
> of it. The issue is especially annoying, because you can't check out
> `some-branch` anymore (as it's already checked out in the worktree).

Git tries hard to prevent the same directory from being registered to
multiple worktrees, however, there is not much it can do to prevent a
person from shooting himself in the foot by making changes like this
outside of Git's control. Thus, this seems like a case of "if it
hurts, don't do it".

However, "git worktree" could possibly do a better job of helping you
recover from such a situation. In particular, I think it should be
reasonably easy to enhance "git worktree prune" to detect this
situation and automatically prune the non-main now-bogus worktree

It may be possible to special-case "git worktree remove" to detect
this situation and automatically prune the bogus entry too, but I'm
quite hesitant to suggest that sort of special case both because the
implementation would likely be ugly, and it could lead to a plethora
of additional ugly special-cases as people discover even more ways to
shoot themselves in the feet.

If you have ideas about how else the situation can be improved, please
feel free to share them, as such discussion may shed light on
possibilities which are not presently obvious.