Git Version Control With Eclipse (EGit)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Tutorials

Contact us

Services

Products

Books

Company

Donate

GitversioncontrolwithEclipse(EGit)Tutorial
Get the book
LarsVogel
Version3.6
Copyright2009,2010,2011,2012,2013,2014vogellaGmbH
GitwithEclipse(EGit)
ThistutorialdescribestheusageofEGitanEclipseplugintousethedistributed
versioncontrolsystemGit.ThistutorialisbasedonEclipse4.3(Kepler).

TableofContents
1.Scopeofthisdescription
2.WhatisEGit
3.CommandlineGit
4.InstallationofGitintoEclipse
5.SettingupGitinEclipse
5.1.GitandEclipseconfiguration
5.2.Defaultclonelocation
5.3.GitandEclipseconfiguration
5.4.Configurefilesanddirectoriestoignore
5.5.ActivatingtheGittoolbar
6.WorkingwithalocalGitrepositoryinEclipse
6.1.Introduction
6.2.CreatinganEclipseproject
6.3.CreatingalocalGitrepository
6.4.Create.gitignorefile
6.5.UsingtheGitStagingview
6.6.UsingtheGitStagingviewforcommittingchanges
6.7.StagingandcommittingfilesintheGitcommitdialog
7.PackageExplorerintegration
8.Historyviewtoviewthecommithistory
8.1.Purposeofthehistoryview
8.2.Importantsettingsinthehistoryview
9.Repositoryview
9.1.WorkingwithyourGitrepositories
9.2.Contentarea
9.3.Openacommit
9.4.Possibleoperationsfromacommit
10.Cloneexistingproject
11.PerformingGitoperationsinEclipse
11.1.Basicoperations
11.2.Commitamend

12.BranchinginEclipse
13.MerginginEclipse
13.1.Merge
13.2.Solvingmergeconflicts
14.UsingrebaseinEclipse
15.Workingwithcommits
15.1.gitreset
15.2.FindinglostcommitwiththeReflogview
15.3.Moveacommitwithgitcherrypick
16.Createpatches
17.Blameannotations
18.StashviatheGitrepositoryview
19.Gitrepositoryformultipleprojects
19.1.Createanewrepository
19.2.AddaprojecttoanexistingGitrepository
20.Tutorial:CreateGitrepositoryformultipleprojects
21.UsingEGitwithGithub
21.1.Github
21.2.CreaterepositoryinGithub
21.3.Cloneproject
21.4.Pushchanges
22.EclipseintegrationwithGithub
22.1.TheEclipseMylynplugin
22.2.Githubissueintegration
22.3.ManagepullrequestsinEclipse
22.4.ImportprojectsdirectlyfromGithub
22.5.MoreinfosabouttheGithubMylynintegration
23.Writinggoodcommitmessages
23.1.ImportanceofGitcommitmessages
23.2.Guidelinesforusefulcommitmessages
23.3.Examplemessage
23.4.Examplehistories
24.ContributingtoEGitGettingthesourcecode
25.Gitseries
26.GettheBook
27.Aboutthiswebsite
27.1.Donatetosupportfreetutorials
27.2.Questionsanddiscussion
27.3.Licenseforthistutorialanditscode
28.LinksandLiterature
28.1.SourceCode
28.2.EGitResources
28.3.vogellaResources

1.Scopeofthisdescription
Note: Thisdescriptioncontainssufficientinformationaboutworking
withGitinEclipse,butitdoesnotcoverallconceptsforGit.Fora
detaileddescriptionoftheGitconceptsanddifferentoptionsplease
seethefollowinglinkorthecorrespondingGitbookfromLarsVogel:
MasteringtheGitcommandlinefromLarsVogel

2.WhatisEGit
EGitisanEclipseplugin(softwarecomponent)whichallowsyoutousethe
distributedversioncontrolsystemGitdirectlywithintheEclipseIDE.
EGitisbasedontheJGitlibrary.JGitisalibrarywhichimplementstheGit
functionalityinJava.

3.CommandlineGit
ThistutorialdescribestheusageofEGit.Ifyouwanttolearnabouttheusageofthe
Gitcommandline,youcanusetheGitTutorialasareference.
ThistutorialalsoexplainsthebasicGitterminology,e.g.,whatisacommit,branch,
etc.

4.InstallationofGitintoEclipse
TheEGitplugincanbeinstalledintoeveryEclipseIDEinstallation.UsuallyEGit
supportsthelasttwoEclipsereleases.
MostEclipse4.2andEclipse4.3downloadsfromEclipse.orgcontainEGitintheir
defaultconfiguration.Inthiscasenoadditionalinstallationisrequired.
IftheEGitpluginismissinginyourEclipseinstallation,youcaninstallitviathe
Eclipseinstallationmanager.StartthismanagerviatheHelpInstallnewSoftware
menuentry.
EGitcanbeinstalledfromthefollowingURL:
http://download.eclipse.org/egit/updates

