Dev In The Mountain Header
A Developer In The mountains having fun

Git Worktrees and Secret Management

Git Worktrees

Branches

git branch switch <branchname>

Creating a New Worktree

  • Create a new worktree for an existing branch at the specified path:
    git worktree add <WORKTREE-PATH> <BRANCH>
    
  • Create a new branch and its worktree at the specified path:
    git worktree add -b <BRANCH> <WORKTREE-PATH>
    

Listing Worktrees

  • List all current worktrees, including the main worktree:
    git worktree list
    
  • List worktrees in a machine-readable format:
    git worktree list --porcelain
    

Deleting a Worktree

  • Delete a worktree:
    git worktree remove <WORKTREE-PATH>
    
  • Clean up worktree metadata:
    git worktree prune
    

Other Worktree Commands

  • Lock a worktree to prevent it from being pruned:
    git worktree lock [--reason <string>] <worktree>
    
  • Move a worktree to a new location:
    git worktree move <worktree> <new-path>
    
    Worktrees allow you to check out multiple branches simultaneously in separate directories, avoiding the need to constantly switch between branches or use git stash.

Merge Worktrees

  1. Identify the worktrees you want to merge: Determine which branches/worktrees you want to combine into a single branch. You can list all your current worktrees using the command git worktree list.

  2. Checkout the target branch: Switch to the branch you want to merge the other worktree(s) into using git switch <target-branch>. This will be the branch that will contain the final merged changes.

  3. Merge the worktree branches: Use the standard git merge command to incorporate the changes from the other worktree branches into the target branch. For example, to merge the feature-x branch into the main branch:

    git switch main
    git merge feature-x
    

    This will merge the feature-x branch into the currently checked out main branch.

  4. Resolve any conflicts: If there are any conflicts between the branches, Git will pause the merge process. You'll need to manually resolve the conflicts, stage the resolved files, and then continue the merge:

    git merge --continue
    

    Alternatively, you can abort the merge and start over if needed:

    git merge --abort
    
  5. Clean up the worktrees: Once the merge is complete, you can optionally delete the now-merged worktrees using git worktree remove <worktree-path>. This will remove the linked worktree directory while keeping the main repository intact.

Secrets in Git Repository

Scan for Problems

Remove Secrets Securely

  1. Rewrite history:
    git filter-repo --replace-text replacements.txt --replace-refs delete-no-add
    
  2. Force push all changes to remote:
    1. git push origin --force --all
      
    2. git push origin --force --tags
      

Manage Secrets in Git Repo

More places to find me
Mental Health
follow me on Mastodon