Git cheat sheet

Jul 10, 2013

Git overview: Operation and File lifecycle

Image are hotlinked from Pro Git book, written by Scott Chacon.


Some of the commands listed here may use alias and/or configuration defined in ~/.gitconfig (see near the end of the post).

General operations

  • Help with git: git --help # List available git commands git help <command> # More details about a specific command git <command> --help # More details about a specific command
  • Display status of (local) repository: git status git st # Abbreviated using ~/.gitconfig git status -sb # Shorter output git status -uno # Hide details of untracked files
  • Adding files to staging area: git add --dry-run <file1> <file2...fileN> # Dry run. No change in repository git add -n <file1> <file2...fileN> # Abbreviated flag for dry run git add <file1> <file2...fileN> # Add files to staging area git add *.m *.txt # Also supports wildcards
  • Commit changes with message: git commit -m 'message' # Commit ONLY staged files git commit -a -m 'message' # Commit ALL changes, including unstaged files git ci 'message' # Abbreviated using ~/.gitconfig

Compare and inspect

  • Changes in working directory: git diff --color # Colored diff git diff --stat # Show diffstat git diff --ignore-all-space # Ignore all whitespace git diff -w # Abbreviated --ignore-all-space git diff --ignore-space-changes # Ignore change in amount of whitespace git diff -b # Abbreviated --ignore-space-changes git diff -w --color-words # Colored word diff (rather than line diff) ignoring whitespace git diff --cached # Show changes in staged files git diff --staged # Same as --cached
  • Inspect changes:
    (gitk is a tcl/tk based gui; Beginner tutorial) gitk --all # Browse all branches in local repository git log --oneline --graph # Inspect repository with summary of changes git log --oneline --graph --stat # Inspect repository with diffstats git whatchanged --oneline --graph # Similar to git log git lg # Abbreviated using ~/.gitconfig git show <commit> # Shows details of changes in commit
  • Inspect changes beyond file renames:
    (Take care with renames: NEVER commit renames and modifications in the same commit. Check these as well.) git log --oneline --follow <filename> # Summary of changes git log --follow -p <filename> # Detailed changes gitk <filename> # Detailed changes using gitk

Branching

  • Pro Git book has an excellent chapter on Branching and Merging.
  • When typing in the name of a branch in following commands, try using TAB for auto-completion. It works most of the times.
  • git branch # List local branches git branch -a # List all local and remote branches git checkout <branch_name> # Switch to other existing branch git checkout -b <branch_name> # Create a branch and switch to it git branch -d <branch name> # Delete a branch
  • Compare branches: (order of branches matter) git diff <branch1>..<branch2> git diff --stat <branch1>..<branch2> # Generate diffstat git diff --name-status <branch1>..<branch2> # Short diff with only name and status git diff <branch1> <branch2> <filename> # Show differences only for a file git difftool <branch1> <branch2> <filename> # Use (external) diff tool
  • Compare directories (branches/commits): (requires git version >=1.7.10) git difftool --dir-diff <commit1>..<commit2> git difftool --dir-diff <commit1> git difftool --dir-diff <branch1> git difftool --dir-diff <branch1>..<branch2>
  • Remote branches & its management
    A very good and detailed description of remote branch management can be found in Pro Git book. # Pushing to remote git push origin localBranch # Pushes localBranch to origin git push -u origin localBranch # Pushes/sets association of localBranch to origin git push origin localBranch:remoteBranchName # Pushes localBranch to origin/remoteBranchName git push -u origin localBranch:remoteBranchName # Similar effect to -u above # Tracking or defining association. Also see this. git branch -u origin/remoteBranchName # Associates current branch to origin/remoteBranchName git branch -u origin/remoteBranchName localBranch # Associates localBranch to origin/remoteBranchName # Checking out from remote git fetch origin && git checkout remoteBranchName # Checkout origin/remoteBranchName git checkout -b localBranch origin/remoteBranchName # Checkout origin/remoteBranchName to localBranch git pull # Works after checking out or associating. # Deleting remote branch git push origin :remoteBranchName # Deletes origin/remoteBranchName git push origin --delete remoteBranchName # Deletes origin/remoteBranchName # Prune stale branch. See git remote branch deleted but still appears in 'branch -a' git remote prune origin # Removes all stale branches git fetch -p # Fetches from origin and prunes all stale branches # Show details of branch tracking information git remote -v show origin git branch -vv -a

Merge conflicts