ThedialogtoinstallEGitisdepictedinthefollowingscreenshot.

5.SettingupGitinEclipse
5.1.GitandEclipseconfiguration
EclipseusesthesameconfigurationfilesastheGitcommandlinetoolshenceifyou
haveconfiguredyourGitsetupviaEclipseorviathecommandline,bothwillbeusing
thesamesetup.
BeforeusingGityoumustconfigureyournameandemailaddresswhichisusedto
filltheauthorandcommitterinformationofcommitsyoucreate.
TheGitconfigurationsettingscanbeadjustedviatheEclipsepreferencesetting.
SelectWindowPreferencesTeamGitConfigurationtoseethecurrent
configurationandtochangeit.
YoucanaddentriestoyourGitconfigurationbypressingtheAddEntriesbuttonon
theGitConfigurationpreferencepage.Toaddyouruser,usetheuser.nameaskey
andyourrealnameasvalue.Repeattheprocedureforyouremailaddress.

Youcanaddmorevaluesinthisdialog.Thesevaluesarestoredinthesamewaythe
Gitcommandlinewouldstorethem,sothatyoucanuseEGitandGitforthesame
Gitrepository.

5.2.Defaultclonelocation
YoucanalsoconfigureinEclipsethedefaultfolderforstoringGitrepositoriesviathe
WindowPreferencesGitTeamDefaultRepositoryFolderentry.

Note: YoucanalsouseEclipseconfigurationvariablestodefinethis
path,e.g.ifyouwanttostorerepositoriesinthefolder"git"underthe
Eclipseworkspaceyoumayuse${workspace_loc}/git.

5.3.GitandEclipseconfiguration
Eclipsealsosupportsthe.gitignorefileforexcludingfilesanddirectoriesfromthe
Gitoperations.

5.4.Configurefilesanddirectoriestoignore
5.4.1.Ignoringfilesanddirectorieswitha.gitignorefile
Gitcanbeconfiguredtoignorecertainfilesanddirectoriesforrepositoryoperations.
Thisisconfiguredviaoneorseveral.gitignorefiles.Typically,thisfileislocatedat
therootofyourGitrepositorybutitcanalsobelocatedinsubdirectories.Inthe
secondcasethedefinedrulesareonlyvalidforthesubdirectoryandbelow.
Youcanusecertainwildcardsinthisfile.*matchesseveralcharacters.More
patternsarepossibleanddescribedunderthefollowingURL:gitignoremanpage
Forexample,thefollowing.gitignorefiletellsGittoignorethebinandtarget
directoriesandallfilesendingwitha~.
#ignoreallbindirectories
#matches"bin"inanysubfolder
bin/
#ignorealltargetdirectories
target/
#ignoreallfilesendingwith~
*~

Youcancreatethe.gitignorefileintherootdirectoryoftheworkingtreetomakeit
specificfortheGitrepository.

Tip: The.gitignorefiletellsGittoignorethespecifiedfilesinGit
commands.Youcanstilladdignoredfilestothestagingareaofthe
Gitrepositorybyusingthe force parameter,i.e.withthe
gitaddforce[paths] command.Thisisusefulifyouwantto
add,forexample,autogeneratedbinaries,butyouneedtohavea
finecontrolabouttheversionwhichisaddedandwanttoexclude
themfromthenormalworkflow.

Itisgoodpracticetocommitthelocal.gitignorefileintotheGitrepositorysothat
everyonewhoclonesthisrepositoryhaveit.

5.4.2.Global(crossrepository).gitignoresettings
Youcanalsosetupaglobal.gitignorefilevalidforallGitrepositoriesviathe
core.excludesfile setting.Thesetupofthissettingisdemonstratedinthe
followingcodesnippet.
#Createa~/.gitignoreinyouruserdirectory
cd~/
touch.gitignore
#Excludebinand.metadatadirectories
echo"bin">>.gitignore
echo".metadata">>.gitignore
echo"*~">>.gitignore
echo"target/">>.gitignore

#forMac
echo".DS_Store">>.gitignore
echo"._*">>.gitignore
#ConfigureGittousethisfile
#asglobal.gitignore
gitconfigglobalcore.excludesfile~/.gitignore

Theglobal.gitignorefileisonlylocallyavailable.

