Git Version Control With Eclipse (EGit)

43
Git version control with Eclipse (EGit) Tutorial Lars Vogel Version 3.6 Copyright © 2009, 2010, 2011, 2012, 2013, 2014 vogella GmbH Git with Eclipse (EGit) This tutorial describes the usage of EGit; an Eclipse plugin to use the distributed version control system Git. This tutorial is based on Eclipse 4.3 (Kepler). Table of Contents 1. Scope of this description 2. What is EGit 3. Command line Git 4. Installation of Git into Eclipse 5. Setting up Git in Eclipse 5.1. Git and Eclipse configuration 5.2. Default clone location 5.3. Git and Eclipse configuration 5.4. Configure files and directories to ignore 5.5. Activating the Git toolbar 6. Working with a local Git repository in Eclipse 6.1. Introduction 6.2. Creating an Eclipse project 6.3. Creating a local Git repository 6.4. Create .gitignore file 6.5. Using the Git Staging view 6.6. Using the Git Staging view for committing changes 6.7. Staging and committing files in the Git commit dialog 7. Package Explorer integration 8. History view to view the commit history 8.1. Purpose of the history view 8.2. Important settings in the history view 9. Repository view 9.1. Working with your Git repositories 9.2. Content area 9.3. Open a commit 9.4. Possible operations from a commit 10. Clone existing project 11. Performing Git operations in Eclipse 11.1. Basic operations 11.2. Commit amend Get the book Tutorials Services Products Books Company Donate Contact us

description

Step by Step tutorial on how to setup git with Eclipse.This includes setting up, pull request, merge etc all from within eclipse.Screenshots are included with step by step instructions.

Transcript of Git Version Control With Eclipse (EGit)

