Git tips and tricks¶
Sometimes you have to make very rare manipulations with your git repo, but can't remember how exactly it works. Here I'm collecting useful git use cases.
Rebase previous N to one¶
If you need to unite last N commits on current brunch run this rebase command with your number of last commits
git rebase -i HEAD~4
It could be useful if you don't want to show in remote repo all the history of your commits on the branch. Or maybe want to hide some of them.
Undoing last commit¶
git reset --soft HEAD~1
git reset --hard HEAD~1
Show diff between branches¶
This shows only the changes between current local branch and the remote master branch, and ignores any changes in the local branch that came from merge commits.
git diff origin/master...
Replace master with better branch¶
git checkout master
git reset --hard better_branch
git push -f origin master
Merge master to current branch¶
Merge all changes from master to your current branch:
git pull origin master
Merge with squash¶
Merge from branch with squash will erase all commits history in the branch
# Work in feature/1 branch
git branch "feature/1"
git checkout "feature/1"
# Move to the master branch.
git checkout master
# Merge the "feature/1" branch and squash the commits.
git merge --squash feature/1
# Resolve conflicts
# Commit your changes and add a single commit message for all your commits.
# You can omit the "-m" to have a template popping up based on your previous commit messages.
git commit -m "Feature 1 : 1, 2 et 3"
# Delete the "feature/1" branch that is no longer needed.
git branch -D feature/1
Reset¶
Soft¶
You've done a few tiny commits and want them all be put into one commit:
A -> B -> C -> D || A with ALL (B,C,D) -> E
git reset --soft A
git commit -m “my new merged commit”
git push origin branch
Mixed¶
You’ve just pushed a few commits, but you want to go back and remove a couple of files in a previous commit.
A -> B-> C -> D || A with ANY (B,C,D) -> E
git reset --mixed A
git add <files>
git commit -m "updated commit"
git push origin branch
Hard¶
Do it only if you want to go back a few commits and get rid of every change you’ve made since.
git reset --hard A
git push origin branchname --force
Add submodule¶
git submodule add <link_to_git_repo> <link_to_submodule_folder>
git submodule init
git submodule update
Edit last commit message¶
1 |
|
Add missed file to last commit¶
1 2 |
|
Move last commit from master to branch¶
1 2 3 |
|
Clean up local commits before pushing¶
git rebase --interactive
git rebase --interactive origin branch
Work With Multiple Branches Simultaneously¶
Creates a linked working tree (i.e., another directory on the file system associated with the repo) called path
, one level above your current working directory, with the specified branch
checked out.
#create
git worktree add <../path> <branch>
# remove
git worktree remove [-f] <../path>