GIT Cheatsheet

Here are some of the GIT commands that comes handy in day to day work.

CATEGORY COMMAND DESCRIPTION
INIT
git init Initialize a git repository in the current directory
CONFIG
git config –global http.sslVerify false To avoid validating server source.
CLONE
e.g:Minion
git clone –recursive https://github.com/nishabe/Minion.git -b Master /Users/user_name/Documents/Repositories/minion  Note: Make sure to create and add ssh keys before cloning repositories. Refer this page to create new ssh key: https://confluence.atlassian.com/display/STASH033/Creating+SSH+keys .
STATUS git status To check the modification/current status of the local repository
BRANCH info git branch To see the local branches and currently checked out branch.
git branch -a List local as well as remote branches
git branch -r List remote branches
PULL git pull origin Develop git pull = git fetch + git merge
git pull origin task/abc
git pull –rebase
FETCH git fetch origin Get the latest updates from remote and make the local repo in sync with the remote
CREATE A BRANCH git branch story/abc_abc Creating a branch with the user story / defect name.
CREATE A REMOTE BRANCH git config –global push.default current To push local branch that you are locally working on to remote.configure git with push.default = current. More here.
ATTACH TO REMOTE REPO git remote add origin [URL] Attach your local repo to a remote repo.
CHECK REMOTE REPO URL git remote show origin Check remote URL of the local repo.
git branch task/a_b_c
REMOVE BRANCH git branch -d the_local_branch Remove local branch
git push origin –delete Remove remote branch
CHECKOUT git checkout story/abc-abc Switch to the abc/abc-abc branch.
git checkout task/abc
CREATE & CHECKOUT git checkout -b newbranch
ADD/STAGE git add -u Stage all modified files other than untracked files for commit.
git add . Add all folder with subdirectories in it
git add Minion.xcodeproj/xcshareddata/ -f Adding a file which was perviously ignored in git
COMMIT git commit -m “Commit message for the code changes” Committing to local repository.
PUSH git push origin task/MinionView Push the changes back to remote repository story/abc-abc branch, origin is the name of the remote.

task/Minionview is the name of local branch.

eg: git push -u origin task/

Minionview

The -u tells Git to remember the parameters, so that next time we can simply run git push and Git will know what to do.

git push –all To push a local branch to remote repo
eg: git push origin story/ABC-1234:task/Minionview If you want to push to a remote branch with a different
name than your local branch, separate the local and remote names with a colon
MERGING

example 2:

  1. git checkout Develop
  2. git merge story/ABC-1234
  3. Manually resolve conflicts if any.
  4. git commit -a m “Commit message for the merge”
  5. git push origin Develop
example 2: git checkout Project1_PROD
git pull origin Project1_PRODgit checkout Project2_PROD
git pull origin Project2_PRODgit branch -> To make sure I am on Project2_PROD branch which is the target branch
git merge Project1_PRODgit mergetool -> To see the files in UIgit push origin Project2_PROD
Requirement: Merge Project1_PROD to Project2_PROD.

The line (or lines) between the lines beginning <<<<<<< and ====== is what you already had locally – you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>> is what was introduced by the other commit

RESET git reset HEAD To unstage changes. Reset can be used in commit level and file level
git checkout filename To discard change in a file.
git checkout . To discard all changes.
git reset –hard origin/branch Reset the local branch to look like a remote branch.
git reset –hard Undo local changes in current branch. git reset without the –hard option resets the commit history, but not the files. With the –hard option the files in working tree are also reset.
git reset –hard 2343546fvbbcd7be1434a2cf57a0323d3d4fgsg67yhfdet Reset branch to a particular point in codebase
git push -f If you wish to commit that state, so remote repository also points to rolled back commit do
RESET – REMOTE git reset –hard
git push –force
CLEAN git clean -f Removes all untracked files from your working copy
RELEASE WORKFLOW

