Sunday, December 08, 2019

Git Cheat Shit v2

Squash last N Commits

Carry the HEAD where you want to start squashing (eg. 3 commits before) :
$> git reset --hard HEAD~3
HEAD@{1} is previous location on branch. Merge it to last commit of your branch :
$> git merge --squash HEAD@{1}
Then commit your change :
$> git commit
Option 2: Soft Reset
Soft reset :
$> git reset HEAD~3
stage all change (better not use --all and handle all of them manually):
$> git add ./changed-file1.md src/file.2.md blabla/bla.md
commit again with message:
$> git commit -m "This is squash merge"
  • Note: Compared the previous option you need to carefully stage add all files that need to be included and commit message will not automatically include all messages of squashed commits. I can’t see any advantage of this over first option.
Option 3: You may also use interactive rebase for this. But you might end up solving conflicts for past merges. Given solutions above is far more cleaner.



Create & Apply Patch

Create Patch :

Create patch file from stash :
$> git stash show -p stash@{0} > mychanges.patch
Create patch file from commit (this will have commit author data as well) :
$> git format-patch -1 <commit id>

Apply Patch :

  • Check which files will be patched :
$> git apply --stat mychanges.patch
Check if patch file can be applicable :
$> git apply --check mychanges.patch
Just apply :
$> git apply --3way mychanges.patch
Note: You better use this option if you create your patch from diff file where no commit info is included
Apply as a commit (with author and shit) :
$> git am --3way < mychanges.patch

Stash with message

$> git stash push -m "message"
You may use apply option to not lose your

Stash Untracked and Ignored Files

$> git stash --all

Clean Local Branch (BE CAREFULL)

This will remove your uncommited changes, dont forget to stash them if you need them later :
$> git fetch
$> git reset origin/<branch-name> --hard
Carry head to past commits
$> git reset <commit id> --hard

Backward Rebase

Note: You will need to resolve all conflicts for merge commits.
A : branch should go back to commit c0
├── c0 ── c1 ── c2 ── c3
                       └──(A)──c4──c5──c6

├── c0 ── c1 ── c2 ── c3
     └──(A)──c4──c5──c6
$> git checkout A
$> git rebase -i --onto c0 c4^
During rebase solve conflicts, stage them and just do git commit to proceed.

Change Last Commit Author

$> git commit --amend --author="John Doe <john@doe.org>"
Type :wq in vim and proceed.

Change Author of Specific Commit in Past


Include New Changes to Last commit

Stage your change :
$> git add changed.md
Include it to last commit :
$> git commit --amend
Type :wq in vim and proceed.
If you wanna change it on remote branch too, then you will need to push it with force as history is changed now :
$> git push --force

Abort Cherry-pick, Rebase or Merge

$> git merge --abort
$> git rebase --abort
$> git cherry-pick --abort

No comments: