Github Cookbook

Inhaltsverzeichnis

Github hints

Repository — Quick setup

.. or create a new repository on the command line

echo "# Init " >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin <url>
git push -u origin master

…or push an existing repository from the command line

git remote add origin git@github.axa.com:axa-de-nps/scope_sch_010.git
git push -u origin master

Merge branch with master

Merging via command line

Step 1: From your project repository, bring in the changes and test.

git fetch origin
git checkout -b develop origin/develop
git merge master

Step 2: Merge the changes and update on GitHub.

git checkout master
git merge --no-ff develop
git push origin master

Usefull commands

To show information about a remote, for example if tracked branches are up-to-date:

$ git remote show origin
$ git remote -v show

Working with remote

$ git remote -v
$ git remote add <shortname> <url>
$ git fetch <remote>
$ git push <remote> <branch>
$ git remote show <remote>
$ git remote rename <old> <new>
$ git remote remove <name>

To show log messages of the changes between branches:

$ git log origin/master ^master

Show log graph

git log --pretty=format:"%h %s" --graphs

To show differences between branches:

$ git diff master origin/master

Show , what git pull will doing

$ git fetch && git diff HEAD..@{u}

Or add the command to ~/.gitconfig file:

[alias]
        diffpull=!git fetch && git diff HEAD..@{u}

Run this to see how git diff resolution works

git rev-parse origin

Delete remote branch

git clone <repository> master
cd master
git push origin --delete feature-2.01.03

Show log

git log --oneline --graph --all --decorate

Undo commit

$ git commit --amend

Unstaging a staged file

$ git reset HEAD <filename>

Unmodifying a Modified File

$ git checkout -- <filename>

Retrieve last modification date

$ git ls-files -z | xargs -0 -n1 -I{} -- git log -1 --format="%ai {}" {}

Git Configuration

DESCRIPTIONGIT COMMAND
Configure the author name to be used with your commits.git config --global user.name "XXX"
Configure the author email address to be used with your commitsgit config --global user.email xxx@example.com
Will remove user credential details from the repositorygit config --local credential.helper ""
git config —show-origin
List all currently configured remote repository URLsgit remote -v
If you haven’t connected your local repository to a remote server, To add a remote server to a local repositorygit remote add origin <repo_url>

Git Commit and Push

DESCRIPTIONGIT COMMAND
Create a file name README.md with Readme content contentecho "Readme content" >> README.md
List the files you’ve changed and those you still need to add or commitgit status
Add all or one file to staginggit add . OR git add file_name
Commit changes to head with messagegit commit -m 'message'
Commit any files you’ve added with git add, and also commit any files you’ve changed since thengit commit -a
Send all commits from local repository to remote repositorygit push
Do a git push and sets the default remote branch for the current local branch. So any future git pull command will attempt to bring in commits from the <remote-branch>into the current local branchgit push -u <remote-branch>
Send changes to the master branch of your remote repositorygit push origin master
Push a specific branch to your remote repositorygit push origin <branch_name>
Push all branches to your remote repositorygit push --all origin

Working with the Git Workflow

The following steps are based on a branching model, described here.

Name Beschreibung
master
hotfixes
release
develop
feature

Working with branches

Create branch ‚develop‘

$ git clone git@github.com:<USER>/<REPO>.git develop
$ cd develop
$ git checkout -b develop
$ git push --set-upstream origin develop

Create branch ‚feature-xxx‘

We dont’t want do clone the whole repository, but only the files needed for the feature

$ git clone -b develop -n --depth 1 git@github.com:<USER>/<REPO>.git feature-2.2.0
$ cd feature-2.2.0

Branch löschen

$ git push origin -delete hotfix-1.2.1-compress-data

Workflow – Cheatsheet

Working with branches

How to rename git local and remote branches

Check out branch with old name

git checkout feature-2.1.2

Rename branch

git branch -m feature-2.01.02

Checkin branch with new name

git push origin :feature-2.1.2 feature-2.01.02

1. Rename your local branch.

If you have named a branch incorrectly AND pushed this to the remote repository follow these steps before any other developers get a chance to jump on you and give you shit for not correctly following naming conventions.

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

2. Delete the old-name remote branch and push the new-name local branch.

git push origin :old-name new-name

3. Reset the upstream branch for the new-name local branch.Switch to the branch and then:

git push origin -u new-name