GitversioncontrolwithEclipse(EGit)TutorialLarsVogelVersion3.6Copyright2009,2010,2011,2012,2013,2014vogellaGmbHGitwithEclipse(EGit)ThistutorialdescribestheusageofEGitanEclipseplugintousethedistributedversioncontrolsystemGit.ThistutorialisbasedonEclipse4.3(Kepler).TableofContents1.Scopeofthisdescription2.WhatisEGit3.CommandlineGit4.InstallationofGitintoEclipse5.SettingupGitinEclipse5.1.GitandEclipseconfiguration5.2.Defaultclonelocation5.3.GitandEclipseconfiguration5.4.Configurefilesanddirectoriestoignore5.5.ActivatingtheGittoolbar6.WorkingwithalocalGitrepositoryinEclipse6.1.Introduction6.2.CreatinganEclipseproject6.3.CreatingalocalGitrepository6.4.Create.gitignorefile6.5.UsingtheGitStagingview6.6.UsingtheGitStagingviewforcommittingchanges6.7.StagingandcommittingfilesintheGitcommitdialog7.PackageExplorerintegration8.Historyviewtoviewthecommithistory8.1.Purposeofthehistoryview8.2.Importantsettingsinthehistoryview9.Repositoryview9.1.WorkingwithyourGitrepositories9.2.Contentarea9.3.Openacommit9.4.Possibleoperationsfromacommit10.Cloneexistingproject11.PerformingGitoperationsinEclipse11.1.Basicoperations11.2.CommitamendGet the bookTutorials Services Products Books Company DonateContact us12.BranchinginEclipse13.MerginginEclipse13.1.Merge13.2.Solvingmergeconflicts14.UsingrebaseinEclipse15.Workingwithcommits15.1.gitreset15.2.FindinglostcommitwiththeReflogview15.3.Moveacommitwithgitcherrypick16.Createpatches17.Blameannotations18.StashviatheGitrepositoryview19.Gitrepositoryformultipleprojects19.1.Createanewrepository19.2.AddaprojecttoanexistingGitrepository20.Tutorial:CreateGitrepositoryformultipleprojects21.UsingEGitwithGithub21.1.Github21.2.CreaterepositoryinGithub21.3.Cloneproject21.4.Pushchanges22.EclipseintegrationwithGithub22.1.TheEclipseMylynplugin22.2.Githubissueintegration22.3.ManagepullrequestsinEclipse22.4.ImportprojectsdirectlyfromGithub22.5.MoreinfosabouttheGithubMylynintegration23.Writinggoodcommitmessages23.1.ImportanceofGitcommitmessages23.2.Guidelinesforusefulcommitmessages23.3.Examplemessage23.4.Examplehistories24.ContributingtoEGitGettingthesourcecode25.Gitseries26.GettheBook27.Aboutthiswebsite27.1.Donatetosupportfreetutorials27.2.Questionsanddiscussion27.3.Licenseforthistutorialanditscode28.LinksandLiterature28.1.SourceCode28.2.EGitResources28.3.vogellaResources1.ScopeofthisdescriptionNote: ThisdescriptioncontainssufficientinformationaboutworkingwithGitinEclipse,butitdoesnotcoverallconceptsforGit.ForadetaileddescriptionoftheGitconceptsanddifferentoptionspleaseseethefollowinglinkorthecorrespondingGitbookfromLarsVogel:MasteringtheGitcommandlinefromLarsVogel2.WhatisEGitEGitisanEclipseplugin(softwarecomponent)whichallowsyoutousethedistributedversioncontrolsystemGitdirectlywithintheEclipseIDE.EGitisbasedontheJGitlibrary.JGitisalibrarywhichimplementstheGitfunctionalityinJava.3.CommandlineGitThistutorialdescribestheusageofEGit.IfyouwanttolearnabouttheusageoftheGitcommandline,youcanusetheGitTutorialasareference.ThistutorialalsoexplainsthebasicGitterminology,e.g.,whatisacommit,branch,etc.4.InstallationofGitintoEclipseTheEGitplugincanbeinstalledintoeveryEclipseIDEinstallation.UsuallyEGitsupportsthelasttwoEclipsereleases.MostEclipse4.2andEclipse4.3downloadsfromEclipse.orgcontainEGitintheirdefaultconfiguration.Inthiscasenoadditionalinstallationisrequired.IftheEGitpluginismissinginyourEclipseinstallation,youcaninstallitviatheEclipseinstallationmanager.StartthismanagerviatheHelpInstallnewSoftwaremenuentry.EGitcanbeinstalledfromthefollowingURL:http://download.eclipse.org/egit/updatesThedialogtoinstallEGitisdepictedinthefollowingscreenshot.5.SettingupGitinEclipse5.1.GitandEclipseconfigurationEclipseusesthesameconfigurationfilesastheGitcommandlinetoolshenceifyouhaveconfiguredyourGitsetupviaEclipseorviathecommandline,bothwillbeusingthesamesetup.BeforeusingGityoumustconfigureyournameandemailaddresswhichisusedtofilltheauthorandcommitterinformationofcommitsyoucreate.TheGitconfigurationsettingscanbeadjustedviatheEclipsepreferencesetting.SelectWindowPreferencesTeamGitConfigurationtoseethecurrentconfigurationandtochangeit.YoucanaddentriestoyourGitconfigurationbypressingtheAddEntriesbuttonontheGitConfigurationpreferencepage.Toaddyouruser,usetheuser.nameaskeyandyourrealnameasvalue.Repeattheprocedureforyouremailaddress.Youcanaddmorevaluesinthisdialog.ThesevaluesarestoredinthesamewaytheGitcommandlinewouldstorethem,sothatyoucanuseEGitandGitforthesameGitrepository.5.2.DefaultclonelocationYoucanalsoconfigureinEclipsethedefaultfolderforstoringGitrepositoriesviatheWindowPreferencesGitTeamDefaultRepositoryFolderentry.Note: YoucanalsouseEclipseconfigurationvariablestodefinethispath,e.g.ifyouwanttostorerepositoriesinthefolder"git"undertheEclipseworkspaceyoumayuse${workspace_loc}/git.5.3.GitandEclipseconfigurationEclipsealsosupportsthe.gitignorefileforexcludingfilesanddirectoriesfromtheGitoperations.5.4.Configurefilesanddirectoriestoignore5.4.1.Ignoringfilesanddirectorieswitha.gitignorefileGitcanbeconfiguredtoignorecertainfilesanddirectoriesforrepositoryoperations.Thisisconfiguredviaoneorseveral.gitignorefiles.Typically,thisfileislocatedattherootofyourGitrepositorybutitcanalsobelocatedinsubdirectories.Inthesecondcasethedefinedrulesareonlyvalidforthesubdirectoryandbelow.Youcanusecertainwildcardsinthisfile.*matchesseveralcharacters.MorepatternsarepossibleanddescribedunderthefollowingURL:gitignoremanpageForexample,thefollowing.gitignorefiletellsGittoignorethebinandtargetdirectoriesandallfilesendingwitha~.#ignoreallbindirectories#matches"bin"inanysubfolderbin/#ignorealltargetdirectoriestarget/#ignoreallfilesendingwith~*~Youcancreatethe.gitignorefileintherootdirectoryoftheworkingtreetomakeitspecificfortheGitrepository.Tip: The.gitignorefiletellsGittoignorethespecifiedfilesinGitcommands.YoucanstilladdignoredfilestothestagingareaoftheGitrepositorybyusingthe force parameter,i.e.withthegitaddforce[paths] command.Thisisusefulifyouwanttoadd,forexample,autogeneratedbinaries,butyouneedtohaveafinecontrolabouttheversionwhichisaddedandwanttoexcludethemfromthenormalworkflow.Itisgoodpracticetocommitthelocal.gitignorefileintotheGitrepositorysothateveryonewhoclonesthisrepositoryhaveit.5.4.2.Global(crossrepository).gitignoresettingsYoucanalsosetupaglobal.gitignorefilevalidforallGitrepositoriesviathecore.excludesfile setting.Thesetupofthissettingisdemonstratedinthefollowingcodesnippet.#Createa~/.gitignoreinyouruserdirectorycd~/touch.gitignore#Excludebinand.metadatadirectoriesecho"bin">>.gitignoreecho".metadata">>.gitignoreecho"*~">>.gitignoreecho"target/">>.gitignore#forMacecho".DS_Store">>.gitignoreecho"._*">>.gitignore#ConfigureGittousethisfile#asglobal.gitignoregitconfigglobalcore.excludesfile~/.gitignoreTheglobal.gitignorefileisonlylocallyavailable.5.4.3.LocalperrepositoryignorerulesYoucanalsocreatelocalperrepositoryrulesbyeditingthe.git/info/excludefileinyourrepository.Theserulesarenotcommittedwiththerepositorysotheyarenotsharedwithothers.Thisallowsyoutoexclude,forexample,locallygeneratedfiles.5.5.ActivatingtheGittoolbarTosimplifyaccesstothecommonGitoperationsyoucanactivatetheGittoolbar.ForthisselectWindowCustomizeperspective...andcheckthecommandgroupsGitandGitNavigationActionsintheCommandGroupsAvailabilitytab.6.WorkingwithalocalGitrepositoryinEclipse6.1.IntroductionThefollowingsectionexplainshowtocreatealocalGitrepositoryforoneprojectwithEclipse.Thisallowsyoutokeeptrackofyourchangesintheprojectandallowsyoutoreverttoanotherstateatalaterpointintime.6.2.CreatinganEclipseprojectCreateanewJavaprojectcalledde.vogella.git.firstinEclipse.Createthede.vogella.git.first packageandthefollowingclass.packagede.vogella.git.first;publicclassGitTest{publicstaticvoidmain(String[]args){System.out.println("Gitisfun");}}6.3.CreatingalocalGitrepositoryToputyournewprojectunderversioncontrolwithGit,rightclickonyourproject,selectTeamShareProjectGit.DependingonyourinstallationyoumayhavetoselectthatyouwanttouseGitasaversioncontrolsystem.OnthenextdialogpresstheCreatebutton.ItisrecommendedtoseparateyourGitrepositoryfromanyadditionalmetadatawhichEclipsemightcreate,itisrecommendedtoplaceyourGitrepositoriesoutsidetheEclipseworkspace.EclipsefollowsthisrecommendationandtheEGitpluginproposesadirectoryoutsideyourworkspace.PlacingGitrepositoriesdirectlyintheworkspacemaycauseperformanceissuessincetheGitsupportinEclipsethenmayneedtoscanalargenumberoffilesreachableundertheworkspace.EnteryourprojectnameasNameforyourlocalGitrepository.SelecttheFinishbutton.AfterpressingtheFinishbutton,thewizarddisplaysthesettingsforyourlocalGitrepository.SelecttheFinishbuttonagaintoputyourrepositoryunderGitversioncontrol.YouhavecreatedalocalGitrepository.TheGitrepositoryisinthiscasedirectlystoredinthespecifiedfolderina.gitfolder.Thefollowingscreenshotshowsthegenerateddirectorystructure.6.4.Create.gitignorefileGitcanbeconfiguredtoignorecertainfilesanddirectories.Thisisconfiguredviathe.gitignorefile.Createa.gitignorefileinyourGitrepositorywiththefollowingcontent.bin.metadataAllfilesanddirectorieswhichapplytothepatterndescribedinthisfilewillbeignoredbyGit.Inthisexampleallfilesinthebinandthe.metadatadirectorywillbeignored.Youcanalsocreatealocal.gitignorefilebyrightclickingonaresource(fileorfolder)andbyselectingtheTeamIgnorecontextmenuentry.Excludingindividualfilescanbetimeconsuming.Preferrablyyoudefineapatterninyour.gitignorefileintherootdirectoryoftherepository.Note: YoucanalsoconfigureEclipsetoautomaticallyignorederivedresources,e.g.classfilesviatheWindowPreferencesTeamGitProjectsAutomaticallyignorederivedresources..setting.6.5.UsingtheGitStagingviewEclipsegivesyouseveraloptionstostageandcommityourchanges.TheGitStagingviewprovidesaconvenientcompactoverviewonallchangesyouhavedonesincecheckingoutabranch.TheGitStagingviewisnonmodal,youcanswitchbetweendifferentrepositorieswithoutloosingacommitmessageanditallowsincrementalstagingforchanges.OpentheGitStagingviewviatheWindowShowViewOther...GitGitStagingmenu.InthisviewyouselectallfileswhichhavechangedanddragthemintotheStagedChangesarea.TocommitthestagedchangesyouwriteadescriptivecommitmessageandpresstheCommitbuttonwhichishighlightedinthefollowingscreenshot.Performtheseactionsforyourinitialchanges.AfterwardsthefirstversionofyourJavaprojectisunderversioncontrol.Ifyoudon'texperienceanyhardwareerroryourdataisnowsavelystoredinyourlocalGitrepositoryandyoucanalwaysrestoreyourEclipseprojecttothisinitialpoint.6.6.UsingtheGitStagingviewforcommittingchangesChangethe System.out.println messageinyour GitTest class.packagede.vogella.git.first;publicclassGitTest{publicstaticvoidmain(String[]args){System.out.println("Gitiscool");}}Alsocreateanewfilecalledreadme.txtWewanttocommitthechangesof GitTest classbutnotaddandcommitthereadme.txtfiletotheGitrepository.UsingtheGitStagingviewdragonlythe GitTest classintotheStagedChangesarea,writeameaningfulcommitmessageandpressthecommitbutton.ThischangeisnowalsostoredinyourlocalGitrepository.Thereadme.txtisneitherstagednorcommittedtotheGitrepository.6.7.StagingandcommittingfilesintheGitcommitdialogTheGitStagingviewisaveryconvenientwayofworkingwithGitasitgivesyouagroupedviewofallthependingchangeswithoutanadditionaldialog.IfyouprefertoinvoketheGitcommitdialogdirectlyyoucandothisviaselectingtheTeamCommitdialog.Thedialogallowsyoutoaddchangedandnewfilestothestagingareaandcommitthechanges.7.PackageExplorerintegrationThePackageExplorerviewshowsindicatorsonthefilestoshowtheirstatus.Themostimportanticondecoratorsaredepictedinthefollowingscreenshot.Thefilenamedescribesthestateofthefilefromthefollowingtable:Table1.SampleTableState Descriptionstaged Changes in the file will be include be included in the next commit.added toindexStaged but not yet committed, i.e. snapshot of this file has been storedin the git database. This status is the same as the staged status, but thefile 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:somepartsofthechangedfilehavebeenstagedwhilesomearestillunstaged.Thiscanhappenifyoustageafileandthenagainmodifythefilebeforecreatingthenextcommit.Youcanalsochangethestagedpartsusingthecompareeditoropenedbydoubleclickingfilesinthestagingview.OnaprojectlevelthePackageExplorerviewaddstothelabeloftheprojectnametheinformationwhichGitrepositoryisused.Italsoaddsthenumberofcommitsthataredifferentbetweenlocalandremotetrackingbranch.Thiswayyoucanquicklyseeifyourlocalbranchisaheadorbehindtheremotebranchitistracking.8.Historyviewtoviewthecommithistory8.1.PurposeofthehistoryviewTheHistoryviewallowsyoutoanalyzethecommittimeline,seethebranches,andtowhichcommitstheypoint,etc.Thisviewisdepictedinthefollowingscreenshot.Toseethehistoryofaresource,selectyourproject,afileorafolder,rightclickonitandselecttheShowinHistorycontextmenuentry.AlternativeyoucanusetheAlt+Shift+WshortcutandselecttheHistoryentry.Ifyouselectacommityouseethecommitmessageandtheinvolvedfiles.Note: Ifyouwanttoseemoredetailsaboutacommit,rightclickitandselecttheOpeninCommitViewerentry.Viarightclickonanindividualfileyoucancomparethisfilewithitsancestor(thecommitbeforethat)orwiththecurrentversionintheworkspace.TheHistoryviewallowsyoutofilterbasedonresources.Seethetooltipsofthetoolbarforthemeaningofthedifferentfilteroptions.InordertoseeallcommitsclicktheShowallchangesinthisrepositoryandShowallbranchesandtagsbuttons.Commitswhicharenotreachablefromanybranch,tagorsymboliclink,e.g.HEADarenotdisplayedintheHistoryview.Youcanalsosearchforcommitsbasedoncommitter,author,IDorcomment.Thefindfeatureofthehistoryviewismainlyinterestingtoquicklymovetoacommityouaresearching.Note: TheGitSearchavailableintheSearchSearchmenuismuchmorepowerfulandconsumeslessmemorysinceitdoesn'tneedtoalsodisplaythehistory.8.2.ImportantsettingsinthehistoryviewThetoolbaroftheHistoryviewallowsyoutocustomizethedisplayedelements.BydefaulttheHistoryviewfiltersthehistorybasedonthecurrentselectionandshowsonlytheactivatebranch.Ifyouworkwithseveralbranches,e.g.,becauseyouusingGerritforcodereviews,youtypicallywanttoseeallbranchinformationandremovethefilterbasedontheresource.Thisselectionishighlightedinthefollowingscreenshot.9.Repositoryview9.1.WorkingwithyourGitrepositoriesEGithasaGitrepositoryviewwhichallowyoutobrowseyourrepositories,cloneGitrepositories,checkoutprojects,manageyourbranchesandmuchmore.ThetoolbarentriesallowyoutoaddanexistinglocalGitrepositorytotheview,cloneaGitrepositoryandtocreateanewGitrepository.9.2.ContentareaThecontentareashowtheexistingGitrepositoriesandthestructuralelementsofthisview.Thefollowingscreenshothighlightsthedifferentmainelementsofthisview.Arightclick(contextmenu)onanelementintheGitrepositoryviewallowsyoutoperformrelatedGitoperations.Forexampleifyouclickonabranchyoucancheckoutthebranchordeleteit.9.3.OpenacommitIfyouareintheGitrepositoryviewyoucanopenacommitviaNavigateOpenGitCommitmenuentry.9.4.PossibleoperationsfromacommitIfyouopenacommityoucancreateatagorbranchfromit.Youcanalsorevertit,cherrypickitorcheckitout.10.CloneexistingprojectEclipseallowsyoutocloneanexistingGitrepositoryandtoimportexistingprojectsfromthisrepositoryintoyourEclipseworkspacebyusingawizard.SelectFileImportGitProjectfromGit.SelectURIinthenextdialog.EntertheURLtoyourGitrepository.Gitsupportsseveralprotocols,e.g.git://andhttps://.YouonlyhavetopastetheURLtothefirstlineofthedialog,therestwillbefilledoutautomatically.Pleasenotethatsomeproxyserversblockthegit://protocol.Ifyoufaceissues,pleasetrytousethehttps://orhttp://protocol.ForexamplethefollowingURIcanbeusedtoclonetheexampleprojectsoftheEclipse4applicationdevelopmentbook:git://github.com/vogella/eclipse4book.gitTheabovelinksusesthegitprotocol,alternativelyyoucanalsousethehttpprotocol:http://github.com/vogella/eclipse4book.gitAfterpressingtheNextbuttonthesystemwillallowyoutoimporttheexistingbranches.Youshouldselectatleastmasterasthisistypicallythemaindevelopmentbranch.Thenextdialogallowsyoutospecifywheretheprojectshouldbecopiedtoandwhichbranchshouldbeinitiallyselected.AftertheGitrepositoryiscloned,EGitopensanadditionalimportdialogwhichallowstoimporttheEclipseprojectsfromtheGitrepository.Oncethisdialogiscompleted,youhavecheckedout(cloned)theprojectsintoalocalGitrepositoryandyoucanuseGitoperationontheseprojects.11.PerformingGitoperationsinEclipse11.1.BasicoperationsOnceyouhaveplacedaprojectunderversioncontrolyoucanstartusingteamoperationsonyourproject.Theteamoperationsareavailableviarightclickonyourprojectorfile.Themostimportantoperationsaredescribedinthefollowinglist.Select:TeamAddtoindex,toaddtheselectedresource(s)totheindexofGitTeamCommit,toopenthecommitdialogforcommittingtoyourGitrepositoryTeamCreatePatch...,tocreateapatchTeamApplyPatch...,toapplyapatchtoyourfilesystemTeamIgnore,toaddthefiletoa.gitignorefileTeamShowinHistory,todisplaytheselectedfilesandfoldersintheHistoryviewIfyouselectaprojectyoucanuseadditionalteamoperationsfromthecontextmenu.TeamPulltopullinchangesfromyourremoteGitrepositoryTeamFetchtofetchthecurrentstatefromtheremoterepositoryTeamSwitchTotoswitchorcreatenewbranchesTeamPushtopushchangestoyourremoteGitrepositoryTeamTagtocreateandmanagetags.11.2.CommitamendGitamendallowstoadjustthelastcommit.Forexampleyoucanchangethecommitmessage.TheGitStagingviewallowsyoutoperformtheGitamendcommandviathehighlightedbuttoninthefollowingscreenshot.12.BranchinginEclipseRightclickyourprojectandselectTeamBranchtocreatenewbranchesortoswitchbetweenexistingbranches.YoucanalsoswitchbranchesintheHistoryview.13.MerginginEclipse13.1.MergeEGitsupportsmergingofbranchestoaddthechangesofonebranchintoanother.SelectyourprojectandTeamMergetostartthemergedialog.13.2.SolvingmergeconflictsIfyoupullinchangesormergeabranchandyouhaveconflictingchanges,EGitwillhighlighttheaffectedfiles.EGitalsosupportstheresolutionofthesemergeconflicts.RightclickonafilewithmergeconflictsandselectTeamMergeTool.Tip: UsetheGitstagingviewtofindtheconflictingfiles,inlargeprojectsthatisusuallyfasterthannavigatingthePackageExplorerview.Thisopensadialog,askingyouwhichmergemodeyouwouldliketouse.TheeasiestwaytoseetheconflictingchangesistousetheUseHEAD(thelastlocalversion)ofconflictingfilesasmergemode.Thiswayyouseetheoriginalchangesontheleftsideandtheconflictingchangesontherightside.YoucanmanuallyeditthetextontheleftsideorusetheCopycurrentchangefromrighttoleftbuttontocopytheconflictingchangesfromrighttoleft.Onceyouhavemanuallymergedthechanges,selectTeamAddfromthecontextmenuoftheresourcetomarktheconflictsasresolvedandcommitthemergeresolutionviaTeamCommit.14.UsingrebaseinEclipseTheGitRepositoriesviewallowsyoutorebaseyourcurrentlycheckoutbranchontoanotherbranch.RightclickonarepositorynodeandselectRebaseasdepictedinthefollowingscreenshot.Inthefollowingdialogyoucanselectthebranchontowhichyouwanttorebase.Tip: YoucanalsoselectdirectlythebranchtorebaseontofromtheBranchesnodeofthetree.Iftherebasewassuccessfuladialogisshown.Youhavetoresolverebaseconflictsiftheyoccur.Afterresolvingthem,selectRebaseContinueorifyouwanttocanceltherebaseoperationselectRebaseSkipandRebaseAbort.15.Workingwithcommits15.1.gitresetTheHistoryviewallowsyoutoresetyourcurrentbranchtoacommit.RightclickonacertaincommitandselectResetandtheresetmodeyouwouldliketouse.15.2.FindinglostcommitwiththeReflogviewTheGitReflogviewkeepstrackofthemovementsoftheHEADpointer.Thisviewallowsyoutofindcommitagain,e.g.ifyouusedthe gitresethard commandtoremovecertaincommits.15.3.MoveacommitwithgitcherrypickAcombinationofgitresetandgitcherrypickallowsyoutomoveacommit.Assumeyouhaveabadcommitwhichyouwouldliketoremovefromthehistoryofbranchfollowedbyagoodcommit.Thissituationisdepictedinthefollowingscreenshot.Forthisyouwouldmakeahardresetonthecommitoforigin/master.Afterwardsyoucancherrypickthegoodcommit.Thisresultsinahistorywithoutthebadcommit.16.CreatepatchesApatchisatextfilewhichcontainsinstructionshowtoupdateasetoffilestoadifferentstate.IfyouuseGityoucancreateapatchforthechangesyoumade.Thispatchcanbeappliedtothefilesystem.TocreateapatchforasetofchangeswithEGit,selecttheresourcesforwhichyouwanttocreateapatchinthePackageExplorerview,rightclickandselectTeamCreatePatch.TheresultingfilecanbeusedtogetappliedtoanotherGitrepository,viaTeamApplyPatch.17.BlameannotationsEGitallowstoaddannotationstoseewhichlinewaslastchangedbywhomandwhichcommit.Toenablethis,rightclickonyourfileandselectTeamShowAnnotations.Afterwardsyoucanplacethemouseontheleftsideoftheeditorandapopupwillshowthecommitinformation.18.StashviatheGitrepositoryviewThe gitstash commandisavailableintheGitrepositoriesview.RightclickonyourGitrepositoryandselectStashChanges.19.Gitrepositoryformultipleprojects19.1.CreateanewrepositoryEclipseallowstoworkwithprojectsthatarenotincludedintheworkspace.ToputseveralEclipseprojectsintothesameGitrepositoryyoucancreateafolderinsideoroutsideyourworkspaceandcreatetheprojectsinsidethisfolder.ThencreateaGitrepositoryforthisfolderandallprojectsinthisfolderwillbehandledbythesamerepository.ThebestpracticeistoputtheGitrepositoryoutsideoftheEclipseworkspace.YoucanimporttheseprojectsintoyourworkspaceviaFileImportGitProjectsfromGitasexplainedbefore.19.2.AddaprojecttoanexistingGitrepositoryToaddanewEclipseprojecttoanexistingGitrepository,selecttheproject,rightclickonitandselectTeamShareGitandselecttheexistingGitrepository.EGitmovestheprojectstotherepositoryandimportstheprojectautomaticallyintoyourworkspace.20.Tutorial:CreateGitrepositoryformultipleprojectsCreatetwoJavaprojectscalledcom.vogella.egit.multi.java1andcom.vogella.egit.multi.java2.CreateatleastoneJavaclassineachproject.Note: Gitdoesn'ttrackthehistoryofemptyfolders,itistrackingfilecontentandcontentchanges.Afterwardsselectbothprojects,rightclickonthemandselectTeamShareProject...Git.Eclipsemayaskyouwhichversioncontrolsystemyouwanttouse,e.g.CVSorGit.Select,ofcourse,theGitentry.NowcreateanewGitrepositoryoutsideyourworkspacesimilartotheprocessyouusedforthecreationofyourfirstGitrepositoryinthebook.YoucreatedanewGitrepositorywhichcontainsbothprojects.Bothprojectsaremovedtothisnewrepository.NowperformyourinitialcommitforallfilesintheprojectstostorethefileinthenewGitrepository.21.UsingEGitwithGithub21.1.GithubGithubisapopularhostingproviderforGitprojectsandifyourrepositoryisapublicrepositorythehostingatGithubisfree.Apublicrepositoryisvisibletoeveryoneandcanbeclonedbyotherpeopleatanypointintime.TouseGitHubcreateanaccountontheGithubWebsite.GithuballowsyoutousetheauthenticationviapasswordorviaSSHkeytoaccessyourrepositories.21.2.CreaterepositoryinGithubCreateanewrepositoryonGithubforexamplede.vogella.git.github.AftercreationofyournewrepositoryGithubdisplaystheinformationwhatyouhavetodoifyouwanttoconnecttothisrepositoryviathecommandline.AswearegoingtouseEGityoucanignorethisinformation.21.3.CloneprojectCopytheURLfromGithubandselectinEclipsefromthemenutheFileImportGitProjectsfromGitEclipsefillsoutmostofthefieldsbasedontheURLintheclipboard.EnteryouruserandpasswordtobeabletopushtoGithub.AlternativeyoucanalsouseanSSHkey.YoucanconfigureEclipsetoknowyourSSHviatheWindowPreferencesGeneralNetworkConnectionSSH2preferencesetting.Thissettingisdepictedinthefollowingscreenshot.21.4.PushchangesAfteryoumadechangesandcommittedthemtoyourlocalrepository,youcanselectTeamPushtoupstreamontheprojectfolder,topushyourchangestoyourGithub.ThisrequireswriteaccesstotheGithubrepository.22.EclipseintegrationwithGithub22.1.TheEclipseMylynpluginEclipseMylynprovidestaskintegrationforGithubissues,GithubpullandGist(shorttextsnippets)intotheEclipseIDE.ThereisaGitHubconnectorforMylynavailable,pleaseseeGithubMylynUserGuidefordetails.YouinstallitviaHelpInstallnewSoftwareandtheupdatesiteofyourrelease.22.2.GithubissueintegrationYoucanintegrateyourGithubissuesintoEclipseviaFileImport...TaskGitHubTaskRepositoriesandbyfollowingthewizard.22.3.ManagepullrequestsinEclipseYoucanintegrateyourpullrequestsatGithubintoEclipsebycreatinganewqueryfromtheTaskListview.Thisisdemonstratedviathefollowingscreenshots.Note: UnfortunatelytheGithubconnectdoescurrentlynotsupportthatyoumergethepullrequest.22.4.ImportprojectsdirectlyfromGithubYoucanalsoimportnowdirectlyprojectsfromGithubrepositories.22.5.MoreinfosabouttheGithubMylynintegrationForadetaileddescriptionoftheMylynandEGitintegrationpleaseseethefollowingwebpage.http://wiki.eclipse.org/EGit/GitHub/UserGuide23.Writinggoodcommitmessages23.1.ImportanceofGitcommitmessagesAcommitaddsanewversiontotherepository.Thisversionisdescribedbyacommitmessage.ThecommitmessagedescribesthechangesrecordedinacommitandhelpstheusertounderstandthehistoryofthefilescontainedinaGitrepository.Acommitmessageshouldthereforebedescriptiveandinformativewithoutrepeatingthecodechanges.23.2.GuidelinesforusefulcommitmessagesAcommitmessageshouldhaveaheaderandabody.Theheadershouldbelessthan50charactersandthebodyshouldwrapitstextat72sothatthecommitmessageisdisplayedwellonthecommandlineoringraphicaltoolsdisplayingthehistory.Thebodyshouldbeseparatedfromtheheaderbyanemptyline.Thebodyshouldmainlydescribethereasonwhythechangewasmade.ThechangesinthefilecanbereviewedwiththehelpofGit.Thecommitmessageshouldbeinpresenttense,e.g."Addbettererrorhandling"insteadof"Addedbettererrorhandling".Thelastparagraphcanalsocontainmetadataaskeyvaluepairs,alsoreferredtoasthecommitmessagefooter.Thismetadatacanbeusedtotriggercertainbehavior.ForexampletheGerritcodereviewsystemusestheChangeIdkeyfollowedbyachangeid,whichdoesnotchangeacrossdifferentversionsofthesamecodereview.Thischangedidisusedtoidentifytowhichreviewthemessagebelongs.Thecommitmessagefootercanalsohavee.g.'SignedOffBy'andmaybeusedtolinktoabugtrackingsysteme.g.'Bug:1234'.23.3.ExamplemessageThefollowingcanserveasanexampleforacommitmessage.Shortsummary(lessthan50characters)Detailedexplanation,ifrequired,linebreakataround72charactersmorestufftodescribe...Fixes:bug#8009ChangeId:I26b5f96ccb7b2293dc9b7a5cba0760294afba9fd23.4.ExamplehistoriesNote: A Git commit object is identified by its SHA-1 whichconsists of 40 bytes. In a typical Git repository you need lesscharacters to uniquely identify a commit object, e.g. youneed only 7 or 8 characters. Thegitlogonelinecommandlists the commit history in one line using the shortened SHA-1 of the commit objects.Thefollowinglistingshowstheoutputofthe gitlogoneline commandofaGitrepositorywithbadcommitmessages.ThefirstvalueineachlineistheshortenedSHA1,thesecondthecommitmessage.Thishistoryisnotuseful.21a8456update29f4219update016c696update29bc541update740a130initialcommitThenextlistingshowsthehistoryofanotherGitrepositoryinwhichbettercommitmessageshavebeenused.Thishistoryalreadygivesagoodoverviewabouttheactivities.7455823bug391086:Searchandfilterthemodeleditortree.9a84a8a[404207]MissingDynamicMenuContributioninchildselector952e014[404187]SpellingerrorinToolbar/Addchild71eeea9bug402875:ImportingmodelelementsfromlegacyRCP123672cBug403679NewApplicationwizardismissingdependencies97cdb9aBug388635createsanidforhandlers24.ContributingtoEGitGettingthesourcecodeEGitisselfhostedongit://git.eclipse.org.SeeEGitcontributorguideforadescriptionhowtoworkwiththeEGitandJGitsource.25.GitseriesThistutorialispartofaseriesabouttheGitversioncontrolsystem.Seetheothertutorialsformoreinformation.IntroductiontoGitHostingGitrepositoriesatGitHub,BitbucketoronyourownserverTypicalworkflowswithGitEGitTeamproviderforEclipse26.GettheBookThistutorialispartofabookavailableaspaperprintandelectronicformforyourKindle.27.Aboutthiswebsite27.1.DonatetosupportfreetutorialsPleaseconsideracontribution ifthisarticlehelpedyou.ItwillhelptomaintainourcontentandourOpenSourceactivities.27.2.QuestionsanddiscussionWritingandupdatingthesetutorialsisalotofwork.Ifthisfreecommunityservicewashelpful,youcansupportthecausebygivingatipaswellasreportingtyposandfactualerrors.Ifyoufinderrorsinthistutorial,pleasenotifyme(seethetopofthepage).PleasenotethatduetothehighvolumeoffeedbackIreceive,Icannotanswerquestionstoyourimplementation.EnsureyouhavereadthevogellaFAQasIdon'trespondtoquestionsalreadyansweredthere.27.3.LicenseforthistutorialanditscodeThistutorialisOpenContentundertheCCBYNCSA3.0DElicense.SourcecodeinthistutorialisdistributedundertheEclipsePublicLicense.SeethevogellaLicensepagefordetailsonthetermsofreuse.28.LinksandLiterature28.1.SourceCodeSourceCodeofExamples28.2.EGitResourcesEGitUserGuideEGitcontributorguide28.3.vogellaResourcesTRAINING SERVICE & SUPPORTThe vogella company providescomprehensive training andeducation services from experts inthe areas of Eclipse RCP, Android, Git,Java, Gradle and Spring. We offer bothpublic and inhouse training. Whichevercourse you decide to take, you areguaranteed to experience what manybefore you refer to as The best ITclass I have ever attended.The vogella company offers expertconsulting services, developmentsupport and coaching. Our customersrange from Fortune 100 corporationsto individual developers.