5.4.3.Localperrepositoryignorerules
Youcanalsocreatelocalperrepositoryrulesbyeditingthe.git/info/excludefile
inyourrepository.Theserulesarenotcommittedwiththerepositorysotheyarenot
sharedwithothers.
Thisallowsyoutoexclude,forexample,locallygeneratedfiles.

5.5.ActivatingtheGittoolbar
TosimplifyaccesstothecommonGitoperationsyoucanactivatetheGittoolbar.For
thisselectWindowCustomizeperspective...andcheckthecommandgroupsGit
andGitNavigationActionsintheCommandGroupsAvailabilitytab.

6.WorkingwithalocalGitrepositoryinEclipse
6.1.Introduction
ThefollowingsectionexplainshowtocreatealocalGitrepositoryforoneprojectwith
Eclipse.Thisallowsyoutokeeptrackofyourchangesintheprojectandallowsyou
toreverttoanotherstateatalaterpointintime.

6.2.CreatinganEclipseproject
CreateanewJavaprojectcalledde.vogella.git.firstinEclipse.Createthe
de.vogella.git.first packageandthefollowingclass.
packagede.vogella.git.first;
publicclassGitTest{
publicstaticvoidmain(String[]args){
System.out.println("Gitisfun");
}
}

6.3.CreatingalocalGitrepository
ToputyournewprojectunderversioncontrolwithGit,rightclickonyourproject,
selectTeamShareProjectGit.
DependingonyourinstallationyoumayhavetoselectthatyouwanttouseGitasa
versioncontrolsystem.

OnthenextdialogpresstheCreatebutton.

ItisrecommendedtoseparateyourGitrepositoryfromanyadditionalmetadata
whichEclipsemightcreate,itisrecommendedtoplaceyourGitrepositoriesoutside
theEclipseworkspace.EclipsefollowsthisrecommendationandtheEGitplugin
proposesadirectoryoutsideyourworkspace.PlacingGitrepositoriesdirectlyinthe
workspacemaycauseperformanceissuessincetheGitsupportinEclipsethenmay
needtoscanalargenumberoffilesreachableundertheworkspace.
EnteryourprojectnameasNameforyourlocalGitrepository.SelecttheFinish
button.

AfterpressingtheFinishbutton,thewizarddisplaysthesettingsforyourlocalGit
repository.SelecttheFinishbuttonagaintoputyourrepositoryunderGitversion
control.

YouhavecreatedalocalGitrepository.TheGitrepositoryisinthiscasedirectly
storedinthespecifiedfolderina.gitfolder.Thefollowingscreenshotshowsthe
generateddirectorystructure.

6.4.Create.gitignorefile
Gitcanbeconfiguredtoignorecertainfilesanddirectories.Thisisconfiguredviathe
.gitignorefile.
Createa.gitignorefileinyourGitrepositorywiththefollowingcontent.
bin
.metadata

Allfilesanddirectorieswhichapplytothepatterndescribedinthisfilewillbeignored
byGit.Inthisexampleallfilesinthebinandthe.metadatadirectorywillbeignored.
Youcanalsocreatealocal.gitignorefilebyrightclickingonaresource(fileor
folder)andbyselectingtheTeamIgnorecontextmenuentry.Excludingindividual
filescanbetimeconsuming.Preferrablyyoudefineapatterninyour.gitignorefile
intherootdirectoryoftherepository.

Note: YoucanalsoconfigureEclipsetoautomaticallyignore
derivedresources,e.g.classfilesviatheWindowPreferences
TeamGitProjectsAutomaticallyignorederivedresources..
setting.

6.5.UsingtheGitStagingview
Eclipsegivesyouseveraloptionstostageandcommityourchanges.TheGitStaging
viewprovidesaconvenientcompactoverviewonallchangesyouhavedonesince

checkingoutabranch.
TheGitStagingviewisnonmodal,youcanswitchbetweendifferentrepositories
withoutloosingacommitmessageanditallowsincrementalstagingforchanges.
OpentheGitStagingviewviatheWindowShowViewOther...GitGit
Stagingmenu.
InthisviewyouselectallfileswhichhavechangedanddragthemintotheStaged
Changesarea.Tocommitthestagedchangesyouwriteadescriptivecommit
messageandpresstheCommitbuttonwhichishighlightedinthefollowing
screenshot.

Performtheseactionsforyourinitialchanges.Afterwardsthefirstversionofyour
Javaprojectisunderversioncontrol.Ifyoudon'texperienceanyhardwareerroryour
dataisnowsavelystoredinyourlocalGitrepositoryandyoucanalwaysrestoreyour
Eclipseprojecttothisinitialpoint.

6.6.UsingtheGitStagingviewforcommittingchanges
Changethe System.out.println messageinyour GitTest class.
packagede.vogella.git.first;
publicclassGitTest{
publicstaticvoidmain(String[]args){
System.out.println("Gitiscool");
}
}

Alsocreateanewfilecalledreadme.txt
Wewanttocommitthechangesof GitTest classbutnotaddandcommitthe
readme.txtfiletotheGitrepository.
UsingtheGitStagingviewdragonlythe GitTest classintotheStagedChanges
area,writeameaningfulcommitmessageandpressthecommitbutton.

ThischangeisnowalsostoredinyourlocalGitrepository.Thereadme.txtis
neitherstagednorcommittedtotheGitrepository.

6.7.StagingandcommittingfilesintheGitcommitdialog
TheGitStagingviewisaveryconvenientwayofworkingwithGitasitgivesyoua
groupedviewofallthependingchangeswithoutanadditionaldialog.
IfyouprefertoinvoketheGitcommitdialogdirectlyyoucandothisviaselectingthe
TeamCommitdialog.
Thedialogallowsyoutoaddchangedandnewfilestothestagingareaandcommit
thechanges.

7.PackageExplorerintegration
ThePackageExplorerviewshowsindicatorsonthefilestoshowtheirstatus.The
mostimportanticondecoratorsaredepictedinthefollowingscreenshot.

Thefilenamedescribesthestateofthefilefromthefollowingtable:
Table1.SampleTable
State

Description

staged

Changes in the file will be include be included in the next commit.

added to
index

Staged but not yet committed, i.e. snapshot of this file has been stored
in the git database. This status is the same as the staged status, but the
file wasn't under Git version control before.

dirty

File has changed since the last commit.

Ignored

File is flagged to be ignored by Git operations.

tracked

File is committed to the Git repository and has not changed.

untracked

File is neither staged nor committed.

Note: Combinationofthestagedanddirtystatusmeans:some
partsofthechangedfilehavebeenstagedwhilesomearestill
unstaged.Thiscanhappenifyoustageafileandthenagainmodify
thefilebeforecreatingthenextcommit.Youcanalsochangethe
stagedpartsusingthecompareeditoropenedbydoubleclicking
filesinthestagingview.
OnaprojectlevelthePackageExplorerviewaddstothelabeloftheprojectname
theinformationwhichGitrepositoryisused.Italsoaddsthenumberofcommitsthat
aredifferentbetweenlocalandremotetrackingbranch.Thiswayyoucanquicklysee
ifyourlocalbranchisaheadorbehindtheremotebranchitistracking.

8.Historyviewtoviewthecommithistory
8.1.Purposeofthehistoryview
TheHistoryviewallowsyoutoanalyzethecommittimeline,seethebranches,andto
whichcommitstheypoint,etc.Thisviewisdepictedinthefollowingscreenshot.

Toseethehistoryofaresource,selectyourproject,afileorafolder,rightclickonit
andselecttheShowinHistorycontextmenuentry.Alternativeyoucanusethe
Alt+Shift+WshortcutandselecttheHistoryentry.
Ifyouselectacommityouseethecommitmessageandtheinvolvedfiles.

Note: Ifyouwanttoseemoredetailsaboutacommit,rightclickit
andselecttheOpeninCommitViewerentry.

Viarightclickonanindividualfileyoucancomparethisfilewithitsancestor(the
commitbeforethat)orwiththecurrentversionintheworkspace.
TheHistoryviewallowsyoutofilterbasedonresources.Seethetooltipsofthe
toolbarforthemeaningofthedifferentfilteroptions.Inordertoseeallcommitsclick
theShowallchangesinthisrepositoryandShowallbranchesandtagsbuttons.
Commitswhicharenotreachablefromanybranch,tagorsymboliclink,e.g.HEAD
arenotdisplayedintheHistoryview.

Youcanalsosearchforcommitsbasedoncommitter,author,IDorcomment.The
findfeatureofthehistoryviewismainlyinterestingtoquicklymovetoacommityou
aresearching.

Note: TheGitSearchavailableintheSearchSearchmenuis
muchmorepowerfulandconsumeslessmemorysinceitdoesn't
needtoalsodisplaythehistory.

8.2.Importantsettingsinthehistoryview
ThetoolbaroftheHistoryviewallowsyoutocustomizethedisplayedelements.By
defaulttheHistoryviewfiltersthehistorybasedonthecurrentselectionandshows
onlytheactivatebranch.
Ifyouworkwithseveralbranches,e.g.,becauseyouusingGerritforcodereviews,
youtypicallywanttoseeallbranchinformationandremovethefilterbasedonthe
resource.Thisselectionishighlightedinthefollowingscreenshot.

9.Repositoryview
9.1.WorkingwithyourGitrepositories