Or you as a fast way to do that, you can use these 3 steps: command in your terminal

git branch -m old_branch new_branch         # Rename branch locally    
git push origin :old_branch                 # Delete old branch    
git push --set-upstream origin new_branch   # Push new branch, set local branch to track new remote
Neues Feature erstellen
Repository clonen$ git checkout -b feature-1.2.2 develop
Änderungen durchführen
Änderungen einchecken$ git checkout develop
$ git merge –no-ff feature-1.2.2
$ git branch -d feature-1.2.2
$ git push origin develop
Neuen Hotfix erstelllen
Repository auschecken$ git checkout -b hotfix-1.2.1 master
Änderungen durchführen
Änderungen einchecken$ git commit -a -m „hotfix: hotfix-1.2.1| compress mart“
Hotfix beenden$ git checkout master
$ git merge –no-ff hotfix-1.2.1
$ git tag -a 1.2.1
Hotfix in Master einchecken$ git checkout develop
$ git merge –no-ff hotfix-1.2.1  
Hotfix Branch entfernen$ git branch -d hotfix-1.2.1
Neues Release erstellen:
Repository clonen$ git checkout -b release-1.2 develop
Änderungen durchführen
Änderungen einchecken$ git commit -a -m „release: changes for release 1.2“
Release beenden$ git checkout master
$ git merge –no-ff release-1.2
$ git tag -a 1.2

Git Flow

Initialize

Start using git-flow by initializing it inside an existing git repository:

$ git flow init

Start a new feature

Development of new features starting from the ‚develop‘ branch.

git flow feature start MYFEATURE

Finish up a feature

Finish the development of a feature. This action performs the following

git flow feature finish MYFEATURE

Publish a feature

Publish a feature to the remote server so it can be used by other users.

git flow feature publish MYFEATURE

Getting a published feature

Get a feature published by another user.

git flow feature pull origin MYFEATURE

You can track a feature on origin by using

git flow feature track MYFEATURE

Start a release

git flow release start RELEASE [BASE]

It’s wise to publish the release branch after creating it to allow release commits by other developers. Do it similar to feature publishing with the command:

git flow release publish RELEASE

(You can track a remote release with the 
git flow release track RELEASEcommand)

Finish up a release

git flow release finish RELEASE

Don’t forget to push your tags with git push origin --tags

Hotfixes

git flow hotfix start VERSION [BASENAME]

Finish a hotfix

git flow hotfix finish VERSION

Usefull commands

basic commandsdescription
git init
git status  [ -s ]status of files and local repo
git ls-filesshow files which are tracked by git
git log [ –oneline ]
git log [–oneline –graph –decorate –all]
shows commit history
git add <changed file>
git add .git add -u
add single file to indexadd all files from the workspace to indexstage current workspace into index to cleanup inconsistencies
git commit [ -m ‚message‘ ]commit into local repo only
git push -u origin masterpush the repo from local to remote repo
git help [option]get help page for specific options
git config –global alias.bla „command“
git bla [– <filename>]
set alias bla to a specific commandexec alias (for specific file)
git mv fileA fileB
git commit -m „…..“
rename fileA to fileBand commit
git rm fileC
git commit -m „…..“
delete fileCand commit
advanced commandsdescription
git reset HEAD <filename>undo changes from index back to workspace
git checkout <filename>
git checkout master
git checkout <branchname>
checkout single file from local repo to workspacecheckout/switch to the master branchcheckout/switch to another branch
git checkout -b <new branchname>
git branch <new branchname>
create new branch and switch to it immediatelycreate new branch in the background, doesn’t switch to it
git branchshows all available branches
git diff
git difftool
show differences of local and committed file
shows diff in vimdiff
git merge <other branch>
git mergetool
merge other branch into master (current branch)manage the different files in vimdiff
git branch -d <branchname>delete branch (does NOT include merge)
git branch -m <new name>rename a
$ git diff master..development compare two branches
git tag <mytag>
git tag -a v1.0 -m „description“
git show v1.0
add an additional label/tag to a branchannotation tag with release informationshows details of tag v1.0
git stash
git reset <ID> [–soft | –mixed | –hard]
git reflog ….
git fetch ….update local repo with changes from remote repo. (non destructive)
git pull …update local repo with changes from remote repo. it does effectively a fetch and merge in one command
git clone https://<username>:<token>@github.com/<organisation-space>/<repository>
download the remote repo into local workspace
git remote -v
git remote show origin
shows url of remote reposhows detail infos of a remote repo
.gitignorecontains filename to exclude from git

Git Workflow

Release

Creating a release branch

Release branches are created from the develop branch. For example, say version 1.1.5 is the current production release and we have a big release coming up. The state of developis ready for the “next release” and we have decided that this will become version 1.2 (rather than 1.1.6 or 2.0). So we branch off and give the release branch a name reflecting the new version number:

$ git checkout -b release-1.2 develop

After creating a new branch and switching to it, we bump the version number. Here, bump-version.sh is a fictional shell script that changes some files in the working copy to reflect the new version. (This can of course be a manual change—the point being that some files change.) Then, the bumped version number is committed.

This new branch may exist there for a while, until the release may be rolled out definitely. During that time, bug fixes may be applied in this branch (rather than on the developbranch). Adding large new features here is strictly prohibited. They must be merged into develop, and therefore, wait for the next big release.

$ ./bump-version.sh 1.2<br>
$ git commit -a -m "Version 1.2"

Finishing a release branch 

$ git checkout master
$ git merge --no-ff release-1.2
$ git tag -a 1.2
$ git checkout develop
$ git merge --no-ff release-1.2
$ git branch -d release-1.2

When the state of the release branch is ready to become a real release, some actions need to be carried out.

First, the release branch is merged into master (since every commit on master is a new release by definition, remember).

Next, that commit on master must be tagged for easy future reference to this historical version.

Finally, the changes made on the release branch need to be merged back into develop, so that future releases also contain these bug fixes.

$ git checkout master
$ git merge --no-ff release-1.2
$ git tag -a 1.2

The release is now done, and tagged for future reference.

To keep the changes made in the release branch, we need to merge those back into develop, though. In Git:

$ git checkout develop
$ git merge --no-ff release-1.2

This step may well lead to a merge conflict (probably even, since we have changed the version number). If so, fix it and commit.

Now we are really done and the release branch may be removed, since we don’t need it anymore:

$ git branch -d release-1.2

Feature

$ git checkout -b myfeature develop
$ .. do changes...

$ git checkout develop
$ git merge --no-ff myfeature
$ git branch -d myfeature
$ git push origin develop

Creating a feature branch 

When starting work on a new feature, branch off from the develop branch.

$ git checkout -b myfeature develop
Switched to a new branch "myfeature"

Incorporating a finished feature on develop 

Finished features may be merged into the develop branch to definitely add them to the upcoming release:

$ git checkout develop<
$ git merge --no-ff myfeature
$ git branch -d myfeature
$ git push origin develop 

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

In the latter case, it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache in the latter situation, whereas it is easily done if the --no-ff flag was used.

Hotfix

$ git checkout -b hotfix-1.2.1 master
$ ... do changes ... 
$ git commit -a -m "Hotfix Version 1.2.1"
$ .. fix bug
$ git commit -m "Fixed severe production problem"

$ git checkout master
$ git merge --no-ff hotfix-1.2.1
$ git tag -a 1.2.1

# incude hotfix into develop
$ git checkout develop
$ git merge --no-ff hotfix-1.2.1

# finally, remove hotfix branch
$ git branch -d hotfix-1.2.1

Troubleshooting

Debugging Github Errors

export GIT_TRACE_PACKET=1
export GIT_TRACE=1
export GIT_CURL_VERBOSE=1

Error Message: Your local changes to the following files would be overwritten by merge:

error: Your local changes to the following files would be overwritten by merge:<br>
        README.md<br>
Please commit your changes or stash them before you merge.

Solution:

$ git fetch origin master
$ git diff origin/master -- [local-path]
$ git add [local-path]
$ gt commit -m "change: in file [local-path]"

fatal: sha1 file ‚<stdout>‘ write error: Broken Pipe

When using ssh to connect to the repositoriy, sometime, you got a timeout if you push to many files or if the files are to big

One possible Solution

Configure ssh to use the following value

~/.ssh/config
Host *
     ServerAliveInterval 30
     ServerAliveCountMax 4

Other Links

Useful Git commands for everyday use

10 useful Git commands you always need

Most useful Git commands

Git Cheat Sheet

Useful Git commands

Using local Filesystem as Respository-Master

Preparation

Set environment variables for easy typing

$ REPOS=$HOME/repos

Create Repository

$ mkdir $REPOS
$ cd    $REPOS
$ git init --bare src

Create src folder

$ mkdir $HOME/entw
$ cd    $HOME/entw
$ mkdir src
$ cd    src
$ git init

Create some content

$ touch README.md
$ git add -A
$ git commit -m "initial commit"
$ git remote add origin $REPOS/src
$ git remote -v
$ git push --set-upstream origin master
$ git push origin master

Create clone

$ mkdir $HOME/test
$ cd    $HOME/test
$ git clone $HOME/repos/src
$ cd src
$ ls -al
total 0
drwxr-xr-x   4 user  wheel  128 19 Mär 18:48 .
drwxr-xr-x   3 user  wheel   96 19 Mär 18:48 ..
drwxr-xr-x  12 user  wheel  384 19 Mär 18:48 .git
-rw-r--r--   1 user  wheel    0 19 Mär 18:48 README.md

You will notice, that the file README.md is empty. Because it was ony created with touch.

Add some content to source repository

$ cd $HOME/entw/src
$ echo "# This is the README.md from ENTW" >README.md
$ touch git_update
$ touch git_push
$ ls -al
total 16
drwxr-xr-x   6 user  wheel  192 19 Mär 18:53 .
drwxr-xr-x   3 user  wheel   96 19 Mär 18:43 ..
drwxr-xr-x  12 user  wheel  384 19 Mär 18:47 .git
-rw-r--r--   1 user  wheel   34 19 Mär 18:52 README.md
-rw-r--r--   1 user  wheel    0 19 Mär 18:53 git_push
-rw-r--r--   1 user  wheel    0 19 Mär 18:53 git_update

Add changes to repository

$ git add -A
$ git commit -m "-"
[master 106b27a] -
 3 files changed, 1 insertion(+)
 create mode 100644 git_push
 create mode 100644 git_update
$ git push --set-upstream origin master
Objekte aufzählen: 5, Fertig.
Zähle Objekte: 100% (5/5), Fertig.
Delta-Kompression verwendet bis zu 8 Threads.
Komprimiere Objekte: 100% (2/2), Fertig.
Schreibe Objekte: 100% (3/3), 320 bytes | 320.00 KiB/s, Fertig.
Gesamt 3 (Delta 0), Wiederverwendet 0 (Delta 0)
To ..../repos/src
   7ed6d3b..106b27a  master -> master
Branch 'master' folgt nun Remote-Branch 'master' von 'origin'.

Update clone

$ cd $OME/test/src
$ git pull
# git fetch   # This updates 'remote' portion of local repo. 
# git reset --hard origin/<your-working-branch>
remote: Objekte aufzählen: 5, Fertig.
remote: Zähle Objekte: 100% (5/5), Fertig.
remote: Komprimiere Objekte: 100% (2/2), Fertig.
remote: Gesamt 3 (Delta 0), Wiederverwendet 0 (Delta 0)
Entpacke Objekte: 100% (3/3), Fertig.
Von .../repos/src
   7ed6d3b..106b27a  master     -> origin/master
$ git merge origin/master
Aktualisiere 7ed6d3b..106b27a
Fast-forward
 README.md  | 1 +
 git_push   | 0
 git_update | 0
 3 files changed, 1 insertion(+)
 create mode 100644 git_push
 create mode 100644 git_update
$ ls -al
total 16
drwxr-xr-x   6 user  wheel  192 19 Mär 19:02 .
drwxr-xr-x   3 user  wheel   96 19 Mär 18:48 ..
drwxr-xr-x  14 user  wheel  448 19 Mär 19:02 .git
-rw-r--r--   1 user  wheel   34 19 Mär 19:02 README.md
-rw-r--r--   1 user  wheel    0 19 Mär 19:02 git_push
-rw-r--r--   1 user  wheel    0 19 Mär 19:02 git_update

TODO

See changes before pulling from remote git repositoryf

# fetch the changes from the remote
git fetch origin
# show commit logs of changes
git log master..origin/master
# show diffs of changes
git diff master..origin/master
# apply the changes by merge..
git merge origin/master
# .. or just pull the changes
git pull

You want to push your local files to remote files

git push -f <remote> <branch>
git push -f origin master

Configure Hooks

git config --global core.hooksPath .githooks
mkdir .githooks
cp .git/hooks/* .githooks

prepare-commit

#!/bin/sh
#

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

branchPath=$(git symbolic-ref -q HEAD)
branchName=${branchPath##*/}


