1

I want to work on two branches simultaneously from my local environment. I need to do that because on one branch, I'm running heavy tests which take lots of time and during this time I can't do anything. I wanted to create another branch for some other task and work on it while the tests are running.

One way to do that is by cloning the repo again (to a different location), create the second branch there, and work on it. I'm wondering if that's the best solution though.

Does anyone have an idea? Thanks ahead!

  • 2
    Checkout a separate worktree in the same local repository. It allows you to do what you want. Read about [`git worktree`](https://git-scm.com/docs/git-worktree). – axiac Jul 25 '21 at 08:17

2 Answers2

4

Checkout a separate worktree in the same local repository. It allows you to do what you want.

The documentation of git worktree explains:

A git repository can support multiple working trees, allowing you to check out more than one branch at a time. With git worktree add a new working tree is associated with the repository. This new working tree is called a "linked working tree" as opposed to the "main working tree" prepared by git init or git clone. A repository has one main working tree (if it’s not a bare repository) and zero or more linked working trees. When you are done with a linked working tree, remove it with git worktree remove.

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Sorry for not accepting the answer yet. I think it's correct but I couldn't find a way to open the same project from IJ in two different windows yet, and therefore I was not able to test the solution yet. – Daniel Shterenberg Jul 27 '21 at 12:30
  • 1
    The second working tree should be in a directory that is not a subdirectory of the original directory. You can create a separate project for it and the IDE won't have anything to complain and will open it in a separate window :-) – axiac Jul 27 '21 at 12:41
  • Could you explain why a worktree is superior to simply another git clone? – DarkTrick May 30 '22 at 02:38
  • A worktree is probably better than a different clone in most cases. One advantage that most of the times probably does not count is the disk space: a new clone takes space on disk, time and network traffic to be created. Another advantage is that one has to update (`git fetch`) only one local repository; also, with a clone, the changes operated locally in one repository need to be pushed and fetched in the other repository (or one of the clones can set the other as a remote and push/fetch the changes directly). – axiac May 30 '22 at 09:56
0

If you're looking to patch in code from a non-working branch to a working branch in order to pinpoint a problem, push the former branch to github, then use the source view on github to grab code to paste into the working branch.

Jeff Lowery
  • 2,492
  • 2
  • 32
  • 40