EGithasaGitrepositoryviewwhichallowyoutobrowseyourrepositories,cloneGit
repositories,checkoutprojects,manageyourbranchesandmuchmore.
ThetoolbarentriesallowyoutoaddanexistinglocalGitrepositorytotheview,clone
aGitrepositoryandtocreateanewGitrepository.

9.2.Contentarea
ThecontentareashowtheexistingGitrepositoriesandthestructuralelementsof
thisview.Thefollowingscreenshothighlightsthedifferentmainelementsofthisview.

Arightclick(contextmenu)onanelementintheGitrepositoryviewallowsyouto
performrelatedGitoperations.Forexampleifyouclickonabranchyoucan
checkoutthebranchordeleteit.

9.3.Openacommit
IfyouareintheGitrepositoryviewyoucanopenacommitviaNavigateOpenGit
Commitmenuentry.

9.4.Possibleoperationsfromacommit
Ifyouopenacommityoucancreateatagorbranchfromit.Youcanalsorevertit,
cherrypickitorcheckitout.

10.Cloneexistingproject
EclipseallowsyoutocloneanexistingGitrepositoryandtoimportexistingprojects
fromthisrepositoryintoyourEclipseworkspacebyusingawizard.
SelectFileImportGitProjectfromGit.

SelectURIinthenextdialog.

EntertheURLtoyourGitrepository.Gitsupportsseveralprotocols,e.g.git://and
https://.YouonlyhavetopastetheURLtothefirstlineofthedialog,therestwill
befilledoutautomatically.
Pleasenotethatsomeproxyserversblockthegit://protocol.Ifyoufaceissues,
pleasetrytousethehttps://orhttp://protocol.
ForexamplethefollowingURIcanbeusedtoclonetheexampleprojectsofthe
Eclipse4applicationdevelopmentbook:git://github.com/vogella/eclipse4book.git
Theabovelinksusesthegitprotocol,alternativelyyoucanalsousethehttpprotocol:
http://github.com/vogella/eclipse4book.git

AfterpressingtheNextbuttonthesystemwillallowyoutoimporttheexisting
branches.Youshouldselectatleastmasterasthisistypicallythemaindevelopment
branch.

Thenextdialogallowsyoutospecifywheretheprojectshouldbecopiedtoand
whichbranchshouldbeinitiallyselected.

AftertheGitrepositoryiscloned,EGitopensanadditionalimportdialogwhichallows
toimporttheEclipseprojectsfromtheGitrepository.

Oncethisdialogiscompleted,youhavecheckedout(cloned)theprojectsintoalocal
GitrepositoryandyoucanuseGitoperationontheseprojects.

11.PerformingGitoperationsinEclipse
11.1.Basicoperations
Onceyouhaveplacedaprojectunderversioncontrolyoucanstartusingteam
operationsonyourproject.Theteamoperationsareavailableviarightclickonyour
projectorfile.

Themostimportantoperationsaredescribedinthefollowinglist.Select:
TeamAddtoindex,toaddtheselectedresource(s)totheindexofGit
TeamCommit,toopenthecommitdialogforcommittingtoyourGit
repository
TeamCreatePatch...,tocreateapatch
TeamApplyPatch...,toapplyapatchtoyourfilesystem
TeamIgnore,toaddthefiletoa.gitignorefile

TeamShowinHistory,todisplaytheselectedfilesandfoldersintheHistory
view
Ifyouselectaprojectyoucanuseadditionalteamoperationsfromthecontextmenu.

TeamPulltopullinchangesfromyourremoteGitrepository
TeamFetchtofetchthecurrentstatefromtheremoterepository
TeamSwitchTotoswitchorcreatenewbranches
TeamPushtopushchangestoyourremoteGitrepository
TeamTagtocreateandmanagetags.

11.2.Commitamend
Gitamendallowstoadjustthelastcommit.Forexampleyoucanchangethecommit
message.TheGitStagingviewallowsyoutoperformtheGitamendcommandvia
thehighlightedbuttoninthefollowingscreenshot.

12.BranchinginEclipse
RightclickyourprojectandselectTeamBranchtocreatenewbranchesorto
switchbetweenexistingbranches.YoucanalsoswitchbranchesintheHistoryview.

13.MerginginEclipse
13.1.Merge
EGitsupportsmergingofbranchestoaddthechangesofonebranchintoanother.
SelectyourprojectandTeamMergetostartthemergedialog.

13.2.Solvingmergeconflicts
Ifyoupullinchangesormergeabranchandyouhaveconflictingchanges,EGitwill
highlighttheaffectedfiles.EGitalsosupportstheresolutionofthesemergeconflicts.
RightclickonafilewithmergeconflictsandselectTeamMergeTool.

