Menu
Free consultation, no commitment.Book a call

Git: a curse and a blessing in one

Tymoteusz Motylewski
Development
14 min

Git is like a knife: you can use it well or badly. Practical help for people who work in teams.

Don’t be afraid of git!

Most importantly, don’t be afraid. If you are not sure you are doing it right, test it.

reset —hard

If you want to do something on a branch but are afraid you will break something, just make sure you have an identical version of it in the source repository (origin):

git diff origin/<nazwa brancha>

Then, whatever you do on the branch, you can always reset it to the version you started from:

git reset --hard origin/<nazwa brancha>

test branches

Git lets you create as many new branches as you like, and in a way that nobody else can see them. An example of creating a test branch:

git branch -b <nazwa brancha>-test

If something does not go the way we wanted (e.g. a rebase), we can switch back to the original branch:

git checkout <nazwa brancha>

And delete the test branch:

git branch -D <nazwa brancha>-test

push —force

git push --force lets you overwrite a branch’s history in the repository. If we have accidentally deleted master, or merged stage into master, we can ask someone on the team to check out the broken branch and overwrite the broken version with the stable one.

checkout

If we know the hash of the last commit of the stable version, we can switch to it:

git checkout <hash commita>

Delete the branch we want to fix:

git branch -D <nazwa brancha>

and create it again:

git checkout -b <nazwa brancha>

reflog

Git is clever enough that almost anything can be fixed. As a last resort, we can use the reflog. We look for the last entry from before the rebase started and copy its hash (a85e451) or entry number (HEAD@{3}), then switch to it:

git checkout <hash lub numer wpisu>

Then we delete the broken branch:

git branch -D <nazwa brancha>

and create it again:

git checkout -b <nazwa brancha>

The console doesn’t bite

The second most important thing: don’t use git GUI tools if you don’t know how they work and how git works. People who barely know git often use various tools to make their lives easier. In most cases this leads to bad habits, a messy repository and strange situations.

The author went back to the console, because it gives more control over what is going on. Conflicts, however, are resolved with the help of PHPStorm.

If you want to understand how git works, working in the console will definitely make it easier.

Workflow

Trunk-based Development

An approach in which all developers commit their changes directly to a single main branch (trunk). Changes are merged into the trunk often, which minimizes the number of long-lived branches.

Pros:

  • bugs are detected quickly
  • features ship very quickly
  • minimal number of conflicts
  • a very simple workflow

Cons:

  • a serious lack of stability
  • requires experienced developers who are responsible and disciplined
  • no way to release specific features

Feature Branch Workflow

In this model there is one main branch from which feature branches are created, one for each feature. When the work is done, the feature branch is merged directly into master.

Pros:

  • conflicts are infrequent
  • new features are introduced quickly

Cons:

  • no stable branch that can be released to production at any moment
  • no built-in way to release specific features
  • frequent bugs that block work

Used mainly for a new project that is not released to production until its final version.

Stage flow

In this model there is one branch for production releases (master), one branch for releases to the test environment (stage) and feature branches with features. Each feature branch is created from master and, once the work is done, merged into the test branch (stage). After passing tests, the feature branch is merged into master.

Pros:

  • a stable main branch
  • individual features can be released
  • few critical bugs in the repository

Cons:

  • frequent conflicts at different stages of work
  • the test branch has to be deleted and recreated from master, ideally with every deploy
  • feature branches have to be rebased onto master every time another feature branch is merged into master
  • high complexity

Used mainly in ongoing development projects where features must be released at different times.

Git Flow

A development branch (develop) is created from the main branch, and feature branches are created from develop. They are merged into the development branch. Once an appropriate or agreed number of them has accumulated, a release branch is created from develop. It is brought to full stability, then merged into the main branch, which is then tagged.

Pros:

  • conflicts are relatively infrequent
  • changes for everyone are introduced quickly
  • a stable main branch

Cons:

  • no way to release a single feature
  • no way to use a single test environment

Why keep your repository tidy?

  • To make your own life easier
  • To make other people’s lives easier
  • So you don’t waste other people’s time
  • So you don’t annoy other people
  • So you don’t create extra work for others
  • So you don’t waste your own time
  • So you don’t annoy yourself
  • So you don’t create extra work for yourself
  • So that life is better for everyone and peace and harmony reign in the world

Good practices

Commits

A commit title should:

  • describe the general outline of the changes
  • be concise, but not overly so
  • start with the task number

