Showing posts with label Git. Show all posts
Showing posts with label Git. Show all posts

Git Tips Tricks for Developers


Untitled

Install Bash git completion

  • brew install git bash-completion

Caching GitHub password in Git

  • git config --global credential.helper 'cache --timeout 72000'
  • Remove cached password (to reenter new password when it’s changed)
    • git credential-osxkeychain erase

Temporarily ignoring files

  • git update-index --assume-unchanged file-path
  • git update-index --no-assume-unchanged file-path

Remove file from the repository but keep it locally

  • git rm --cached -r somedir/somefile then add them to .gitignore

Reset current HEAD to the specified state

undo last commit
  • git reset --soft HEAD~1
  • Undo commits permanently: git reset --hard HEAD~3
    • The last three commits (HEAD, HEAD^, and HEAD~2) were bad and you do not want to ever see them again.
  • Undo a merge or pull inside a dirty working tree: git reset –merge ORIG_HEAD
  • return to any previous revision
    • git reset --soft commit_hash
  • Reset committed changes to local changes
    • git reset HEAD~

undo git pull

  • git reset --hard

Reset local branch to be same as remote branch

  • git fetch --all && git reset --hard upstream/master
  • If need delete everything(just like re-clone): git clean -x -d -f

~ vs ^

  • Both ~ and ^ on their own refer to the parent of the commit.
  • ~2 means up two levels in the hierarchy, via the first parent if a commit has more than one parent
  • ^2 means the second parent where a commit has more than one parent (i.e. because it’s a merge)
  • HEAD~2^3 means HEAD’s grandparent commit’s third parent commit.

rebase

Edit your X most recent commits interactively (squash, fixup, reword, drop)
  • git rebase -i HEAD~X
Modify a specific commit
Split a commit in two with Git
Delete a commit
  • If it is the last commit this is very straight forward. git reset HEAD

Branch

  • Delete local branch: git branch -d <local_branchname>
  • Delete remote branch: git push origin --delete <remote_branchname> or git push origin :<remote_branchname>
  • Rename local branch name: git branch -m <new-branch-name>
Checkout remote brach

git log

  • git log –oneline [–pretty=oneline]
Show commit id only
  • git log -1 –pretty=format:“%H”

View change in a specific commit

  • git show

Undo anything

Wipes your unstaged changes
  • git checkout
undo rm -rf * - git stash - if no local update

undo git commit –amend

  • git reset –soft HEAD@{1}
Checkout remote file after merge conflict
  • git checkout HEAD the_file

shallow clone

  • git clone --depth 1 https://path/to/repo/foo.git -b bar
  • –no–single–branch instead -b bar, to download first commit form ALL branches.
  • –no-checkout(-n): No checkout of HEAD is performed after the clone is complete.

ls-remote

git ls-remote --tags remote_git_url

Tags

  • git tag

git clean

  • -n: –dry-run
  • git clean -x -d -f

git commit

  • Add change to your last commit, instead of making a new commit
    • git commit --amend
Commit messages
  • <type>(<scope>): <subject>
  • type: feat(new feature), fix, docs, style(format code, no code change), refactor, test(add test cases), chore

git remote

  • List all remotes: git remote
  • Add another remote: git remote add upstream the_url
  • git remote show
  • git remote show upstream

git stash

  • -u|–include-untracked
  • List all stashes: git stash list
  • git stash
  • Also stack untracked files: git stash -u
  • Apply the stash: git stash apply <stash@{n}>
  • Apply last stash and remove the stash: git stash pop
  • git stash clear
  • git checkout <stash@{n}> -- <filePath>

git diff

  • Ignore the white space: git diff -w
  • Show local staged change(added but not committed): git diff --cached
  • Show committed but not pushed change: git diff origin/master..master

emoji

Misc

Git - Tips and Tricks


Git Auto Completion

Help - git help command

Cache Git Authentication
git config --global credential.helper 'cache --timeout 72000'
git credential-osxkeychain erase

Git Config
git config --global help.autocorrect 1
git config --get core.editor
git config --global core.editor vi
git config --global user.email your-email
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
git log -l

Push to a Remote Branch with a Different Name
git push origin local-name:remote-name