Tip: UsetheGitstagingviewtofindtheconflictingfiles,inlarge
projectsthatisusuallyfasterthannavigatingthePackageExplorer
view.
Thisopensadialog,askingyouwhichmergemodeyouwouldliketouse.The
easiestwaytoseetheconflictingchangesistousetheUseHEAD(thelastlocal
version)ofconflictingfilesasmergemode.Thiswayyouseetheoriginalchangeson
theleftsideandtheconflictingchangesontherightside.

YoucanmanuallyeditthetextontheleftsideorusetheCopycurrentchangefrom
righttoleftbuttontocopytheconflictingchangesfromrighttoleft.

Onceyouhavemanuallymergedthechanges,selectTeamAddfromthecontext
menuoftheresourcetomarktheconflictsasresolvedandcommitthemerge
resolutionviaTeamCommit.

14.UsingrebaseinEclipse
TheGitRepositoriesviewallowsyoutorebaseyourcurrentlycheckoutbranchonto
anotherbranch.RightclickonarepositorynodeandselectRebaseasdepictedin
thefollowingscreenshot.

Inthefollowingdialogyoucanselectthebranchontowhichyouwanttorebase.

Tip: Youcanalsoselectdirectlythebranchtorebaseontofromthe
Branchesnodeofthetree.
Iftherebasewassuccessfuladialogisshown.Youhavetoresolverebaseconflicts
iftheyoccur.Afterresolvingthem,selectRebaseContinueorifyouwanttocancel
therebaseoperationselectRebaseSkipandRebaseAbort.

15.Workingwithcommits
15.1.gitreset
TheHistoryviewallowsyoutoresetyourcurrentbranchtoacommit.Rightclickona
certaincommitandselectResetandtheresetmodeyouwouldliketouse.

15.2.FindinglostcommitwiththeReflogview
TheGitReflogviewkeepstrackofthemovementsoftheHEADpointer.Thisview
allowsyoutofindcommitagain,e.g.ifyouusedthe gitresethard commandto
removecertaincommits.

15.3.Moveacommitwithgitcherrypick
Acombinationofgitresetandgitcherrypickallowsyoutomoveacommit.Assume
youhaveabadcommitwhichyouwouldliketoremovefromthehistoryofbranch
followedbyagoodcommit.Thissituationisdepictedinthefollowingscreenshot.

Forthisyouwouldmakeahardresetonthecommitoforigin/master.

Afterwardsyoucancherrypickthegoodcommit.

Thisresultsinahistorywithoutthebadcommit.

16.Createpatches
Apatchisatextfilewhichcontainsinstructionshowtoupdateasetoffilestoa
differentstate.
IfyouuseGityoucancreateapatchforthechangesyoumade.Thispatchcanbe
appliedtothefilesystem.
TocreateapatchforasetofchangeswithEGit,selecttheresourcesforwhichyou
wanttocreateapatchinthePackageExplorerview,rightclickandselectTeam
CreatePatch.

TheresultingfilecanbeusedtogetappliedtoanotherGitrepository,viaTeam
ApplyPatch.

17.Blameannotations
EGitallowstoaddannotationstoseewhichlinewaslastchangedbywhomand
whichcommit.Toenablethis,rightclickonyourfileandselectTeamShow
Annotations.
Afterwardsyoucanplacethemouseontheleftsideoftheeditorandapopupwill
showthecommitinformation.

18.StashviatheGitrepositoryview
The gitstash commandisavailableintheGitrepositoriesview.Rightclickon
yourGitrepositoryandselectStashChanges.

19.Gitrepositoryformultipleprojects
19.1.Createanewrepository
Eclipseallowstoworkwithprojectsthatarenotincludedintheworkspace.
ToputseveralEclipseprojectsintothesameGitrepositoryyoucancreateafolder
insideoroutsideyourworkspaceandcreatetheprojectsinsidethisfolder.Then
createaGitrepositoryforthisfolderandallprojectsinthisfolderwillbehandledby
thesamerepository.ThebestpracticeistoputtheGitrepositoryoutsideofthe
Eclipseworkspace.
YoucanimporttheseprojectsintoyourworkspaceviaFileImportGit

ProjectsfromGitasexplainedbefore.

19.2.AddaprojecttoanexistingGitrepository
ToaddanewEclipseprojecttoanexistingGitrepository,selecttheproject,right
clickonitandselectTeamShareGitandselecttheexistingGitrepository.

EGitmovestheprojectstotherepositoryandimportstheprojectautomaticallyinto
yourworkspace.

