View all posts →

Git Worktrees

git-worktrees

OK, so everyone here faced a common problem on git, which is branch switching in the middle of something! Let me, clear you in the below example.

Consider you are working under the branch x on something, suddenly a friend of yours stuggling with some thing on the same code base, she/he wants your help to debug that in your machine, what will you do now?

Typical flow would be, you will either stash your current work on branch x or do a dummit commit(most probably will forget to squash :D).

To solve this particular problem git-worktree is used, basically git-worktree allows one to seamlessly switch branches by persisting changes on respective branches.

How to use git-worktree?

To use git-worktree, the main change would be, you need to clone your github repo with a flag called --bare.

git clone --bare [email protected]:user/repo

Once done, the repo will contain the above folders. As you can see this is what bare cloning looks like, basically this contains the worktree of the repo.

From here, you can add your branches, checkout new branches with git-worktree command

git worktree list // lists the checked out branches(in the above ss you can see main and stage, since i have already added those two branches)


git worktree add BRANCH_NAME PATH_NAME // eg: git worktree add main main

You can add n number of branches like above to your worktrees. Whenever you want to do something with your code just cd into the branch that you want to work on and do your changes, now considering the initial situation i mentioned, if your are working on branch x, now you want to do something in branch y for your friend, you can easily add that worktree branch and cd to that particular path and do your stuff, so that your working branch(branch x) doesn't even know what is happening.

Some of useful commands:

git clone GIT_REPO --bare - Will clone your repo as a bare, instead of a specific branch(main).

git worktree list - List the number of checked out branches in your worktree.

git worktree add PATH/BRANCH_NAME BRANCH_NAME - Adds your remote branch to your local worktree.

git worktree add PATH/BRANCH_NAME -b BRANCH_NAME BASE_BRANCH - Adds a new branch to your local worktree.

If you are using vim/nvim, i strongly recommend to checkout this git-worktree plugin which integrates easily into the telescope module.

View all posts →