Good read about three-way merge in git: Painless Merge... and Three way git... Here is a summary:
  • Use git mergetool with meld. See ~/.gitconfig below. Mergetool would go through the conflicting files and create various new files with different file extensions so that it can use following command with meld (see git source code for more details). meld --output $MERGED $LOCAL $BASE $REMOTE
  • $LOCAL: Contents of the file on the current branch. This is presented in Left-most column in meld.
  • $REMOTE: Contents of the file to be merged. Right-most column in meld.
  • $BASE: Common base of the merge OR half-finished merge where things started to fail. It is shown in middle column in meld. This is column which you would want to edit.
  • $MERGED: File to which meld would write the merge resolution. It is not shown in meld. However, when $BASE is saved after editing, the output is written to $MERGED. Usually, $MERGED does not have any special extension like above files.
  • Mergetool creates *.orig backup files while resolving merges. These are safe to remove once a file has been merged.

Tagging

  • Create/Delete tags (Also see Pro Git book) git tag -a v1.4 -m 'my version 1.4' # Creates annotated tag to current commit git tag -a v1.4 -m 'my version 1.4 <checksum> # Adds tag to an older commit git tag -d <tag_name> # Deletes a tag
  • List tags git tag -l # Lists tags in alphabetical order git tag # Lists tags in alphabetical order git tag -l -n1 # Lists tags along with annotation git tag -l <pattern> # Lists tags in matching a pattern git tag -l v13* # Lists tags starting with v13 git log --tags --simplify-by-decoration --pretty="%d" # Lists tags in chronological order git tl # Abbreviated by ~/.gitconfig git show <tag_name> # Show details of a tags
  • Remote tags git ls-remote --tags origin # List all tags on origin git push origin <tag_name> # Push a tag to origin git push origin --tags # Push all tags to origin git push origin :refs/tags/<tag_name> # Delete a tag on origin

Others:

  • Revert changes (excellent examples in git-reset documentation) git reset # Undo all add. Retains all changes in working tree git reset --hard # Undo add all. Discards all changes in working tree git reset HEAD <file_name> # Undo add one file. Retains all changes in working tree git reset --soft HEAD^ # Undo last commit. Retains all changes in working tree uncommitted (un-stage) all changes including files and folders:


~/.gitconfig

git difftool falls back to git mergetool config variables when the difftool equivalents have not been defined. If a merge resolution program is not specified, git mergetool will use the configuration variable merge.tool. [core] editor = emacs autocrlf = input [merge] tool = meld [alias] ci = commit -a -m st = status -sb rb = rebase lg = log --graph --all --format=format:'%C(auto)%h (%cd)%C(reset)%C(bold red)%d%C(reset) %C(bold green)%s%C(reset) %C(bold white)- %cn%C(reset)' --abbrev-commit --date=short df = diff -w --color-words dft = difftool -y tl = log --tags --simplify-by-decoration --format=format:'%C(auto)%h (%cd) -%C(reset)%C(bold red)%d%C(reset) %C(bold white)- %cn%C(reset)' --date=short --author-date-order [color] ui = true [color "status"] added = yellow changed = red untracked = cyan [push] default = current

Other great Git references:
Read more ...

Dropbox Bug?

Mar 10, 2013
UPDATE: This is an expected behavior of dropbox. See relevant discussion at Dropbox Forums.

It seems that there is a dropbox bug which may affect the recovery of deleted files and folders in this specific situation. I will try to document and elaborate my observations in this post. In short, dropbox seems to be not able to recover a deleted folder if a new file with exact same name is replaced at the exact same location as the deleted folder. I am a free user of dropbox and I am not sure whether this is one of the free features. I found this particular problem 7-8 months back & I could recover the files from my personal backup, which is separate and independent from dropbox.

