# Git
## Metrics
List commits with Author and Date:
`git log --since=1.week --pretty=format:"%h - %an, %ar : %s"`
Count commits per author:
`git shortlog -sne --since=1.week`
Show files modified by each commit:
`git log --since=1.week --name-only --pretty=format:"%h - %an, %ar : %s"`
## Commits and Details
Remove item from staging:
`git restore —staged file.py`
Show commit history:
`git log`
Show condesed commit history:
`git log —oneline`
Show detailed info on commits:
`git log —stat`
Show detailed info on specific commit:
`git show <commit hash>`
How to undo change of a file:
`git restore <filename>`
Add files to the most recent commit:
`git commit —amend —no-edit`
Undo most recent commit:
`git reset HEAD~1`
## Branching
Switch replaced checkout:
`git switch -c <branch name>`
## Cherry Pick
Pulls a commit or commits to the current branch.
Cherry pick pulls commit to current branch:
`git cherry-pick <commit-hash>`
Cherry pick multiple commits:
`git cherry-pick <commit-1-hash> <commit-2-hash>`
Cherry pick range of commits:
`git cherry-pick <commit-1-hash>~..<commit-2-hash>`
## Stash
Remove changes from a branch and store them so you can work on something else.
Stash changes:
`git stash -u -m ‘Description'`
List stashes:
`git stash list`
Apply a stash from stack:
`git stash pop —index <stash-num>`
Remove stash entry:
`git stash drop <stash-num>`
Remove all stash entries:
`git stash clear`
## Rebase
To incorporate changes between branches, rebase rewrites where commits occurred in Git history. Rebase copies commits from one branch, and replays them onto another branch. During rebasing, the file diffs from each commit are preserved, but parent pointers are rewritten.
Rebase can do the following to commits:
- Split
- Delete
- Amend
- Reorder
- Reword
- Squash
Rebase feature branch with new changes on main:
`git rebase main <feature_branch>`
Continue rebase after solving conflicts:
`git rebase —continue`
Cancel rebase:
`git rebase —abort`
Using merge instead of rebase to catch up feature branch:
`git merge main`
Interactive rebase
`git rebase -i HEAD~2`
Reword most recent commit message:
`git commit —amend -m ‘New message'`
## Collaboration
List all local and remote branches:
`git branch —all`
List remote repo info
`git remote -v`
Show linked branches
`git branch -vv`
Git pull = fetch + merge
`git pull origin main`
Manually pull
`git fetch origin main`
`git merge`
Pull fastforward
`git pull —ff-only`
Stash before pull
Upload branch to remote repo
`git push -u <repo> <branch>`