JoeL JoeL - 3 months ago 16
Git Question

Git - Where do files go when you change branches?

Just beginning to learn about git and I love the concept of it. There's one thing that is a bit weird to me so far that I can't seem to find in a search. When I type

git checkout branchName
to change to whatever branch I want to, when I look at the Finder window I can visually see files/folders appear or disappear in the repo based on what branch I'm in.

The 2 images below showcase how I am in one branch and then go to a different branch (This is from doing a Lynda.com course). The left side shows the Finder and how the folder _fonts disappears because it wasn't present in the other branch.

But where exactly is it (and the other files that have changes)? From what I see here, I can't physically view files from different branches at one time, but I'm just curious where they actually go in the system when I change branches.

Inside one branch with a _fonts folder

Inside a different branch that does not have the _fonts folder

Answer

From what I see here, I can't physically view files from different branches at one time, but I'm just curious where they actually go in the system when I change branches.

Yes you can do it

You simply need to follow this:

Git has exposed this feature back in 2007 under the name git workdir. It was located under the git contrib folder for many years.

In git version 2.5 it was exposed as git worktree. It allow you to work simultaneously on multiple branches.

How to do it?

# create a new working directory
# the path will be added and the given branch name will be checkout out
git worktree add <path to the new working directory/ branch name> 

# now you have 2 folders with different branches in each one of them.
# if you used something like `git worktree /tmp/aaa` than you will have 
# branch aaa checked out in the new folder and you can switch to any branch
# you wish

Each worktree has its own 3-states so you cannot the same branch on multiple worktrees.

for example:

git worktree add <second path>

will create another folder on your computer which allow you to work on different branch simultaneously.

git worktree will create 2 separate working folders separated from each other while pointing to the same repository.

This will allow you do to any experimentals on the new worktree without having any effect on the repository itself. In the attached image you can see that there are 2 separate working folder but both of them are using a single repo and share the content.

Here is a sample on how to create new worktree and what is the result of it:

enter image description here

Comments