if [ -n "$branchName" ]; then
    echo "$branchName | $(cat $1)" > $1
fi

pre-commit

#!/bin/sh

_BRANCHPATH=$(git symbolic-ref -q HEAD)
_BRANCHNAME=${_BRANCHPATH##*/}

_TIMESTAMP="$(date '+%Y-%m-%d %H:%M:%S')"

echo "HOOK      : $0"
echo "PARAMETER : '$*''"
echo "BRANCHPATH: $_BRANCHPATH"
echo "BRANCHNAME: $_BRANCHNAME"

LOG() {
    [[ "$GIT_COMMIT_DETAILED_LOGGING" == "YES" ]] && echo "LOG: $*"
}

REPLACE()
{
   local _TYP;   _TYP="$1"; shift
   local _TAG;   _TAG="$1"; shift
   local _WITH; _WITH="$1"; shift
   local _FILE; _FILE="$1"; shift

   case "$_TYP" in
      PYTHON)   perl -pi -e 's/(\s*)(__DEPLOY_'${_TAG}'\s*=\s*)(".+")/${1}${2}"'"${_WITH}"'"/' "${_FILE}"
                ;;
      *)        LOG "Undefined typ '$TYP' for file $_FILE"
                ;;
   esac

   rm -f "${_FILE}.bak"
}

LOG "working on branch $_BRANCH"

for _FILE in $(git diff-index --name-status --cached HEAD | grep -v ^D | cut -c3-)
do
    LOG "checking: $_FILE"

    # Only examine known text files
    if [[ "$_FILE" =~ [.](py)$ ]]; then
        LOG "patching: $_FILE"

        REPLACE PYTHON TAG       "$_BRANCHNAME" "$_FILE"
        REPLACE PYTHON TIMESTAMP "$_TIMESTAMP"  "$_FILE"
    fi
done

#

_BRANCHPATH=$(git symbolic-ref -q HEAD)
_BRANCHNAME=${_BRANCHPATH##*/}

_TIMESTAMP=“$(date ‚+%Y-%m-%d %H:%M:%S‘)“

echo „HOOK : $0“
echo „PARAMETER : ‚$*““
echo „BRANCHPATH: $_BRANCHPATH“
echo „BRANCHNAME: $_BRANCHNAME“

LOG() {
[[ „$GIT_COMMIT_DETAILED_LOGGING“ == „YES“ ]] && echo „LOG: $*“
}

REPLACE()
{
local _TYP; _TYP=“$1″; shift
local _TAG; _TAG=“$1″; shift
local _WITH; _WITH=“$1″; shift
local _FILE; _FILE=“$1″; shift

case „$_TYP“ in
PYTHON) perl -pi -e ’s/(\s)(_DEPLOY’${_TAG}’\s=\s*)(„.+“)/${1}${2}“‚“${_WITH}“‚“/‘ „${_FILE}“
;;
*) LOG „Undefined typ ‚$TYP‘ for file $_FILE“
;;
esac

rm -f „${_FILE}.bak“
}

LOG „working on branch $_BRANCH“

for _FILE in $(git diff-index –name-status –cached HEAD | grep -v ^D | cut -c3-)
do
LOG „checking: $_FILE“

# Only examine known text files
if [[ "$_FILE" =~ [.](py)$ ]]; then
    LOG "patching: $_FILE"

    REPLACE PYTHON TAG       "$_BRANCHNAME" "$_FILE"
    REPLACE PYTHON TIMESTAMP "$_TIMESTAMP"  "$_FILE"
fi

done

Get Information

Show current path of git repository

$ git rev-parse --show-toplevel

Config

Change Github repository for local clone

$ git clone https://github.com/<original repository>
$ cd <original repository>
$ git remote set-url origin https://github.com/<new git user>/<new project name>
$ git push -u origin master

CR/LF Mapping

git config core.autocrlf true
git config --global core.safecrlf false

Create Release

#!/bin/bash

if [ $# -ne 1 ]; then
  echo "Syntax: release [VERSION]"
  exit 1
fi

VERSION=$1

# Create release
git flow release start $VERSION || exit 1
GIT_MERGE_AUTOEDIT=no git flow release finish -m $VERSION $VERSION

# Publish release
git push origin HEAD --tags

# Merge release into develop
git checkout develop
git merge master