[Merge from release branch to Master branch]

  1. git checkout Release_branch // switching to Release Branch
  2. git pull origin Release_branch // updating Release code from its remote branch
  3. git checkout master // switching to master branch
  4. git pull origin master // updating master code from its remote branch
  5. git merge Release_branch // merging release code to local master
  6. git status // identify current changes if any
  7. git push origin master // pushing merged master code to remote.
  8. git status // identify current changes if any
More: http://nvie.com/posts/a-successful-git-branching-model/
RELEASE TAGGING
  1. git tag -a ABC.X.X -m “Release ABC.X.X Product RXX” // tagging a specific production release.
  2. git push –tags // pushing all tags to remote.
  3. git status // identify current changes if any
  4. git tag // list all tags in repository.
STAGE git add Stage a new file for tracking / commit
git add -u Stage already tracking files
UNSTAGE git reset HEAD Unstage already staged file
DIFF gitk To see the diff in GUI
git diff –name-only 3453534534 456456456 Show all changed files between two Git commits
git diff HEAD To take a look at what is different from our last commit. In this case we want the diff of our most recent commit, which we can refer to using the HEAD pointer.
HISTORY git log origin/master.. –stat Changes since last push
git log -p changes added in the last commit
git diff —name-only [commit number] Lists the names of the files that have changed since the commit number
BROWSE BRANCH git branch -r See all remote branches
git branch -a See local and remote branches
CREDENTIAL >create a file called .netrc in your home directory with the following content
>cat ~/.netrc
machine .company.net
login Domain\
password
git clone/push/pull without entering username password
GIT NAME, EMAIL show your Git username
git config user.name
or
git config –listview

Show your Git email address
git config user.email

change your Git username globally:
git config –global user.name “my_name_here”
change your Git username locally:
git config user.name “my_name_here”

change your Git email address globally
git config –global user.email my_email@email.com
change your Git email address locally
git config user.email my_email@email.com

RENAMING git push origin origin/oldnamebranch:refs/heads/newnamebranch
git push origin :oldnamebranch
git checkout newnamebranch
git branch -d oldnamebranch
rename remote 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

local branch
MISC git submodule update update submodule pointer from main project
PATCH git checkout bugfix_branch generate a patch file of all the changes done in the bug fix branch
git format-patch main_branch –stdout > bugfix.patch
git format-patch -M -C ~1.. generate a patch file for commit commitID
CHERRYPICK git checkout branchA cherry pick a commit from branch A to branch B
git tree //to get the commit id
git checkout branchB
git cherry-pick
STASH git stash create a stash
git stash list list all stashes
git stash apply stash@{1} apply a stash
git stash drop stash@{1} remove a stash
git stash pop apply a stash and remove from list
TAGS git tag list all the tags
git tag -l ‘v.1.4.2.*’ search for tags
git tag -a v1.5 -m ‘version 1.5’ add new tag
git show v1.5 show tag info
git tag -s v1.5 -m ‘signed version 1.5 tag’ signed tags
git tag -v v1.5 verify signed tag
git push origin {tagName} push single tag to the remote server
git push origin –tags push all the tags to the remote server
Trace GIT_TRACE=1 git_command_here Trace the execution

Reference:

GIT Cheatsheet

Mac OSX TIPS

Make All Folders visible in Mac OSX:

This is a handy line of command that I use often when working with system internals.

1. Run the below command in Terminal:
defaults write com.apple.Finder AppleShowAllFiles YES
2. Restart the finder

Customize Terminal in order to move cursor faster:

Ability to move between long strings of commands is awesome.

Refer this page to get it done.

 

Mac OSX TIPS

Simple, Secure Folder Backup on Mac OSX

Your system may crash at any time. You may lose all your data any time.
Keeping this in mind, I did set up a time machine back up after creating a separate partition within the hard drive.

Apparently that was not enough.
My hard drive failed beyond recovery and I lost all my precious data.
I learnt my lesson. Always back up to a physically separated hard drive.
Technically you can set up a time machine backup over the network provided, you have an OSX server.