20.Tutorial:CreateGitrepositoryformultipleprojects
CreatetwoJavaprojectscalledcom.vogella.egit.multi.java1and
com.vogella.egit.multi.java2.
CreateatleastoneJavaclassineachproject.

Note: Gitdoesn'ttrackthehistoryofemptyfolders,itistrackingfile
contentandcontentchanges.
Afterwardsselectbothprojects,rightclickonthemandselectTeamShare
Project...Git.Eclipsemayaskyouwhichversioncontrolsystemyouwanttouse,
e.g.CVSorGit.Select,ofcourse,theGitentry.
NowcreateanewGitrepositoryoutsideyourworkspacesimilartotheprocessyou
usedforthecreationofyourfirstGitrepositoryinthebook.

YoucreatedanewGitrepositorywhichcontainsbothprojects.Bothprojectsare
movedtothisnewrepository.
Nowperformyourinitialcommitforallfilesintheprojectstostorethefileinthenew
Gitrepository.

21.UsingEGitwithGithub
21.1.Github
GithubisapopularhostingproviderforGitprojectsandifyourrepositoryisapublic
repositorythehostingatGithubisfree.Apublicrepositoryisvisibletoeveryoneand
canbeclonedbyotherpeopleatanypointintime.
TouseGitHubcreateanaccountontheGithubWebsite.
GithuballowsyoutousetheauthenticationviapasswordorviaSSHkeytoaccess
yourrepositories.

21.2.CreaterepositoryinGithub
CreateanewrepositoryonGithubforexamplede.vogella.git.github.

AftercreationofyournewrepositoryGithubdisplaystheinformationwhatyouhave
todoifyouwanttoconnecttothisrepositoryviathecommandline.Aswearegoing
touseEGityoucanignorethisinformation.

21.3.Cloneproject
CopytheURLfromGithubandselectinEclipsefromthemenutheFileImport
GitProjectsfromGit
EclipsefillsoutmostofthefieldsbasedontheURLintheclipboard.Enteryouruser
andpasswordtobeabletopushtoGithub.AlternativeyoucanalsouseanSSHkey.
YoucanconfigureEclipsetoknowyourSSHviatheWindowPreferences
GeneralNetworkConnectionSSH2preferencesetting.Thissettingisdepicted
inthefollowingscreenshot.

21.4.Pushchanges
Afteryoumadechangesandcommittedthemtoyourlocalrepository,youcanselect
TeamPushtoupstreamontheprojectfolder,topushyourchangestoyour
Github.ThisrequireswriteaccesstotheGithubrepository.

22.EclipseintegrationwithGithub
22.1.TheEclipseMylynplugin
EclipseMylynprovidestaskintegrationforGithubissues,GithubpullandGist(short
textsnippets)intotheEclipseIDE.
ThereisaGitHubconnectorforMylynavailable,pleaseseeGithubMylynUser
Guidefordetails.
YouinstallitviaHelpInstallnewSoftwareandtheupdatesiteofyourrelease.

22.2.Githubissueintegration
YoucanintegrateyourGithubissuesintoEclipseviaFileImport...Task
GitHubTaskRepositoriesandbyfollowingthewizard.

22.3.ManagepullrequestsinEclipse
YoucanintegrateyourpullrequestsatGithubintoEclipsebycreatinganewquery
fromtheTaskListview.Thisisdemonstratedviathefollowingscreenshots.

Note: UnfortunatelytheGithubconnectdoescurrentlynotsupport
thatyoumergethepullrequest.

22.4.ImportprojectsdirectlyfromGithub
YoucanalsoimportnowdirectlyprojectsfromGithubrepositories.

22.5.MoreinfosabouttheGithubMylynintegration
ForadetaileddescriptionoftheMylynandEGitintegrationpleaseseethefollowing
webpage.
http://wiki.eclipse.org/EGit/GitHub/UserGuide

23.Writinggoodcommitmessages
23.1.ImportanceofGitcommitmessages
Acommitaddsanewversiontotherepository.Thisversionisdescribedbyacommit
message.
Thecommitmessagedescribesthechangesrecordedinacommitandhelpsthe
usertounderstandthehistoryofthefilescontainedinaGitrepository.
Acommitmessageshouldthereforebedescriptiveandinformativewithoutrepeating
thecodechanges.

23.2.Guidelinesforusefulcommitmessages
Acommitmessageshouldhaveaheaderandabody.Theheadershouldbeless
than50charactersandthebodyshouldwrapitstextat72sothatthecommit
messageisdisplayedwellonthecommandlineoringraphicaltoolsdisplayingthe
history.Thebodyshouldbeseparatedfromtheheaderbyanemptyline.
Thebodyshouldmainlydescribethereasonwhythechangewasmade.The
changesinthefilecanbereviewedwiththehelpofGit.
Thecommitmessageshouldbeinpresenttense,e.g."Addbettererrorhandling"
insteadof"Addedbettererrorhandling".
Thelastparagraphcanalsocontainmetadataaskeyvaluepairs,alsoreferredtoas
thecommitmessagefooter.Thismetadatacanbeusedtotriggercertainbehavior.

