About the go command - go.dev

文章推薦指數: 80 %
投票人數:10人

For example, the source code of the Google logging package glog is obtained by running ... We can install both with the " go get " subcommand: WhyGo GetStarted Docs Packages Play Blog Aboutthegocommand TheGodistributionincludesacommand,named "go",that automatesthedownloading,building,installation,andtestingofGopackages andcommands.Thisdocumenttalksaboutwhywewroteanewcommand,whatit is,whatit'snot,andhowtouseit. Motivation YoumighthaveseenearlyGotalksinwhichRobPikejokesthattheidea forGoarosewhilewaitingforalargeGoogleservertocompile.That reallywasthemotivationforGo:tobuildalanguagethatworkedwell forbuildingthelargesoftwarethatGooglewritesandruns.Itwas clearfromthestartthatsuchalanguagemustprovideawayto expressdependenciesbetweencodelibrariesclearly,hencethepackage groupingandtheexplicitimportblocks.Itwasalsoclearfromthe startthatyoumightwantarbitrarysyntaxfordescribingthecode beingimported;thisiswhyimportpathsarestringliterals. AnexplicitgoalforGofromthebeginningwastobeabletobuildGo codeusingonlytheinformationfoundinthesourceitself,not needingtowriteamakefileoroneofthemanymodernreplacementsfor makefiles.IfGoneededaconfigurationfiletoexplainhowtobuild yourprogram,thenGowouldhavefailed. Atfirst,therewasnoGocompiler,andtheinitialdevelopment focusedonbuildingoneandthenbuildinglibrariesforit.For expedience,wepostponedtheautomationofbuildingGocodebyusing makeandwritingmakefiles.Whencompilingasinglepackageinvolved multipleinvocationsoftheGocompiler,weevenusedaprogramto writethemakefilesforus.Youcanfinditifyoudigthroughthe repositoryhistory. Thepurposeofthenewgocommandisourreturntothisideal,thatGo programsshouldcompilewithoutconfigurationoradditionalefforton thepartofthedeveloperbeyondwritingthenecessaryimport statements. Configurationversusconvention Thewaytoachievethesimplicityofaconfiguration-freesystemisto establishconventions.Thesystemworksonlytotheextentthatthoseconventions arefollowed.WhenwefirstlaunchedGo,manypeoplepublishedpackagesthat hadtobeinstalledincertainplaces,undercertainnames,usingcertainbuild tools,inordertobeused.That'sunderstandable:that'sthewayitworksin mostotherlanguages.Overthelastfewyearsweconsistentlyremindedpeople aboutthegoinstallcommand (nowreplacedbygoget) anditsconventions:first,thattheimportpathisderivedinaknownwayfrom theURLofthesourcecode;second,thattheplacetostorethesourcesin thelocalfilesystemisderivedinaknownwayfromtheimportpath;third, thateachdirectoryinasourcetreecorrespondstoasinglepackage;and fourth,thatthepackageisbuiltusingonlyinformationinthesourcecode. Today,thevastmajorityofpackagesfollowtheseconventions. TheGoecosystemissimplerandmorepowerfulasaresult. Wereceivedmanyrequeststoallowamakefileinapackagedirectoryto providejustalittleextraconfigurationbeyondwhat'sinthesourcecode. Butthatwouldhaveintroducednewrules.Becausewedidnotaccedetosuch requests,wewereabletowritethegocommandandeliminateouruseofmake oranyotherbuildsystem. Itisimportanttounderstandthatthegocommandisnotageneral buildtool.Itcannotbeconfiguredanditdoesnotattempttobuild anythingbutGopackages.Theseareimportantsimplifying assumptions:theysimplifynotonlytheimplementationbutalso,more important,theuseofthetoolitself. Go'sconventions Thegocommandrequiresthatcodeadherestoafewkey, well-establishedconventions. First,theimportpathisderivedinaknownwayfromtheURLofthe sourcecode.ForBitbucket,GitHub,GoogleCode,andLaunchpad,the rootdirectoryoftherepositoryisidentifiedbytherepository's mainURL,withoutthehttps://prefix.Subdirectoriesarenamedby addingtothatpath. Forexample,thesourcecodeoftheGoogleloggingpackageglog isobtainedbyrunning gitclonehttps://github.com/golang/glog andthustheimportpathofthe glog packageis"github.com/golang/glog". Thesepathsareonthelongside,butinexchangewegetan automaticallymanagednamespaceforimportpathsandtheabilityfor atoollikethegocommandtolookatanunfamiliarimportpathand deducewheretoobtainthesourcecode. Second,theplacetostoresourcesinthelocalfilesystemisderived inaknownwayfromtheimportpath,specifically $GOPATH/src/. Ifunset,$GOPATHdefaultstoasubdirectory namedgointheuser'shomedirectory. If$GOPATHissettoalistofpaths,thegocommandtries

