SlideShare a Scribd company logo
Working with Git
Sanghoon Hong
Contents
Git Introduction
How-to basics
• commit / add / merge / push and pull
Work efficiently with Git
• rebase / stash
• Workflow / commit guidelines
Git Introduction
SVN (Centralized VCS)
Pros
• Have been used for years
 …
Cons
 …
Git (Distributed VCS)
Pros
 Can work offline
 Very fast commit / log-retrieval
 Interesting workflows
Cons
 High disk usage (but who cares?)
 Can’t checkout a part of a repository
Git Introduction
SVN
• Track changes
Git
• Track snapshots
• Checksum is used
as a commit ID
Git Introduction
What are stored in a single commit?
• Hash ID
• parent
• trees and blobs
• author and messages
• …
SHA-1 Hash: 34ac26552252987aa493b52f8696cd6d3b00373
Git Introduction
Staging Area
• One additional step
(doesn’t exist in SVN)
• Modified files must be added
at the staging area before creating a commit
Work-steps
1. Edit one or more files in your working directory
2. Stage it
3. Commit it
How-to Basics
Initializing a Repository
Git init
Git clone
$ git clone https://github.com/schacon/ticgit
Cloning into 'ticgit'...
remote: Reusing existing pack: 1857, done.
remote: Total 1857 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1857/1857), 374.35 KiB | 268.00 KiB/s, done.
Resolving deltas: 100% (772/772), done.
Checking connectivity... done.
$ cd ticgit
$ git remote
origin
$ git status
fatal: Not a git repository (or any of the parent directories): .git
$ git init
Initialized empty Git repository in ~/test/.git/
$ git status
On branch master
Initial commit
nothing to commit (create/copy files and use "git add" to track)
Create a repository (in current directory)
Create a directory for a new repository,
and clone a remote repository
Creating a Commit
$ git status
On branch master
nothing to commit, working directory clean
$ echo 'My Project' > README
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
README
nothing added to commit but untracked files present (use "git add" to track)
$ git add README
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: README
$ vim benchmarks.rb
$ git add benchmarks.rb
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: README
modified: benchmarks.rb
$ git commit
No changes
README is created,
but untracked
README is staged
benchmarks.rb is modified
benchmarks.rb is staged
Commit!!
Now everything is clean
Creating a Commit
What if I modify a staged file?
• The file exists in two different states
• You must add again to reflect your modification
What if I want to roll-back a staged/modified file?
$ vim benchmarks.rb
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: README
modified: benchmarks.rb
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working
directory)
modified: benchmarks.rb
$ git reset [filename]
$ git checkout –- [filename]
Unstage a specific (or all) file. File contents doesn’t change (unless you specify --hard)
Roll-back a specific (or all) file. Unstaged/commited changes will disappear
Diff-ing / Log Retrieval
Diff
Log / Show
$ git diff
diff --git a/benchmarks.rb b/benchmarks.rb
index 3cb747f..e445e28 100644
--- a/benchmarks.rb
+++ b/benchmarks.rb
@@ -36,6 +36,10 @@ def main
@commit.parents[0].parents[0].parents[0]
end
+ run_code(x, 'commits 1') do
+ git.commits.size
+ end
+
run_code(x, 'commits 2') do
log = git.commits('master', 15)
log.size
$ git diff <commit ID or branch name>
git diff --stagedgit diff
$ git log
$ git show <commit ID or branch name>
Branch
Using branches is so convenient with Git!!
 Instant creation
 Quick switch between branches
 Simple and fast merging
How Branches are Handled?
 “branch” is merely a pointer to a specific commit
