I used to do what was proposed in Just Shadow's answer, and that works fine. It's also what most Git tutorials recommend when you're starting out with Git. But since you specifically asked for an "efficient way", here's what I currently do which I've found to be significantly more "efficient":
- Rarely, if ever, checkout
main
! This may sound crazy at first, but there are multiple reasons for this: It very quickly becomes out of date, you might forget to update it and accidentally use an older version of it, and you actually don't ever need to check it out.
- Anytime you would have previously used your local copy of
main
, use origin/main
instead (assuming you are calling your remote "origin", which is the default).
If you do this, the workflow is simplified. The biggest change you need to make conceptually is that you will now rarely, if ever use the pull
command. Instead you'll use fetch
to update your copy of the remote branches, which you reference with origin
. For example:
Create a new branch:
git fetch
git switch -c branchname origin/main --no-track
Later when you wish to update your branch with the latest main:
git fetch
git rebase origin/main
It takes some getting used to, but once you become comfortable with this it's second nature. The key to understanding it is that there are 3 conceptual "buckets" to think about in Git:
- Your local branches.
- Your copy of the remote branches.
- The actual remote branches.
Every time you git fetch
, you're basically copying #3 to #2. (BTW, pull does a fetch behind the scenes.) The trick is realizing that you can access anything in bucket #2 without needing to check it out, if you don't wish to.
Side Note: the title of your question:
Branching strategy to avoid conflicts on two branches
suggests that the branching strategy you use can help avoid conflicts, but that isn't necessarily true. Even keeping your not-yet-merged branches up to date with the latest main
(or origin/main
) can still lead to conflicts, but if you do it often the conflicts will be relatively small and easier to resolve, compared with long running feature branches that don't get updated until just before a PR is created and could potentially have larger conflicts to deal with.