ForexampletheGerritcodereviewsystemusestheChangeIdkeyfollowedbya
changeid,whichdoesnotchangeacrossdifferentversionsofthesamecodereview.
Thischangedidisusedtoidentifytowhichreviewthemessagebelongs.
Thecommitmessagefootercanalsohavee.g.'SignedOffBy'andmaybeusedto
linktoabugtrackingsysteme.g.'Bug:1234'.

23.3.Examplemessage
Thefollowingcanserveasanexampleforacommitmessage.
Shortsummary(lessthan50characters)
Detailedexplanation,ifrequired,linebreakataround72characters
morestufftodescribe...
Fixes:bug#8009
ChangeId:I26b5f96ccb7b2293dc9b7a5cba0760294afba9fd

23.4.Examplehistories
Note: A Git commit object is identified by its SHA-1 which
consists of 40 bytes. In a typical Git repository you need less
characters to uniquely identify a commit object, e.g. you
need only 7 or 8 characters. The

gitlogoneline

command

lists the commit history in one line using the shortened SHA1 of the commit objects.
Thefollowinglistingshowstheoutputofthe gitlogoneline commandofaGit
repositorywithbadcommitmessages.Thefirstvalueineachlineistheshortened
SHA1,thesecondthecommitmessage.Thishistoryisnotuseful.
21a8456update
29f4219update
016c696update
29bc541update
740a130initialcommit

ThenextlistingshowsthehistoryofanotherGitrepositoryinwhichbettercommit
messageshavebeenused.Thishistoryalreadygivesagoodoverviewaboutthe
activities.
7455823bug391086:Searchandfilterthemodeleditortree.
9a84a8a[404207]MissingDynamicMenuContributioninchildselector
952e014[404187]SpellingerrorinToolbar/Addchild
71eeea9bug402875:ImportingmodelelementsfromlegacyRCP
123672cBug403679NewApplicationwizardismissingdependencies
97cdb9aBug388635createsanidforhandlers

24.ContributingtoEGitGettingthesourcecode
EGitisselfhostedongit://git.eclipse.org.SeeEGitcontributorguidefora
descriptionhowtoworkwiththeEGitandJGitsource.

25.Gitseries
ThistutorialispartofaseriesabouttheGitversioncontrolsystem.Seetheother

tutorialsformoreinformation.
IntroductiontoGit
HostingGitrepositoriesatGitHub,Bitbucketoronyourownserver
TypicalworkflowswithGit
EGitTeamproviderforEclipse

26.GettheBook
Thistutorialispartofabookavailableaspaperprintandelectronicformforyour
Kindle.

27.Aboutthiswebsite
27.1.Donatetosupportfreetutorials

Pleaseconsideracontribution
ifthisarticlehelpedyou.Itwillhelptomaintain
ourcontentandourOpenSourceactivities.

27.2.Questionsanddiscussion
Writingandupdatingthesetutorialsisalotofwork.Ifthisfreecommunityservice
washelpful,youcansupportthecausebygivingatipaswellasreportingtyposand
factualerrors.
Ifyoufinderrorsinthistutorial,pleasenotifyme(seethetopofthepage).Please
notethatduetothehighvolumeoffeedbackIreceive,Icannotanswerquestionsto
yourimplementation.EnsureyouhavereadthevogellaFAQasIdon'trespondto
questionsalreadyansweredthere.

27.3.Licenseforthistutorialanditscode
ThistutorialisOpenContentundertheCCBYNCSA3.0DElicense.Sourcecode
inthistutorialisdistributedundertheEclipsePublicLicense.Seethevogella
Licensepagefordetailsonthetermsofreuse.

28.LinksandLiterature
28.1.SourceCode
SourceCodeofExamples

28.2.EGitResources
EGitUserGuide
EGitcontributorguide

28.3.vogellaResources

TRAINING

SERVICE & SUPPORT

The vogella company provides


comprehensive training and
education services from experts in
the areas of Eclipse RCP, Android, Git,
Java, Gradle and Spring. We offer both
public and inhouse training. Whichever
course you decide to take, you are
guaranteed to experience what many
before you refer to as The best IT
class I have ever attended.

The vogella company offers expert


consulting services, development
support and coaching. Our customers
range from Fortune 100 corporations
to individual developers.

You might also like