Skip to content

Instantly share code, notes, and snippets.

@somahargitai
Last active April 22, 2024 09:30
Show Gist options
  • Save somahargitai/fedae3883e01db0e5c5a2cfe292287d3 to your computer and use it in GitHub Desktop.
Save somahargitai/fedae3883e01db0e5c5a2cfe292287d3 to your computer and use it in GitHub Desktop.
Git cheatsheet

cheatsheet list

GIT tips and tricks

Target: This Gist is not intended to replace any basic or advanced learning material. The goal is to help junior developers by collecting quick reminders in a nutshell and to pack some best practice sugar (for devs on all levels) which we regularly use - but which can be found only in random Stackoverflow comments. Don't forget to do research in Git docs or the free Git Pro Book. The Learning Materials chapter is not really detailed yet, but I would recommend you to do the Codecademy Git Training and Github's own basic tutorial, then other Github guides.

Contents:

  1. Start and setup
  2. My favourites
  3. Basics
  4. FAQ
  5. Detailed Basics
  6. Github
  7. Nice tools in Github environment
  8. Learning Materials
  9. Customizing Git

0) Start and Setup

  • Download Git
  • Setup login data and editor
  • Setup Remote (ssh)
  • Download repository (or create if new)
  • the very basic things you will use most often
details

Download

Install with installer file or from command line

Login

Set name, email, code editor (I prefer Visual Studio Code over Vim, Emacs or Nano), then print the fresh setup.

git config --global user.name "Bob Dylan"
git config --global user.email Bob.Dylan@fancycompany.com
git config --global core.editor code
The git config --list

more info here

Remote

One main purpose of using Git is to share code base. In theory you don't need a server for it, but of course everybody use one: Github, Gitlab or BitBucket. First choose one and register.

Then create an ssh key and copy it to clipboard:

ssh-keygen -o -f ~/.ssh/id_rsa
pbcopy < ~/.ssh/id_ed25519.pub

Now login to Github (or which you use) and find ssh keys in Settings. Paste the key there, give it a name (doesn't really matter) and save it.

more info here

Setup repo

existing project

If you open the project on Github, you will see a big green button on the right Clone or Download. Copy the SSH key (like git@github.something.com:big_project/project_name.git) and clone it in your computer's terminal:

git clone git@github.something.com:big_project/project_name.git

It will create its own project folder and download everything into it.

new

If you start a new project, you'd better create the project on Github. In the end you will have your own project and you can download it as I described above in part "existing folder".

If you already have a local project, you can create an empty project on Github, clone it to your local and copy everything into the version-controlled project folder. (Then add and commit new files and push them to the server, see them below)

If you still want to setup your project locally, you will have to create the project on Github to get the project ssh key. Go to your project folder, then:

git init
git add .
git commit -m "First commit"
git remote add origin git@github.something.com:big_project/project_name.git
git remote -v
git push -u origin master

git remote -v listed your remote settings, you can check there if everything is okay.

How you use it

You will create a new file or modify an existing one. git add newfilename will add it to the project and then git commit -m "I added some important line" will actually save it (to the actual repo's active branch*) as a new change. If you type git push, it will save all the commited changes to Github (on the active branch, using the default remote).

If others changed a branch of your repo, you can get it from Github by git checkout branchname, then git pull.

* If you use Git alone, you can use master branch directly but usually we create a new branch, write new code there, then after testing merge it back to master. Best practice is to merge it on the serves through a Pull Request (a.k.a. Merge Request in Gitlab)

1) My favourites

most-used, but not obvious things

Viewers

list, view, show, compare information

  • List remotes: git remote -v
  • List local repo config: git config --local --list
  • List global config: git config --global --list
  • List all your repos and gists:
curl https://api.github.com/users/somahargitai/repos | grep git_url
curl https://api.github.com/users/somahargitai/gists | grep filename
more with graph and diff
  • list changed files in the last commit / specific commit
git diff-tree --no-commit-id --name-only -r ^HEAD
git diff-tree --no-commit-id --name-only -r <hash>
  • see branch history tree theserverside reference

    • for the actual branch and the merged branches
    git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short
    • for all the branches
    git log --graph --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ai)%C(reset) %C(white)%an%C(reset)%C(bold yellow)%d%C(reset) %C(dim white)- %s%C(reset)' --all --date=short
  • compare actual HEAD to last one, see last commit changes

git diff HEAD~1
  • see branch tree between master and your actual branch head
    (It is much concise than simple git log. you may also use it to compare any branches or commits)
    git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative master..HEAD

  • print changes containing a specific test
    git diff -G console - before commiting, use this to find console.logs

Cleanups and fixes

  • Get last 5 branches modified
    git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(refname:short)' --count=5

  • remove all branches but master
    git branch | grep -v "master" | xargs git branch -D
    I found it here and of course it won't remove your active branch. Quite cool.

  • stats of contributor profiles

    • which files have the most commits
    git rev-list --objects --all | awk '$2' | sort -k2 | uniq -cf1 | sort -rn | head
    • who had the most commits
    git shortlog -s -n --all --no-merges

2) Basics

details
  • Everyday commands:

    • git add . add changes
    • git commit -m "<message>" commit changes
    • git pull pulling latest version of actual branch
    • git push push latest commit to remote
    • git push --set-upstream origin task234
      create a remote copy of your task234 branch and push all your commits
    • git push origin master
    • git status get files statuses of local repository
    • git branch
    • git checkout -b task123
      create a new branch (from actual branch) called task123 and change to it
    • git branch -d task123
      remove branch task123. Git will ask if you are sure about it, you should approve it using uppercase -D
    • git checkout master change to master branch
    • git log get log history
  • Create branch:
    git checkout -b "<new_branch_name>"

  • Clone:
    git clone <ssh from> <location to clone>

  • Push:
    git push <ssh to>

  • Undo / Reset

    • Reset to a previous repo version and delete all the stuff since that:
      git reset --hard HEAD - HEAD is reference to last commit
      git reset --hard 86c410f2227ecbaaaaaaaaeb29049b2c0387b473 - direct reference to commit ID
    • Remove last commit but keep changes
      git reset --soft HEAD~1
    • Remove last commit and actually delete everything that you never get them back
      git reset --hard HEAD~1
      git reset --hard HEAD^ - equivalent solution
      git reset --hard 0ad5a7a6 - equivalent solution
    • Two commits back
      git reset --hard HEAD~2
  • Remove local untracked files (Thanks to Aram Koukia )

    • git clean -fd - files and directories too
    • git clean -f - files only
    • git clean -n -d - list untracked files which you will delete, and untracked folders too
    • git clean -fX - remove ignored files
  • And of course you can just pile up flags separately, like git clean -f -d -x is equal to git clean -fdx, it will just clean everything. But I would rather not use git clean -x to remove node_modules, it takes a lifetime

  • git clean i will provide a nice little menu, for example to make decision about all the files individually. I also recommend here to use it with -d flag, you will want to see untracked folders too

  • Reset to the previous repo version But keep changes in staged are (a.k.a. added):
    git reset --soft HEAD^

  • Hard Reset of a single file git checkout HEAD -- my-file.txt

  • Push to Github and force Git to overwrite different Git history (caused by resetting):
    git push -f origin develop

  • Stash
    git stash save --keep-index
    git stash show -p - show last stash changes on console
    git stash show -p stash@{2} - show a previous stash change on console
    git stash drop
    stash unstaged changes and untracked files (new files) and keep staged files.
    git stash -k -u
    git checkout -- .
    git stash -u
    git clean -df
    git checkout -- .
    git rm .gitattributes
    git add -A
    git reset --hard

  • Tagging . Check it on abeautifulsite

3) FAQ

Remotes - what does 'origin' mean in 'git push origin master'?

As a hobbyist or employee the most likely situation is that you have a local repository and one remote server (Github or corporate Github). Your coworkers may pull their own instances, you can pull several instances to different folders too. It is part of the normal workflow.
By default you have only one remote. As long as you don't change it, git push (with master as actual branch) and git push origin master will work the same way: pushing your actual branch (now master) to your default (origin) remote. If you want, you can add more remotes. You can list remotes by git remote -v. For more info about remotes check the documentation.

  • shows ignored content status: git status --ignored
  • Adds gitignore content: git add . -f

git init

About git pull

pull equals to git fetch combined by git merge

more

cases TO BE DONE

  • git pull when the local repository is behind remote new remote commits will be appended to local, so we will have an exact copy

  • git pull when the local repository is synced with remote and we have an unstaged change

  • git pull when the local repository is synced with remote and we have a staged change

  • git pull when the local repository is synced with remote and we have a commited change

  • git pull when the local repository is one commit ahead of remote

  • git pull when the local repository is one commit behind of remote but we have commited a new local change

  • git pull when the local repository is one commit ahead of remote

    </details>
    