Branch
$ git branch iss53
$ git checkout iss53
$ vim index.html
$ git commit -a -m 'added a new footer [issue 53]'
Create a new branch
Change working branch
Create a commit at ‘iss53’
‘master’ stays on its position
$ git checkout masterChange work branch
Branch
$ git checkout master
Switched to branch 'master'
$ git checkout master
$ git merge hotfix
Updating f42c576..3a0874c
Fast-forward
index.html | 2 ++
1 file changed, 2 insertions(+)
$ git checkout -b hotfix
Switched to a new branch 'hotfix'
$ vim index.html
$ git commit -a -m 'fixed the broken email address‘
[hotfix 1fb7853] fixed the broken email address
1 file changed, 2 insertions(+)
Create another branch
and checkout it
Merge two branches
Create a commit
with all modified files
(-a: stage all modified files)
Fast-forward merge
- Just move the branch pointer!
Branch / Merge
Merge two branches into a single branch
$ git checkout master
Switched to branch 'master'
$ git merge iss53
Merge made by the 'recursive' strategy.
README | 1 +
1 file changed, 1 insertion(+)
$ git branch -d iss53
Create a merge commit
and move the working branch
Merge commit
Branch / Merge
Resolving conflicts
• Modify files with conflicts, add them and then create a merge commit!
$ git merge iss53
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
$ git status
On branch master
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: index.html
no changes added to commit (use "git add" and/or "git commit -a")
<<<<<<< HEAD:index.html
<div id="footer">contact : email.support@github.com</div>
=======
<div id="footer">
please contact us at support@github.com
</div>
>>>>>>> iss53:index.html
<<<< (from our branch)
… contents …
==== (divider)
… contents …
>>>> (from their branch)
What you see
when you open the conflicted file
Syncing
Fetch / Pull
• Import commits from a remote repository
• pull = fetch + merge
Push
• Transfer local commits to a remote repository
Remote repository
(origin)
Local repository
push
fetch/pull
Syncing
What if remote branch is modified?
• You can’t push your commits!
• All commits in remote should be pulled before pushing commits
(Only fast-forward merge is accepted.)
# John's Machine
$ git clone john@githost:simplegit.git
Initialized empty Git repository in /home/john/simplegit/.git/
...
$ cd simplegit/
$ vim lib/simplegit.rb
$ git commit -am 'removed invalid default value'
[master 738ee87] removed invalid default value
1 files changed, 1 insertions(+), 1 deletions(-)
# John's Machine
$ git push origin master
To john@githost:simplegit.git
! [rejected] master -> master (non-fast forward)
error: failed to push some refs to 'john@githost:simplegit.git'
===== Jesicca modified the remote branch =====
Jessica’s new commit
Remote repository
Local repository
Your local repository
thinks the remote master is here
Remote branch is one commit ahead
Syncing
What if remote branch is modified?
• Run pull (fetch and merge) before push
$ git fetch origin
...
From john@githost:simplegit
+ 049d078...fbff5bc master -> origin/master
$ git merge origin/master
Merge made by recursive.
TODO | 1 +
1 files changed, 1 insertions(+), 0 deletions(-)
$ git push origin master
...
To john@githost:simplegit.git
fbff5bc..72bbc59 master -> master
git fetch
git merge
git push
Remote repository has been updated
Update origin/master branch in your local repository
Merge two branches
How to work efficiently with Git
Rebase
What is rebase?
• Create additional commit(s)
which contains the contents of the existing commits
$ git checkout master
$ git merge experiment
$ git checkout experiment
$ git rebase master
First, rewinding head to replay your work on top of it...
Applying: added staged command
Important!
Commits of the working branch
will be moved and applied to the target branch
(different from ‘merge’)
A new commit for C4
Rebase
What we can get from rebase?
• Keep linear commit logs
• Remove dirty commit logs
• Merge commits selectively
commit: merge commit
commit: C10
commit: merge commit
commit: C9
commit: C8
commit: C6
commit: C5
commit: C4
commit: C3
commit: C2
commit: C1
Expected logs after ‘merge’
commit: C10’
commit: C4’
commit: C3’
commit: C9’
commit: C8’
commit: C6
commit: C5
commit: C2
commit: C1
Expected logs after ‘rebase’
rebase client onto master,
then rebase server onto client
Rebase
Never use ‘git rebase’ on public branches
• Never use rebase on pushed commits
My recommendations
• Use rebase on your private branches, to beautify commit logs
• If you’ve finished working / reviewing a branch
and the only thing for you to do is ‘merging’ the branch with masters,
its okay to use rebase
• Otherwise, use merge
Further Readings
• Pro Git
• Atlassian tutorias - Merging vs. Rebasing (link)
• Check ‘interactive rebase’
How to work with branches
Creating many branches are recommended!
Branch examples
• master: stable and released code
• ver1.x: publicly released version (can be a tag)
• develop: test-passed, but may have some bugs
• topic: small branches for issues, feature development, or hotfix, …
• …
How to work with branches
One example of branch workflows
Further readings
• Atlassian Git Tutorials – Git Workflows (link)
Stash
Stash
• Temporary storage for changes.
• Useful when you have some changes to keep (without creating a commit)
and want to start working on other items
$ git status
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: index.html
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: lib/simplegit.rb
$ git stash
Saved working directory and index state 
"WIP on master: 049d078 added the index file"
HEAD is now at 049d078 added the index file
(To restore them type "git stash apply")
$ git status
# On branch master
nothing to commit, working directory clean
Current changes
are stored in ‘stash’ You can go on
working on other items
Context switching!
Everything is clean
Original Commit
Your changes
Working directoryStash area
Original CommitYour changes
Working directoryStash area
Stash
How to restore stashed changes
• Don’t need to be at the same branch or HEAD
$ git stash list
stash@{0}: WIP on master: 049d078 added the index file
stash@{1}: WIP on master: c264051 Revert "added file_size"
stash@{2}: WIP on master: 21d80a5 added number to log
$ git stash apply
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
#
# modified: index.html
# modified: lib/simplegit.rb
#
$ git stash drop stash@{0}
Dropped stash@{0} (364e91f3f268f0900bc3ee613f9f733e82aaed43)
Saved changes are restored
Remove stashed item
Important!
Stash is stored in a stack with reverse order. (0 is the newest one)
So, running ‘git stash drop stash@{0}’ twice will remove two different changes
Change C
Change B
Change A
stash@{0}
stash@{2}
stash@{1}
Change B
Change A
stash@{0}
stash@{1}
Stash area
Stash area
Commit Guidelines
One issue per one commit
• Use ‘git add –p’
to stage only some parts
of a modified file
Commit messages
• See the example
Further readings
• How to Write
a Git Commit Message (link)
• 5 Useful Tips For
A Better Commit Message (link)
Summarize changes in around 50 characters or less
More detailed explanatory text, if necessary. Wrap it to about 72
characters or so. In some contexts, the first line is treated as the
subject of the commit and the rest of the text as the body. The
blank line separating the summary from the body is critical (unless
you omit the body entirely); various tools like `log`, `shortlog`
and `rebase` can get confused if you run the two together.
Explain the problem that this commit is solving. Focus on why you
are making this change as opposed to how (the code explains that).
Are there side effects or other unintuitive consequenses of this
change? Here's the place to explain them.
Write your commit message in the imperative: "Fix bug" and not "Fixed bug"
or "Fixes bug." This convention matches up with commit messages generated
by commands like git merge and git revert.
Further paragraphs come after blank lines.
- Bullet points are okay, too
- Typically a ‘-’ or ‘*’ is used for the bullet, preceded
by a single space, with blank lines in between, but conventions
vary here
If you use an issue tracker, put references to them at the bottom,
like this:
Resolves: #123
See also: #456, #789
Excerpts from ‘How to Write a Git Commit Message’ and ‘A Note About Git Commit Messages (link)’
Git Workflows
Centralized workflow
• Simple server-client structure (like SVN)
Integration-Manager workflow
• Suit for bigger projects
• Dedicated integration manager
to review/filter/merge commits
Further readings
• Pro Git – Chapter 5
Some other comments
.gitignore
• You can specify files to be excluded in Git
• Files you should exclude
• Compile results: *.o / *.a / *.pyc / executables
• Temporary files: *.swp / *~
• …
Don’t commit big / temporary binary files
• They will remain in your repository history,
and consume large disk storage / slow down your work with Git (cloning, especially)
• Small library / image files are usually accepted.
However, a script to download those files are much better
Git Cheatsheet
Two recommended git cheatsheets
• Git cheat sheet, extended edition by Jan Krüger (link)
• Git cheat sheet by Zack Rusin (link)
References
 Pro Git (Korean version)