What is the best you can do with what you have currently?
The answer is you can setup a scheduled job that will trigger a script based on rsync. rsync is tool available in unix to sync files between different locations. Your mac already has it. No need to install anything new. rsync is secure, it uses SSH.

I did some research and made it work.

These were the steps I followed.

1. Create the rsync script.
2. Create and configure SSH keys if you don’t have it.
3. Test the script
4. Create a scheduled job top run the script using launchd.

In my case, my work machine is a Macbook pro and I wanted to create back up of a specific folder to an iMac.
The iMac and Macbook pro are in same LAN.

Now the above steps in detail:

1. Create the rsync script.

The script is pretty straight forward.

rsync -a your_folder_name user_name@backup_machine_name:Desktop

2. Create and configure SSH keys if you don’t have it.

Please refer to steps 3 and 4 in this post.

3. Test the script

Make sure your script has necessary permissions.
Open terminal.
CD in to the folder, where you have your script.
type
ls -l
and hit enter
By default, the permission status will look like: -rw-r–r–
On the same terminal, type
chmod 755 your_script_file
and hit enter

Do a,
ls -l and verify the permission as -rwxr-xr-x

Assuming that you have your SSH ready, run the script.
Once it is working, lets modify the script so that it is easier to make any future changes. Instead of hardcoding the paths inline, we declare them as variables.

RSYNC=/usr/bin/rsync # this tells the interpreter where to find rsync (run 'which rsync' to be sure)
LPATH=/Users/user_name/Documents/WorkRelated/ # read: "where is the local computer path you wish to sync?"
RPATH=user_name@backupMachineName:/Users/user_name/Documents/WorkRelated/ # read: "And what about the remote path?"

$RSYNC -arvz --progress $LPATH $RPATH

Place the script in your home folder.
Check the permission, run this script in terminal to make sure it works.

4. Create a scheduled job that run the script using launchd.

Now the easier part. We can schedule a job that runs this script at defined interval.
All you need to do is, create a plist and copy it in below path.

~/Library/LaunchAgents/

In finder you can use the shortcut CMD+Shift+G to see ‘Go to Folder’ pop up.

You can use this online PLIST Creation tool.

My plist looked like this:





 Label
 com.folderbackup.job
 ProgramArguments
 
 sh
 -c
 /Users/user_name/folderbackup-script.sh
 
 RunAtLoad
 
 StartInterval
 1800

Make sure to give the correct path to the script. StartInterval defines the interval in seconds. If you put 1800 as StartInterval, the job will start after 30 minutes of your login.

Make sure to save the plist with the same name as the label value within the plist. The above plist name would be ‘com.folderbackup.job.plist’.

Now logout and login your account. The new job will be picked up only during login event. Or you can  execute the below command.

launchctl load -w ~/Library/LaunchAgents/com.folderbackup.job.plist

If you have a many GBs of data, the first sync will take some time. But after that rsync is clever enough to back up only the change delta.

Hope you have crash proof back up setup now!

References:

rsync:

  1. Syncing with Rsync/Cron in Mac OS
    Backing up data using rsync command
  2. chmod

Scheduling:

  1. A launchd Totorial
  2. Scheduling Timed Jobs
  3. Schedule jobs using launchd 
  4. Mac OS X launchd examples (launchd plist example files)
  5. How do I set a task to run every so often?

Update: Aug-13-2017

In case all you need to copy a folder to an external hard drive which is not connected to the system always, you can run the script manually. Follow the steps above to create and make the script executable.
Here is a sample script:

RSYNC=/usr/bin/rsync # this tells the interpreter where to find rsync (run 'which rsync' to be sure)
LPATH=/Users/user_name/Documents/myFolderName/ # read: "where is the local computer path you wish to sync?"
RPATH=/Volumes/drive_name/WorkBackUp/ # read: "And what about the remote path?"
$RSYNC -arvz --progress $LPATH $RPATH
Simple, Secure Folder Backup on Mac OSX

Setting up a local GIT Server

 