About git checkout

git checkout is used to move among branches: git checkout master will checkout the master branch from the actual one.

more
  We also use ot to create a branch (see ___2) Basics___).  

You can also use it to checkout an old commit by giving a hash: git checkout 88bf71d. !important: if you do any new commits on this old commit, that will be off-branch! If you would like to keep it, you have to make a new branch there, and likely you may want to merge this commit to your original branch's latest commit.

About fixing, undoing commits

Modifications on past actions in Git is a long rabbithole. Sometimes you realize that you have commited passwords and have to remove it from history, sometimes you simply want to remove the last commit. I will write more about it later, but for now I just link Seth Robertson, who wrote this wonderful article about fixes. Enjoy.

cases

4) Detailed Basics

  • git add

    • git add -A stages All
    • git add . stages new and modified, without deleted
    • git add -u stages modified and deleted, without new
  • git commit

  • git etc

5) Github

  1. You can use Github issues for tracking
  1. Github Markdown For Github documentation use .MD files. Here is adam-p's Cheatsheet

6) Nice tools in Github environment

Slate Master Documentation tool for Github Pages

This tool is based on Swagger. Swagger provides a very nice documentation tool for REST APIs
https://swagger.io/tools/
http://idratherbewriting.com/learnapidoc/pubapis_swagger.html

https://github.com/lord/slate/wiki/Deploying-Slate
workflow: [NOT READY YET]

  1. Save JSON from Swagger
    Swagger JSON location (Spring should be running):
    (http://localhost:7000/apiname/v2/api-docs)
  2. Generate MD file
    swagger-to-slate -i /users/username/Desktop/filename.json -o /users/Desktop/swaggerindex.md
  3. Go to the master branch of your repo
  4. replace repofolder/docs/index.html.md content with the generated .md file content
  5. commit and push repo to Github master branch
  6. run ./deploy.sh to refresh Github page

7) Learning Materials

Codecademy Git training is a must. There is a collection on try.github.io.

copypasted DO I NEED IT?
# Check the current remote
$ git remote show origin

# Set new remote
# example git remote set-url origin http://192.168.1.120:10010/jack/Daniels.git
$ git remote set-url origin <giturl>

# Create new local branch
$ git checkout -d NewBranch

# Delete the local branch
$ git checkout <another branch>
$ git branch -d <branchtobedeleted>

# Revert files to the last commited Head state
$ git checkout HEAD -- www/index.html

# Rename your local branch:
# If you are on the branch you want to rename:
$ git branch -m new-name
# If you are on a different branch:
$ git branch -m old-name new-name

# Delete the old-name remote branch and push the new-name local branch.
$ git push origin :old-name new-name

# Reset the upstream branch for the new-name local branch.
# Switch to the branch and then:
$ git push origin -u new-name

# If you get the error: The following untracked working tree files would be overwritten by merge:
# Run the following command to delete the files
$ git clean -d -fx ""

# Incorporating a finished feature on develop
# Finished features may be merged into the develop branch to definitely add them to the upcoming release:
# Switch to branch 'develop'
$ git checkout develop
# Merge the feature branch to your develop branch
$ git merge --no-ff -m "mymessage" myfeaturebranch
# Delete the feature branch
$ git branch -d myfeaturebranch

# Resetting a remote branch to a previous commit
# First reset your local branch
$ git checkout <branchname>
$ git reset --hard <commit-hash>
# Then push your current state to origin
# git push -f origin <branchname>

8) Customizing Git

  • Oh my zsh is a nice terminal tool, also quite handy for git use cases

  • Usually you don't have so much branches that you need a pager for git branch (See remove all branches but master above). Switch it off with:

      git config --global pager.branch false

9) Other fun stuff

Remove node_modules from the whole history

After making your backup copy, run:

 git filter-branch --force --index-filter \
"git rm -rf --cached --ignore-unmatch node_modules" \
--prune-empty --tag-name-filter cat -- --all

delete all the references to the old, unfiltered branches and tags:

git for-each-ref --format 'delete %(refname)' refs/original | git update-ref --stdin

Then save it to the remote by overwriting old history (history is always old, but... you know what I mean)

git push origin --force --all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment