Git Tutorial
Git Tutorial
JonLoeliger
TM
GitTutorialTourOutline
RepositoryManagement
GitRepositoryConcepts
InterRepositoryDataFlow
Branches
Merges
LocalUseCases
PullUpdates
GeneratingPatches
Examples
SupplementalSlides
Slide2
TM
GitConcepts:Repositories
Gitrepositoryisselfcontained,localandcomplete
Doesn'trequireexternalcontent
Nocentralizedrepository
Includescompletehistoryofeveryfileandchangelog
Gitrepositoryisnotdistributed
No:parthere,partthere,partoverthere...
Nogitrepositoryisinherentlyauthoritative
Onlyauthoritativebyconventionandagreement
Slide3
TM
GitConcepts:DistributedDevelopment
Developmentcanbedistributed
Multiplerepositoriescancreatedifferenthistoriesandchanges
Eveniftheyoriginatedfromacommonancestor
Multiplerepositorieswithdifferentdevelopmentcanbecombined
Developmentcanbeshared
Multipledeveloperscanuseandupdateacommonrepository
Nomatteriftherepositoryislocalorremote
Developmentcanbeprivate
RevisioncontrolyourAddressListathome
Slide4
TM
RepositoryNetwork
torvalds
someos-2.6
jgarzik
netdev
paulus
sometree
perex
alsa
herbert
crypto
Susan
Bob
galak
85xx
Chris
Eric
Kim
Anne
Brandi
Fnord
A
Slide5
TM
B is cloned from A
RepositoryDataFlow
Downstream
Upstream
Colors indicate
action instigator
Linus
someos-2.6
pull
push
pull
pull
patches
push
pull
patches
push
Mackerras
sometree
push
pull
Susan
Slide6
TM
patches
push
GitConcepts:Branchesingit
Cheap,fastandeasy
Topic/DevelopmentBranches
Stable,development,bugfix,testingbranches
Smalldevelopmentlines,perfeature,perdeveloper,etc
Collect,reorderororganizechanges
Cherrypickparticularpatches
TrackingBranches
Followupstreamchangesinlocalrepository
Don'tcommittotrackingbranches
IdentifiedasRHSofPull:refspecs
BranchnamesrefertothecurrentbranchHEADrevision
Branchesdon'thaveabeginningperse
$ git merge-base <original-branch> <branch-name>
Slide7
TM
Branches:Cloning
ClonefromupstreamURL
Original Repository
$ git clone
git://www.jdl.com/software/dtc.git
master
Copiescompleteupstreamrepositoryinto
alocalrepository
git clone
Createsorigintrackingbranch
Tracksupstreammasterbranch
ClonedRepository
Introducesmasterdevelopmentbranch
Initiallythesameplaceasorigin
Foryourdevelopment
Slide8
TM
origin
master
Branches:CommitOntoBranches
Masterbranchinyourrepoisforyourdevelopment!
$ git checkout master
# Edit a file.
$ git commit -a -m "Add copyright.
Introduceyourowntopicdevelopmentbranchestoo
$ git checkout -b jdl
# Edit a file.
$ git commit -a -m "Remove dead code."
Gotcha:Commitsrequireanauthor!
Environmentvariables:GIT_AUTHOR_NAME,GIT_AUTHOR_EMAIL
Configfile:$ git repo-config user.name 'Eric S. Raymond'
Gecosvalue:/etc/passwd
Slide9
TM
Branches:VisualizingBranches
$ git show-branch
! [jdl] Remove dead code.
* [master] Add copyright. Fix 80-column line.
! [origin] dtc: add setting of physical boot cpu
--* [master] Add copyright. Fix 80-column line.
+
[jdl] Remove dead code.
+*+ [origin] dtc: add setting of physical boot cpu
Branch Timeline
1
2
jdl
master
origin
time
Slide10
TM
2
1
GitConcepts:Merges
Merge:Combinedirectoryandfilecontentsfromseparatesourcestoyield
onecombinedresult.
Sourcesformergesarelocalbranches
Mergesalwaysoccurinthecurrent,checkedoutbranch
Acompletemergeendswithanewcommit
Mergeresolutionisinherentlyambiguous
Gitusesseveralmergeheuristics:
Severalmergestrategies:resolve,recursive,octopus,ours
Techniques:fastforward,threeway
Somemergeconflictsmayneedtoberesolvedbythedeveloper
Slide11
TM
MergejdlbranchTomaster
Branch Timeline
Mergejdlbranchintomaster
$ git checkout master
$ git pull . jdl
1
0
ResultingBranchHistory
$ git show-branch
jdl
3
origin
time
master
Outline:UseCases
RepositoryManagement
LocalUseCases
PullingUpdates
MakingPatches
FindingaCommit
CherryPicking
RevertingaCommit
ResolvingMerges
RebasingLocalChanges
SupplementalSlides
Slide13
TM
PullingUpdates
Original Repository
Thedefaultoriginremotesfile
master
$ cat .git/remotes/origin
URL: git://www.jdl.com/software/dtc.git
Pull: refs/heads/master:refs/heads/origin
Getupdatesfromremoterepository
git pull
Cloned Repository
Pullisafetchthenmerge
origin
Placesfetchedupdatesin
ref/heads/origin
Mergesoriginintothecurrent,
checkedoutbranch,master
Slide14
TM
merge
master
Pull:FetchandMergeBranchTimeline
Before
After
Public Repository
Public Repository
master
master
1- fetch
2- fast-forward
origin
master
Your Repository
origin
3 - merge
master
Your Repository
time
time
Slide15
TM
Pull:WhatElse?
Pullisafetchfollowedbyamerge
Mergesshouldstartwithsomecommonbase,though
Canfetch/pullanybranchfromanyrepository
SupplyURLoncommandlinedirectly
MaybeaddnewremotesfilewithURLandPull:line
Eventhisrepository:git pull . <branch>
Couldjustgit
fetchanupstreambranchtoo
Abletothencherry-pickcommitsratherthanfullmerge
Abletousegit diff,git log,etc.
Slide16
TM
Pull:When?
Whenyouwantto!
Whenitisconvenient,stable,Wednesday...
Whentheupstreamtreeisstable
Whenyourworkingdirectoryisstable
...andyouhavetherightbranchcheckedout
Yourworkingdirectoryshouldprobablybeclean
Technicallynotnecessary,but...
Slide17
TM
SendingChangesUpstream
Generateandsendpatchesviaemail
Mostdeveloperssendpatchestoamaintainerorlist
Highlyvisiblepublicreviewofpatchesonmaillist
Maintainerpullsupdatesfromadownstreamdeveloper
Maintainercandirectlypullfromyourpublishedrepository
Initiatedbyupstreammaintainer
Developerpushesupdatestoanupstreammaintainer
Somedevelopershavewritepermissionsonanupstreamrepository
Initiatedbydownstreamdeveloper
Slide18
TM
Patches:GenerateaPatch
Usegit
format-patchcommand
Slide19
TM
Patches:ASideNote
ReadtheREADME
Followthecodingstandards
Compileandtestyourcode
Fixthewhitespaceissues
Knowwhotheupstreammaintaineris
Understandanysignoffpolicy
Slide20
TM
Patches:FormattingandSendingMail
SendplainASCII,notHTML
Sendpatchesinline
Don'tuseattachments
Sendonlyyourchanges
Onelinecommitsummaryfirst
Becarefulofcutnpastesolutions
Usefilebrowseandinsertifpossible
Maybemovepreformattedpatches
toyourMUAdraftfolder
Sendgitformatpatchoutputdirectly
$ git send-email --to
maintainer@example.com my.patch
Slide21
TM
FindingaCommit
SHA1hashnamesareconstant
Symboliccommitnameslikemaster~4changeovertime!
TheyarerelativetothecurrentHEAD
Waystodeterminethenameofacommityouwant
Note:
$ git rev-parse paul~38^2~10^2
9ad494f62444ee37209e85173377c67612e66ef1
Slide22
TM
CherryPickingExample
Youwantoneormoreparticularcommitsfromsomeotherbranch
appliedtoyourcurrentbranch
Bugfixfromsomeotherbranch
Transferpartialfunctionalityfromdevelopmentbranch
Getthatcommitintoyourrepository
Alreadypresentonadifferentbranch
Perhapsusinggit fetchfromanotherrepository
Cherrypickitintoappropriatebranch
$ git checkout master
$ git cherry-pick 9ad494
Slide23
TM
CherryPicking:BeforeandAfter
BranchTimelinePicture
4'isadifferentcommitwiththesamecontentas4
Before
mpc86xx
master
After
mpc86xx
master
time
4'
Slide24
TM
RevertExample
Situation:
Somecommitburiedinthepastneedstobeundone
...andithasalreadybeenmergedtomastertoo!
$ git show-branch --more=10 master mpc86xx
*
!
-*+
*+
*+
*+
*+
*+
*+
Thisisajobforgit
revert
Slide25
TM
Revert:BeforeandAfter
Commit4isreverted,creatingcommit0inyellow
Commit0ismergedtomasterascommit0'
Before
6
mpc86xx
master
After
0
mpc86xx
master
0'
time
Slide26
TM
Revert:Commands
Revertappliesanewinversepatchforagivencommit
Revertworkswithoutrewritingthecommithistory
Canrevertmultiplecommitsatthesametime
Revertcommitonmpc86xxtopicbranch:
$ git checkout mpc86xx
$ git revert mpc86xx~4
Reflectitontomasterbranchaswell:
$ git checkout master
$ git pull . mpc86xx
Slide27
TM
Revert:BranchHistoryAfter
$ git show-branch --more=10 master mpc86xx
*
!
-*+
*+
*+
*+
*+
*+
*+
*+
Slide28
TM
RevertversusResetversusCheckout
ResetversusRevert:Tryingtoundothelastcommit?
Ask:Doessomeoneelsehavethisversionoftherepositoryhistory?
Yes:Usegit revertanddonotchangehistory
No:Couldusegit resetorgit commit --amendperhaps
ResetversusCheckout
Resetdoesn'tchangeyourcurrentbranch
Checkoutestablishesyourcurrentbranch
Thesecanbesimilarunlessnamingadifferentbranch:
git reset --hard topic
git checkout -f topic
Slide29
TM
MergeResolutionHell...er,Examples
Pullingupdatesfromupstreamcangowrongforanumberofreasons!
Conflictingfilecontents
Newormodifiedfilesinyourworkingtree
Differentfilemodes
Possibleforyourupstreamchangestocomebackdifferently
Alteredupstreambymaintainer?
Weretheypulledorpatchedupstream?
Samefilecontent,butdifferentcommits?
Mergeisaheuristic!
Slide30
TM
MergeResolutionStrategies
Beforedoingthepullormerge
Checkoutthecorrectmergeintobranch,likelymaster
Ensureacleanworkingdirectoryfirst
git ls-files --others
git status
Afterfailedpull/mergerequest:
git ls-files -u
git diff
Makeprogressresolvingconflicts:
git update-index
Bedone:
Fullyresolved:git commit
Abandonmerge:git reset --hard
ORIG_HEAD
Slide31
TM
FailedMerge:UntrackedWorkingTreeFile
Gitsays:
git-read-tree: fatal: Untracked working tree file
'Documentation/ABI/README' would be overwritten by merge.
Huh?Idon'thavethatfile...
Maybeyoudohavethatfileandshouldcheck!
Butmaybeitisleftoverfromapreviousmergeeffort?
Areyouontherightbranch?
git branch
git show-branch
Slide32
TM
FailedMerge:UntrackedFileResolution
Yourkey:
git ls-files --others
git status
git clean -d
Resettheworkingdirectory:
Maybeabandonthismerge?
Lookforotherfiles
Cleanouttheoldfiles
Dothemergeagain!
$
$
$
$
git
git
git
git
Slide33
TM
FailedMerge:CONFLICTContent
Gitmessage:
CONFLICT (content): Merge conflict in drivers/net/phy/Makefile
Semitraditional"<<<<====>>>>"stylefilecontentdifferences.
$ git diff drivers/net/phy/Makefile
@@@ -8,4 -8,5 +8,9 @@@
obj-$(CONFIG_CICADA_PHY)
+= cicada.o
obj-$(CONFIG_LXT_PHY)
+= lxt.o
obj-$(CONFIG_QSEMI_PHY)
+= qsemi.o
++<<<<<<< HEAD/drivers/net/phy/Makefile
+obj-$(CONFIG_VITESSE_PHY)
+= vitesse.o
++=======
+ obj-$(CONFIG_SMSC_PHY)
+= smsc.o
+ obj-$(CONFIG_VITESSE_PHY)
+= vitesse.o
++>>>>>>>
501b7c77de3e90519e95fd99e923bf9a29cd120d/drivers/net/phy/Makefile
Slide34
TM
FailedMerge:ResolveContentConflict
Yourkey:
git diff
git ls-files -s arch/somearch/Kconfig
Editandfix
Useyourfavoriteeditor,emacs
Makeprogress
git update-index arch/somearch/Kconfig
Slide35
TM
FailedMerge:CONFLICTadd/add
Gitsayseither:
Twobranchesaddedthesamefile,butdifferently.
TheversionfrommymasterHEADisleftwith~HEADsuffix.
Theversionfromincomingoriginisleftwith~501b7csuffix.
Resolution:
Picktherightoneormergethem
Usegit addtoadditbackwiththerightname(drop~suffix)
Removetheother
Slide36
TM
FailedMerge:CONFLICTrename/add
Gitsays:
CONFLICT (rename/add): Rename
arch/{mips/configs/ddb5476_defconfig =>
somearch/configs/mpc8641_hpcn_defconfig} in 501b7c...
arch/somearch/configs/mpc8641_hpcn_defconfig added in HEAD
Maybeitlies!
Renamedetectionisn't100%precise.Itisaheuristic!
ddb5476_defconfigjusthappenstoberemoved
mpc8641_hpcn_defconfigreallyadded!
Resolution:
Additback!Holycow!
Makesureindexhascorrect,addedfileandeither:
git update-index arch/somearch/configs/mpc8641_hpcn_defconfig
git add arch/somearch/configs/mpc8641_hpcn_defconfig
Slide37
TM
RebaseLocalChangesExample
Situation:
Youhavedonedevelopmentworkonyourtopicbranch
Youpullinupstreamoriginandmergeittomaster
Youdon'twanttomergemasterintoyourtopicbranch
Youdon'twanttomergeyourtopicintothemasterbranch
Nooneelsehasclonedyourtopicbranch!
Why?Don'trewritehistory
Butyouwanttosendyourtopicbranchpatchesupstream!
Thisisajobforgit
rebase
Slide38
TM
Rebase:BeforeandAfter
Rebasecommits04oftopicontomasterbranchatAas0'4'
Before
2
C
1
B
topic
After
master
origin
4'
C
3' 2'
time
Slide39
TM
1'
0'
topic
master
origin
Rebase:Commands
RebaseCommands
$ git checkout topic
$ git rebase master
Createsaseriesofpatchesfromtopictobeappliedtomaster
Mayhavetoresolveconflictsateachstepduetomergeoperation
git rebase --continue
git rebase --skip
git rebase --abort
Slide40
TM
GitResources
SourcesandDocumentation:
Gitsources,documentationandmanyrepositories:kernel.org/git
TheGitWiki:git.or.cz/gitwiki
FrontendsandViewers:
Cogito:kernel.org/pub/software/scm/cogito
StackedGit:www.procode.org/stgit
PatchyGit:www.spearce.org/category/projects/scm/pg
QTGuiviewer:sourceforge.net/project/qgit
MailList:git@vger.kernel.org
IRC:freenode.net#git
Slide41
TM
Outline:Supplemental
RepositoryManagement
LocalUseCases
SupplementalSlides
SendingChangesUpstreamUsingPullandPush
ScreenCaptureofgitk
Slide42
TM
SendChangesUpstreamUsinggitpull
Upstreammaintainertrustsyouandyourwork
Youhavetheabilitytopublishapublicrepository
Youhavealotofchanges,morethanafewpatches
Advertiseyourrepositoryandbranch
Waitforupstreammaintainertopullit
Profit.
Slide43
TM
UsingPull:DataFlowPicture
Public Repository
Maintainer's Repository
Instigator
from_jdl
master
git push
merge
Your Development
Repository
git pull
master
Slide44
TM
master
SendingChangesUpstreamUsinggitpush
Directpushintoremoterepository
Sendsobjects,packs,branchestoremoterepository
Pushtoarepositoryfromwhichyouhavefetched
Canonlypushtoabranchthatisapropersubset
Shouldresultina"fastforward"ontheremoteend
Technicallyyoucanpushelsewhere,but...
Requireswriteaccessontheremoteend
Likelyviassh
Slide45
TM
UsingPush:SetupRemotesFile
Createaremotesfile
StateupstreamrepositoryURL
Statebranchestobepushedupstream
Canpushmultiplebranches,asneeded
JustaddaPush:refspeclineforeachbranch
Canpushtodifferentremotebranchnames
Push: master:incoming
$ cat .git/remotes/publish
URL: ssh://www.jdl.com/software/dtc.git
Push: master:master
Push: jdl:jdl
Slide46
TM
UsingPush:gitpush
$ git push publish
Password:
updating 'refs/heads/master'
from 38e8f8fd88dae07ef8ada9d6baa41b06a4d9ac9f
to
a73b7d43d4f60e76d82018fb9a4d137b089a1325
Generating pack...
Done counting 11 objects.
Result has 8 objects.
Deltifying 8 objects.
100% (8/8) done
Total 8, written 8 (delta 5), reused 0 (delta 0)
Unpacking 8 objects
refs/heads/master: 38e8f8 -> a73b7d
Slide47
TM
UsingPush:DataFlowPicture
Public
Repository
master
jdl
git push
Your Development
Repository
push
instigator
jdl
master
Slide48
TM
gitkExample
Slide49
TM