CSE 391 Lecture 9 - courses.cs.washington.edu

Preview:

Citation preview

1

CSE 391Lecture 9

VersioncontrolwithGit

slidescreatedbyRuthAnderson,MartyStepp,BrettWortzman andZorah Fungimagesfromhttp://git-scm.com/book/en/http://www.cs.washington.edu/391/

2

Problems Working Alone• Everdoneoneofthefollowing?

§ Hadcodethatworked,madeabunchofchangesandsavedit,whichbrokethecode,andnowyoujustwanttheworkingversionback…

§ Accidentallydeletedacriticalfile,hundredsoflinesofcodegone…§ Somehowmessedupthestructure/contentsofyourcodebase,andwanttojust“undo”thecrazyactionyoujustdid

§ Harddrivecrash!!!!Everything’s gone,thedaybeforedeadline.

• Possibleoptions:§ Saveas(MyClass-v1.java)

• Ugh.Justugh.Andnowasinglelinechangeresults induplicatingtheentirefile…

3

Problems Working in teams• Whosecomputerstores the"official" copyoftheproject?

§ Canwestoretheprojectfilesinaneutral"official"location?

• Willwebeabletoread/writeeachother'schanges?§ Dowehavetherightfilepermissions?§ Letsjustemailchangedfilesbackandforth!Yay!

• Whathappensifwebothtrytoeditthesamefile?§ Billjustoverwrote afileIworkedonfor6hours!

• Whathappensifwemakeamistakeandcorruptanimportantfile?§ Isthereawaytokeepbackupsofourprojectfiles?

• HowdoIknowwhatcodeeachteammateisworkingon?

4

Solution: Version Control• versioncontrolsystem:Softwarethattracksandmanageschangestoasetoffilesandresources.

• Youuseversioncontrolallthetime§ Builtintowordprocessors/spreadsheets/presentation software

• Themagical“undo”buttontakesyoubackto“theversionbeforemylastaction”

§ Wikis• Wikisareallaboutversioncontrol,managingupdates,andallowingrollbackstopreviousversions

5

Software Version Control• Manyversioncontrolsystemsaredesignedandusedespeciallyforsoftwareengineeringprojects§ examples:CVS,Subversion(SVN),Git,Monotone,BitKeeper,Perforce

• helpsteamstoworktogetheroncodeprojects§ asharedcopyofallcodefilesthatalluserscanaccess§ keepscurrentversionsofallfiles,andbackupsofpastversions§ canseewhatfilesothershavemodifiedandviewthechanges§ managesconflictswhenmultipleusersmodifythesamefile

§ notparticulartosourcecode;canbeusedforpapers,photos,etc.• butoftenworksbestwithplaintext/codefiles

6

Repositories• Repository(aka“repo”):alocationstoringacopyofallfiles.

§ youdon'teditfilesdirectlyintherepo;§ youeditalocalworkingcopyor“workingtree”§ thenyoucommit youreditedfilesintotherepo

• Theremaybeonlyonerepositorythatallusersshare(CVS,Subversion)

• Oreachusercouldalsohavetheirowncopyoftherepository(Git,Mercurial)

• Filesinyourworkingdirectorymustbeaddedtotherepoinordertobetracked.

7

What to put in a Repo?• Everythingneeded tocreateyourproject:

§ Sourcecode(Examples: .java,.c,.h,.cpp )§ Buildfiles(Makefile, build.xml)§ Otherresourcesneeded tobuildyourproject:icons,textetc.

• ThingsgenerallyNOTputinarepo(thesecanbeeasilyre-createdandjusttakeupspace):§ Objectfiles(.o)§ Executables(.exe)§ Machine-specificconfigurationfiles

8

Repository Location• Cancreatetherepositoryanywhere

§ Canbeonthesamecomputerthatyou’regoingtoworkon,whichmightbeokforapersonalprojectwhereyoujustwantrollbackprotection

• But,usuallyyouwanttherepositorytoberobust:§ Onacomputerthat’supandrunning24/7