Make an existing Git branch track a remote branch
git branch -u upstream/foo foo

Switch to a different remote branch
git branch --all
git checkout remotes/origin/develop
git checkout -b develop

Disable push to remote branch
git remote set-url --push remote-name DISABLE
git branch --unset-upstream
--set-upstream-to=remote-name/branch-name

List what remote branch your current branch is tracking
git branch -vv or just git status

Show only modified files
git status -uno
git status | grep modified:
git ls-files -m

git fetch --dry-run

git fetch -p 
-p, --prune After fetching, remove any remote-tracking branches which no longer exist on the remote.


git branch -d[D] the_local_branch
Temporarily ignoring files
git update-index --assume-unchanged file-path
git update-index --no-assume-unchanged file-path
Get a list of files marked --assume-unchanged:
git ls-files -v|grep '^h'

Git Diff
git diff --name-only  -- *.java
git diff --cached

Compare files from different branches
git diff branch1:branch2 file-path
git diff ..branch2 file-path

git diff branch2.. file-path

Viewing Unpushed Git Commits
git diff origin/master..HEAD

Change commit message:
git commit --amend -m ”YOUR-NEW-COMMIT-MESSAGE”
Changing the Last Commit
git commit --amend
Skip commit hooks

git commit --no-verify (-n)

Force push without any change
git commit --allow-empty --amend  && git push -f

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

Unmodifying a Modified File
git checkout -- ..." to discard changes in working directory

Git reset
https://davidzych.com/difference-between-git-reset-soft-mixed-and-hard/
Reset local branch to be same as remote branch
git fetch --all
git reset --hard origin/master

Reset committed file:
git reset file

Undo add
git reset

Undo last commit
git reset --soft HEAD~
git reset --soft HEAD~X(number)

Unstaging a Staged File
use "git reset HEAD ..." to unstage

Reset local repository branch to be same as remote repository
git reset --hard origin/master

Squash Last 2 Git Commits
git reset --soft HEAD~2
git commit -m "New message for the combined commit"

Undo last reset
git reset 'HEAD@{1}'

Replace local file with file from remote another branch
git checkout remote/branch -- a/file (seems we can ignore --)

Delete Local Branch:
git branch -D branch-name
Delete remote branch:
git push origin --delete branch-name

git log
git --no-pager log -n 20 --graph --pretty=format:'%Cred%h%Creset %an: %s - %Creset %C(yellow)%d%Creset %Cgreen(%cr)%Creset' --abbrev-commit --date=relative
Filtering
By amount - show last 3 commits only
git log -3

git log --author=abc
git log -S "search-term"
git log file
git log -Ssearch-term -p - show the diff of each commit
Search for the regex in the diff of each commit
git log -G'regx'


git grep -n something

Show all of the commits that are in branchA, but aren’t the master
git log master..branchA

View unpushed commits
git log origin/master..HEAD
git diff origin/master..HEAD


Checkout file from another branch
git checkout branch2 filePath
Checkout file from remote brnach
git checkout origin/master filePath Create a branch from a tag
git checkout -b newbranch theTag

Patch
git format-patch master --stdout > a.patch
git apply --stat a.patch
git apply --check a.patch
git apply --reject --whitespace=fix a.patch

No one shall rebase a shared branch
stash
- We can stash change and apply it in another branch
git stash
git stash save "a_name_here"
git stash list

git stash drop stash@{0}

Git commands
Merge code from another remote branch to current local branch
git pull origin remote-branch-name

Merge code from a branch from another remote to current local branch
git pull another-remote remote-branch-name

After git remote add, run git fetch --all to fetch remote branch info/

Find who made the change
Find any commit that added or removed the string 
git log -Sthe-query

gitk filePath
Get a file from a specific commit
git show commitHash:/path/to/file - show whole file content in that commit
git show commitHash /path/to/file - show changes only

Track all remote branches
- When there are remote branches on the server that aren't tracked by local branches
git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done

GUI
sourceTree

Github
Searching - link
in:path, in:file repo:org_name/repo_name
path:sub-project/sub-folder
filename:the-name
extension:yml
repo:org/repo-name
-repo:repo1 -repo:repo2
"extends XYZClass"

Comparing
https://github.com/octo-org/wikimania/compare/master@{2weeks}...master

View/Monitor PRs or issues in one places
https://github.com/pulls
https://github.com/issues

Use split diff view to compare PR and commits
https://github.com/blog/1884-introducing-split-diffs

Compare changes between tags/branches
https://github.com/{username}/{repo}/compare/{older-tag}...{newer-tag}

Ignore Whitespace in pull request
Adding ?w=1 to any diff URL will remove any changes only in whitespace, enabling you to see only that code that has changed.

Shortcuts
press ? to show all shortcuts
Pressing t will bring up a file explorer.
Pressing s will focus the search field for the current repository. Pressing Backspace to delete the “This repository” to search all of GitHub.
Pressing w will bring up the branch selector.

octotree : Chrome extensio to display GitHub code in tree format
https://chrome.google.com/webstore/detail/octotree/bkhaagjahfmjljalopjnoealnfndnagc?hl=en-US

Expand all "outdated diff" comments in a GitHub pull request
Run in chrome dev console:
elements = document.getElementsByClassName("outdated-diff-comment-container");
for (var i=0; i<elements.length; i++) { elements[i].className += " open"; }

Sort user and organization repositories by star count on the repositories tab and org home page
https://github.com/search?q=user:abc&s=stars&type=Repositories

URL to create a pull request between different two branches
/compare/remote:branch...remote:branch

Close pull request without merging
https://help.github.com/articles/closing-a-pull-request/

Revert Pull Request

Resources
https://git-scm.com/book/en/v2

Lazy Developer: Using git pre-commit to auto tun test and findbugs


The Goal:
We developers wish our code is perfect, no bug, and we never want to check in code that will break test and found out later by peers.


We should always use tools like findbugs to check our code and run test locally before we push the change to git repository.

But would be better if git could just run test, check bugs for us before commit or push?

Using git pre-commit to run mvn test automatically
Luckily we can use git pre-commit hooks to do this for us.
We just need create pre-commit file in .git/hooks folder, make it executable(chmod 755), In this script, we can do anything we want.

In the following script, it will check whether we changed java code or pom file in this commit, if no, just commit it(we don't have test for UI side yet).

If yes, it will first stash(save and hide) unstaged changes before running tests, so we are really testing code that will be committed. 
#!/bin/bash
# At root folder project: run ln -s ../../utils/git/pre-commit .git/hooks/pre-commit
echo "running pre-commit hooks"

STAGED_FILES_CMD=`git diff --cached --name-only | grep -E "(\.java$)|(pom.xml)"`
# Determine if a file list is passed
ECHO "INPUT: $#"
if [ "$#" -eq 1 ]
then
 oIFS=$IFS
 IFS='
 '
 SFILES="$1"
 IFS=$oIFS
fi
SFILES=${SFILES:-$STAGED_FILES_CMD}

echo "STAGED_FILES_CMD: $STAGED_FILES_CMD, SFILES: $SFILES"
# Determine whether need run maven java test
if [ "$SFILES" == "" ]
then
 echo "no need to run maven test";
 exit 0;
fi

echo "Running maven clean test for errors"

# Stash changes
git stash -q --keep-index

# retrieving current working directory, if don't want to call this hook, run git commit --no-verify
CWD=`pwd`
MAIN_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# go to main project dir
cd $MAIN_DIR/../../
mkdir logs/

set -o pipefail
/usr/local/bin/mvn clean test package | tee logs/mvn.log

RESULT=$?
# Restore changes
git stash pop -q

if [ $RESULT -ne 0 ]; then
  echo "Error while testing the code"
  # in case when we run it in eclipse.
  open logs/mvn.log
  # go back to current working dir
  cd $CWD
  exit 1
fi
# go back to current working dir
cd $CWD
Add pre-commit hooks into git
Each developer should run ln -s ../../tools/git/pre-commit .git/hooks/pre-commit
So if we make any change, others can just pick the change.

Run findbugs during compile, fail build if find bugs
Add findbugs to pom:
<plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>findbugs-maven-plugin</artifactId>
 <version>${org.codehaus.mojo.version}</version>
 <configuration>
  <effort>Max</effort>
  <threshold>Medium</threshold>
  <xmlOutput>true</xmlOutput>
  <failOnError>true</failOnError>
 </configuration>
 <executions>
  <!-- Ensures that FindBugs inspects source code when project is compiled. -->
  <execution>
   <id>analyze-compile</id>
   <phase>compile</phase>
   <goals>
    <goal>check</goal>
   </goals>
  </execution>
 </executions>
</plugin>

We also added Google Error Prone as a step of mvn compile
Resources:

Git Clone a Specific Version/Tag/Branch


I am trying to learning guava implementation detail. So I git-clone the source code as described here.
https://code.google.com/p/guava-libraries/source/checkout
git clone https://code.google.com/p/guava-libraries/
Cloning into 'guava-libraries'...
error: error setting certificate verify locations:
  CAfile: chrome\depot_tools\git-1.8.0_bin/bin/curl-ca-bundle.crt
  CApath: none
 while accessing https://code.google.com/p/guava-libraries/info/refs?service=git-upload-pack
fatal: HTTP request failed
I changed from https to http:
git clone http://code.google.com/p/guava-libraries/ 

It works, then I ran "mvn eclipse:eclipse, it failed with the following exception:
[ERROR] Failed to execute goal on project guava-testlib: Could not resolve dependencies for project com.google.guava:guava-testlib:jar:16.0-SNAPSHOT: Failure to find com.google.guava:guava:jar:16.0-SNAPSHOT in https://oss.sonatype.org/content/repositories/snapshots was cached in the local repository, resolution will not be reattempted until the update interval of sonatype-nexus-snapshots has elapsed or updates are forced -> [Help 1]

So I tried to check out the old version: release 15.0.
I run command: git clone tag and dint the tag name of release 15.0: v15.0

To change local repo to release 15.0, I use: git checkout vlocal_15.0 -b v15.0
The format is: git checkout ] -b remote_branch_name.

