32
1 CSE 391 Lecture 9 Version control with Git slides created by Ruth Anderson, Marty Stepp, Brett Wortzman and Zorah Fung images from http://git-scm.com/book/en/ http://www.cs.washington.edu/391/

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

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSE 391 Lecture 9 - courses.cs.washington.edu

1

CSE 391Lecture 9

VersioncontrolwithGit

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

Page 2: CSE 391 Lecture 9 - courses.cs.washington.edu

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…

Page 3: CSE 391 Lecture 9 - courses.cs.washington.edu

3

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

§ Canwestoretheprojectfilesinaneutral"official"location?

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

• Whathappensifwebothtrytoeditthesamefile?§ Billjustoverwrote afileIworkedonfor6hours!

• Whathappensifwemakeamistakeandcorruptanimportantfile?§ Isthereawaytokeepbackupsofourprojectfiles?

• HowdoIknowwhatcodeeachteammateisworkingon?

Page 4: CSE 391 Lecture 9 - courses.cs.washington.edu

4

Solution: Version Control• versioncontrolsystem:Softwarethattracksandmanageschangestoasetoffilesandresources.

• Youuseversioncontrolallthetime§ Builtintowordprocessors/spreadsheets/presentation software

• Themagical“undo”buttontakesyoubackto“theversionbeforemylastaction”

§ Wikis• Wikisareallaboutversioncontrol,managingupdates,andallowingrollbackstopreviousversions

Page 5: CSE 391 Lecture 9 - courses.cs.washington.edu

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

Page 6: CSE 391 Lecture 9 - courses.cs.washington.edu

6

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

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

• Theremaybeonlyonerepositorythatallusersshare(CVS,Subversion)

• Oreachusercouldalsohavetheirowncopyoftherepository(Git,Mercurial)

• Filesinyourworkingdirectorymustbeaddedtotherepoinordertobetracked.

Page 7: CSE 391 Lecture 9 - courses.cs.washington.edu

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

Page 8: CSE 391 Lecture 9 - courses.cs.washington.edu

8

Repository Location• Cancreatetherepositoryanywhere

§ Canbeonthesamecomputerthatyou’regoingtoworkon,whichmightbeokforapersonalprojectwhereyoujustwantrollbackprotection

• But,usuallyyouwanttherepositorytoberobust:§ Onacomputerthat’supandrunning24/7

• Everyonealwayshasaccesstotheproject§ Onacomputerthathasaredundantfilesystem(ie RAID)

• Nomoreworriesaboutthatharddiskcrashwipingawayyourproject!

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

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

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.

Page 10: CSE 391 Lecture 9 - courses.cs.washington.edu

10

Git

HTTP://XKCD.COM/1597/

Page 11: CSE 391 Lecture 9 - courses.cs.washington.edu

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/

Page 12: CSE 391 Lecture 9 - courses.cs.washington.edu

12

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

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

Page 13: CSE 391 Lecture 9 - courses.cs.washington.edu

13

Git uses a distributed model

Centralized Model Distributed Model

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

Page 14: CSE 391 Lecture 9 - courses.cs.washington.edu

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!)

Page 15: CSE 391 Lecture 9 - courses.cs.washington.edu

15

Git Operations

Working changes

Changes you’re

prepping to commit

Local copy of the repo with your commitedchanges

Remoteshared

repo

also called “stage”

Page 16: CSE 391 Lecture 9 - courses.cs.washington.edu

16

Git Operations

git add

git commit

git push

Page 17: CSE 391 Lecture 9 - courses.cs.washington.edu

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.

Page 18: CSE 391 Lecture 9 - courses.cs.washington.edu

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 "[email protected]" -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

Page 19: CSE 391 Lecture 9 - courses.cs.washington.edu

19

Get ready to use Git!1. SetthenameandemailforGit tousewhenyoucommit:

$ git config --global user.name “Bugs Bunny”$ git config --global user.email [email protected]

§ 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

Page 20: CSE 391 Lecture 9 - courses.cs.washington.edu

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 [email protected]:rea/superTest.git

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

Page 21: CSE 391 Lecture 9 - courses.cs.washington.edu

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

Page 22: CSE 391 Lecture 9 - courses.cs.washington.edu

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.

Page 23: CSE 391 Lecture 9 - courses.cs.washington.edu

23

Use Good Commit Messages

HTTP://XKCD.COM/1296/

Page 24: CSE 391 Lecture 9 - courses.cs.washington.edu

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

Page 25: CSE 391 Lecture 9 - courses.cs.washington.edu

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.$

Page 26: CSE 391 Lecture 9 - courses.cs.washington.edu

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.

Page 27: CSE 391 Lecture 9 - courses.cs.washington.edu

27

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

1677b2dEditedfirstlineofreadme258efa7Addedlinetoreadme0e52da7Initialcommit

• git log -5 (toshowonlythe5mostrecentupdates,etc.)

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

Page 28: CSE 391 Lecture 9 - courses.cs.washington.edu

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)

Page 29: CSE 391 Lecture 9 - courses.cs.washington.edu

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.

Page 30: CSE 391 Lecture 9 - courses.cs.washington.edu

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!

Page 31: CSE 391 Lecture 9 - courses.cs.washington.edu

31

SVN vs. Git• SVN:

§ centralrepositoryapproach– themainrepository istheonly“true”source,onlythemainrepositoryhasthecompletefilehistory

§ Userscheckoutlocalcopiesofthecurrentversion• Git:

§ Distributedrepositoryapproach– every checkoutoftherepository isafullfledgedrepository,completewithhistory

§ Greaterredundancyandspeed§ Branchingandmergingrepositories ismoreheavilyusedasaresult

Page 32: CSE 391 Lecture 9 - courses.cs.washington.edu

32

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

• HW9(Git)hasmoredetailsandwalksyouthroughcreatingaGitrepoandaddingtoasharedrepo.