• Everyonealwayshasaccesstotheproject§ Onacomputerthathasaredundantfilesystem(ie RAID)

• Nomoreworriesaboutthatharddiskcrashwipingawayyourproject!

• Options:§ attu,CSEGitLab,GitHub(doNOTuseGitHubforhomework!!!)

9

Aside: So what is GitHub?• GitHub.com isasiteforonlinestorageof Git repositories.• Manyopensourceprojectsuseit,suchasthe Linuxkernel.• Youcangetfreespaceforopensourceprojectsoryoucanpayforprivateprojects.

• DoNOTuseGitHubtostoreyourhomework!!Question:DoIhavetouseGitHubtouseGit?Answer:No!• youcanuseGit completely locallyforyourownpurposes,or• youcanusetheCSEGitLab server,or• youcouldsharearepowithusersonthesamefilesystem(e.g.attu)aslongeveryone hastheneeded filepermissions.

10

Git

HTTP://XKCD.COM/1597/

11

Git Resources• Atthecommandline:(where<verb> = config,add,commit,etc.)

$ git help <verb> $ git <verb> --help $ man git-<verb>

• Freeon-linebook: https://git-scm.com/book/en/v2• Git tutorial:http://schacon.github.com/git/gittutorial.html• ReferencepageforGit:http://gitref.org/index.html• Git website:http://git-scm.com/

• Git forComputerScientists:http://eagain.net/articles/git-for-computer-scientists/

12

History of Git• CameoutofLinuxdevelopment community• LinusTorvalds,2005• Initialgoals:

§ Speed§ Supportfornon-lineardevelopment (thousandsofparallelbranches)§ Fullydistributed§ AbletohandlelargeprojectslikeLinuxefficiently

13

Git uses a distributed model

Centralized Model Distributed Model

(CVS, Subversion, Perforce) (Git, Mercurial)Result: Many operations are local

14

Ways to use Git

Using Git on your own computer, one user

Using Git on multiple computers,multiple users or one user onmultiple computers

Possible servers:• CSE GitLab• attu• GitHub (NOT for homework!)

15

Git Operations

Working changes

Changes you’re

prepping to commit

Local copy of the repo with your commitedchanges

Remoteshared

repo

also called “stage”

16

Git Operations

git add

git commit

git push

17

Basic WorkflowBasicGit workflow:

1. Modify filesinyourworkingdirectory.2. Stage files,addingsnapshotsofthemtoyourstagingarea.3. Doacommit,whichtakesthefilesastheyareinthestagingarea

andstoresthatsnapshotpermanentlytoyourlocalGit directory(yourlocalcopyoftherepo).

• Notes:§ Ifaparticularversionofafileisinyourlocalgit directory,it’sconsideredcommitted.§ Ifit’smodifiedbuthasbeenaddedtothestagingarea,itisstaged.§ Ifitwaschanged since itwascheckedoutbuthasnot beenstaged,itismodified.

18

CSE GitLabEveryone inthiscoursehasbeengivenanaccountonCSEGitLabTouseCSEGitLab:1. LogontoCSEGitLab:https://gitlab.cs.washington.edu/

§ IMPORTANT:IfyouhaveaCSENetID usethat,otherwiseuseyourUWNetID

2. Addanssh key:https://gitlab.cs.washington.edu/help/ssh/README.md

§ FollowtheinstructionsinREADME.mdwhichsaytotype:ssh-keygen -t rsa -C "yourUWNetID@uw.edu" -b 4096

• Justhitreturntoacceptthedefaultfilelocationandyoudonotneedapassword so hitreturnbothtimes when prompted forapassword

§ Thentype: cat ~/.ssh/id_rsa.pub

§ Copy-pastethekeytothe'SSHKeys'sectionunder‘ProfileSettings'inyouruserprofileonCSEGitLab.Orgodirectlyhere:https://gitlab.cs.washington.edu/profile/keys

19

Get ready to use Git!1. SetthenameandemailforGit tousewhenyoucommit:

$ git config --global user.name “Bugs Bunny”$ git config --global user.email bugs@gmail.com

