a quick (and maybe practical) guide to gitand version...

Post on 21-May-2020

8 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Aquick(andmaybepractical)guidetoGit andversioncontrol

ByJayJohnson

Necessaryshoutoutsandreferencelinks

• fromslidesfromCSE380withDr.ChrisSimmons(UT-Austin)and• notesfromProf.Jean-LucThiffeault (UW-Madison)• https://betterexplained.com/articles/a-visual-guide-to-version-control/• http://www.math.wisc.edu/~jeanluc/gitlab_instructions.php• https://betterexplained.com/articles/a-visual-guide-to-version-control/• http://rogerdudler.github.io/git-guide/• https://git-scm.com/book/en/v2/Getting-Started-Git-Basics• https://docs.gitlab.com/ce/gitlab-basics/start-using-git.html

Whatisversioncontrol?

• Ittracksyourfilesovertime!• Makeslifeeasier.

Youprobablyhavealreadydonethis…

• Haveyoueverdonesomethinglike?...• Resume-may2015.docx• Resume-june2017.docx

• Orthis…• Seminar_20171116_Spratt_Draft1.tex• Seminar_20171116_Spratt_Draft2.tex

• Wewantanewversionwithoutdestroyingtheoldones!• Wemayevenuseasharedfoldersoyoudon’thavetoemailthingsbackandforth,andhopefullyeveryonerelabelsthemwhentheychangethings.

Thisworksforsmallprojectsbutlargeones?Awholedissertation?Notreally…

Whatdoesversioncontroldo?• BackupandRestore. Filesaresavedastheyareedited,andyoucanjumptoanymomentintime.NeedthatfileasitwasonFeb23,2007?Noproblem.

• Synchronization. Letspeoplesharefilesandstayup-to-datewiththelatestversion.• Short-termundo.Monkeyingwithafileandmesseditup?(That’sjustlikeyou,isn’tit?).Throwawayyourchangesandgobacktothe“lastknowngood”versioninthedatabase.

• Long-termundo. Sometimeswemessupbad.Supposeyoumadeachangeayearago,andithadabug.Jumpbacktotheoldversion,andseewhatchangewasmadethatday.

• TrackChanges.Asfilesareupdated,youcanleavemessagesexplainingwhythechangehappened(storedintheVCS,notthefile).Thismakesiteasytoseehowafileisevolvingovertime,andwhy.

• TrackOwnership. AVCStagseverychangewiththenameofthepersonwhomadeit.Helpfulfor blamestorming givingcredit.

• Sandboxing,orinsuranceagainstyourself.Makingabigchange?Youcanmaketemporarychangesinanisolatedarea,testandworkoutthekinksbefore“checkingin”yourchanges.

• Branchingandmerging.Alargersandbox.Youcan branch acopyofyourcodeintoaseparateareaandmodifyitinisolation(trackingchangesseparately).Later,youcanmerge yourworkbackintothecommonarea.

Usingversioncontrol

• Actuallyusingversioncontrolisthefirststep• PutEVERYTHINGunderversioncontrolConsiderputtingpartsofyourhomedirectoryunderVCUseaconsistentprojectstructureandnamingconventionCommitoftenandinlogicalchunks

• Writemeaningfulcommitmessages

• DoallfileoperationsintheVCSSetupchangenotificationsifworkingwithmultiplepeople

Manyonlineserversofferfreecodestorage…

• wholeWikipediapageaboutit:https://en.wikipedia.org/wiki/Comparison_of_source_code_hosting_facilities

GitLab hasunlimitedprivatereposforanunlimitednumberofcollaboratorsplus itistheonlyonewhichiscompletelyopensource.

IhaveusedBitbucket foryearsandtheyhaveagreatGUIenvironment(SourceTree)butIammigratingtoGitLab.

Somepossibletools

• Freetools!• RCS– revisioncontrolsystems• CVS– concurrentversionsystems• SVN- subversion• Mercurial• Git – whichwewilltalkabouttoday

• Commercial• MSVisualStudioTeamSystem• IBMRationalSoftware:• Clearcase AccuRev• MKSIntegrity

WhousesGit?

Whatisgit?

• DISTRIBUTEDversioncontrolsystem• Everyonehasthecompletehistory• Everythingisdoneoffline• Nocentralauthority• Changescanbesharedwithoutaserver

• Thismeansyoudon’thavetobeconnectedtoyourservertomakechanges,youcandothemwheneverandjust’push’themlater.