http://git-scm.com/book/ko/v2
• Also available in many other languages
 “Getting Git Right” slides from Atlassian
http://www.slideshare.net/svenpeters/getting-git-right

More Related Content

What's hot (20)

PDF
Version control Git -Lecture-2
Abdul Rahim
 
PPTX
Introduction to Git / Github
Paige Bailey
 
PDF
Version control git - lecture-1
Abdul Rahim
 
PDF
What is Git | What is GitHub | Git Tutorial | GitHub Tutorial | Devops Tutori...
Edureka!
 
PDF
Github - Git Training Slides: Foundations
Lee Hanxue
 
PDF
Git and github - Verson Control for the Modern Developer
John Stevenson
 
PPTX
Git hub ppt presentation
AyanaRukasar
 
PDF
手把手教你如何串接 Log 到各種網路服務
Mu Chun Wang
 
PPTX
An introduction to Git
Muhil Vannan
 
PPTX
Git tips and tricks
Chris Ballance
 
PDF
Intro to Git and GitHub
Matthew McCullough
 
PDF
Lessons from Etsy: Avoiding Kitchen Nightmares - #ChefConf 2012
Patrick McDonnell
 
PDF
What’s New in Rails 5.0?
Unboxed
 
PPTX
Techoalien git
Aditya Tiwari
 