§ Youcancallgit config –-list toverifytheseareset.§ ThesewillbesetgloballyforallGit projectsyouworkwith.§ Youcansetvariablesonaproject-onlybasisbynot usingthe--global flag.

• Thelatestversionofgit willalsopromptyouthatpush.default isnotset,youcanmakethiswarninggoawaywith:$ git config --global push.default simple

• Youcanalsosettheeditorusedforwritingcommitmessages:$git config --global core.editor emacs (itisvimbydefault)

vim tips: “a” add, “esc” when done adding, “wq:” to save and quitvim editor: http://www.gentoo.org/doc/en/vi-guide.xmlvim ref card: http://tnerual.eriogerg.free.fr/vimqrc.pdf

20

Create a local copy of a repo2. Twocommonscenarios:(onlydooneofthese)

a) Tocloneanalreadyexistingrepotoyourcurrentdirectory:$ git clone <url> [local dir name]Thiswillcreateadirectorynamed localdir name,containingaworkingcopyofthefilesfromtherepo,anda.git directorywhichyoucanignore(usedtoholdthestagingareaandyourlocalrepo)

Example:git clone git@gitlab.cs.washington.edu:rea/superTest.git

b) TocreateaGit repoinyourcurrentdirectory:$ git initThiswillcreatea.git directoryinyourcurrentdirectorywhichyoucanignore(usedtoholdthestagingareaandyourlocalrepo).Thenyoucancommitfilesinyourcurrentdirectoryintothelocalrepo:$ git add file1.java$ git commit –m “initial project version”

21

Git commandscommand description

git clone url [dir] copyagitrepositorysoyoucanaddtoitgit add files addsfilecontentstothestagingareagit commit recordsasnapshotofthestagingareagit status viewthestatusofyourfilesintheworking

directoryandstagingareagit diff showsdiffofwhatisstagedandwhatis

modifiedbutunstagedgit help [command] gethelpinfoaboutaparticularcommandgit pull fetchfromaremoterepoandtrytomerge

intothecurrentbranchgit push pushyournewbranchesanddatatoa

remoterepositoryothers: init, reset, branch, checkout, merge, log, tag

22

Adding & Committing files1. Thefirsttimeweaskafiletobetracked,and everytimebefore

wecommitafilewemustaddittothestagingarea:$ git add README.txt hello.java

Thistakesasnapshotofthesefilesatthispointintimeandaddsittothestagingarea.Note:Tounstage achangeonafilebeforeyouhavecommittedit:$ git reset HEAD filename

2. Tomovestagedchangesintothelocalrepowecommit:$ git commit –m “Fixing bug #22”Note:Youcanedityourmostrecentcommitmessage (ifyouhavenotpushedyourcommityet)using:git commit –-amend

Note:Thesecommandsarejustactingonyourlocalversionofrepo.

23

Use Good Commit Messages

HTTP://XKCD.COM/1296/

24

Status and Diff• Toviewthestatus ofyourfilesintheworkingdirectoryandstagingarea:

$ git status or$ git status –s

(-s showsashortonelineversion)

• Toseedifference between yourworkingdirectoryandthestagingarea(Thisshowswhatismodifiedbutunstaged):

$ git diff

• Toseedifferencebetweenthestagingareaandyourlocalcopyoftherepo(Thisshowsstagedchanges):(--staged is synonymous)

$ git diff --cached

25

After editing a file…$emacs rea.txt$git status#Onbranchmaster#Changesnotstagedforcommit:#(use"git add<file>..."toupdatewhatwillbecommitted)#(use"git checkout-- <file>..."todiscardchangesinworkingdirectory)##modified:rea.txt#nochangesaddedtocommit(use"git add"and/or"git commit-a")$git status-sMrea.txt ß Note:Misinsecondcolumn=“workingtree”$git diff ß Showsmodificationsthathavenot beenstaged.diff--git a/rea.txtb/rea.txtindex66b293d..90b65fd100644--- a/rea.txt+++b/rea.txt@@-1,2+1,4@@Here isrea's file.++Onenewlineadded.$git diff--cached ß Showsnothing,nomodificationshavebeenstagedyet.$

