This is a follow-up on this question on creating branches.
It strikes me as odd that I would still work on one repository because the files on my local machine will be a weird mix of different experiments.
I would imagine the best-practice method is to duplicate the repository and work in different folders on my computer for each branch — but I don’t know how to set this up. I have my current repository at Documents/San/CompProj so what are the commands I’d use to create a new repository tied to a different branch on a different local folder?
Git is fairly new to me so I’d love any corrections you can make on what I’m assuming/asking above.
As of Git 2.5,
git-worktreedirectly supports this workflow. See VonC’s answer to this question for details.My answer below may suffice if you don’t like
git-worktreefor whatever reason.Git is designed to allow you to work within a single folder on disk. This is a single repository that contains all the branches you care about.† You checkout whichever branch you want to work on at the time.
Within a Git repository, you can only have a single branch checked out at a time. If you check out a second branch, the files on disk are removed and replaced with those from the second branch.
If you have the following branches:
When you’re on branch-A and you checkout branch-B, then
bravo.txtwill be removed anddelta.txtwill be added to your working directory.However,
git-checkoutwill not overwrite changes you’ve made to files unless you supply the-fargument. If you make a change toalpha.txtthen try to switch to branch-B, you’ll get a message warning you that your changes would be lost and aborts the checkout.The exceptions are untracked files. If you have branch-A checked out and you create a new file called
echo.txt, Git will not touch this file when you checkout branch-B. This way, you can decide that you want to commitecho.txtagainst branch-B without having to go through the hassle of (1) move the file outside the repo, (2) checkout the correct branch, and (3) move the file back into the repo.Footnote
† Actually, Git doesn’t force you to use a single working directory. If you want, nothing is stopping you from creating different paths on disk for each branch you want to work on.
Each of these paths is its own Git repository (each one has a
.gitfolder inside), and you can push and pull commits between the repos.This is how some people use Mercurial if they aren’t using named branches: they clone the repository into a new directory on disk for each branch they want, then push and pull changesets between them.