Here are the steps to reproduce the results. (I did backup all the data, so nothing was lost in reality. This is just a demonstration.) Here, I am going to delete a folder named 'Image Fun' from my dropbox which has some more files and folders in it. The goal is to check, if I can recover those files and folders inside the folder Image Fun.
  1. Make sure Dropbox is running. (I am using Linux Mint 13)
  2. Delete the folder Image Fun, with some files and folders.
  3. Create a file with name Image Fun (no extensions) somewhere outside the Dropbox folder and then copy the file to the location of original Image Fun folder.
  4. Log on to dropbox.com website and hit "Show deleted files". I can not see any folder which has been deleted & has name Image Fun. Though, I can see the file I created with the exact same name (among normal files, not deleted files).
  5. Navigate to "Events" link on the left on dropbox website. This is the part where it gets interesting. I could see the notification which says that I deleted Image Fun and other 45 files in that folder. See the screenshot below. Now when I click on Image Fun, I am taken to home page where it highlighted the new Image Fun file.

  6. Clicking on "output" link in events page (output was a folder inside the delete folder) showed a message in red saying "The folder /Image Fun/output is deleted" (screenshot below).

  7. When I clicked on "45 more files" in the events page, it showed me a page where all the files were listed, but I could not click on any of them in order to recover. 

  8. But, when I clicked on link "a1.jpg" in events page (where it said "You deleted a1.jpg and 45 more files"), I was taken to a page where I can actually see the older version of that particular file - a1.jpg. Clicking on version 0 shows the correct original file. 
  9. You must have noticed the "Restore" button on a1.jpg link (above screenshot). When I clicked on it, something unexpected happened. The file which I created, with name Image Fun, was actually removed with the folder Image Fun and a1.jpg was restored in the folder. Now I could navigate to the folder and even see deleted files. This could be one way to recover the file. But I would count it as very unreliable method. It relies on finding and clicking on one particular file's deleted link and then recovering it. That particular link may actually get lost if many other files in other locations were also deleted. Events page after the recovery looks like this:

Hopefully, this will help to fix or address the issue I mentioned. It is probably an expected behavior. See relevant discussion at Dropbox Forums.
Read more ...

gs (GhostScript) cheat sheet

Aug 28, 2012
Cheat-sheet for versatile interpreter GhostScript. It can be used to tweak, convert, produce high quality Postscript and PDF files.

Convert postscript (ps) to pdf:

gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=fileout.pdf filein.ps

Merge ps and/or pdf:

gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=fileout.pdf filein1.ps filein2.pdf filein3.pdf

Extract page(s) from a ps or a pdf document:

gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dFirstPage=3 -dLastPage=3 -sOutputFile=fileout.pdf filein.ps

Embed fonts in a pdf:

gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=fileout.pdf -dPDFSETTINGS=/prepress -dEmbedAllFonts=true -dSubsetFonts=true -dCompatibilityLevel=1.6 filein.pdf

Convert images to pdf:

Check this post. Or else use ImageMagic's convert.

PDF optimization options

-dPDFSETTINGS=/screen (screen-view-only quality, 72 dpi images) -dPDFSETTINGS=/ebook (low quality, 150 dpi images) -dPDFSETTINGS=/printer (high quality, 300 dpi images) -dPDFSETTINGS=/prepress (high quality, color preserving, 300 dpi imgs) -dPDFSETTINGS=/default (almost identical to /screen)

Paper size options

-sPAPERSIZE=letter -sPAPERSIZE=a4 -dDEVICEWIDTHPOINTS=w -dDEVICEHEIGHTPOINTS=h (point=1/72 of an inch) -dFIXEDMEDIA (force paper size over the PostScript defined size) -gWIDTHxHEIGHT (page size in pixels)

Output devices:

-sDEVICE=pdfwrite -sDEVICE=ps2write -sDEVICE=png16m (24-bit RGB color) -sDEVICE=pnggray (grayscale) -sDEVICE=pngmono (black-and-white) -sDEVICE=pngalpha (32-bit RGBA color) -sDEVICE=jpeg (color JPEG) -sDEVICE=jpeggray (grayscale JPEG) -sDEVICE=epswrite (encapsulated postscript) -sDEVICE=txtwrite (text output, UTF-8) Check -sOutputFile below, for separate images for each page of a multi-page document. Tiff, PNM and many more formats are supported. Check details in Ghostscript output devices.

Help & list of available devices:

gs -h

Other options

-dNOPAUSE (no pause after page) -dBATCH (exit after last file) -sOutputFile=ABC-%03d.pgm (produces 'ABC-001.pgm'..'ABC-010.pgm'..) -dEmbedAllFonts=true -dSubsetFonts=true (Embeds only the characters used in document) -dCompatibilityLevel=1.4 (Adobe's PDF specifications, >=1.4 for font embedding, =1.6 for OpenType font embedding) -dCompressPages=true (compress page content) -dFirstPage=pagenumber -dLastPage=pagenumber -dAutoRotatePages=/PageByPage (or /All or /None) -rXRESxYRES (XRES & YRES in pixels/inch) -rRES (same XRES & YRES, affects images and fonts converted to bitmaps) -sPDFPassword=password More details & defaults on ps2pdf documentation.
Adobe® PDF Creation Settings - Used by GhostScript.
GhostScript Documentation.

Read more ...

Cheat Sheets

Jul 21, 2012
Cheat sheets in this blog are not static posts and they keep getting updates from time to time. Here is the list of cheat sheet (from this blog) for different applications:

Some other useful cheat sheet resources: 

Read more ...