/src/foreachofthedirectoriesin thatlist. Eachofthosetreescontains,byconvention,atop-leveldirectorynamed "bin",forholdingcompiledexecutables,andatop-leveldirectory named"pkg",forholdingcompiledpackagesthatcanbeimported, andthe"src"directory,forholdingpackagesourcefiles. Imposingthisstructureletsuskeepeachofthesedirectorytrees self-contained:thecompiledformandthesourcesarealwaysneareach other. Thesenamingconventionsalsoletusworkinthereversedirection, fromadirectorynametoitsimportpath.Thismappingisimportant formanyofthegocommand'ssubcommands,aswe'llseebelow. Third,eachdirectoryinasourcetreecorrespondstoasingle package.Byrestrictingadirectorytoasinglepackage,wedon'thave tocreatehybridimportpathsthatspecifyfirstthedirectoryand thenthepackagewithinthatdirectory.Also,mostfilemanagement toolsandUIsworkondirectoriesasfundamentalunits.Tyingthe fundamentalGounit—thepackage—tofilesystemstructuremeans thatfilesystemtoolsbecomeGopackagetools.Copying,moving,or deletingapackagecorrespondstocopying,moving,ordeletinga directory. Fourth,eachpackageisbuiltusingonlytheinformationpresentin thesourcefiles.Thismakesitmuchmorelikelythatthetoolwill beabletoadapttochangingbuildenvironmentsandconditions.For example,ifweallowedextraconfigurationsuchascompilerflagsor commandlinerecipes,thenthatconfigurationwouldneedtobeupdated eachtimethebuildtoolschanged;itwouldalsobeinherentlytied totheuseofaspecifictoolchain. Gettingstartedwiththegocommand Finally,aquicktourofhowtousethegocommand. Asmentionedabove,thedefault$GOPATHonUnixis$HOME/go. We'llstoreourprogramsthere. Touseadifferentlocation,youcanset$GOPATH; seeHowtoWriteGoCodefordetails. Wefirstaddsomesourcecode.Supposewewanttouse theindexinglibraryfromthecodesearchprojectalongwithaleft-leaning red-blacktree.Wecaninstallbothwiththe"goget" subcommand: $gogetgithub.com/google/codesearch/index $gogetgithub.com/petar/GoLLRB/llrb $ Bothoftheseprojectsarenowdownloadedandinstalledinto$HOME/go, whichcontainsthetwodirectories src/github.com/google/codesearch/index/and src/github.com/petar/GoLLRB/llrb/,alongwiththecompiled packages(inpkg/)forthoselibrariesandtheirdependencies. Becauseweusedversioncontrolsystems(MercurialandGit)tocheck outthesources,thesourcetreealsocontainstheotherfilesinthe correspondingrepositories,suchasrelatedpackages.The"golist" subcommandliststheimportpathscorrespondingtoitsarguments,and thepattern"./..."meansstartinthecurrentdirectory ("./")andfindallpackagesbelowthatdirectory ("..."): $cd$HOME/go/src $golist./... github.com/google/codesearch/cmd/cgrep github.com/google/codesearch/cmd/cindex github.com/google/codesearch/cmd/csearch github.com/google/codesearch/index github.com/google/codesearch/regexp github.com/google/codesearch/sparse github.com/petar/GoLLRB/example github.com/petar/GoLLRB/llrb $ Wecanalsotestthosepackages: $gotest./... ? github.com/google/codesearch/cmd/cgrep [notestfiles] ? github.com/google/codesearch/cmd/cindex [notestfiles] ? github.com/google/codesearch/cmd/csearch [notestfiles] ok github.com/google/codesearch/index 0.203s ok github.com/google/codesearch/regexp 0.017s ? github.com/google/codesearch/sparse [notestfiles] ?github.com/petar/GoLLRB/example[notestfiles] okgithub.com/petar/GoLLRB/llrb0.231s $ Ifagosubcommandisinvokedwithnopathslisted,itoperatesonthe currentdirectory: $cdgithub.com/google/codesearch/regexp $golist github.com/google/codesearch/regexp $gotest-v ===RUNTestNstateEnc ---PASS:TestNstateEnc(0.00s) ===RUNTestMatch ---PASS:TestMatch(0.00s) ===RUNTestGrep ---PASS:TestGrep(0.00s) PASS ok github.com/google/codesearch/regexp 0.018s $goinstall $ That"goinstall"subcommandinstallsthelatestcopyofthe packageintothepkgdirectory.Becausethegocommandcananalyzethe dependencygraph,"goinstall"alsoinstallsanypackagesthat thispackageimportsbutthatareoutofdate,recursively. Noticethat"goinstall"wasabletodeterminethenameofthe importpathforthepackageinthecurrentdirectory,becauseoftheconvention fordirectorynaming.Itwouldbealittlemoreconvenientifwecouldpick thenameofthedirectorywherewekeptsourcecode,andweprobablywouldn't picksuchalongname,butthatabilitywouldrequireadditionalconfiguration andcomplexityinthetool.Typinganextradirectorynameortwoisasmall pricetopayfortheincreasedsimplicityandpower. Limitations Asmentionedabove,thegocommandisnotageneral-purposebuild tool. Inparticular,itdoesnothaveanyfacilityforgeneratingGo sourcefilesduringabuild,althoughitdoesprovide go generate, whichcanautomatethecreationofGofilesbeforethebuild. Formoreadvancedbuildsetups,youmayneedtowritea makefile(oraconfigurationfileforthebuildtoolofyourchoice) torunwhatevertoolcreatestheGofilesandthencheckthosegeneratedsourcefiles intoyourrepository.Thisismoreworkforyou,thepackageauthor, butitissignificantlylessworkforyourusers,whocanuse "goget"withoutneedingtoobtainandbuild anyadditionaltools. Moreinformation Formoreinformation,readHowtoWriteGoCode andseethegocommanddocumentation.



請為這篇文章評分?