26

After adding file to staging area…$git addrea.txt$git status#Onbranchmaster#Changestobecommitted:#(use"git resetHEAD<file>..."tounstage)##modified:rea.txt#$git status-sMrea.txt ß Note:Misinfirstcolumn=“stagingarea”$git diff ß Note:Showsnothing,nomodificationsthathavenot beenstaged.$git diff--cached ß Note:Showsstagedmodifications.diff--git a/rea.txtb/rea.txtindex66b293d..90b65fd100644--- a/rea.txt+++b/rea.txt@@-1,2+1,4@@Here isrea's file.++Onenewlineadded.

27

Viewing logsToseealogofallchangesinyourlocalrepo:• $ git log or• $ git log --oneline (toshowashorterversion)

1677b2dEditedfirstlineofreadme258efa7Addedlinetoreadme0e52da7Initialcommit

• git log -5 (toshowonlythe5mostrecentupdates,etc.)

Note:changeswillbelistedbycommitID #,(SHA-1hash)Note:changesmadetotheremoterepobeforethelasttimeyoucloned/pulledfromitwillalsobeincludedhere

28

Pulling and PushingGoodpractice:1. AddandCommit yourchangestoyourlocalrepo2. Pull fromremoterepo togetmostrecentchanges(fixconflictsif

necessary, thenaddandcommitthosechangestoyourlocalrepo)3. Push yourchangestotheremoterepo

Tofetchthemostrecentupdatesfromtheremoterepointoyourlocalrepo,andputthemintoyourworkingdirectory:$ git pull origin masterTopushyourchangesfromyourlocalrepototheremoterepo:$ git push origin masterNotes: origin =analiasfortheURLyouclonedfrom

master =theremotebranchyouarepullingfrom/pushingto,(thelocalbranchyouarepullingto/pushingfromisyourcurrentbranch)

29

Avoiding Common ProblemsFromCSE331:http://courses.cs.washington.edu/courses/cse331/18wi/tools/versioncontrol.html#git-pitfalls

• Donotedittherepository(the .git directory)manually.Itwasn'tdesignedformodificationsbyhumans.

• Trynottomakemanydrasticchangesatonce.Instead,makemultiplecommits,eachofwhichhasasinglelogicalpurpose.Thiswillminimizemergeconflicts.Thisisgoodcodingpracticeingeneral.

• Always git pull beforeeditingafile.It'seasytoforgetthis.Ifyouforget,youmayendupeditinganoutdated version,whichcancausenastymergeconflicts.

• Don'tforget git push afteryouhavemadeandcommittedchanges.Theyarenotcopiedtotheremoterepositoryuntilyoudoapush.

30

BranchingTocreateabranchcalledexperimental:• $ git branch experimental

Tolistallbranches:(*showswhichoneyouarecurrentlyon)• $ git branch

Toswitchtotheexperimentalbranch:• $ git checkout experimental

Lateron,changesbetween thetwobranchesdiffer,tomergechangesfromexperimental intothemaster:• $ git checkout master• $ git merge experimental

Note:git log --graph canbeusefulforshowingbranches.Note:Thesebranchesareinyourlocalrepo!

31

SVN vs. Git• SVN:

§ centralrepositoryapproach– themainrepository istheonly“true”source,onlythemainrepositoryhasthecompletefilehistory

§ Userscheckoutlocalcopiesofthecurrentversion• Git:

§ Distributedrepositoryapproach– every checkoutoftherepository isafullfledgedrepository,completewithhistory

§ Greaterredundancyandspeed§ Branchingandmergingrepositories ismoreheavilyusedasaresult

32

Wrap-up• You*will*useversioncontrolsoftwarewhenworkingonprojects,bothhereandinindustry§ Ratherfoolishnotto§ Advice:justsetuparepository,evenforsmallprojects,itwillsaveyoutimeandhassle

• HW9(Git)hasmoredetailsandwalksyouthroughcreatingaGitrepoandaddingtoasharedrepo.

Recommended