PPTX
Git 101 for Beginners
Anurag Upadhaya
 
PPTX
GIT presentation
Naim Latifi
 
PPTX
MakingGitWorkForYou
Kwen Peterson
 
PDF
Introduction To Git For Version Control Architecture And Common Commands Comp...
SlideTeam
 
PDF
Quick Introduction to git
Joel Krebs
 
PDF
Git the Docs: A fun, hands-on introduction to version control
Becky Todd
 
Version control Git -Lecture-2
Abdul Rahim
 
Introduction to Git / Github
Paige Bailey
 
Version control git - lecture-1
Abdul Rahim
 
What is Git | What is GitHub | Git Tutorial | GitHub Tutorial | Devops Tutori...
Edureka!
 
Github - Git Training Slides: Foundations
Lee Hanxue
 
Git and github - Verson Control for the Modern Developer
John Stevenson
 
Git hub ppt presentation
AyanaRukasar
 
手把手教你如何串接 Log 到各種網路服務
Mu Chun Wang
 
An introduction to Git
Muhil Vannan
 
Git tips and tricks
Chris Ballance
 
Intro to Git and GitHub
Matthew McCullough
 
Lessons from Etsy: Avoiding Kitchen Nightmares - #ChefConf 2012
Patrick McDonnell
 
What’s New in Rails 5.0?
Unboxed
 
Techoalien git
Aditya Tiwari
 
Git 101 for Beginners
Anurag Upadhaya
 
GIT presentation
Naim Latifi
 
MakingGitWorkForYou
Kwen Peterson
 
Introduction To Git For Version Control Architecture And Common Commands Comp...
SlideTeam
 
Quick Introduction to git
Joel Krebs
 
Git the Docs: A fun, hands-on introduction to version control
Becky Todd
 

Similar to Working with Git (20)

PDF
Pro git - grasping it conceptually
seungzzang Kim
 
PDF
Git and github 101
Senthilkumar Gopal
 
PDF
Git basics
Surabhi Gupta
 
PDF
Git with the flow
Dana White
 
PPTX
Git 101 - An introduction to Version Control using Git
John Tighe
 
PPTX
Git walkthrough
Bimal Jain
 
PPTX
Git and git workflow best practice
Majid Hosseini
 
PPTX
github ppt git ppt on git hub to know ab
infoinnext
 
PPTX
git.ppt.pptx power point presentation got Google internet
rani marri
 
PPTX
GIT.pptx
Soumen Debgupta
 
PPTX
Techoalien git
Aditya Tiwari
 
PPTX
Techoalien git
Aditya Tiwari
 
PPTX
Git - Version Control System
Namig Hajiyev
 
PPTX
Introduction to Git and GitHub
Bioinformatics and Computational Biosciences Branch
 
PPTX
Git_new.pptx
BruceLee275640
 
PDF
Source Code Management with Git
Things Lab
 
PPTX
Learn Git - For Beginners and Intermediate levels
Gorav Singal
 
KEY
Gittalk
prtinsley
 
PPTX
Git-ing out of your git messes
Katie Sylor-Miller
 
PPTX
Git more done
Kwen Peterson
 
Pro git - grasping it conceptually
seungzzang Kim
 
Git and github 101
Senthilkumar Gopal
 
Git basics
Surabhi Gupta
 
Git with the flow
Dana White
 
Git 101 - An introduction to Version Control using Git
John Tighe
 
Git walkthrough
Bimal Jain
 
Git and git workflow best practice
Majid Hosseini
 
github ppt git ppt on git hub to know ab
infoinnext
 
git.ppt.pptx power point presentation got Google internet
rani marri
 
GIT.pptx
Soumen Debgupta
 
