VersionControlwithGit
KayleaNelson
VersionControlwithGit
• WhatisVersionControlandGit?• Pu8ngYourCodeintoGit• Connec<ngYourRepositorytoBitbucket• U<lizingYourRepository’sHistory• Collabora<on:MergingandConflicts
WhatisVersionControl?
“Thewholeideabehindanyversioncontrolsystemistostore“safe”copiesofaprojectsothatyouneverhavetoworryaboutirreparablybreakingyourcodebase.”
–Bitbucket.org• Easyandpowerfulwaytotrackchangestoyourwork• Usefulforbothwri<ng(ifusinge.g.LaTeX)andcode• Backupsofyourwork• Generalcodingsafetynet
WhatisGit?Howdoesitwork?Gittrackschangestoafile(orsetoffiles)throughaseriesofsnapshotscalled“commits”or“revisions”.
Thesesnapshotsarestoredina“repository”whichcontainsahistoryofallthechangestothefiles.
HowisGitusefultome?
• “Whyisn’titworkingallofasudden?”• Cleanerfilesystem(nomore“code,codev2,codev3_test,codev3_test1”directories)
• Recordofyouredits(andthoughtprocess!)• Checkforbugsininconsistentresults• Unlimitedandpowerful“undo”• Collabora<on!
Pu8ngYourCodeintoGit
ConfigureGit
• Globalconfigura<onsforGit$ git config --global user.name "Your Name"$ git config --global user.email "[email protected]"
SetupRepository
• Ini<alizerepository
Thiscreatea.git directoryinyourdirectorythatcontainsalltheversioncontrolinforma<on.DONOTDELETE!!!
$ git init
$ ls -a. .. .git
AddExis<ngFilestoRepository
• TheGitrepositorycanbeini<alizedbeforeoraeeryoucreateanyfiles.Toversioncontrolexis<ngfiles,justaddthemtotherepository.
$ git add myplot.py
CheckStatusofRepository
$ git statusOn branch master
Initial commit
Changes to be committed: (use "git rm --cached <file>..." to unstage)
new file: myplot.py
Untracked files: (use "git add <file>..." to include in what will be committed)
myfigure.png
MakeIni<alCommit
• Nowwewanttopermanentlysavethechangestorepository,anac<oncalled“commi8ng”$ git commit –m "initial commit"
LeavingFilesOutofRepository
• Youdon’twanttoaddeveryfiletoyourrepository.Thegoodruleofthumbistoexcludefilesiftheyareaproductofyourcode.Examplesoffilestoexclude:– Imagefiles– PDFs– Compiledcode(including.oor.pycfiles)– Systemfiles(e.g.,.DS_Store)
AutomateExclusions• Toeasilyautomateexclusions,createa.gitignore file.
• Nowthesefileswon’tshowupas“untracked”inthegit status commandandcan’taccidentallygetaddedtotherepository
$ cat .gitignaore.DS_Store*.png*.pyc
$ git add .gitignore$ git commit –m "added .gitignore"
MakeChanges!
• Makechangestothefileandthencheckontherepository$ git statusOn branch masterChanges not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory)
modified: myplot.py
no changes added to commit (use "git add" and/or "git commit -a")
MakeChanges!
• Addandcommityourchanges
$ git add myplot.py$ git commit -m "increased frequency"[master 21e2dd2] increased frequency 1 file changed, 1 insertion(+), 1 deletion(-)
ReviewChanges
• Youcanchecktoseewhathasbeenmodifiedbeforeaddingfilesusinggit diff$ git diffdiff --git a/myplot.py b/myplot.pyindex 3c179cc..3eb9a45 100644--- a/myplot.py+++ b/myplot.py@@ -2,7 +2,7 @@ import matplotlib.pyplot as plt import numpy as np
t = np.arange(0.0, 2.0, 0.01)-s = np.sin(2*np.pi*t)+s = np.sin(4*np.pi*t)
plt.plot(t, s) plt.xlabel('time (s)')
ReviewChanges
• Youcanchecktoseewhathasbeenmodifiedbeforecommi8ngusinggit diff --staged$ git diff --stageddiff --git a/myplot.py b/myplot.pyindex 3c179cc..3eb9a45 100644--- a/myplot.py+++ b/myplot.py@@ -2,7 +2,7 @@ import matplotlib.pyplot as plt import numpy as np
t = np.arange(0.0, 2.0, 0.01)-s = np.sin(2*np.pi*t)+s = np.sin(4*np.pi*t)
plt.plot(t, s) plt.xlabel('time (s)')
Wri<ngaGoodCommitMessage• Thecommitmessageshouldbeahighlevelexplana<onofthechange– Don’tbetoobrief– Also,don’texactlyquotethechange
• Example:– Bad:“Changes”– Bad:“Changedline178inplot_bM_vs_t.py”– Beier:“Changecolorofpressurelinetored”
• Mostimportantques<on:Ifyouarelookingatthismessagein6months,isitgoingtomakesenseandbeuseful?
OtherUsefulCommands
• Renameormoveafileintherepository
• Deleteafilefromtherepository
$ git mv <old_filename> <new_filename>
$ git rm <filename>
Connec<ngYourRepositorytoBitbucket
1. Createrepositoryonyouronlineaccount2. Followincludedinstruc<onstogetyourlocal
repositoryconnectedtoyourremoterepository
3. Pushcommiiedchangestotheremoterepository…$ git commit -m "<message>"$ git push
CreateaNewRepositoryonBitbucket
CreateaNewRepositoryonBitbucket
CreateaNewRepositoryonBitbucket
FollowtheInstruc<ontoPush
PushFutureCommits
• Aeertheini<al“push”totheremoterepository,justremembertopushanynewcommitsandyouwillhaveeasyremotebackupsofyourwork!
…$ git commit -m "<message>"$ git push
RemoteRepositoryHosts Op<ons
• Bitbucket.org–unlimitedfreepublicandprivatereposwith.eduemailaddress
• github.com–unlimitedfreePUBLICrepos• git.yale.edu–freefullyfeaturedaccounts.OnlyavailableonYalenetworkorVPNandwithYalene<d
U<lizingYourRepository’sHistory
ReviewHistory
• Youcanseeahistoryofallrecentcommits– DetailedLog:
– SimplifiedLog
$ git log$ git log -1
$ git log --oneline$ git log --oneline --graph --decorate
CompareRevisions
• Youcancomparetworevisionstoseewhatchangesweremadewithgit diff$ git diff HEAD 0c7aa71diff --git a/myplot.py b/myplot.pyindex 3c179cc..3eb9a45 100644--- a/myplot.py+++ b/myplot.py@@ -2,7 +2,7 @@ import matplotlib.pyplot as plt import numpy as np
t = np.arange(0.0, 2.0, 0.01)-s = np.sin(2*np.pi*t)+s = np.sin(4*np.pi*t)
plt.plot(t, s) plt.xlabel('time (s)')
ReviewHistory
• TheinterfacesonBitbucketandGithubarealsogreatforexploringthecommithistoryandtrackingchanges
CheckoutPreviousCommits
CheckoutPreviousCommits
• Aeer,youhaveiden<fiedtherevisionyouneedtorevertto,“checkout”thatrevision
• Orjustaspecificfilefromthatrevision
Warning:Ifyoucheckoutfromanoldrevision,anyuncommiiedchangestotheprojectwillbelost.
$ git checkout <revision>
$ git checkout <revision> <filename>
ThrowawayAllNewChanges
• Revertyourworkingdirectorytothelastcommit
Warning:Anyuncommiiedchangestotheprojectwillbelost.
$ git reset --hard
Ge8ngYourCodeinaNewLoca<on
• Ifyouhavearemoterepository,youcan“clone”ittoanewloca<ontocon<nueyourwork(e.g.,copyingcodetothecluster,recoveringyourcodetoanewlaptop)
$ git clone https://[email protected]/kayleanelson/my_latest_work.git
Collabora<on
• Onceyourworkisinaremoterepository,itisveryeasytobeingtocollaboratewithothers– Githasasophis<catedsystemformanagingmul<plepeopleedi<ngthesamecodebasethrough“merging”
• UsageExamples– Mul<plecollaboratorsonacode– LaTeXpapers!
SharingYourRepository
BasicCollabora<veWorkflow
• Pulldownnewcommits• Makeyouredits• Addyourmodifiedfilesandcommit• Pushcommitstoremote
$ git pull…$ git add <files>$ git commit –m <message>$ git push
Merging
Conflicts
• Inevitably,youandyourcollaboratorwillcommitoverlappingchangestoafile.Thiswillcreatea“mergeconflict”.
ResolvingConflicts
• PullincommitsandOops!$ git pullAuto-merging myplot.pyCONFLICT (content): Merge conflict in myplot.pyAutomatic merge failed; fix conflicts and then commit the result.
ResolvingConflicts
• Gitmarkstheconflictedlineinthefile
• Manuallymergethecodeinatexteditorandcommitthechanges
$ cat myplot.pyimport matplotlib.pyplot as pltimport numpy as np
t = np.arange(0.0, 2.0, 0.01)<<<<<<< HEADs = np.sin(3*np.pi*t)=======s = np.sin(4*np.pi*t)>>>>>>> 7232b521f34cf3deed50f4d8aac6260616683ddf
UncommiiedConflicts
• Gitwillalsocomplainifyoupullinchangestoafileyouhavemodifiedbutnotcommiied.Youhavetwoop<ons.– UndothechangestothefilebacktolastcommiiedrevisionbycheckingitoutfromtheHEAD
– Commityourchangesandthenredothepull(andpoten<allymergethechanges,ifapplicable)
$ git checkout -- <filename>
Ques<ons?
Tosummarize,add3commandstoyourdailyworkflowforunlimitedundoandonlinebackupsofyourcode!
$ git add <files>$ git commit –m <message>$ git push
try.github.io
Evenmoreinforma<on:
• Greatindepthtutorialonallthingsgit:– hips://www.atlassian.com/git/tutorials
• SoewareCarpentry(thanksfortheimages!)– hips://swcarpentry.github.io/git-novice/01-basics/