Then run mvn eclipse:eclipse and mvn install, it works

To directly clone release 15.0, we can use:
git clone http://code.google.com/p/guava-libraries/  -b v15.0
Resources
git-clone manual page
http://stackoverflow.com/questions/3231079/how-to-see-all-tags-in-a-git-repository-in-command-line
http://stackoverflow.com/questions/791959/how-to-use-git-to-download-a-particular-tag

Linux Notes All In One


Add third-party yum-repositories
rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm
yum install --enablerepo=webtatic git-all
Using CentOS 5 Repos in RHEL 5 Server
wget http://mirrors.nl.kernel.org/centos/5/os/x86_64/CentOS/centos-release-notes-5.10-0.x86_64.rpm
wget http://mirrors.nl.kernel.org/centos/5/os/x86_64/CentOS/centos-release-5-10.el5.centos.x86_64.rpm
rpm -e redhat-release-notes-5Server redhat-release-5Server --nodeps
rpm -ivh centos-release-notes-5.10-0.x86_64.rpm centos-release-5-10.el5.centos.x86_64.rpm
Installing RPMforge
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el5.rf.x86_64.rpm
rpm -ivh rpmforge-release-0.5.3-1.el5.rf.x86_64.rpm
yum search java | grep 'java-'
cd /etc/yum.repos.d

Open a file browser from bash
nautilus --browser .
Exit from git diff
Window+Q 
VNC Server Setup
/etc/sysconfig/vncservers
VNCSERVERS="1:vncuser 2:vncuser2 3:vncuser3"
VNCSERVERARGS[1]="-geometry 1600x1200"

service vncserver start|stop|restart
Create xstartup scripts
vi ~/.vnc/xstartup
Uncomment the following two lines (remove the "#" characters):
unset SESSION_MANAGER
exec /etc/X11/xinit/xinitrc
Managing your VNC sessions
vncserver -kill :1
List all VNC server sessions

ls ~/.vnc/*.pid
Check vnc version in redhat
rpm -qa | grep vnc-server
rpm -qf /usr/bin/vncserver

Copy and paste stops working in VNC session
Run vncconfig &

Install Java in Redhat
Add CentOs repository
yum search java-1.7
yum install java-1.7**
alternatives --display java
/usr/sbin/alternatives --config java

alternatives --install /usr/bin/java java

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)