Merges / Rebasing safely

There are a few things in git that can cause data loss, and rebase is one of them.

Don’t rebase common history, ever.

There’s a few golden rules for rebasing that I stick by with working in git repositories

  1. Don’t rebase things you’ve pushed into master/develop branches, ever
  2. If you still want to do it, ask yourself why you want to see pain in this world, then still don’t do it

Rebasing feature branches

There is a notable exception, feature branches. Say you’ve branched off master and made a new thing, great. But you started it before a holiday, and you pushed it to keep it safe, fine. Now you want to rebase it - you still don’t rebase common history.

Instead, you take a new branch, a copy of the one you made and pushed, and rebase this instead:

  1. Make a new branch
  2. Rebase these commits
  3. Push the new branch

This way, you are making new commits, and not changing the ones you’ve already pushed. If a co-worker has made updates to your branch (how nice of them!), rebasing that branch could overwrite and lose their work.

So just use a new branch, push that, and you’ll be fine.

Updating feature branches with forced-updates

Say you fetch branches and you see this (forced update)

$ git fetch
remote: Counting objects: 46, done.
remote: Compressing objects: 100% (45/45), done.
remote: Total 46 (delta 28), reused 0 (delta 0)
Unpacking objects: 100% (46/46), done.
From https://bitbucket.org/researchbods-team/security-design
 + a6e9f3e9...c52cbe97 better-docker-dev -> origin/better-docker-dev  (forced update)

This means the references to the better-docker-dev branch on your machine have changed - a push --force has happened on that feature branch.

To reset our local branch to the new origin branch…

git checkout better-docker-dev git reset --hard origin/better-docker-dev

And you’ll be with the cool kids, up-to-date with the latest changes.


--force-with-lease

Even if you ignore all these warnings and still want to create havoc for your friends and loved ones, please use --force-with-lease and not just git push --force… the ‘-with-lease’ bit makes sure that if any references have changed since the last fetch, it won’t go through with the force push.

git push --force-with-lease


Now we can move onto looking into git log