Techoalien git
Aditya Tiwari
 
Techoalien git
Aditya Tiwari
 
Git - Version Control System
Namig Hajiyev
 
Git_new.pptx
BruceLee275640
 
Source Code Management with Git
Things Lab
 
Learn Git - For Beginners and Intermediate levels
Gorav Singal
 
Gittalk
prtinsley
 
Git-ing out of your git messes
Katie Sylor-Miller
 
Git more done
Kwen Peterson
 
Ad

Recently uploaded (20)

PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Salesforce Experience Cloud Consultant.pdf
VALiNTRY360
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PDF
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Salesforce Experience Cloud Consultant.pdf
VALiNTRY360
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Ad

Working with Git

  • 2. Contents Git Introduction How-to basics • commit / add / merge / push and pull Work efficiently with Git • rebase / stash • Workflow / commit guidelines
  • 3. Git Introduction SVN (Centralized VCS) Pros • Have been used for years  … Cons  … Git (Distributed VCS) Pros  Can work offline  Very fast commit / log-retrieval  Interesting workflows Cons  High disk usage (but who cares?)  Can’t checkout a part of a repository
  • 4. Git Introduction SVN • Track changes Git • Track snapshots • Checksum is used as a commit ID
  • 5. Git Introduction What are stored in a single commit? • Hash ID • parent • trees and blobs • author and messages • … SHA-1 Hash: 34ac26552252987aa493b52f8696cd6d3b00373
  • 6. Git Introduction Staging Area • One additional step (doesn’t exist in SVN) • Modified files must be added at the staging area before creating a commit Work-steps 1. Edit one or more files in your working directory 2. Stage it 3. Commit it
  • 8. Initializing a Repository Git init Git clone $ git clone https://github.com/schacon/ticgit Cloning into 'ticgit'... remote: Reusing existing pack: 1857, done. remote: Total 1857 (delta 0), reused 0 (delta 0) Receiving objects: 100% (1857/1857), 374.35 KiB | 268.00 KiB/s, done. Resolving deltas: 100% (772/772), done. Checking connectivity... done. $ cd ticgit $ git remote origin $ git status fatal: Not a git repository (or any of the parent directories): .git $ git init Initialized empty Git repository in ~/test/.git/ $ git status On branch master Initial commit nothing to commit (create/copy files and use "git add" to track) Create a repository (in current directory) Create a directory for a new repository, and clone a remote repository
  • 9. Creating a Commit $ git status On branch master nothing to commit, working directory clean $ echo 'My Project' > README $ git status On branch master Untracked files: (use "git add <file>..." to include in what will be committed) README nothing added to commit but untracked files present (use "git add" to track) $ git add README $ git status On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: README $ vim benchmarks.rb $ git add benchmarks.rb $ git status On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: README modified: benchmarks.rb $ git commit No changes README is created, but untracked README is staged benchmarks.rb is modified benchmarks.rb is staged Commit!! Now everything is clean
  • 10. Creating a Commit What if I modify a staged file? • The file exists in two different states • You must add again to reflect your modification What if I want to roll-back a staged/modified file? $ vim benchmarks.rb $ git status On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: README modified: benchmarks.rb Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: benchmarks.rb $ git reset [filename] $ git checkout –- [filename] Unstage a specific (or all) file. File contents doesn’t change (unless you specify --hard) Roll-back a specific (or all) file. Unstaged/commited changes will disappear
  • 11. Diff-ing / Log Retrieval Diff Log / Show $ git diff diff --git a/benchmarks.rb b/benchmarks.rb index 3cb747f..e445e28 100644 --- a/benchmarks.rb +++ b/benchmarks.rb @@ -36,6 +36,10 @@ def main @commit.parents[0].parents[0].parents[0] end + run_code(x, 'commits 1') do + git.commits.size + end + run_code(x, 'commits 2') do log = git.commits('master', 15) log.size $ git diff <commit ID or branch name> git diff --stagedgit diff $ git log $ git show <commit ID or branch name>
  • 12. Branch Using branches is so convenient with Git!!  Instant creation  Quick switch between branches  Simple and fast merging How Branches are Handled?  “branch” is merely a pointer to a specific commit
  • 13. Branch $ git branch iss53 $ git checkout iss53 $ vim index.html $ git commit -a -m 'added a new footer [issue 53]' Create a new branch Change working branch Create a commit at ‘iss53’ ‘master’ stays on its position $ git checkout masterChange work branch
  • 14. Branch $ git checkout master Switched to branch 'master' $ git checkout master $ git merge hotfix Updating f42c576..3a0874c Fast-forward index.html | 2 ++ 1 file changed, 2 insertions(+) $ git checkout -b hotfix Switched to a new branch 'hotfix' $ vim index.html $ git commit -a -m 'fixed the broken email address‘ [hotfix 1fb7853] fixed the broken email address 1 file changed, 2 insertions(+) Create another branch and checkout it Merge two branches Create a commit with all modified files (-a: stage all modified files) Fast-forward merge - Just move the branch pointer!
  • 15. Branch / Merge Merge two branches into a single branch $ git checkout master Switched to branch 'master' $ git merge iss53 Merge made by the 'recursive' strategy. README | 1 + 1 file changed, 1 insertion(+) $ git branch -d iss53 Create a merge commit and move the working branch Merge commit
  • 16. Branch / Merge Resolving conflicts • Modify files with conflicts, add them and then create a merge commit! $ git merge iss53 Auto-merging index.html CONFLICT (content): Merge conflict in index.html Automatic merge failed; fix conflicts and then commit the result. $ git status On branch master You have unmerged paths. (fix conflicts and run "git commit") Unmerged paths: (use "git add <file>..." to mark resolution) both modified: index.html no changes added to commit (use "git add" and/or "git commit -a") <<<<<<< HEAD:index.html <div id="footer">contact : [email protected]</div> ======= <div id="footer"> please contact us at [email protected] </div> >>>>>>> iss53:index.html <<<< (from our branch) … contents … ==== (divider) … contents … >>>> (from their branch) What you see when you open the conflicted file
  • 17. Syncing Fetch / Pull • Import commits from a remote repository • pull = fetch + merge Push • Transfer local commits to a remote repository Remote repository (origin) Local repository push fetch/pull
  • 18. Syncing What if remote branch is modified? • You can’t push your commits! • All commits in remote should be pulled before pushing commits (Only fast-forward merge is accepted.) # John's Machine $ git clone john@githost:simplegit.git Initialized empty Git repository in /home/john/simplegit/.git/ ... $ cd simplegit/ $ vim lib/simplegit.rb $ git commit -am 'removed invalid default value' [master 738ee87] removed invalid default value 1 files changed, 1 insertions(+), 1 deletions(-) # John's Machine $ git push origin master To john@githost:simplegit.git ! [rejected] master -> master (non-fast forward) error: failed to push some refs to 'john@githost:simplegit.git' ===== Jesicca modified the remote branch ===== Jessica’s new commit Remote repository Local repository Your local repository thinks the remote master is here Remote branch is one commit ahead
  • 19. Syncing What if remote branch is modified? • Run pull (fetch and merge) before push $ git fetch origin ... From john@githost:simplegit + 049d078...fbff5bc master -> origin/master $ git merge origin/master Merge made by recursive. TODO | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) $ git push origin master ... To john@githost:simplegit.git fbff5bc..72bbc59 master -> master git fetch git merge git push Remote repository has been updated Update origin/master branch in your local repository Merge two branches
  • 20. How to work efficiently with Git
  • 21. Rebase What is rebase? • Create additional commit(s) which contains the contents of the existing commits $ git checkout master $ git merge experiment $ git checkout experiment $ git rebase master First, rewinding head to replay your work on top of it... Applying: added staged command Important! Commits of the working branch will be moved and applied to the target branch (different from ‘merge’) A new commit for C4
  • 22. Rebase What we can get from rebase? • Keep linear commit logs • Remove dirty commit logs • Merge commits selectively commit: merge commit commit: C10 commit: merge commit commit: C9 commit: C8 commit: C6 commit: C5 commit: C4 commit: C3 commit: C2 commit: C1 Expected logs after ‘merge’ commit: C10’ commit: C4’ commit: C3’ commit: C9’ commit: C8’ commit: C6 commit: C5 commit: C2 commit: C1 Expected logs after ‘rebase’ rebase client onto master, then rebase server onto client
  • 23. Rebase Never use ‘git rebase’ on public branches • Never use rebase on pushed commits My recommendations • Use rebase on your private branches, to beautify commit logs • If you’ve finished working / reviewing a branch and the only thing for you to do is ‘merging’ the branch with masters, its okay to use rebase • Otherwise, use merge Further Readings • Pro Git • Atlassian tutorias - Merging vs. Rebasing (link) • Check ‘interactive rebase’
  • 24. How to work with branches Creating many branches are recommended! Branch examples • master: stable and released code • ver1.x: publicly released version (can be a tag) • develop: test-passed, but may have some bugs • topic: small branches for issues, feature development, or hotfix, … • …
  • 25. How to work with branches One example of branch workflows Further readings • Atlassian Git Tutorials – Git Workflows (link)
  • 26. Stash Stash • Temporary storage for changes. • Useful when you have some changes to keep (without creating a commit) and want to start working on other items $ git status Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: index.html Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: lib/simplegit.rb $ git stash Saved working directory and index state "WIP on master: 049d078 added the index file" HEAD is now at 049d078 added the index file (To restore them type "git stash apply") $ git status # On branch master nothing to commit, working directory clean Current changes are stored in ‘stash’ You can go on working on other items Context switching! Everything is clean Original Commit Your changes Working directoryStash area Original CommitYour changes Working directoryStash area
  • 27. Stash How to restore stashed changes • Don’t need to be at the same branch or HEAD $ git stash list stash@{0}: WIP on master: 049d078 added the index file stash@{1}: WIP on master: c264051 Revert "added file_size" stash@{2}: WIP on master: 21d80a5 added number to log $ git stash apply # On branch master # Changed but not updated: # (use "git add <file>..." to update what will be committed) # # modified: index.html # modified: lib/simplegit.rb # $ git stash drop stash@{0} Dropped stash@{0} (364e91f3f268f0900bc3ee613f9f733e82aaed43) Saved changes are restored Remove stashed item Important! Stash is stored in a stack with reverse order. (0 is the newest one) So, running ‘git stash drop stash@{0}’ twice will remove two different changes Change C Change B Change A stash@{0} stash@{2} stash@{1} Change B Change A stash@{0} stash@{1} Stash area Stash area
  • 28. Commit Guidelines One issue per one commit • Use ‘git add –p’ to stage only some parts of a modified file Commit messages • See the example Further readings • How to Write a Git Commit Message (link) • 5 Useful Tips For A Better Commit Message (link) Summarize changes in around 50 characters or less More detailed explanatory text, if necessary. Wrap it to about 72 characters or so. In some contexts, the first line is treated as the subject of the commit and the rest of the text as the body. The blank line separating the summary from the body is critical (unless you omit the body entirely); various tools like `log`, `shortlog` and `rebase` can get confused if you run the two together. Explain the problem that this commit is solving. Focus on why you are making this change as opposed to how (the code explains that). Are there side effects or other unintuitive consequenses of this change? Here's the place to explain them. Write your commit message in the imperative: "Fix bug" and not "Fixed bug" or "Fixes bug." This convention matches up with commit messages generated by commands like git merge and git revert. Further paragraphs come after blank lines. - Bullet points are okay, too - Typically a ‘-’ or ‘*’ is used for the bullet, preceded by a single space, with blank lines in between, but conventions vary here If you use an issue tracker, put references to them at the bottom, like this: Resolves: #123 See also: #456, #789 Excerpts from ‘How to Write a Git Commit Message’ and ‘A Note About Git Commit Messages (link)’
  • 29. Git Workflows Centralized workflow • Simple server-client structure (like SVN) Integration-Manager workflow • Suit for bigger projects • Dedicated integration manager to review/filter/merge commits Further readings • Pro Git – Chapter 5
  • 30. Some other comments .gitignore • You can specify files to be excluded in Git • Files you should exclude • Compile results: *.o / *.a / *.pyc / executables • Temporary files: *.swp / *~ • … Don’t commit big / temporary binary files • They will remain in your repository history, and consume large disk storage / slow down your work with Git (cloning, especially) • Small library / image files are usually accepted. However, a script to download those files are much better
  • 31. Git Cheatsheet Two recommended git cheatsheets • Git cheat sheet, extended edition by Jan Krüger (link) • Git cheat sheet by Zack Rusin (link)
  • 32. References  Pro Git (Korean version) http://git-scm.com/book/ko/v2 • Also available in many other languages  “Getting Git Right” slides from Atlassian http://www.slideshare.net/svenpeters/getting-git-right