Sometimes we come across code whose logic or purpose we don’t understand. Then we can use, for example, the git blame <nazwa pliku> command, which shows the whole file line by line with information about who last changed it, when and in which commit.

Then, with git show <hash commita>, we can see all the changes along with the commit’s title and message.

Whether we can work out on our own what the author meant depends on the title, the message and how readable the changes are. That’s why it is worth writing messages so that nobody has to bother us with questions.

The title should not be long-winded, but it should describe in general what the changes were about.

Example situations

The title “Refactoring” does not tell us much. A more detailed description can be added in the message (the next line after the commit title, with no character limit).

Example:

Refactoring

- Entity\User
- Entity\Address
- Entity\Order
- Service\Factory\User
- Service\Factory\Order
- Service\Factory\Address

This way, when browsing a file’s change history, we can first focus on the titles and then check the message.

The commit message should not describe the logic of the changes in detail. That is what the task description, e.g. in Jira, is for.

1 commit = 1 feature

Sometimes a feature stops working and you want to find the commits that were added recently and concern it. It helps if the first line of the message says which feature it concerns.

What if a commit concerns many features? 1 commit = 1 feature. That way the message will be simpler and more readable, and the code changes easier to understand.

Example:

  • “[TICKET-121] Add entity User”: creating the entity, wiring up the relations and adding a migration
  • “[TICKET-121] Add User grid”: creating a controller with a table
  • “[TICKET-121] Add add/edit form for User”: creating the create/edit form
  • “[TICKET-121] Add translation for User controls”: adding translations
  • “[TICKET-121] Add User fixtures”: adding fixtures
  • “[TICKET-121] Add unit tests”: adding unit tests

Just remember that each of these commits must work.

If, while working on a task, you notice that a method you are using needs refactoring, it is a good idea to put those changes in a separate commit.

Thanks to this rule:

  • it is easier to find the commit that causes bugs
  • you can roll back the part of a feature that causes bugs
  • code review is easier

Branches

Sometimes something goes wrong while working on a feature branch. Instead of fixing the problem or “resetting” the branch, some people create a new branch with some suffix.

Instead, “reset” the branch:

git reset –hard origin/<nazwa brancha>

If you have already pushed the “broken” branch to the shared repository, don’t create a new branch. Delete it:

git remove -D <nazwa brancha>

and create it again. Once everything works, push it, overwriting the broken version:

git push –force --set-upstream origin <nazwa brancha>

Useful commands

Tab

Tab, or autocompletion. With it you won’t make typos, you don’t have to remember whole commands and their parameters, and you don’t have to copy branch names.

add .

Adds all modified files to the staging area. You don’t have to add each file separately.

add *

Works like the command above, but without adding files and directories that start with a dot.

commit -am

The a here means that git should add all changes to the staging area before committing. Remember that this only works for files that are already tracked.

stash

This command lets you set aside all your changes without losing them. Remember that it only applies to “tracked” files (git add).

To restore the changes, just add the pop parameter (git stash pop), which restores the changes and removes them from the list.

checkout -

The - parameter means the previous branch we were on.

Showing the current branch

If you work with git in the console, it is worth setting it up to show the current branch.

If you work on Linux and have no add-ons, just put the code below at the end of your ~/.bashrc file:

parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^\[^\*\]/d' -e 's/\* \\(.\*\\)/ (\\1)/'
}
export PS1="\u@\h \[\\033[32m\]\w\[\\033[33m\]\$(parse_git_branch)\[\\033[00m\] $ "

add <katalog>

Sometimes, for whatever reason, we want to undo changes in a large number of files. Instead of copying them into git checkout by hand, we can try using the staging area.

We can add them by path:

git add src/Service

And then undo all changes outside the staging area:

git checkout .

add -p

Sometimes we don’t want to add all the changes in a file to the staging area at once. Adding files to the staging area with the p parameter makes git split the changes into chunks and ask what to do with each one.

  • y – adds the whole chunk of changes to the staging area
  • n – skips the changes
  • q – cancels adding
  • s – splits into smaller chunks
  • e – lets you manually edit what will be added
  • ? – shows a list of all options

tig

Tig is a tool for browsing git history interactively from the console. When you run tig in the console, it shows a list of commits with their date, author, message and a simplified branch tree.

The ↑ and ↓ arrows change the selected commit. Enter opens the commit preview window. The ‘Q’ key closes the preview.

Its main advantage is that you can browse the history of a specific file:

tig <adres pliku>

How to keep your repository tidy

Fixing a commit