Credit: This post is heavily relied on two articles.
1. How To Set Up A Secure Git Server At Home (OSX)  written by Tom Dalling.
The above post addresses the scenario, where you want to access your private GIT server over internet.
2. Creating an SSH key on Linux & Mac OS X 

The purpose of this post is to focus on the steps that is needed to set up and access a local GIT server.
I am taking the liberty to re-use the original description and screenshots from the original articles wherever applicable.

If you work for a big company, you don’t have to worry much. You will have Atlassian Stash or GitHub who will take care of the source control mechanism for you.
What if you are a sole developer in your company and you don’t want to spend a lot in third party managed source control set up?

You set up your own GIT server. This post is about setting up a GIT server locally.
In our case, there are two developers with MacBook Pros and an extra iMac.
So we decided to set up GIT server in the extra iMac we had.

These were the steps we followed.

1.  Add a GIT user account in Server machine.
2. Turn on remote login for GIT user in Server machine.
3. Creating SSH keys in client machines
4. Adding up client’s public keys in Server
5. Making a bare repo in the server
6. Using the new GIT server!

Now the above steps in detail:

For the brevity of the post, assume that you are setting up the GIT server on an iMac.
Also it is assumed that you have an account with admin access in this iMac.

1. Add a GIT user account in Server machine.

Login to the admin account in the iMac.
Open up System Preferences » Accounts and add a standard user


Log into the new git user account.
Open Terminal.app and type the following:

echo 'export PATH="$PATH:/usr/local/git/bin/"' >> ~/.bashrc

2.Turn on remote login for GIT user in Server machine.

Log out of the git user, and log back into your administrator account.
Open up System Preferences » Sharing and turn on Remote Login (this is ssh).

Set Allow access for to Only these users, and add the git user to the list.

3.Set up SSH in client machines

Open a terminal on your local computer and enter the following:

ssh-keygen -t rsa -C "your_email@example.com"

Associating the key with your email address helps you to identify the key later on.
You’ll see a response similar to this:

Just press <Enter> to accept the default location and file name. If the .ssh directory doesn’t exist, the system creates one for you.

Enter, and re-enter, a passphrase when prompted.
The whole interaction will look similar to this:

You are done.

4.Setting up client’s public keys in Server

You can use the below command to add the public key of the client machine added to the authorized_keys file in the server.
Log into the git user in the iMac
Run this command in the client machine:

cat ~/.ssh/id_rsa.pub | ssh git@MachineName "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"

If you have more client machines, repeat the above steps in all of them. You may see some prompts similar to the screenshot below in step 6. Select yes and proceed.

5.Making a bare repo in the server

This is the definition of a “bare” git repo: a repository that can never have files checked out. Everyone pulls and pushes from the server like normal, but nobody can actually work on the server (unless they make a non-bare clone).

If you are creating a new repository called “myrepo.git”, you can make it bare like so:
git init –bare myrepo.git

6.Using the new GIT server

In the client machine all you have to do is the usual clone.
eg: git clone ssh://iMacName/Users/git/myrepo
You may get a prompt like this in the client machine. Opt for YES and enter the password.

prompt
You should have the cloned copy in the local machine by this time.

Where to go from here?

In my case, the project was already there in my local machine. I wanted to have the project data centralized in the new git server.

Here are the steps along with the commands that I followed:

 

1 Connect to the remote server ssh git@yourGITMachineName
2 Go to the repo folder cd Documents/repositories/
3 Create the sub folder under main repo directory mkdir myNewProjectFolder
4 Create a bare repo in server on the created folder git init –bare
5 Clone the new repo to local machine git clone ssh://git@yourGITMachineName/Users/git/Documents/repositories/myNewProjectFolder
6 Checkout as a new branch The default branch of the repo is ‘master’. Checkout as ‘develop’. More concepts here.
7 Make necessary changes like adding project files to the cloned repo folder git add .
8 Commit the changes git commit -m “First Commit”
9 Push the changes to server git push origin master

Reference:

  1. Creating an SSH key on Linux & Mac OS X
  2. How To Set Up SSH Keys
Setting up a local GIT Server