Git

I use the git cli every single day for my source code management needs. Sometimes I forget how to do certain things with git or I just haven’t automated it yet, so I’m writing it all down so that I have something to easily refer to:

Squash all commits on a branch

git reset $(git merge-base main $(git rev-parse --abbrev-ref HEAD))

source

Get the number of commits added to your branch

git rev-list --count main..

source

Squash and merge your X latest commits

git reset --soft HEAD~3 && 
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"

source

Create a repo on GitHub

gh repo create <name> --private

create a repo on github and push current changes

gh repo create <name> --private --push --source .

Merging in a branch with lots of commits without a merge commit

git merge --squash v1.0
git commit

Delete a remote branch

git push origin --delete branch-name

Delete local branch

git branch -D branch-name

Show diff of last commit

git show

Undo a git add

git reset <file>

source

Undo changes to a single file

git checkout <file>

source

Undo changes to all unstaged files

This was the initial way I removed all my unstaged files:

git diff --name-only | xargs -n1 git checkout

but a much better way is:

git restore .

source

Create a PR

gh pr create --fill

Create a draft PR

gh pr create --fill --draft

Fetch a remote branch

I often have my own remote separate from origin that I need to pull a branch from.

git fetch <remote> <rbranch>:<lbranch>
git checkout <lbranch>

source

Change/Amend last commit message

Sometimes you notice a typo in your commit message after generating a PR or looking at it on GitHub. If it’s not too late you can fix your commit message and then force push it up.

git commit --amend

Search commit messages

git log --grep=<regex>

Disable LEFTHOOK checks

Sometimes you just want to save your work no matter what state it is in

git commit --no-verify

View your remote branches

On GitHub.com you can view your branches on a repo by appending /yours to the branches url.

https://github.com/discourse/discourse/branches/yours

List files changed in a branch

I often resume working on a branch, but I don’t remember all the filenames I’ve been working on.

git diff --name-only main

Have vim open up all those files in tabs:

vim -p $(git diff --name-only main | tr '\n' ' ')

This appears to be more accurate if your working branch wasn’t just created off of the current main branch state:

vim -p $(git diff --name-only HEAD~$(git rev-list --count main..) | tr '\n' ' ')

And this one appears to accomplish the same thing with a single git command

git log --oneline --pretty="format:" --name-only main..

all together now:

vim -p $(git log --oneline --pretty="format:" --name-only main..)