DEV Community

LokiDev
LokiDev

Posted on

Advanced Git: Worktree

Image description

One of my favorite unknown features of Git is the worktree. A part from the Git toolbelt which allows us to have multiple checked out branches with just one repository.

This is perfect for code reviews where you actually want to dig into the code and don't want to use the webfeatures of Git(lab|hub) or other alternatives.

Enough the words, lets see how this works...

Git Worktree

What we could get

$ tree
project_name/
 |- master/
 |- develop/
 |- feature/
 |   |- ABC-123_implement_death_laser/
 |- hotfix/
     |- ABC-42_solve_climate_crisis/
Enter fullscreen mode Exit fullscreen mode

Each branch has it's own Git repository, but all share the repository metadata.

How do we get there?

  1. create project folder: mkdir project_name and cd into the folder cd project_name
  2. clone your repository, but with some feature flags: git clone --bare GIT_URL .bare
    • this clones from GIT_URL to the local hidden folder .bare
    • --bare makes it so, that we don't get any specific branch
  3. create the .git file and tell it (by writing in it ;) where our bare repository is:
   # project_name/.git
   gitdir: ./.bare
Enter fullscreen mode Exit fullscreen mode

Now our repository knows where all the desired metadata can be found

  1. Lets add our desired branches: git worktree add develop or git worktree add featre/some_feature. The / creates automagically new folders for us.

Additional helpful stuff

Remove a single branch/folder

Two possibilities:

  1. remove the folder just like every other folder and run git worktree prune after that
  2. git worktree remove BRANCH_NAME

Show all worktree folders

git worktree list
Enter fullscreen mode Exit fullscreen mode

Create a branch folder outside of the repository folder

Yes. this is indeed possible. Say, you have your project cookie_bakery in your project folder: /home/lokidev/projects/cookie_bakery.
But now you want to have new branch in which you have a huge project which shouldn't be INSIDE this cookie_bakery folders, but it's really important and needs to be on some external harddrive. Here you go:

git worktree add -b BRANCH_NAME FOLDER
# e.g.
git woktreee add -b feature/super_important /media/usb-drive/important
Enter fullscreen mode Exit fullscreen mode

Move/Rename branch-folder

git worktree move SOURCE_FOLDER DESTINATION
Enter fullscreen mode Exit fullscreen mode

More awesome Git stuff?

There is more awesome stuff in the Git toolbelt like bisect which helps you find the exact moment in the git history, where an error was introduced.

Another nice feature is hunk based adding/committing of files and changes.

If you want more of this, just tell me. If you have things I can make better: even better!

Additional Links

Discussion (0)