Skip to content

Commit

Permalink
pyinfra/operations: git worktree add --force support
Browse files Browse the repository at this point in the history
-- Why is this needed?

Current scenario:

1. During pyinfra deployment: `git worktree add /path/to/wk commitish`
2. `rm -f /path/to/wk` happens
3. Deployment is run again, however `git worktree add /path/to/wk commitish` fails:

   ```
   fatal: '../wk' is a missing but already registered worktree;
    use 'add -f' to override, or 'prune' or 'remove' to clear
   ```

   Requiring manual intervention: `git worktree prune` and even `git branch -d wk` if
   the branch was created.

Solution:

Use `-f`/`--force` (i.e. `force`) to avoid the failure entirely.
  • Loading branch information
Pirols authored and Fizzadar committed Sep 1, 2024
1 parent 78c7376 commit 2fb4fb0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
13 changes: 12 additions & 1 deletion pyinfra/operations/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def worktree(
+ from_remote_branch: a 2-tuple ``(remote, branch)`` that identifies a remote branch
+ present: whether the working tree should exist
+ assume_repo_exists: whether to assume the main repo exists
+ force: remove unclean working tree if should not exist
+ force: whether to use ``--force`` when adding/removing worktrees
+ user: chown files to this user after
+ group: chown files to this group after
Expand All @@ -205,6 +205,14 @@ def worktree(
commitish="4e091aa0"
)
git.worktree(
name="Create a worktree from the tag `4e091aa0`, even if already registered",
repo="/usr/local/src/pyinfra/master",
worktree="/usr/local/src/pyinfra/2.x",
commitish="2.x",
force=True
)
git.worktree(
name="Create a worktree with a new local branch `v1.0`",
repo="/usr/local/src/pyinfra/master",
Expand Down Expand Up @@ -304,6 +312,9 @@ def worktree(
elif detached:
command_parts.append("--detach")

if force:
command_parts.append("--force")

command_parts.append(worktree)

if commitish:
Expand Down
19 changes: 19 additions & 0 deletions tests/operations/git.worktree/create_force.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"args": ["/home/myworktree"],
"kwargs": {
"repo": "/home/mainrepo",
"force": true
},
"facts": {
"files.Directory": {
"path=/home/mainrepo": {},
"path=/home/mainrepo/.git": {
"mode": 0
},
"path=/home/myworktree": null
}
},
"commands": [
"cd /home/mainrepo && git worktree add --force /home/myworktree"
]
}

0 comments on commit 2fb4fb0

Please sign in to comment.