Git tracksyourfolderinaseriesofsnapshotsintime

Somequickjargon

• Repository(repo):thefolder/directoryinwhichyouaretrackingchanges• Master:thinkthetreetrunk– allchangesareonhere• Branch:Anothercopyofyourfilesystemwhereyoucanmakechangeswithnoworriesaboutbreakingthings!• Add:pickwhichfilesyouwanttochange.• Commit:Think‘savinganewversion’thisisasnapshotintimeofyourfiles• Push:SendthechangestoGitlab oryourserver• Pull:Whenaskforthechangesbyothers(oryouonothercomputers)• HEAD:Themostcurrentcommitintheworkingdirectory

TheGit workflow:ThreeSteps

TheGit workflow:ThreeSteps

ThebasicGit workflowgoessomethinglikethis:1.Youmodifyfilesinyourworkingtree.2.Youselectivelystagejustthosechangesyouwanttobepartofyournextcommit,whichadds onlythosechangestothestagingarea.3.Youdoacommit,whichtakesthefilesastheyareinthestagingareaandstoresthatsnapshotpermanentlytoyourGit directory.

add&commit

Whentocommit?

• Committingtoooftenmayleavetherepoinastatewherethecurrentversiondoesn’treallywork,oryoucan’treasonablyfindwhenthingsbroke• Committingtooinfrequentlymeansthatyoucan’ttrackyourchangesverywell anditmakesconflictsmuchmorelikely

pushingchanges

branching(moreadvanced)

usefulhints

Let’sstarttogether!

Makeafolder

• mkdir mynewrepo• cd mynewrepo• git init

Introduceyourselftogit

• $ git config --global user.name "John Doe" • $ git config --global user.emailjohndoe@example.com

Optional:Setyourdefaulttexteditor

• ForNotepad++onwindows• git config --globalcore.editor "'C:/ProgramFiles/Notepad++/notepad++.exe'-multiInst -nosession”

• Forvim(oremacs)onUnix-based• git config –globalcore.editor vim

Checkyoursettings….

• git config --list

Orforaspecifickey’svalue• git config <key>e.g.• git config user.name

CreatinganSSHkeypair

• Whydowedothis?• Itmakeslogginginawholeloteasier.

CheckifyoualreadyhaveanSSHkey

Git BashonWindows/GNU/Linux/macOS /PowerShell:• $ cat ~/.ssh/id_rsa.pub

WindowsCommandPrompt:• $ type %userprofile%\.ssh\id_rsa.pub

• Ifyouseesomethingstartingwith‘ssh-rsa’thenyouareset!Youcanjustskipaheadandcopyit.• Ifyoudon’t,thenyouneedtomakeone!

GeneratinganewSSHkeypair

Git BashonWindows/GNU/Linux/macOS:• $ ssh-keygen

Whenaskedforafilepath,justusethedefaultbypressingenter.IfyoualreadyhaveanSSHkeypairbutwanttouseanewone,Googlehowtodoit…

Nextyouwillbeaskedforapassword,youshould*putoneinbutdon’tneedonefornow.Enteroneorskipitbypressingenter.Tochangethepasswordinthefutureuse…• ssh-keygen -p <keyname>

CopytheSSHpairtoyourclipboard

macOS:• $ pbcopy < ~/.ssh/id_rsa.pubGNU/Linux(requiresthexclip package):• $ xclip -sel clip < ~/.ssh/id_rsa.pubWindowsCommandLine:• $ type %userprofile%\.ssh\id_rsa.pub | clip Git BashonWindows/WindowsPowerShell:• $ cat ~/.ssh/id_rsa.pub | clip

AddthekeytoGitLab

• Goto‘SSHKeys’tabin’ProfileSettings’• Pasteyourkeyinthe‘Key’section• Giveareasonablename“Laptop”• Makesurethatcopiedeverythingstartingwith‘ssh-rsa’andendingwithyouremail.• Optionally,testyoursetup(replace‘example.com’withyourGitLabdomain)…

ssh –T git@example.com

CreateanewprojectinGitLab

• getthefolderfromgitlab makeafile,addit,commititandsenditback!• $ git clone git@gitlab.com:jayjohnson/mynewrepo.git• $ cd mynewrepo• $ touch README.md• $ git add README.md• $ git commit -m "add README" • $ git push -u origin master

Mergesanddiffs

Ifsomeoneelse(oranothercomputer)madeachangeanditconflictswithwhatyouhavecommitted,youcancombinethemwith:$ git merge