It turns out a commit contains a file that should not be there, or you ran CS Fixer only after making all your commits and now have changes to add.

The last commit

If you want to add changes to the last commit, just add them to the staging area and then commit with the ammend parameter:

git commit --amend

Git will then not create a new commit but add the changes to the last one, and let you change its title and message.

An earlier commit

For changes to older commits, things get a bit more complicated. Add the changes to the staging area. Find the commit you want to update in the history and copy its hash. Then commit the changes with the fixup parameter:

git commit --fixup=779245451cb388c3fa686f83cf086715839e3683

and rebase:

git rebase --interactive --autosquash 779245451cb388c3fa686f83cf086715839e3683^

or:

git rebase --i --autosquash 779245451cb388c3fa686f83cf086715839e3683^

If there are conflicts, resolve them. Your commit is now fixed.

Removing unnecessary commits

The last commits

If we want to remove the last few commits from a branch’s history, we can simply use:

git reset –hard ~<number of commits to remove>

Commits from history

If we want to remove a commit that is not the last one in the branch’s history, we can use rebase:

git rebase --interactive <hash commita>^

The interactive parameter shows an editable list of commits starting from the commit we specified. Before each commit there is the word pick, which means the commit stays in the history as normal. To remove a commit from the history, we have to replace pick with d (for drop).

When there are many conflicts

If rebasing produces a lot of conflicts, we can use cherry-pick. We write down the hashes of the commits we want to keep, create a new branch from the base branch and add the commits in any order:

git cherry-pick <hash brancha>

After each cherry-pick we can add a new commit.

Disabling some of the changes

Sometimes we want to remove a commit but cannot modify the branch’s history. That is where revert comes in:

git revert <hash commita>

This creates a new commit with changes that are the reverse of those in the given commit.

If a feature we want to disable spans several commits, remember to revert them in order from the newest to the oldest commit to avoid conflicts.

If we want to bring the feature back in the future, we can simply remove the reverting commit.

How to clean up a branch with too many commits

Soft undo of commits

While working, we may not want to spend time making tidy commits. So once we have finished a task, we can undo all the quick commits without losing the changes and create commits that follow good practices:

git reset –soft HEAD~<number of commits>

Then, with the p parameter of add, we can create commits as we see fit.

Merging/squashing commits

If for some reason we want to combine several consecutive commits in the history into one:

git rebase –interactive <hash of the commit to squash the rest into>

For the commits we want to merge, we have to change pick to squash (if we want to keep the commit message) or fixup (if we don’t want to merge the commit message).

Pushing fixed commits to the repository

If the commit we want to fix has already been pushed to the shared repository, before we start fixing it we should tell everyone on the project that we want to modify the branch’s history and ask that nobody push anything to it.

Just in case, create a new branch on which you make a commit with all the changes. Then pull the latest version of the branch. After you make your changes, the history will differ from the one in the main repository.

When you then check the status (git status), you will see a message saying something like the branch is “ahead” and “behind”.

To reconcile the history, you have to push your changes with the force parameter:

git push –force

This overwrites the existing history with your version. Now tell the others that they have to refresh their branch history with:

git fetch
git rebase origin/<nazwa brancha>

and resolve any conflicts.

This is a fairly troublesome and risky operation, so think carefully about whether you really can do it.

A good practice is to protect base branches so that nobody can push to them, only merge.

Stash VS Commit

Should we always stash changes when we need to “set them aside” for a moment and come back to them later? In theory there is nothing wrong with that. However, the stash tends to swell, because we often forget about the changes we keep in it.

I suggest using a commit when you switch context (move to another branch). You can always remove it when you come back without losing the changes. Use the stash within a single context, for example when you want to pull or rebase, or to test a mechanism without your current changes.

Rebase VS Merge

Sometimes, while rebasing, we have to resolve the same conflicts several times. This leads some people to conclude that it is better to merge, because then you resolve all conflicts in one go.

However, this causes serious complications:

  • When you try to merge such a branch into the source branch, you get the same conflicts, because both branches contain the same changes but in different commits
  • In an MR, GitLab shows all the merged-in changes as new
  • It can lead to a situation where code that was deliberately removed from the repository reappears after such a branch is merged
Tymoteusz Motylewski
Tymoteusz MotylewskiCTO & Co-founder Macopedia

CTO and co-founder of Macopedia, and a board member of the TYPO3 Association. He owns the technical direction of our implementations, from B2B platforms and pricing engines to headless TYPO3. On the blog he writes about craft: performance, digital accessibility and the tools a developer actually works with every day.