Allison Machado Gonçalves

Allison Machado Gonçalves


Git Cheat Sheet

Table of Contents

Introduction

This cheat sheet provides a quick overview of some time saving git commands. If you need more information or context, click the title of each section.

Undo last commit (locally)

$ git reset HEAD~ 

Merge last N commits

$ git reset --soft "HEAD~n"
$ git commit -m "new commit message"

Change commit order

Here, 3 is the number of commits that need reordering:

$ git rebase -i HEAD~3

Then use the editor to edit the commit lines.

Reuse the previous commit message

$ git commit -C HEAD

Reuse the previous commit message and also want to edit it

$ git commit -c HEAD

Avoid Rebase Hell

$ git checkout -b work target_branch
$ git merge --squash problematic_rebase_branch

Auto Resolve Repetitive Conflicts

$ git checkout --theirs ./path/to/file/or/directory
$ git checkout --ours ./path/to/file/or/directory

Clean up local branches by prefix (e.g 'MT-')

$ git branch -D `git branch | grep MT-`

Clean up local remote-tracking branches by prefix (e.g 'MT-')

$ git branch -rd `git branch -r | grep MT-`

Use GitHub to compare two branches

https://github.com/MobieTrain/mobietrain-api/compare/{old-branch}...{new-branch}

Alternatives to .gitignore

.git/info/exclude (per project basis)
 ~/.config/git/ignore (per user basis)

Create and apply patches

Send the diffs to a patch file:

git diff > mypatch.patch

You can later apply the patch:

git apply mypatch.patch

Git Submodules

Clone and automatically initialize/update each submodule in the repository:

git clone --recurse-submodules https://github.com/chaconinc/MainProject

Go into your submodules and fetch and update for you.

git submodule update --init --remote

Change commit's author

$ git commit --amend --author="Author Name <email@address.com>" --no-edit

The author name and email can be found using git log.

Restore local deleted branch

The commit hash should be known (maybe inspecting terminal log history)

$ git branch branchName <sha1>