Butthenyouwillhavetocommitthemagain$ git commit –m "Merged changes."

Importantotherfunctions

$ git statuswhichgives"statusreport"ofthecurrentstateofyourlocalfiles,and$git diffor$ git diff paper.texwhichliststhedifferencesbetweenlocalfileandtheoriginalfile.Itisalsousefultoviewthechangehistory(orlog)forafileordirectory:$ git log paper.texFinally,toremoveafileordirectoryrun$ git rm paper.texwhichdeletesthefile,butwillalsodeleteforyoucollaboratorswhentheypullchangesfromtheserver.Notethatremovalsshouldbeexplainedinthecommitlogmessage(asshouldeverythingelse!).

Sometips• Donotbeafraidtocommitchanges! Git rememberseverythingbeforeyourcommit,soitisvirtuallyimpossibletobreakanything.

• Commitchangesoften! Itisbettertohaveadetailedlogofsmallchangesthanahugenumberofsimultaneouschanges.Inparticular,ifyoudon'tcommitchangesoftenyouwillforgetwhatyouchanged(thoughliberaluseof'git diff'helpstofigurethatout).Thatsaid,acommittedchangesetshouldusuallybe'consistent,'inthesensethatitdoesn'tbreakthingsforeveryoneelse.Butsometimesitispreferabletohavesmallerchangesets thatdobreakthings,aslongasyoudon'tpushyourchangestotheserveruntildone.Justmakesurethelogmessagereflectsthis.

• Writehelpfullogmessages! Ittakesafewsecondsmorebutit'sworthit.Refertochangesinspecificindividualfiles.Yourcollaboratorswillthankyou,andyouwillthankyourselfwhenyourevisittheprojecttwoyearsdowntheline.Formultilinelogmessages,thefirstlineshouldbeasummaryofthechanges.

• Donotincludebinaries,executables,logs,etc.oranyotherfilesthatcanberecreated. Theideabehindversioncontrolistokeeptrackofmeaningfulchangestofiles.Binaryfilestendtochangeoften,andaredesignedtoberecreatedfromsources.Logfilesalsochangeoften,sincetheyusuallycontaindates.Unlessthebinaryorloginformationistrulyessential(i.e,thePDFfiguresinapaper),theseshouldnotbeversioned. Seenextslide forhowtoavoidthemshowingupon'gitstat'.

Excludecertainfiletypeson$ git status.gitignore file:Toavoid unversioned filesshowingupon'git stat',whichisdistractingandmightleadtoyounotnoticingchanges,addtheirfilenamestothespecial .gitignore file,whichlivesatthebaseoftheprojectfolder.Forexample,whendealingwithLaTeX documents,my .gitignore fileusuallycontains*.aux*.bbl *.blg *.log.DS_Store ThefinallineignorestheclutterfilesgeneratedbyOSX.Notethatthefile .gitignore shoulditselfbeunderversioncontrol('gitadd.gitignore').

replacelocalchanges

Goingbacktoanearlycommit

• Greatflowchartfordecidinghowtogobacktosomethingolder…• https://raw.githubusercontent.com/emmajane/gitforteams/master/resources/workflow-undoing-changes.png• Moreinfoat:• https://stackoverflow.com/questions/4114095/how-to-revert-git-repository-to-a-previous-commit• Simpleway

• Findwhichcommityouwanttogobacktowith(rememberthesha1#whereyouaregoing• $ git log

• Gotothatcommityouwant• $ git checkout <hash>

• Gobacktowhereyouwerewith• $ git checkout -

git logtips

• ifyouwanttogobackandseewhatyoucommitted(withoutgoingonlinetoGitlab)use$git log• options

• onlyshowXnumberofentries• $ -[number]

• showeachononeline• $ --pretty=oneline (can also be ‘short’, ‘full’, etc..)

• showthedifferenceofeachcommit• $ -p

• simpleclean• $ git log -oneline –n 10

• Ex:$ git log -3 --pretty=oneline• somanywaystocustomizewhatyouwanttosee• https://git-scm.com/book/id/v2/Git-Basics-Viewing-the-Commit-History

Moreadvancedfeatures…

newbranchandswitchtoit

update&merge

tagging

Moreinfo/references

• https://betterexplained.com/articles/a-visual-guide-to-version-control/• http://rogerdudler.github.io/git-guide/• https://git-scm.com/book/en/v2/Getting-Started-Git-Basics• https://docs.gitlab.com/ce/gitlab-basics/start-using-git.html

top related