How to use git worktree to optimize git workflow

How to use git worktree to optimize git workflow

Imagine you're working on multiple code branches at the same time. Usually, this would mean a lot of switching back and forth to make changes. Sounds tedious, doesn't it? That's where Git Worktree comes in. This Git feature simplifies things by letting you work on several branches all at once. In our article, we'll give you a deep dive into Git Worktree, covering its benefits, how you might use it, potential challenges, and tips for using it most effectively. Let's get started!

What is git worktree?

Git Worktree is a handy feature that came into the picture with Git version 2.5. Using this, developers can create multiple working directories from a single Git repository. Each guide is linked to a specific branch within the repository, allowing developers to carry on their work on different branches or features simultaneously.

Git worktrees, with each different branch in its own separate folder.
Source: Gitraken

This feature is a relief for all the developers working on complex code with multiple code branches. Without switching across different branches, developers can work in various branches without worrying about errors without switching across other branches. It has saved developers time and effort and reduced the risk of accidentally committing changes to the wrong branch.

How to use “git worktree”?

  1. Create a new git branch:

    Create a new branch in the Git repository, named “my-branch” using the following command.

    git branch first-branch
  2. Switch between git branch:

    You will see a new branch in your repository, but you will be in your working directory. To change to the new directory, check the working directory.

    git checkout first-branch
  3. Create worktree:

    Now, you are in the new branch. You can use git worktree to create a new work tree for the branch using the below command.

    (git worktree add <path> <branch>)

    - Where- <path> is the location where you want to create the new work tree

    - The <branch> argument specifies the branch that you want to use for the work tree

    git worktree add my-work-tree first-branch

    This will set up a new work tree in the given location and switch to the my-branch branch within that work tree.
  4. Pushing changes to worktree:

    You can use the work tree just like any typical folder and make required changes to its files. You can use the simple git add, and git commit commands.

    git add <files>

    git commit -m "Commit changes"

    Now push the changes to the remote repository using the git push command.

    git push origin first-branch
  5. Removing worktree:

    To remove the no longer needed worktree, run the following command to save some space.

    git worktree remove [-f] first-branch

Benefits of using git worktree

Curious about how “Git Worktree” improves the software development process? The below benefits shed some light on it.

  1. Parallel workflows:

    As Git Worktree allows developers to work on multiple branches simultaneously, they can work on different features or bugs at the same time. Deploying new features and instant on-demand changes can be implemented quickly to fast-track the entire software delivery process. This efficiency can lead to quicker releases, adaptability to market needs, and a high chance of competitive advantage.
  2. Optimized resource allocation:

    Efficient development practices lead to cost savings. By enabling parallel workflows without frequent context switching, Git Worktree can reduce the person-hours required for simple to complex tasks and minimize downtime. It allows developers to address critical fixes in one branch while continuing regular work in another. It helps organizations to put the right resources in the right place without overusing them. When everything works fine, it will bring better results to business.
  3. Improved team collaboration:

    Multiple team members can work on different branches or features without interfering with each other’s work. This can benefit large teams or teams distributed across different geographies and time zones.
  4. Robust testing and reduced Risks:

    Developers can experiment and test new features in isolation without affecting the main development branch. This encourages innovation while minimizing disruptions to the main product. Developers and QA (Quality Assurance) teams can do parallel testing without complex setups or multiple repository clones.

    Addressing bugs is crucial and can interrupt ongoing tasks. Instead of constantly stashing changes, having separate folders via worktrees for different tasks streamlines the process.

5. Continuous Integration (CI) and Continuous Deployment (CD) Ease:

For CI/CD environments that need to build multiple branches or versions simultaneously, using worktrees can help optimize the build process. Instead of cloning the repository multiple times, you can use a single clone and multiple worktrees. Managing multiple release versions at once becomes streamlined, aligning more effectively with CD practices.

6. Efficient Code reviews:

In team settings, prompt pull request reviews are essential. To thoroughly understand the code, sometimes it's necessary to run it, which can interrupt other tasks. Creating a temporary worktree for the effective code review and deleting it post-review is a practical solution.

7. Experimentation space:

Developers often need to try multiple solutions for a problem. For example, when integrating tests, having separate worktrees lets you experiment freely without affecting your main codebase. In case of unexpected issues or a need to revert, worktrees can act as a backup, allowing developers to compare or restore changes quickly.

8. Training and onboarding:

New team members can use worktree to get accustomed to the codebase, working on training tasks without affecting the main branches. It helps them to get along with the company’s coding standard and understand existing code.

Challenges while using git worktree

While git worktree can be a powerful tool, it also comes with its own set of challenges. Here are some potential issues that users might encounter.

  1. Complexity for novices:

    Git worktree can be complex and daunting for those new to Git. A steeper learning curve is involved, potentially leading to mistakes or mismanagement of branches.
  2. Risk of mistakes with multiple directories:

    When managing multiple active worktrees, it's easy to confuse them, leading to changes made in the wrong directory or branch. This risk grows as more worktrees are in play, potentially causing data inconsistency or lost work.
  3. Maintenance overhead:

    Worktrees can accumulate, and if not regularly pruned, they can clutter the development environment. This requires an additional maintenance step, using commands like git worktree prune to keep things clean. Certain operations with worktree might have performance implications for vast repositories due to the need to manage multiple checkouts simultaneously.
  4. Syncing issues:

    With multiple worktrees in use, there's an increased risk of some becoming outdated if regular updates from the main repository aren't fetched. This can lead to merge conflicts, redundant work, or even overlooking critical updates.
  5. Tooling and integration challenges:

    Not all development tools, scripts, or Git GUIs fully support or are optimized for git worktree. This can cause inconsistencies, errors, or inefficient workflows when using tools that need to be worktree-aware.

    While these challenges exist, knowing them and following best practices can help effectively leverage git worktree in development workflows.

Git worktree best practices

Follow these best practices to get the most out of git worktree.

  1. Organized directory structure:

    Adopt a consistent naming convention for your worktree directories to quickly identify the associated branch or task. Consider grouping worktrees in a dedicated sub-directory to maintain a clean primary repository area.
  2. Limit active worktrees:

    Create worktrees only for your current, active tasks. Excessive worktrees can complicate your workspace. Once a branch or job is complete, remove the associated worktree to reduce clutter.
  3. Routine maintenance and syncing:

    Regularly use git worktree prune to clean up metadata from old or deleted worktrees. Ensure that each worktree stays updated with the latest changes from the main repository to prevent merge conflicts and ensure consistency.
  4. Awareness with tooling:

    Ensure your development tools, scripts, or other processes are compatible with git worktree. Some devices might have specific path dependencies or configurations.
  5. Commit and backup regularly:

    Commit your changes frequently within each worktree to safeguard against potential data loss. Also, maintain regular backups of your primary repository and worktrees as a safety net.

    Implementing these best practices will help ensure that git worktree becomes a boon to your development process rather than a source of confusion.

Final thoughts

Quick delivery is a USP for any growing or experienced business. If they fail to do so, they can face critical reputation damage. Staying ahead with fast and efficient deliveries is essential in this competitive market. And Git Worktree helps developers in achieving that.

Using Git is a great start for any development project. To take it up a notch, consider adding an engineering analytics solution to the mix. DevDynamics offers integrations with CI/CD tools like GitHub, Jira, GitLab, and BitBucket to provide insights into code review, shipping velocity, deployment, and more.

Colored Box with Buttons

Ready to drive engineering success?


Ready to maximise the ROI of your Engineering teams?

SET UP IN 10 MINUTES

21 DAY FREE TRIAL