Friday 13 January 2023

Fun with Git and branching

In very brief terms, I hit an issue last week where I'd created four branches in a repo, having cloned the main branch of the upstream repo.

Therefore, I'd done something like this: -

git clone -b main git@github.com:snafu/foobar@github.com

cd ~/foobar

git fetch origin && git rebase origin/main

to bring the main branch down to my Mac.

I'd then created my first branch: -

git branch dave1

git switch dave1

and added/changed some code, committed it, and pushed my new branch upstream.

I then went ahead and created a second branch: -

git branch dave2

git switch dave2

git fetch origin && git rebase origin/main

and again added/changed some code, committed it, and pushed the new branch upstream

All seemed fine ...

And I did the same for two more branches - dave3 and dave4 - with a PR for each branch being reviewed/approved and merged into main.

And then I found, when merging in separate Pull Request, that my changes from dave2 overwrote the changes made in dave1.

Which was weird....

A colleague helped explain ...

I see the 4 PRs were created from a shared branch instead of independently being created from main. That could explain the unexpected behavior where they kept rewriting each other. 

He went onto explain how to avoid the issue ...

When you run git checkout -b branchname it creates a branch branching off of your current branch.

I am used to running git checkout main; git checkout -b branchname to ensure my branches are direct branches off of main. That helps rebase them based on other PRs merging to main.

which worked a treat

So, now I've learned this, and am trying hard to add this to my "muscle memory" ...

git clone -b main git@github.com:snafu/foobar@github.com

cd foobar

git fetch origin && git rebase origin/main

git checkout main; git checkout -b dave1

etc.

We shall see if that sticks ....

No comments:

Visual Studio Code - Wow đŸ™€

Why did I not know that I can merely hit [cmd] [p]  to bring up a search box allowing me to search my project e.g. a repo cloned from GitHub...