Skip to content

Instantly share code, notes, and snippets.

@citizen428
Created July 9, 2018 04:00
Show Gist options
  • Save citizen428/16fb925fcca59ddfb652c7cb22809018 to your computer and use it in GitHub Desktop.
Save citizen428/16fb925fcca59ddfb652c7cb22809018 to your computer and use it in GitHub Desktop.

I originally wrote this article for Codementor in October 2014. It should have something for everyone, from fairly new git users to experienced developers.

1. Discard local file modifications

Sometimes the best way to get a feel for a problem is diving in and playing around with the code. Unfortunately, the changes made in the process sometimes turn out to be less than optimal, in which case reverting the file to its original state can be the fastest and easiest solution:

https://gist.github.com/e809e4b6a81e399ce00b39886e8122c0

In case you’re wondering, the double dash (--) is a common way for command line utilities to signify the end of command options.

2. Undo local commits

Alas, sometimes it takes us a bit longer to realize that we are on the wrong track, and by that time one or more changes may already have been committed locally. This is when git reset comes in handy:

https://gist.github.com/e670d90a8bed43e392e1012dd6fd1ad8

Be careful with the --hard option! It resets your working tree as well as the index, so all your modifications will be lost for good.

3. Remove a file from git without removing it from your file system

If you are not careful during a git add, you may end up adding files that you didn’t want to commit. However, git rm will remove it from both your staging area, as well as your file system, which may not be what you want. In that case make sure you only remove the staged version, and add the file to your .gitignore to avoid making the same mistake a second time:

https://gist.github.com/3c41324a1ab6d178fd2d1d443e2d7bf9

4. Edit a commit message

Typos happen, but luckily in the case of commit messages, it is very easy to fix them:

https://gist.github.com/3ec56e7e1f0c9eeaae595df8837c205c

But that’s not all git-amend can do for you. Did you forget to add a file? Just add it and amend the previous commit!

https://gist.github.com/31c426d1ba93d2f787428a6a990cb856

Please keep in mind that --amend actually will create a new commit which replaces the previous one, so don’t use it for modifying commits which already have been pushed to a central repository. An exception to this rule can be made if you are absolutely sure that no other developer has already checked out the previous version and based their own work on it, in which case a forced push (git push --force) may still be ok. The --force option is necessary here since the tree’s history was locally modified which means the push will be rejected by the remote server since no fast-forward merge is possible.

5. Clean up local commits before pushing

While --amend is very useful, it doesn’t help if the commit you want to reword is not the last one. In that case an interactive rebase comes in handy:

https://gist.github.com/8c20c9a5d21fb57f1e15b313d4b08cb5

This will open your configured editor and present you with the following menu:

https://gist.github.com/97c984333294f1bd826a0f5d86d4285a

On top you’ll see a list of local commits, followed by an explanation of the available commands. Just pick the commit(s) you want to update, change pick to reword (or r for short), and you will be taken to a new view where you can edit the message.

However, as can be seen from the above listing, interactive rebases offer a lot more than simple commit message editing: you can completely remove commits by deleting them from the list, as well as edit, reorder, and squash them. Squashing allows you to merge several commits into one, which is something I like to do on feature branches before pushing them to the remote. No more “Add forgotten file” and “Fix typo” commits recorded for eternity!

6. Reverting pushed commits

Despite the fixes demonstrated in the previous tips, faulty commits do occasionally make it into the central repository. Still this is no reason to despair, since git offers an easy way to revert single or multiple commits:

https://gist.github.com/56b7b84705418b13a61a95cd14cc504d

In case you don’t want to create additional revert commits but only apply the necessary changes to your working tree, you can use the --no-commit/-n option.

https://gist.github.com/55f0002c22846d16016ccfd77e645eeb

The manual page at man 1 git-revert list further options and provides some additional examples.

7. Avoid repeated merge conflicts

As every developer knows, fixing merge conflicts can be tedious, but solving the exact same conflict repeatedly (e.g. in long running feature branches) is outright annoying. If you’ve suffered from this in the past, you’ll be happy to learn about the underused reuse recorded resolution feature. Add it to your global config to enable it for all projects:

https://gist.github.com/42eeb30f2f025a74c89efbdb3c9b3129

Alternatively you can enable it on a per-project basis by manually creating the directory .git/rr-cache.

This sure isn’t a feature for everyone, but for people who need it, it can be real time saver. Imagine your team is working on various feature branches at the same time. Now you want to merge all of them together into one testable pre-release branch. As expected, there are several merge conflicts, which you resolve. Unfortunately it turns out that one of the branches isn’t quite there yet, so you decide to un-merge it again. Several days (or weeks) later when the branch is finally ready you merge it again, but thanks to the recorded resolutions, you won’t have to resolve the same merge conflicts again.

The man page (man git-rerere) has more information on further use cases and commands (git rerere status, git rerere diff, etc).

8. Find the commit that broke something after a merge

Tracking down the commit that introduced a bug after a big merge can be quite time consuming. Luckily git offers a great binary search facility in the form of git-bisect. First you have to perform the initial setup:

https://gist.github.com/d80129b005dfc02124f3890b90d92cee

After this git will automatically checkout a revision halfway between the known “good” and “bad” versions. You can now run your specs again and mark the commit as “good” or “bad” accordingly.

https://gist.github.com/5d60d4077fa373159838659ad93041b8

This process continues until you get to the commit that introduced the bug.

9. Avoid common mistakes with git hooks

Some mistakes happen repeatedly, but would be easy to avoid by running certain checks or cleanup tasks at a defined stage of the git workflow. This is exactly the scenario that hooks were designed for. To create a new hook, add an executable file to .git/hooks. The name of the script has to correspond to one of the available hooks, a full list of which is available in the manual page (man githooks). You can also define global hooks to use in all your projects by creating a template directory that git will use when initializing a new repository (see man git-init for further information). Here’s how the relevant entry in ~/.gitconfig and an example template directory look like:

https://gist.github.com/68077e00c96a3fdd44df0cc00b097700

When you initialize a new repository, files in the template directory will be copied to the corresponding location in your project’s .git directory.

What follows is a slightly contrived example commit-msg hook, which will ensure that every commit message references a ticket number like “#123“.

https://gist.github.com/6e008145de56be2dc448d38f90bbca63

10. When all else fails

So far we covered quite a lot of ground on how to fix common errors when working with git. Most of them have easy enough solutions, however there are times when one has to get out the big guns and rewrite the history of an entire branch. One common use case for this is removing sensitive data (e.g. login credentials for production systems) that were committed to a public repository:

https://gist.github.com/cb43bf997ec25739857b805ed738f693

This will remove the file secrets.txt from every branch and tag. It will also remove any commits that would be empty as a result of the above operation. Keep in mind that this will rewrite your project’s entire history, which can be very disruptive in a distributed workflow. Also while the file in question has now been removed, the credentials it contained should still be considered compromised!

GitHub has a very good tutorial on removing sensitive data and man git-filter-branch has all details on the various available filters and their options.

@HaQadosch
Copy link

I was about to say that using the sandwich technique: compliment | request for improvement | compliment.

Something every body could use a bit more.

@oscard0m
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment