Git tips and tricks

2024-02-20

Validate your git config

Do this before starting work on the new project or working on multiple projects simultaneously.

For example if you're working as a developer you can use your global git config, and if you contribute to open-source on weekend you can specify local config for each repository you're working with.

First of all have a look on your global git config by calling:

git config --list --global

The output maybe something like:

branch.master.rebase=true
branch.develop.rebase=true
user.name=FirstName SecondName
user.email=user@example.com
pull.rebase=true
core.autocrlf=input
apply.whitespaces=nowarn
color.ui=auto

The most important thing here is your user.name and user.email.

After that navigate to your project dir and validate local config:

cd ~/projects/projectX
git config --list --local

It may output something like this:

core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
user.name=Super Developer
user.email=SuperDeveloper@projectX.example.com
remote.origin.url=ssh://user@gitserver/repos/projectX.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master

As you can see user.name and user.email differs from the global ones.

If you want to change your user.name and user.email for a specific repository do this:

git config --local user.name "YourName YourSurname or nickname or whatever"
git config --local user.email "yourname@yourproject.com"

Keeping git history clean by avoiding merge-commits on non-master branches

The good practice is to never do a merge of a master branch into your feature-branch.

This is extremely important to keep git history clean and it really helps your CodeReviewer to see and analyze the changes in your Pull Request in the most clean and readable state.

Instead of this do rebase and force push. For example you are working on your branch named featureX:

git checkout -b featureX
git add file1 file2
git commit -m 'Add file1 file2'
git push origin featureX

Your code is on this branch.

And during your work there were some important updates pushed into the master branch and you need them to continue your work upon them. Here is how you should do this:

git checkout master
git pull
git checkout featureX
git rebase master
git push origin featureX --force

There might be some rebase conflicts in the code, and if you face them after doing rebase, solve them - make changes in conflicted files, use git add to add modified files and use git rebase --continue to finish rebasing.

By this tip you'll have your changes on top of the latest updates from master-branch and your git history stays clean without any merge-commits.