Daniel's working notes

Using git worktree to quickly changing branch

Checking out other branch, rebuild the project just to fix silly mistakes (ACL, swiftlint so CI build failed) could be annoying. Moreover when we already in the ‘flow’ of creating a wonderful feature.

Fortunately, there’s a solution for that.

Enter git worktree

From the documentation:

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.

By using worktree, we could open multiple Xcode window without worrying about common issue caused by cache files in DerivedData, which sometimes lead to Xcode unable to build project.

Why using git worktree instead of cloning projects into multiple places?

  1. Waste of disk space, especially when you working on large codebase
  2. separate state between one repository with the other. you need to fetch or maintain to keep the repository up to dates

Now, to use git worktree

  1. Let’s say you are currently working on feature/my_awesome_feature then you got Slack notifications about failing build on CI because of ACL or swiftlint on your feature/fix_annoying_bug branch
  2. Now instead of commit your current work, checkout to bug fix branch and so on, you could use git worktree command.
  3. First, create a worktree like this: git worktree add ../ios/toko-temp feature/fix_annoying_bug then checkout, generate project and open it in Xcode as usual.
  4. After you finish fixing things, you can commit and push your changes.
  5. Finally, you can remove worktree once it’s no longer used. git worktree remove ../ios/toko-temp
  6. Now you can continue on working on your awesome feature!

Linked Notes: