cons 220 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829
  1. #!/usr/bin/env perl
  2. # NOTE: Cons intentionally does not use the "perl -w" option or
  3. # "use strict." Because Cons "configuration files" are actually
  4. # Perl scripts, enabling those restrictions here would force them
  5. # on every user's config files, wanted or not. Would users write
  6. # "better" Construct and Conscript files if we forced "use strict"
  7. # on them? Probably. But we want people to use Cons to get work
  8. # done, not force everyone to become a Perl guru to use it, so we
  9. # don't insist.
  10. #
  11. # That said, Cons' code is both "perl -w" and "use strict" clean.
  12. # Regression tests keep the code honest by checking for warnings
  13. # and "use strict" failures.
  14. use vars qw( $CVS_id $CVS_ver $ver_num $ver_rev $version );
  15. $CVS_id = 'Id';
  16. $CVS_ver = (split(/\s+/, $CVS_id))[2];
  17. $ver_num = "2.3";
  18. $ver_rev = ".1";
  19. $version = "This is Cons $ver_num$ver_rev ($CVS_id)\n";
  20. # Cons: A Software Construction Tool.
  21. # Copyright (c) 1996-2001 Free Software Foundation, Inc.
  22. #
  23. # This program is free software; you can redistribute it and/or modify
  24. # it under the terms of the GNU General Public License as published by
  25. # the Free Software Foundation; either version 2 of the License, or
  26. # (at your option) any later version.
  27. #
  28. # This program is distributed in the hope that it will be useful,
  29. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. # GNU General Public License for more details.
  32. #
  33. # You should have received a copy of the GNU General Public License
  34. # along with this program; see the file COPYING. If not, write to
  35. # the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  36. # Boston, MA 02111-1307, USA.
  37. require 5.003;
  38. # See the NOTE above about why Cons doesn't "use strict".
  39. use integer;
  40. use Cwd;
  41. use File::Copy;
  42. use vars qw( $_WIN32 $_a $_exe $_o $_so );
  43. #------------------------------------------------------------------
  44. # Determine if running on win32 platform - either Windows NT or 95
  45. #------------------------------------------------------------------
  46. use vars qw( $PATH_SEPARATOR $iswin32 $_WIN32 $usage $indent @targets );
  47. BEGIN {
  48. use Config;
  49. # if the version is 5.003, we can check $^O
  50. if ($] < 5.003) {
  51. eval("require Win32");
  52. $_WIN32 = (!$@);
  53. } else {
  54. $_WIN32 = ($^O eq "MSWin32") ? 1 : 0;
  55. }
  56. # Fetch the PATH separator from Config;
  57. # provide our old defaults in case it's not set.
  58. $PATH_SEPARATOR = $Config{path_sep};
  59. $PATH_SEPARATOR = $_WIN32 ? ';' : ':' if ! defined $PATH_SEPARATOR;
  60. # Fetch file suffixes from Config,
  61. # accomodating differences in the Config variables
  62. # used by different Perl versions.
  63. $_exe = $Config{_exe};
  64. $_exe = $Config{exe_ext} if ! defined $_exe;
  65. $_exe = $_WIN32 ? '.exe' : '' if ! defined $_exe;
  66. $_o = $Config{_o};
  67. $_o = $Config{obj_ext} if ! defined $_o;
  68. $_o = $_WIN32 ? '.obj' : '.o' if ! defined $_o;
  69. $_a = $Config{_a};
  70. $_a = $Config{lib_ext} if ! defined $_a;
  71. $_a = $_WIN32 ? '.lib' : '.a' if ! defined $_a;
  72. $_so = ".$Config{so}";
  73. $_so = $_WIN32 ? '.dll' : '.so' if ! defined $_so;
  74. }
  75. # Flush stdout each time.
  76. $| = 1;
  77. # Seed random number generator.
  78. srand(time . $$); # this works better than time ^ $$ in perlfunc manpage.
  79. $usage = q(
  80. Usage: cons <arguments> -- <construct-args>
  81. Arguments can be any of the following, in any order:
  82. <targets> Build the specified targets. If <target> is a directory
  83. recursively build everything within that directory.
  84. +<pattern> Limit the cons scripts considered to just those that
  85. match <pattern>. Multiple + arguments are accepted.
  86. <name>=<val> Sets <name> to value <val> in the ARG hash passed to the
  87. top-level Construct file.
  88. -cc Show command that would have been executed, when
  89. retrieving from cache. No indication that the file
  90. has been retrieved is given; this is useful for
  91. generating build logs that can be compared with
  92. real build logs.
  93. -cd Disable all caching. Do not retrieve from cache nor
  94. flush to cache.
  95. -cr Build dependencies in random order. This is useful when
  96. building multiple similar trees with caching enabled.
  97. -cs Synchronize existing build targets that are found to be
  98. up-to-date with cache. This is useful if caching has
  99. been disabled with -cc or just recently enabled with
  100. UseCache.
  101. -d Enable dependency debugging.
  102. -f <file> Use the specified file instead of "Construct" (but first
  103. change to containing directory of <file>).
  104. -h Show a help message local to the current build if
  105. one such is defined, and exit.
  106. -k Keep going as far as possible after errors.
  107. -o <file> Read override file <file>.
  108. -p Show construction products in specified trees.
  109. -pa Show construction products and associated actions.
  110. -pw Show products and where they are defined.
  111. -q Be quiet; multiple -q flags increase quietness level:
  112. 1: quiet about Installing and Removing targets
  113. 2: quiet about build commands, up-to-date targets
  114. -r Remove construction products associated with <targets>
  115. -R <repos> Search for files in <repos>. Multiple -R <repos>
  116. directories are searched in the order specified.
  117. -S <pkg> Use package sig::<pkg> to calculate file signatures.
  118. Currently supported values are "md5" for MD5
  119. signatures (the default) and "md5::debug" for MD5
  120. signature debug information.
  121. -t Traverse up the directory hierarchy looking for a
  122. Construct file, if none exists in the current directory.
  123. (Targets will be modified to be relative to the
  124. Construct file.)
  125. -v Show cons version and continue processing.
  126. -V Show cons version and exit.
  127. -wf <file> Write all filenames considered into <file>.
  128. -x Show this message and exit.
  129. Please report any suggestions through the cons-discuss@gnu.org mailing
  130. list.
  131. To subscribe, send mail to cons-discuss-request@gnu.org with body
  132. 'subscribe'.
  133. If you find a bug, please report it through the bug-cons@gnu.org
  134. mailing list.
  135. Information about CONS can be obtained from the official cons web site
  136. http://www.dsmit.com/cons/ or its mirrors (listed there).
  137. The cons maintainers can be contacted by email at cons-maintainers@gnu.org
  138. User documentation of cons is contained in cons and can be obtained
  139. by doing 'perldoc /path/to/cons'.
  140. );
  141. # Simplify program name, if it is a path.
  142. {
  143. my ($vol, $dir, $file) = File::Spec->splitpath(File::Spec->canonpath($0));
  144. $0 = $file;
  145. }
  146. # Default parameters.
  147. $param::topfile = 'Construct'; # Top-level construction file.
  148. $param::install = 1; # Show installations
  149. $param::build = 1; # Build targets
  150. ### $param::show = 1; # Show building of targets.
  151. $param::sigpro = 'md5'; # Signature protocol.
  152. $param::depfile = ''; # Write all deps out to this file
  153. $param::salt = ''; # Salt derived file signatures with this.
  154. $param::sourcesig = ['*' => 'content'];# Source file signature calculation
  155. $param::rep_sig_times_ok = 1; # Repository .consign times are in sync
  156. # w/files.
  157. $param::conscript_chdir = 0; # Change dir to Conscript directory
  158. $param::quiet = 0; # should we show the command being executed.
  159. @param::defaults = ();
  160. #
  161. $indent = '';
  162. # Display a command while executing or otherwise. This
  163. # should be called by command builder action methods.
  164. sub showcom {
  165. print($indent . $_[0] . "\n") if ($param::quiet < 2);
  166. }
  167. # Default environment.
  168. # This contains only the completely platform-independent information
  169. # we can figure out. Platform-specific information (UNIX, Win32)
  170. # gets added below.
  171. @param::base = (
  172. 'SIGNATURE' => [ '*' => 'build' ],
  173. 'SUFEXE' => $_exe, # '' on UNIX systems
  174. 'SUFLIB' => $_a, # '.a' on UNIX systems
  175. 'SUFLIBS' => "$_so:$_a", # '.so:.a' on UNIX
  176. 'SUFOBJ' => $_o, # '.o' on UNIX systems
  177. 'SUFMAP' => {
  178. '.c' => 'build::command::cc',
  179. '.s' => 'build::command::cc',
  180. '.S' => 'build::command::cc',
  181. '.C' => 'build::command::cxx',
  182. '.cc' => 'build::command::cxx',
  183. '.cxx'=> 'build::command::cxx',
  184. '.cpp'=> 'build::command::cxx',
  185. '.c++'=> 'build::command::cxx',
  186. '.C++'=> 'build::command::cxx',
  187. },
  188. 'PERL' => $^X,
  189. );
  190. %param::rulesets =
  191. (
  192. # Defaults for Win32.
  193. # Defined for VC++ 6.0 by Greg Spencer <greg_spencer@acm.org>
  194. # Your mileage may vary.
  195. 'msvc' => [
  196. 'CC' => 'cl',
  197. 'CFLAGS' => '/nologo',
  198. 'CCCOM' => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
  199. 'CXX' => '%CC',
  200. 'CXXFLAGS' => '%CFLAGS',
  201. 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
  202. 'INCDIRPREFIX' => '/I',
  203. 'INCDIRSUFFIX' => '',
  204. 'LINK' => 'link',
  205. 'LINKCOM' => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
  206. 'LINKMODULECOM' => '%LD /r /o %> %<',
  207. 'LIBDIRPREFIX' => '/LIBPATH:',
  208. 'LIBDIRSUFFIX' => '',
  209. 'AR' => 'lib',
  210. 'ARFLAGS' => '/nologo ',
  211. 'ARCOM' => "%AR %ARFLAGS /out:%> %<",
  212. 'RANLIB' => '',
  213. 'LD' => 'link',
  214. 'LDFLAGS' => '/nologo ',
  215. 'PREFLIB' => '',
  216. ],
  217. # Defaults for a typical (?) UNIX platform.
  218. # Your mileage may vary.
  219. 'unix' => [
  220. 'CC' => 'cc',
  221. 'CFLAGS' => '',
  222. 'CCCOM' => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
  223. 'CXX' => '%CC',
  224. 'CXXFLAGS' => '%CFLAGS',
  225. 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
  226. 'INCDIRPREFIX' => '-I',
  227. 'INCDIRSUFFIX' => '',
  228. 'LINK' => '%CXX',
  229. 'LINKCOM' => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
  230. 'LINKMODULECOM' => '%LD -r -o %> %<',
  231. 'LIBDIRPREFIX' => '-L',
  232. 'LIBDIRSUFFIX' => '',
  233. 'AR' => 'ar',
  234. 'ARFLAGS' => 'r', # rs?
  235. 'ARCOM' => ['%AR %ARFLAGS %> %<', '%RANLIB %>'],
  236. 'RANLIB' => 'ranlib',
  237. 'AS' => 'as',
  238. 'ASFLAGS' => '',
  239. 'ASCOM' => '%AS %ASFLAGS %< -o %>',
  240. 'LD' => 'ld',
  241. 'LDFLAGS' => '',
  242. 'PREFLIB' => 'lib',
  243. 'ENV' => { 'PATH' => '/bin:/usr/bin' },
  244. ],
  245. );
  246. # Set the rules based on the platform.
  247. script::DefaultRules(script::RuleSet($_WIN32 ? 'msvc' : 'unix'));
  248. # Handle command line arguments.
  249. while (@ARGV) {
  250. $_ = shift @ARGV;
  251. last if /^--$/; # Argument passing to Construct.
  252. &option, next if s/^-//;
  253. push (@param::include, $_), next if s/^\+//;
  254. &equate, next if /=/;
  255. push (@targets, $_), next;
  256. }
  257. sub option {
  258. my %opt = (
  259. 'cc' => sub { $param::cachecom = 1; },
  260. 'cd' => sub { $param::cachedisable = 1; },
  261. 'cr' => sub { $param::random = 1; },
  262. 'cs' => sub { $param::cachesync = 1; },
  263. 'd' => sub { $param::depends = 1; },
  264. 'h' => sub { $param::localhelp = 1; },
  265. 'k' => sub { $param::kflag = 1; },
  266. 'p' => sub { $param::pflag = 1;
  267. $param::build = 0; },
  268. 'pa' => sub { $param::pflag = 1;
  269. $param::aflag = 1;
  270. $indent = "... ";
  271. $param::build = 0; },
  272. 'pw' => sub { $param::pflag = 1;
  273. $param::wflag = 1;
  274. $param::build = 0; },
  275. 'q' => sub { $param::quiet++; },
  276. 'r' => sub { $param::rflag = 1;
  277. $param::build = 0; },
  278. 't' => sub { $param::traverse = 1; },
  279. 'v' => sub { print($version); },
  280. 'V' => sub { print($version), exit(0); },
  281. 'x' => sub { print($usage), exit 0; },
  282. );
  283. my %opt_arg = (
  284. 'f' => sub { $param::topfile = $_[0]; },
  285. 'o' => sub { $param::overfile = $_[0]; },
  286. 'R' => sub { script::Repository($_[0]); },
  287. 'S' => sub { $param::sigpro = $_[0]; },
  288. 'wf' => sub { $param::depfile = $_[0]; },
  289. );
  290. if (defined $opt{$_}) {
  291. &{$opt{$_}}();
  292. return;
  293. }
  294. while ($_) {
  295. $_ =~ m/(.)(.*)/;
  296. if (defined $opt{$1}) {
  297. &{$opt{$1}}();
  298. $_ = $2;
  299. next;
  300. }
  301. if (defined $opt_arg{$1}) {
  302. if (! $2) {
  303. $_ = shift @ARGV;
  304. die("$0: -$1 option requires an argument.\n") if ! $_;
  305. }
  306. &{$opt_arg{$1}}($2 || $_);
  307. return;
  308. }
  309. $_ =~ m/(..)(.*)/;
  310. if (defined $opt_arg{$1}) {
  311. if (! $2) {
  312. $_ = shift @ARGV;
  313. die("$0: -$1 option requires an argument.\n") if ! $_;
  314. }
  315. &{$opt_arg{$1}}($2 || $_);
  316. return;
  317. }
  318. if ($_) {
  319. die qq($0: unrecognized option "-$_". Use -x for a usage message.\n);
  320. }
  321. }
  322. }
  323. # Process an equate argument (var=val).
  324. sub equate {
  325. my($var, $val) = /([^=]*)=(.*)/;
  326. $script::ARG{$var} = $val;
  327. }
  328. # Define file signature protocol.
  329. 'sig'->select($param::sigpro);
  330. # Cleanup after an interrupt.
  331. $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub {
  332. $SIG{PIPE} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
  333. $SIG{HUP} = $SIG{INT} if ! $main::_WIN32;
  334. warn("\n$0: killed\n");
  335. # Call this first, to make sure that this processing
  336. # occurs even if a child process does not die (and we
  337. # hang on the wait).
  338. sig::hash::END();
  339. wait();
  340. exit(1);
  341. };
  342. $SIG{HUP} = $SIG{INT} if ! $main::_WIN32;
  343. # Cleanup after a broken pipe (someone piped our stdout?)
  344. $SIG{PIPE} = sub {
  345. $SIG{PIPE} = $SIG{HUP} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
  346. warn("\n$0: broken pipe\n");
  347. sig::hash::END();
  348. wait();
  349. exit(1);
  350. };
  351. if ($param::depfile) {
  352. open (main::DEPFILE, ">".$param::depfile) ||
  353. die ("$0: couldn't open $param::depfile ($!)\n");
  354. }
  355. # If the supplied top-level Conscript file is not in the
  356. # current directory, then change to that directory.
  357. {
  358. my ($vol, $dir, $file) =
  359. File::Spec->splitpath(File::Spec->canonpath($param::topfile));
  360. if ($vol || $dir) {
  361. my($cd) = File::Spec->catpath($vol, $dir, undef);
  362. chdir($cd) || die("$0: couldn't change to directory $cd ($!)\n");
  363. $param::topfile = $file;
  364. }
  365. }
  366. # Walk up the directory hierarchy looking for a Conscript file (if -t set).
  367. my($target_top);
  368. my(@targetdir) = ();
  369. if ($param::traverse && ! -f $param::topfile) {
  370. my($vol, $dirs, $file) = File::Spec->splitpath(cwd());
  371. my(@dirs) = (File::Spec->splitdir($dirs), $file);
  372. while (! -f File::Spec->catpath($vol, File::Spec->catdir(@dirs),
  373. $param::topfile)) {
  374. die("$0: unable to find $param::topfile.\n") if ! @dirs;
  375. unshift(@targetdir, pop(@dirs));
  376. }
  377. my($cwd) = File::Spec->catpath($vol, File::Spec->catdir(@dirs), '');
  378. print "$0: Entering directory `$cwd'\n";
  379. chdir($cwd);
  380. @targets = map {File::Spec->catdir(@targetdir, $_)} @targets;
  381. }
  382. # Set up $dir::top and $dir::cwd, now that we are in the right directory.
  383. dir::init();
  384. #
  385. if (@targetdir) {
  386. $target_top = $dir::top->lookupdir(File::Spec->catdir(@targetdir));
  387. }
  388. # Now handle override file.
  389. package override;
  390. if ($param::overfile) {
  391. my($ov) = $param::overfile;
  392. die qq($0: can\'t read override file "$ov" ($!)\n) if ! -f $ov; #'
  393. do $ov;
  394. if ($@) {
  395. chop($@);
  396. die qq($0: errors in override file "$ov" ($@)\n);
  397. }
  398. }
  399. # Provide this to user to setup override patterns.
  400. sub Override {
  401. my($re, @env) = @_;
  402. return if $param::overrides{$re}; # if identical, first will win.
  403. $param::overrides = 1;
  404. $param::overrides{$re} = \@env;
  405. push(@param::overrides, $re);
  406. }
  407. package main;
  408. use vars qw( %priority $errors );
  409. # Check script inclusion regexps
  410. my $re;
  411. for $re (@param::include) {
  412. if (! defined eval {"" =~ /$re/}) {
  413. my($err) = $@;
  414. $err =~ s/in regexp at .*$//;
  415. die("$0: error in regexp $err");
  416. }
  417. }
  418. # Read the top-level construct file and its included scripts.
  419. doscripts($param::topfile);
  420. # Status priorities. This lets us aggregate status for directories
  421. # and print an appropriate message (at the top-level).
  422. %priority =
  423. ('none' => 1, 'handled' => 2, 'built' => 3, 'unknown' => 4, 'errors' => 5);
  424. # If no targets were specified, supply default targets (if any).
  425. @targets = @param::default_targets if ! @targets;
  426. $errors = 0;
  427. # Build the supplied target patterns.
  428. my $tgt;
  429. for $tgt (map($dir::top->lookup($_), @targets)) {
  430. if ($target_top && ! $tgt->is_under($target_top)) {
  431. # A -t option was used, and this target is not underneath
  432. # the directory where we were invoked via -t.
  433. # If the target is a directory and the -t directory
  434. # is underneath it, then build the -t directory.
  435. if (ref $tgt ne "dir" || ! $target_top->is_under($tgt)) {
  436. next;
  437. }
  438. $tgt = $target_top;
  439. }
  440. buildtoptarget($tgt);
  441. }
  442. exit 0 + ($errors != 0);
  443. sub buildtoptarget {
  444. my($tgt) = @_;
  445. return if ! $tgt;
  446. my($status) = buildtarget($tgt);
  447. if ($status ne 'built') {
  448. my($path) = $tgt->path;
  449. if ($status eq "errors") {
  450. print qq($0: "$path" not remade because of errors.\n);
  451. $errors++;
  452. } elsif ($status eq "handled") {
  453. print qq($0: "$path" is up-to-date.\n) if ($param::quiet < 2);
  454. } elsif ($status eq "unknown") {
  455. # cons error already reported.
  456. $errors++;
  457. } elsif ($status eq "none") {
  458. # search for targets that may be linked to the given path.
  459. my @linked = dir::linked_targets($tgt) if $target_top;
  460. if (@linked) {
  461. my @names = map($_->path, @linked);
  462. print "Linked targets: @names\n" if ($param::quiet < 1);
  463. map(buildtoptarget($_), @linked);
  464. } else {
  465. print qq($0: nothing to be built in "$path".\n)
  466. if $param::build && ($param::quiet < 2);
  467. }
  468. } else {
  469. print qq($0: don\'t know how to construct "$path".\n); #'
  470. $errors++;
  471. }
  472. }
  473. }
  474. # Build the supplied target directory or files. Return aggregated status.
  475. sub buildtarget {
  476. my($tgt) = @_;
  477. if (ref($tgt) eq "dir") {
  478. my($result) = "none";
  479. my($priority) = $priority{$result};
  480. if (exists $tgt->{member}) {
  481. my($members) = $tgt->{member};
  482. my $entry;
  483. for $entry (sort keys %$members) {
  484. next if $entry eq $dir::CURDIR || $entry eq $dir::UPDIR;
  485. my($tgt) = $members->{$entry};
  486. next if ref($tgt) ne "dir" && !exists($tgt->{builder});
  487. my($stat) = buildtarget($members->{$entry});
  488. my($pri) = $priority{$stat};
  489. if ($pri > $priority) {
  490. $priority = $pri;
  491. $result = $stat;
  492. }
  493. }
  494. }
  495. return $result;
  496. }
  497. if ($param::depends) {
  498. my($path) = $tgt->path;
  499. if ($tgt->{builder}) {
  500. my(@dep) = (@{$tgt->{dep}}, @{$tgt->{sources}});
  501. my($dep) = join(' ',map($_->path, @dep));
  502. print("Target $path: $dep\n");
  503. } else {
  504. print("Target $path: not a derived file\n");
  505. }
  506. }
  507. if ($param::build) {
  508. return build $tgt;
  509. } elsif ($param::pflag || $param::wflag || $param::aflag) {
  510. if ($tgt->{builder}) {
  511. if ($param::wflag) {
  512. print qq(${\$tgt->path}: $tgt->{script}\n);
  513. } elsif ($param::pflag) {
  514. print qq(${\$tgt->path}:\n) if $param::aflag;
  515. print qq(${\$tgt->path}\n) if !$param::aflag;
  516. }
  517. if ($param::aflag) {
  518. $tgt->{builder}->action($tgt);
  519. }
  520. }
  521. } elsif ($param::rflag && $tgt->{builder}) {
  522. my($path) = $tgt->path;
  523. if (-f $path) {
  524. if (unlink($path)) {
  525. print("Removed $path\n") if ($param::quiet < 1);
  526. } else {
  527. warn("$0: couldn't remove $path\n");
  528. }
  529. }
  530. }
  531. return "none";
  532. }
  533. package NameSpace;
  534. # Return a hash that maps the name of symbols in a namespace to an
  535. # array of refs for all types for which the name has a defined value.
  536. # A list of symbols may be specified; default is all symbols in the
  537. # name space.
  538. sub save {
  539. my $package = shift;
  540. my(%namerefs, $var, $type);
  541. no strict 'refs';
  542. @_ = keys %{$package."::"} if ! @_;
  543. foreach $var (@_) {
  544. $namerefs{$var} = [];
  545. my $fqvar = $package."::".$var;
  546. # If the scalar for this variable name doesn't already
  547. # exist, *foo{SCALAR} will autovivify the reference
  548. # instead of returning undef, so unlike the other types,
  549. # we have to dereference to find out if it exists.
  550. push(@{$namerefs{$var}}, *{$fqvar}{SCALAR})
  551. if defined ${*{$fqvar}{SCALAR}};
  552. foreach $type (qw(ARRAY HASH CODE IO)) {
  553. push(@{$namerefs{$var}}, *{$fqvar}{$type})
  554. if defined *{$fqvar}{$type};
  555. }
  556. }
  557. return \%namerefs;
  558. }
  559. # Remove the specified symbols from the namespace.
  560. # Default is to remove all.
  561. sub remove {
  562. my $package = shift;
  563. my(%namerefs, $var);
  564. no strict 'refs';
  565. @_ = keys %{$package."::"} if ! @_;
  566. foreach $var (@_) {
  567. delete ${$package."::"}{$var};
  568. }
  569. }
  570. # Restore values to symbols specified in a hash as returned
  571. # by NameSpace::save.
  572. sub restore {
  573. my($package, $namerefs) = @_;
  574. my($var, $ref);
  575. no strict 'refs';
  576. foreach $var (keys %$namerefs) {
  577. my $fqvar = $package."::".$var;
  578. foreach $ref (@{$namerefs->{$var}}) {
  579. *{$fqvar} = $ref;
  580. }
  581. }
  582. }
  583. # Support for "building" scripts, importing and exporting variables.
  584. # With the exception of the top-level routine here (invoked from the
  585. # main package by cons), these are all invoked by user scripts.
  586. package script;
  587. use vars qw( $ARG $caller_dir_path %special_var );
  588. BEGIN {
  589. # We can't Export or Import the following variables because Perl always
  590. # treats them as part of the "main::" package (see perlvar(1)).
  591. %special_var = map {$_ => 1} qw(ENV INC ARGV ARGVOUT SIG
  592. STDIN STDOUT STDERR);
  593. }
  594. # This is called from main to interpret/run the top-level Construct
  595. # file, passed in as the single argument.
  596. sub main::doscripts {
  597. my($script) = @_;
  598. Build($script);
  599. # Now set up the includes/excludes (after the Construct file is read).
  600. $param::include = join('|', @param::include);
  601. # Save the original variable names from the script package.
  602. # These will stay intact, but any other "script::" variables
  603. # defined in a Conscript file will get saved, deleted,
  604. # and (when necessary) restored.
  605. my(%orig_script_var) = map {$_ => 1} keys %script::;
  606. $caller_dir_path = undef;
  607. my $cwd = Cwd::cwd();
  608. my(@scripts) = pop(@priv::scripts);
  609. while ($priv::self = shift(@scripts)) {
  610. my($path) = $priv::self->{script}->rsrcpath;
  611. if (-f $path) {
  612. $dir::cwd = $priv::self->{script}->{dir};
  613. # Handle chdir to the Conscript file directory, if necessary.
  614. my ($vol, $dir, $file);
  615. if ($param::conscript_chdir) {
  616. ($vol, $dir, $file) =
  617. File::Spec->splitpath(File::Spec->canonpath($path));
  618. if ($vol ne '' || $dir ne '') {
  619. $caller_dir_path = File::Spec->catpath($vol, $dir, undef);
  620. chdir($caller_dir_path) ||
  621. die "Could not chdir to $caller_dir_path: $!\n";
  622. }
  623. } else {
  624. $file = $path;
  625. }
  626. # Actually process the Conscript file.
  627. do $file;
  628. # Save any variables defined by the Conscript file
  629. # so we can restore them later, if needed;
  630. # then delete them from the script:: namespace.
  631. my(@del) = grep(! $orig_script_var{$_}, keys %script::);
  632. if (@del) {
  633. $priv::self->{script}->{pkgvars} = NameSpace::save('script',
  634. @del);
  635. NameSpace::remove('script', @del);
  636. }
  637. if ($caller_dir_path) {
  638. chdir($cwd);
  639. $caller_dir_path = undef;
  640. }
  641. if ($@) {
  642. chomp($@);
  643. my $err = ($@ =~ /\n/ms) ? ":\n$@" : " ($@)";
  644. print qq($0: error in file "$path"$err\n);
  645. $run::errors++;
  646. } else {
  647. # Only process subsidiary scripts if no errors in parent.
  648. unshift(@scripts, @priv::scripts);
  649. }
  650. undef @priv::scripts;
  651. } else {
  652. my $where = '';
  653. my $cref = $priv::self->{script}->creator;
  654. if (defined $cref) {
  655. my($_foo, $script, $line, $sub) = @$cref;
  656. $where = " ($sub in $script, line $line)";
  657. }
  658. warn qq(Ignoring missing script "$path"$where);
  659. }
  660. }
  661. die("$0: script errors encountered: construction aborted\n")
  662. if $run::errors;
  663. }
  664. # Return caller info about the method being invoked.
  665. # This is everything from the Perl "caller" builtin function,
  666. # including which Construct/Conscript file, line number,
  667. # subroutine name, etc.
  668. sub caller_info {
  669. my($lev) = 1;
  670. my(@frame);
  671. do {
  672. @frame = caller ++$lev;
  673. if (defined($frame[3]) && $frame[3] eq '(eval)') {
  674. @frame = caller --$lev;
  675. if ($caller_dir_path) {
  676. $frame[1] = File::Spec->catfile($caller_dir_path, $frame[1]);
  677. }
  678. return @frame;
  679. }
  680. } while ($frame[3]);
  681. return;
  682. }
  683. # Link a directory to another. This simply means set up the *source*
  684. # for the directory to be the other directory.
  685. sub Link {
  686. dir::link(@_);
  687. }
  688. # Add directories to the repository search path for files.
  689. # Strip our current directory from the list so Repository
  690. # (or -R options) can be used from within the repository.
  691. sub Repository {
  692. my($my_dir) = Cwd::cwd();
  693. my $dir;
  694. foreach $dir (@_) {
  695. # The following more direct call isn't available in
  696. # Cwd.pm until some time after 5.003...
  697. # my($d) = Cwd::abs_path($dir);
  698. chdir($dir);
  699. my($d) = Cwd::cwd();
  700. chdir($my_dir);
  701. #
  702. next if ! $d || ! -d $d || $d eq $my_dir;
  703. # We know we can get away with passing undef to lookupdir
  704. # as the directory because $dir is an absolute path.
  705. push(@param::rpath, dir::lookupdir(undef, $dir));
  706. push @INC, $d;
  707. }
  708. }
  709. # Return the list of Repository directories specified.
  710. sub Repository_List {
  711. map($_->path, @param::rpath);
  712. }
  713. # Specify whether the .consign signature times in repository files are,
  714. # in fact, consistent with the times on the files themselves.
  715. sub Repository_Sig_Times_OK {
  716. $param::rep_sig_times_ok = shift;
  717. }
  718. sub SourceSignature {
  719. $param::sourcesig = [@_];
  720. }
  721. # Specify whether we should chdir to the containing directories
  722. # of Conscript files.
  723. sub Conscript_chdir {
  724. $param::conscript_chdir = shift;
  725. }
  726. # Specify files/targets that must be present and built locally,
  727. # even if they exist already-built in a Repository.
  728. sub Local {
  729. my(@files) = map($dir::cwd->lookupfile($_), @_);
  730. map($_->local(1), @files);
  731. }
  732. # Export variables to any scripts invoked from this one.
  733. sub Export {
  734. my(@illegal) = grep($special_var{$_}, @_);
  735. if (@illegal) {
  736. die qq($0: cannot Export special Perl variables: @illegal\n);
  737. }
  738. @{$priv::self->{exports}} = grep(! defined $special_var{$_}, @_);
  739. }
  740. # Import variables from the export list of the caller
  741. # of the current script.
  742. sub Import {
  743. my(@illegal) = grep($special_var{$_}, @_);
  744. if (@illegal) {
  745. die qq($0: cannot Import special Perl variables: @illegal\n);
  746. }
  747. my($parent) = $priv::self->{parent};
  748. my($imports) = $priv::self->{imports};
  749. @{$priv::self->{exports}} = keys %$imports;
  750. my($var);
  751. foreach $var (grep(! defined $special_var{$_}, @_)) {
  752. if (!exists $imports->{$var}) {
  753. my($path) = $parent->{script}->path;
  754. die qq($0: variable "$var" not exported by file "$path"\n);
  755. }
  756. if (!defined $imports->{$var}) {
  757. my $path = $parent->{script}->path;
  758. my $err = "$0: variable \"$var\" exported but not " .
  759. "defined by file \"$path\"\n";
  760. die $err;
  761. }
  762. ${"script::$var"} = $imports->{$var};
  763. }
  764. }
  765. # Build an inferior script. That is, arrange to read and execute
  766. # the specified script, passing to it any exported variables from
  767. # the current script.
  768. sub Build {
  769. my(@files) = map($dir::cwd->lookupfile($_), @_);
  770. my(%imports) = map {$_ => ${"script::$_"}} @{$priv::self->{exports}};
  771. my $file;
  772. for $file (@files) {
  773. next if $param::include && $file->path !~ /$param::include/o;
  774. my($self) = {'script' => $file,
  775. 'parent' => $priv::self,
  776. 'imports' => \%imports};
  777. bless $self; # may want to bless into class of parent in future
  778. push(@priv::scripts, $self);
  779. }
  780. }
  781. # Set up regexps dependencies to ignore. Should only be called once.
  782. sub Ignore {
  783. die("Ignore called more than once\n") if $param::ignore;
  784. $param::ignore = join("|", map("($_)", @_)) if @_;
  785. }
  786. # Specification of default targets.
  787. sub Default {
  788. push(@param::default_targets, map($dir::cwd->lookup($_)->path, @_));
  789. }
  790. # Local Help. Should only be called once.
  791. sub Help {
  792. if ($param::localhelp) {
  793. print "@_\n";
  794. exit 2;
  795. }
  796. }
  797. # For windows platforms which use unix tool sets, the msvc defaults may
  798. # not be useful. Also, in the future, other platforms (Mac?) may have the
  799. # same problem.
  800. sub RuleSet {
  801. my $style = shift;
  802. my @rulesets = sort keys %param::rulesets;
  803. die "Unknown style for rules: $style.\n" .
  804. "Supported rules are: (" . join(" ", @rulesets) . ")"
  805. unless eval(join("||", map("\$style eq '$_'", @rulesets)));
  806. return @param::base, @{$param::rulesets{$style}};
  807. }
  808. sub DefaultRules {
  809. @param::defaults = ();
  810. push @param::defaults, @_;
  811. }
  812. # Return the build name(s) of a file or file list.
  813. sub FilePath {
  814. wantarray
  815. ? map($dir::cwd->lookupfile($_)->path, @_)
  816. : $dir::cwd->lookupfile($_[0])->path;
  817. }
  818. # Return the build name(s) of a directory or directory list.
  819. sub DirPath {
  820. wantarray
  821. ? map($dir::cwd->lookupdir($_)->path, @_)
  822. : $dir::cwd->lookupdir($_[0])->path;
  823. }
  824. # Split the search path provided into components. Look each up
  825. # relative to the current directory.
  826. # The usual path separator problems abound; for now we'll use :
  827. sub SplitPath {
  828. my($dirs) = @_;
  829. if (ref($dirs) ne "ARRAY") {
  830. $dirs = [ split(/$main::PATH_SEPARATOR/o, $dirs) ];
  831. }
  832. map { DirPath($_) } @$dirs;
  833. }
  834. # Return true if the supplied path is available as a source file
  835. # or is buildable (by rules seen to-date in the build).
  836. sub ConsPath {
  837. my($path) = @_;
  838. my($file) = $dir::cwd->lookup($path);
  839. return $file->accessible;
  840. }
  841. # Return the source path of the supplied path.
  842. sub SourcePath {
  843. wantarray
  844. ? map($dir::cwd->lookupfile($_)->rsrcpath, @_)
  845. : $dir::cwd->lookupfile($_[0])->rsrcpath;
  846. }
  847. # Search up the tree for the specified cache directory, starting with
  848. # the current directory. Returns undef if not found, 1 otherwise.
  849. # If the directory is found, then caching is enabled. The directory
  850. # must be readable and writable. If the argument "mixtargets" is provided,
  851. # then targets may be mixed in the cache (two targets may share the same
  852. # cache file--not recommended).
  853. sub UseCache($@) {
  854. my($dir, @args) = @_;
  855. # NOTE: it's important to process arguments here regardless of whether
  856. # the cache is disabled temporarily, since the mixtargets option affects
  857. # the salt for derived signatures.
  858. for (@args) {
  859. if ($_ eq "mixtargets") {
  860. # When mixtargets is enabled, we salt the target signatures.
  861. # This is done purely to avoid a scenario whereby if
  862. # mixtargets is turned on or off after doing builds, and
  863. # if cache synchronization with -cs is used, then
  864. # cache files may be shared in the cache itself (linked
  865. # under more than one name in the cache). This is not bad,
  866. # per se, but simply would mean that a cache cleaning algorithm
  867. # that looked for a link count of 1 would never find those
  868. # particular files; they would always appear to be in use.
  869. $param::salt = 'M' . $param::salt;
  870. $param::mixtargets = 1;
  871. } else {
  872. die qq($0: UseCache unrecognized option "$_"\n);
  873. }
  874. }
  875. if ($param::cachedisable) {
  876. warn("Note: caching disabled by -cd flag\n");
  877. return 1;
  878. }
  879. my($depth) = 15;
  880. while ($depth-- && ! -d $dir) {
  881. $dir = File::Spec->catdir($dir::UPDIR, $dir);
  882. }
  883. if (-d $dir) {
  884. $param::cache = $dir;
  885. return 1;
  886. }
  887. return undef;
  888. }
  889. # Salt the signature generator. The salt (a number of string) is added
  890. # into the signature of each derived file. Changing the salt will
  891. # force recompilation of all derived files.
  892. sub Salt($) {
  893. # We append the value, so that UseCache and Salt may be used
  894. # in either order without changing the signature calculation.
  895. $param::salt .= $_[0];
  896. }
  897. # Mark files (or directories) to not be removed before building.
  898. sub Precious {
  899. map($_->{precious} = 1, map($dir::cwd->lookup($_), @_));
  900. }
  901. # These methods are callable from Conscript files, via a cons
  902. # object. Procs beginning with _ are intended for internal use.
  903. package cons;
  904. use vars qw( %envcache );
  905. # This is passed the name of the base environment to instantiate.
  906. # Overrides to the base environment may also be passed in
  907. # as key/value pairs.
  908. sub new {
  909. my($package) = shift;
  910. my ($env) = {@param::defaults, @_};
  911. @{$env->{_envcopy}} = %$env; # Note: we never change PATH
  912. $env->{_cwd} = $dir::cwd; # Save directory of environment for
  913. bless $env, $package; # any deferred name interpretation.
  914. }
  915. # Clone an environment.
  916. # Note that the working directory will be the initial directory
  917. # of the original environment.
  918. sub clone {
  919. my($env) = shift;
  920. my $clone = {@{$env->{_envcopy}}, @_};
  921. @{$clone->{_envcopy}} = %$clone; # Note: we never change PATH
  922. $clone->{_cwd} = $env->{_cwd};
  923. bless $clone, ref $env;
  924. }
  925. # Create a flattened hash representing the environment.
  926. # It also contains a copy of the PATH, so that the path
  927. # may be modified if it is converted back to a hash.
  928. sub copy {
  929. my($env) = shift;
  930. (@{$env->{_envcopy}}, 'ENV' => {%{$env->{ENV}}}, @_)
  931. }
  932. # Resolve which environment to actually use for a given
  933. # target. This is just used for simple overrides.
  934. sub _resolve {
  935. return $_[0] if !$param::overrides;
  936. my($env, $tgt) = @_;
  937. my($path) = $tgt->path;
  938. my $re;
  939. for $re (@param::overrides) {
  940. next if $path !~ /$re/;
  941. # Found one. Return a combination of the original environment
  942. # and the override.
  943. my($ovr) = $param::overrides{$re};
  944. return $envcache{$env,$re} if $envcache{$env,$re};
  945. my($newenv) = {@{$env->{_envcopy}}, @$ovr};
  946. @{$newenv->{_envcopy}} = %$env;
  947. $newenv->{_cwd} = $env->{_cwd};
  948. return $envcache{$env,$re} = bless $newenv, ref $env;
  949. }
  950. return $env;
  951. }
  952. # Substitute construction environment variables into a string.
  953. # Internal function/method.
  954. sub _subst {
  955. my($env, $str) = @_;
  956. if (! defined $str) {
  957. return undef;
  958. } elsif (ref($str) eq "ARRAY") {
  959. return [ map($env->_subst($_), @$str) ];
  960. } else {
  961. # % expansion. %% gets converted to % later, so expand any
  962. # %keyword construction that doesn't have a % in front of it,
  963. # modulo multiple %% pairs in between.
  964. # In Perl 5.005 and later, we could actually do this in one regex
  965. # using a conditional expression as follows,
  966. # while ($str =~ s/($pre)\%(\{)?([_a-zA-Z]\w*)(?(2)\})/"$1".
  967. # $env->{$3}/ge) {}
  968. # The following two-step approach is backwards-compatible
  969. # to (at least) Perl5.003.
  970. my $pre = '^|[^\%](?:\%\%)*';
  971. while (($str =~ s/($pre)\%([_a-zA-Z]\w*)/$1.($env->{$2}||'')/ge) ||
  972. ($str =~ s/($pre)\%\{([_a-zA-Z]\w*)\}/$1.($env->{$2}||'')/ge)) {
  973. }
  974. return $str;
  975. }
  976. }
  977. sub AfterBuild {
  978. my($env) = shift;
  979. my($perl_eval_str) = pop(@_);
  980. my $file;
  981. for $file (map($dir::cwd->lookup($_), @_)) {
  982. $file->{after_build_func} = $perl_eval_str;
  983. }
  984. }
  985. sub Install {
  986. my($env) = shift;
  987. my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
  988. my $file;
  989. for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
  990. my($tgt) = $tgtdir->lookupfile($file->{entry});
  991. $tgt->bind(find build::install($env), $file);
  992. }
  993. }
  994. sub InstallAs {
  995. my $env = shift;
  996. my $tgt = shift;
  997. my $src = shift;
  998. my @sources = ();
  999. my @targets = ();
  1000. if (ref $tgt) {
  1001. die "InstallAs: Source is a file and target is a list!\n"
  1002. if (!ref($src));
  1003. @sources = @$src;
  1004. @targets = @$tgt;
  1005. } elsif (ref $src) {
  1006. die "InstallAs: Target is a file and source is a list!\n";
  1007. } else {
  1008. push @sources, $src;
  1009. push @targets, $tgt;
  1010. }
  1011. if ($#sources != $#targets) {
  1012. my $tn = $#targets+1;
  1013. my $sn = $#sources+1;
  1014. die "InstallAs: Source file list ($sn) and target file list ($tn) " .
  1015. "are inconsistent in length!\n";
  1016. } else {
  1017. foreach (0..$#sources) {
  1018. my $tfile = $dir::cwd->lookupfile($env->_subst($targets[$_]));
  1019. my $sfile = $dir::cwd->lookupfile($env->_subst($sources[$_]));
  1020. $tfile->bind(find build::install($env), $sfile);
  1021. }
  1022. }
  1023. }
  1024. # Installation in a local build directory,
  1025. # copying from the repository if it's already built there.
  1026. # Functionally equivalent to:
  1027. # Install $env $dir, $file;
  1028. # Local "$dir/$file";
  1029. sub Install_Local {
  1030. my($env) = shift;
  1031. my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
  1032. my $file;
  1033. for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
  1034. my($tgt) = $tgtdir->lookupfile($file->{entry});
  1035. $tgt->bind(find build::install($env), $file);
  1036. $tgt->local(1);
  1037. }
  1038. }
  1039. sub Objects {
  1040. my($env) = shift;
  1041. map($dir::cwd->relpath($_), $env->_Objects(@_));
  1042. }
  1043. # Called with multiple source file references (or object files).
  1044. # Returns corresponding object files references.
  1045. sub _Objects {
  1046. my($env) = shift;
  1047. my($suffix) = $env->{SUFOBJ};
  1048. map($env->_Object($_, $_->{dir}->lookupfile($_->base_suf($suffix))),
  1049. map { ref $_ ? $_ : $dir::cwd->lookupfile($env->_subst($_)) }
  1050. grep(defined $_, @_));
  1051. }
  1052. # Called with an object and source reference. If no object reference
  1053. # is supplied, then the object file is determined implicitly from the
  1054. # source file's extension. Sets up the appropriate rules for creating
  1055. # the object from the source. Returns the object reference.
  1056. sub _Object {
  1057. my($env, $src, $obj) = @_;
  1058. return $obj if $src eq $obj; # don't need to build self from self.
  1059. my($objenv) = $env->_resolve($obj);
  1060. my($suffix) = $src->suffix;
  1061. my($builder) = $env->{SUFMAP}{$suffix};
  1062. if ($builder) {
  1063. $obj->bind((find $builder($objenv)), $src);
  1064. } else {
  1065. die("don't know how to construct ${\$obj->path} from " .
  1066. "${\$src->path}.\n");
  1067. }
  1068. $obj
  1069. }
  1070. sub Program {
  1071. my($env) = shift;
  1072. my($tgt) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
  1073. $env->{SUFEXE}));
  1074. my($progenv) = $env->_resolve($tgt);
  1075. $tgt->bind(find build::command::link($progenv, $progenv->{LINKCOM}),
  1076. $env->_Objects(@_));
  1077. }
  1078. sub Module {
  1079. my($env) = shift;
  1080. my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
  1081. my($modenv) = $env->_resolve($tgt);
  1082. my($com) = pop(@_);
  1083. $tgt->bind(find build::command::link($modenv, $com), $env->_Objects(@_));
  1084. }
  1085. sub LinkedModule {
  1086. my($env) = shift;
  1087. my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
  1088. my($progenv) = $env->_resolve($tgt);
  1089. $tgt->bind(find build::command::linkedmodule
  1090. ($progenv, $progenv->{LINKMODULECOM}),
  1091. $env->_Objects(@_));
  1092. }
  1093. sub Library {
  1094. my($env) = shift;
  1095. my($lib) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
  1096. $env->{SUFLIB}));
  1097. my($libenv) = $env->_resolve($lib);
  1098. $lib->bind(find build::command::library($libenv), $env->_Objects(@_));
  1099. }
  1100. # Simple derivation: you provide target, source(s), command.
  1101. # Special variables substitute into the rule.
  1102. # Target may be a reference, in which case it is taken
  1103. # to be a multiple target (all targets built at once).
  1104. sub Command {
  1105. my($env) = shift;
  1106. my($tgt) = $env->_subst(shift);
  1107. my($builder) = find build::command::user($env, pop(@_), 'script');
  1108. my(@sources) = map($dir::cwd->lookupfile($env->_subst($_)), @_);
  1109. if (ref($tgt)) {
  1110. # A multi-target command.
  1111. my(@tgts) = map($dir::cwd->lookupfile($_), @$tgt);
  1112. die("empty target list in multi-target command\n") if !@tgts;
  1113. $env = $env->_resolve($tgts[0]);
  1114. my($multi) = build::multiple->new($builder, \@tgts);
  1115. for $tgt (@tgts) {
  1116. $tgt->bind($multi, @sources);
  1117. }
  1118. } else {
  1119. $tgt = $dir::cwd->lookupfile($tgt);
  1120. $env = $env->_resolve($tgt);
  1121. $tgt->bind($builder, @sources);
  1122. }
  1123. }
  1124. sub Depends {
  1125. my($env) = shift;
  1126. my($tgt) = $env->_subst(shift);
  1127. my(@deps) = map($dir::cwd->lookup($env->_subst($_)), @_);
  1128. if (! ref($tgt)) {
  1129. $tgt = [ $tgt ];
  1130. }
  1131. my($t);
  1132. foreach $t (map($dir::cwd->lookupfile($_), @$tgt)) {
  1133. push(@{$t->{dep}}, @deps);
  1134. }
  1135. }
  1136. # Setup a quick scanner for the specified input file, for the
  1137. # associated environment. Any use of the input file will cause the
  1138. # scanner to be invoked, once only. The scanner sees just one line at
  1139. # a time of the file, and is expected to return a list of
  1140. # dependencies.
  1141. sub QuickScan {
  1142. my($env, $code, $file, $path) = @_;
  1143. $dir::cwd->lookup($env->_subst($file))->{'srcscan',$env} =
  1144. find scan::quickscan($code, $env, $env->_subst($path));
  1145. }
  1146. # Generic builder module. Just a few default methods. Every derivable
  1147. # file must have a builder object of some sort attached. Usually
  1148. # builder objects are shared.
  1149. package build;
  1150. use vars qw( %builder );
  1151. # Every builder must now have at least an associated environment,
  1152. # so we can find its sigarray and calculate the proper signature.
  1153. sub find {
  1154. my($class, $env) = @_;
  1155. $builder{$env} || do {
  1156. my $self = { env => $env };
  1157. $builder{$env} = bless $self, $class;
  1158. }
  1159. }
  1160. # Null signature for dynamic includes.
  1161. sub includes { () }
  1162. # Null signature for build script.
  1163. sub scriptsig { () }
  1164. # Not compatible with any other builder, by default.
  1165. sub compatible { 0 }
  1166. # Builder module for the Install command.
  1167. package build::install;
  1168. use vars qw( @ISA );
  1169. BEGIN { @ISA = qw(build) }
  1170. # Caching not supported for Install: generally install is trivial anyway,
  1171. # and we don't want to clutter the cache.
  1172. sub cachin { undef }
  1173. sub cachout { }
  1174. # Do the installation.
  1175. sub action {
  1176. my($self, $tgt) = @_;
  1177. my($src) = $tgt->{sources}[0];
  1178. main::showcom("Install ${\$src->rpath} as ${\$tgt->path}")
  1179. if ($param::install && $param::quiet < 1);
  1180. return unless $param::build;
  1181. futil::install($src->rpath, $tgt);
  1182. return 1;
  1183. }
  1184. # Builder module for generic UNIX commands.
  1185. package build::command;
  1186. use vars qw( @ISA %com );
  1187. BEGIN { @ISA = qw(build) }
  1188. sub find {
  1189. my($class, $env, $cmd, $package) = @_;
  1190. my($act) = action::new($env, $cmd);
  1191. $package ||= '';
  1192. $com{$env,$act,$package} || do {
  1193. my $self = { env => $env, act => $act, 'package' => $package };
  1194. $com{$env,$act,$package} = bless $self, $class;
  1195. }
  1196. }
  1197. # Default cache in function.
  1198. sub cachin {
  1199. my($self, $tgt, $sig) = @_;
  1200. if (cache::in($tgt, $sig)) {
  1201. if ($param::cachecom) {
  1202. $self->{act}->show($self->{env}, $tgt);
  1203. } else {
  1204. printf("Retrieved %s from cache\n", $tgt->path)
  1205. if ($param::quiet < 1);
  1206. }
  1207. return 1;
  1208. }
  1209. return undef;
  1210. }
  1211. # Default cache out function.
  1212. sub cachout {
  1213. my($self, $tgt, $sig) = @_;
  1214. cache::out($tgt, $sig);
  1215. }
  1216. # Build the target using the previously specified commands.
  1217. sub action {
  1218. my($self, $tgt) = @_;
  1219. $self->{act}->execute($self->{env}, $tgt, $self->{'package'});
  1220. }
  1221. # Return script signature.
  1222. sub scriptsig {
  1223. $_[0]->{act}->scriptsig
  1224. }
  1225. # Create a linked module.
  1226. package build::command::link;
  1227. use vars qw( @ISA );
  1228. BEGIN { @ISA = qw(build::command) }
  1229. # Find an appropriate linker.
  1230. sub find {
  1231. my($class, $env, $command) = @_;
  1232. if (!exists $env->{_LDIRS}) {
  1233. my($ldirs) = '';
  1234. my($wd) = $env->{_cwd};
  1235. my($pdirs) = $env->{LIBPATH};
  1236. if (! defined $pdirs) {
  1237. $pdirs = [ ];
  1238. } elsif (ref($pdirs) ne 'ARRAY') {
  1239. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1240. }
  1241. my($dir, $dpath);
  1242. for $dir (map($wd->lookupdir($env->_subst($_)), @$pdirs)) {
  1243. $dpath = $dir->path;
  1244. # Add the (presumably local) directory to the -L flags
  1245. # if we're not using repositories, the directory exists,
  1246. # or it's Linked to a source directory (that is, it *will*
  1247. # exist by the time the link occurs).
  1248. $ldirs .= " ".$env->{LIBDIRPREFIX}.$dpath.$env->{LIBDIRSUFFIX}
  1249. if ! @param::rpath || -d $dpath || $dir->is_linked;
  1250. next if File::Spec->file_name_is_absolute($dpath);
  1251. if (@param::rpath) {
  1252. my $d;
  1253. if ($dpath eq $dir::CURDIR) {
  1254. foreach $d (map($_->path, @param::rpath)) {
  1255. $ldirs .= " " . $env->{LIBDIRPREFIX} .
  1256. $d . $env->{LIBDIRSUFFIX};
  1257. }
  1258. } else {
  1259. my($rpath);
  1260. foreach $d (map($_->path, @param::rpath)) {
  1261. $rpath = File::Spec->catfile($d, $dpath);
  1262. $ldirs .= " ". $env->{LIBDIRPREFIX} .
  1263. $rpath . $env->{LIBDIRSUFFIX} if -d $rpath;
  1264. }
  1265. }
  1266. }
  1267. }
  1268. $env->{_LDIRS} = "%($ldirs%)";
  1269. }
  1270. # Introduce a new magic _LIBS symbol which allows to use the
  1271. # Unix-style -lNAME syntax for Win32 only. -lNAME will be replaced
  1272. # with %{PREFLIB}NAME%{SUFLIB}. <schwarze@isa.de> 1998-06-18
  1273. if ($main::_WIN32 && !exists $env->{_LIBS}) {
  1274. my $libs;
  1275. my $name;
  1276. for $name (split(' ', $env->_subst($env->{LIBS} || ''))) {
  1277. if ($name =~ /^-l(.*)/) {
  1278. $name = "$env->{PREFLIB}$1$env->{SUFLIB}";
  1279. }
  1280. $libs .= ' ' . $name;
  1281. }
  1282. $env->{_LIBS} = $libs ? "%($libs%)" : '';
  1283. }
  1284. bless find build::command($env, $command);
  1285. }
  1286. # Called from file::build. Make sure any libraries needed by the
  1287. # environment are built, and return the collected signatures
  1288. # of the libraries in the path.
  1289. sub includes {
  1290. return $_[0]->{'bsig'} if exists $_[0]->{'bsig'};
  1291. my($self, $tgt) = @_;
  1292. my($env) = $self->{env};
  1293. my($ewd) = $env->{_cwd};
  1294. my $ldirs = $env->{LIBPATH};
  1295. if (! defined $ldirs) {
  1296. $ldirs = [ ];
  1297. } elsif (ref($ldirs) ne 'ARRAY') {
  1298. $ldirs = [ split(/$main::PATH_SEPARATOR/o, $ldirs) ];
  1299. }
  1300. my @lpath = map($ewd->lookupdir($_), @$ldirs);
  1301. my(@sigs);
  1302. my(@names);
  1303. # Pass %LIBS symbol through %-substituition
  1304. # <schwarze@isa.de> 1998-06-18
  1305. @names = split(' ', $env->_subst($env->{LIBS} || ''));
  1306. my $name;
  1307. for $name (@names) {
  1308. my ($lpath, @allnames);
  1309. if ($name =~ /^-l(.*)/) {
  1310. # -l style names are looked up on LIBPATH, using all
  1311. # possible lib suffixes in the same search order the
  1312. # linker uses (according to SUFLIBS).
  1313. # Recognize new PREFLIB symbol, which should be 'lib' on
  1314. # Unix, and empty on Win32. TODO: What about shared
  1315. # library suffixes? <schwarze@isa.de> 1998-05-13
  1316. @allnames = map("$env->{PREFLIB}$1$_",
  1317. split(/:/, $env->{SUFLIBS}));
  1318. $lpath = \@lpath;
  1319. } else {
  1320. @allnames = ($name);
  1321. # On Win32, all library names are looked up in LIBPATH
  1322. # <schwarze@isa.de> 1998-05-13
  1323. if ($main::_WIN32) {
  1324. $lpath = [$dir::top, @lpath];
  1325. }
  1326. else {
  1327. $lpath = [$dir::top];
  1328. }
  1329. }
  1330. my $dir;
  1331. DIR: for $dir (@$lpath) {
  1332. my $n;
  1333. for $n (@allnames) {
  1334. my($lib) = $dir->lookup_accessible($n);
  1335. if ($lib) {
  1336. last DIR if $lib->ignore;
  1337. if ((build $lib) eq 'errors') {
  1338. $tgt->{status} = 'errors';
  1339. return undef;
  1340. }
  1341. push(@sigs, 'sig'->signature($lib));
  1342. last DIR;
  1343. }
  1344. }
  1345. }
  1346. }
  1347. $self->{'bsig'} = 'sig'->collect(@sigs);
  1348. }
  1349. # Always compatible with other such builders, so the user
  1350. # can define a single program or module from multiple places.
  1351. sub compatible {
  1352. my($self, $other) = @_;
  1353. ref($other) eq "build::command::link";
  1354. }
  1355. # Link a program.
  1356. package build::command::linkedmodule;
  1357. use vars qw( @ISA );
  1358. BEGIN { @ISA = qw(build::command) }
  1359. # Always compatible with other such builders, so the user
  1360. # can define a single linked module from multiple places.
  1361. sub compatible {
  1362. my($self, $other) = @_;
  1363. ref($other) eq "build::command::linkedmodule";
  1364. }
  1365. # Builder for a C module
  1366. package build::command::cc;
  1367. use vars qw( @ISA );
  1368. BEGIN { @ISA = qw(build::command) }
  1369. sub find {
  1370. $_[1]->{_cc} || do {
  1371. my($class, $env) = @_;
  1372. my($cpppath) = $env->_subst($env->{CPPPATH});
  1373. my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
  1374. $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
  1375. my($self) = find build::command($env, $env->{CCCOM});
  1376. $self->{scanner} = $cscanner;
  1377. bless $env->{_cc} = $self;
  1378. }
  1379. }
  1380. # Invoke the associated C scanner to get signature of included files.
  1381. sub includes {
  1382. my($self, $tgt) = @_;
  1383. $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
  1384. }
  1385. # Builder for a C++ module
  1386. package build::command::cxx;
  1387. use vars qw( @ISA );
  1388. BEGIN { @ISA = qw(build::command) }
  1389. sub find {
  1390. $_[1]->{_cxx} || do {
  1391. my($class, $env) = @_;
  1392. my($cpppath) = $env->_subst($env->{CPPPATH});
  1393. my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
  1394. $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
  1395. my($self) = find build::command($env, $env->{CXXCOM});
  1396. $self->{scanner} = $cscanner;
  1397. bless $env->{_cxx} = $self;
  1398. }
  1399. }
  1400. # Invoke the associated C scanner to get signature of included files.
  1401. sub includes {
  1402. my($self, $tgt) = @_;
  1403. $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
  1404. }
  1405. # Builder for a user command (cons::Command). We assume that a user
  1406. # command might be built and implement the appropriate dependencies on
  1407. # the command itself (actually, just on the first word of the command
  1408. # line).
  1409. package build::command::user;
  1410. use vars qw( @ISA );
  1411. BEGIN { @ISA = qw(build::command) }
  1412. sub includes {
  1413. my($self, $tgt) = @_;
  1414. my($sig) = '';
  1415. # Check for any quick scanners attached to source files.
  1416. my $dep;
  1417. for $dep (@{$tgt->{dep}}, @{$tgt->{sources}}) {
  1418. my($scanner) = $dep->{'srcscan',$self->{env}};
  1419. if ($scanner) {
  1420. $sig .= $scanner->includes($tgt, $dep);
  1421. }
  1422. }
  1423. # XXX Optimize this to not use ignored paths.
  1424. if (! exists $self->{_comsig}) {
  1425. my($env) = $self->{env};
  1426. $self->{_comsig} = '';
  1427. my($com, $dir);
  1428. com:
  1429. for $com ($self->{act}->commands) {
  1430. my($pdirs) = $env->{ENV}->{PATH};
  1431. if (! defined $pdirs) {
  1432. $pdirs = [ ];
  1433. } elsif (ref($pdirs) ne 'ARRAY') {
  1434. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1435. }
  1436. for $dir (map($dir::top->lookupdir($_), @$pdirs)) {
  1437. my($prog) = $dir->lookup_accessible($com);
  1438. if ($prog) { # XXX Not checking execute permission.
  1439. if ((build $prog) eq 'errors') {
  1440. $tgt->{status} = 'errors';
  1441. return $sig;
  1442. }
  1443. next com if $prog->ignore;
  1444. $self->{_comsig} .= 'sig'->signature($prog);
  1445. next com;
  1446. }
  1447. }
  1448. }
  1449. }
  1450. return $self->{_comsig} . $sig
  1451. }
  1452. # Builder for a library module (archive).
  1453. # We assume that a user command might be built and implement the
  1454. # appropriate dependencies on the command itself.
  1455. package build::command::library;
  1456. use vars qw( @ISA );
  1457. BEGIN { @ISA = qw(build::command) }
  1458. sub find {
  1459. my($class, $env) = @_;
  1460. bless find build::command($env, $env->{ARCOM})
  1461. }
  1462. # Always compatible with other library builders, so the user
  1463. # can define a single library from multiple places.
  1464. sub compatible {
  1465. my($self, $other) = @_;
  1466. ref($other) eq "build::command::library";
  1467. }
  1468. # A multi-target builder.
  1469. # This allows multiple targets to be associated with a single build
  1470. # script, without forcing all the code to be aware of multiple targets.
  1471. package build::multiple;
  1472. sub new {
  1473. my($class, $builder, $tgts) = @_;
  1474. bless { 'builder' => $builder, 'env' => $builder->{env}, 'tgts' => $tgts };
  1475. }
  1476. sub scriptsig {
  1477. my($self, $tgt) = @_;
  1478. $self->{builder}->scriptsig($tgt);
  1479. }
  1480. sub includes {
  1481. my($self, $tgt) = @_;
  1482. $self->{builder}->includes($tgt);
  1483. }
  1484. sub compatible {
  1485. my($self, $tgt) = @_;
  1486. $self->{builder}->compatible($tgt);
  1487. }
  1488. sub cachin {
  1489. my($self, $tgt, $sig) = @_;
  1490. $self->{builder}->cachin($tgt, $sig);
  1491. }
  1492. sub cachout {
  1493. my($self, $tgt, $sig) = @_;
  1494. $self->{builder}->cachout($tgt, $sig);
  1495. }
  1496. sub action {
  1497. my($self, $invoked_tgt) = @_;
  1498. return $self->{built} if exists $self->{built};
  1499. # Make sure all targets in the group are unlinked before building any.
  1500. my($tgts) = $self->{tgts};
  1501. my $tgt;
  1502. for $tgt (@$tgts) {
  1503. futil::mkdir($tgt->{dir});
  1504. unlink($tgt->path) if ! $tgt->precious;
  1505. }
  1506. # Now do the action to build all the targets. For consistency
  1507. # we always call the action on the first target, just so that
  1508. # $> is deterministic.
  1509. $self->{built} = $self->{builder}->action($tgts->[0]);
  1510. # Now "build" all the other targets (except for the one
  1511. # we were called with). This guarantees that the signature
  1512. # of each target is updated appropriately. We force the
  1513. # targets to be built even if they have been previously
  1514. # considered and found to be OK; the only effect this
  1515. # has is to make sure that signature files are updated
  1516. # correctly.
  1517. for $tgt (@$tgts) {
  1518. if ($tgt ne $invoked_tgt) {
  1519. delete $tgt->{status};
  1520. 'sig'->invalidate($tgt);
  1521. build $tgt;
  1522. }
  1523. }
  1524. # Status of action.
  1525. $self->{built};
  1526. }
  1527. package action;
  1528. sub new {
  1529. my($env, $act) = @_;
  1530. if (ref($act) eq 'CODE') {
  1531. return action::perl->new($act);
  1532. } else {
  1533. return action::command->new($env, $act);
  1534. }
  1535. }
  1536. package action::command;
  1537. use vars qw( @ISA %cmd %_varopts $_varletters );
  1538. BEGIN {
  1539. @ISA = $main::_WIN32 ? 'action::command::win32' : 'action::command::unix';
  1540. # Internal hash for processing variable options.
  1541. # f: return file part
  1542. # d: return directory part
  1543. # F: return file part, but strip any suffix
  1544. # b: return full path, but strip any suffix (a.k.a. return basename)
  1545. # s: return only the suffix (or an empty string, if no suffix is there)
  1546. # a: return the absolute path to the file
  1547. # S: return the absolute path to a Linked source file
  1548. %_varopts = (
  1549. 'f' => sub { return $_[0]->{entry}; },
  1550. 'd' => sub { return $_[0]->{dir}->path; },
  1551. 'F' => sub { my $subst = $_[0]->{entry};
  1552. $subst =~ s/\.[^\.]+$//;
  1553. return $subst; },
  1554. 'b' => sub { my $subst = $_[0]->path;
  1555. $subst =~ s/\.[^\.]+$//;
  1556. return $subst; },
  1557. 's' => sub { my $subst = $_[0]->{entry};
  1558. $subst =~ m/(\.[^\.]+)$/;
  1559. return $1; },
  1560. 'a' => sub { my $path = $_[0]->path;
  1561. if (! File::Spec->file_name_is_absolute($path)) {
  1562. $path = File::Spec->catfile(Cwd::cwd(), $path);
  1563. }
  1564. return $path; },
  1565. 'S' => sub { my $path = $_[0]->srcpath;
  1566. if (! File::Spec->file_name_is_absolute($path)) {
  1567. my $cwd = File::Spec->canonpath(Cwd::cwd());
  1568. $path = File::Spec->catfile($cwd, $path);
  1569. }
  1570. return $path; },
  1571. );
  1572. $_varletters = join('', keys %_varopts);
  1573. }
  1574. # Internal routine for processing variable options.
  1575. # Options are specified in hash in the BEGIN block above.
  1576. # no option: return path to file (relative to top,
  1577. # or absolute if it's outside)
  1578. sub _variant {
  1579. my($opt, $file) = @_;
  1580. $opt = '' if ! defined $opt;
  1581. if (defined $_varopts{$opt}) {
  1582. return &{$_varopts{$opt}}($file);
  1583. }
  1584. return $file->path;
  1585. }
  1586. sub new {
  1587. my($class, $env, $cmd) = @_;
  1588. $cmd = $env->_subst($cmd);
  1589. $cmd{$env,$cmd} || do {
  1590. # Remove unwanted bits from signature -- those bracketed by %( ... %)
  1591. my $sigs = $cmd;
  1592. my $sig = '';
  1593. if (ref($sigs) eq 'ARRAY') {
  1594. # This is an array of commands..
  1595. my $f;
  1596. foreach $f (@$sigs) {
  1597. $sig .= _strip($f);
  1598. }
  1599. } else {
  1600. $sig = _strip($sigs);
  1601. }
  1602. my $self = { cmd => $cmd, cmdsig => 'sig'->cmdsig($sig) };
  1603. $cmd{$env,$cmd} = bless $self, $class;
  1604. }
  1605. }
  1606. sub _strip {
  1607. my $sig = shift;
  1608. $sig =~ s/^\@\s*//mg;
  1609. while ($sig =~ s/%\(([^%]|%[^\(])*?%\)//g) { }
  1610. $sig;
  1611. }
  1612. sub scriptsig {
  1613. $_[0]->{cmdsig};
  1614. }
  1615. # Return an array of all the commands (first word on each line).
  1616. sub commands {
  1617. my($self) = @_;
  1618. my(@cmds) = ();
  1619. my $com;
  1620. my $cmd = $self->{'cmd'};
  1621. my @allcoms;
  1622. push @allcoms, ref $cmd ? @{$cmd} : split(/\n/, $cmd);
  1623. for $com (@allcoms) {
  1624. $com =~ s/^\s*//;
  1625. $com =~ s/\s.*//;
  1626. next if ! $com; # blank line
  1627. push @cmds, $com;
  1628. }
  1629. @cmds;
  1630. }
  1631. # For the signature of a basic command, we don't bother
  1632. # including the command itself. This is not strictly correct,
  1633. # and if we wanted to be rigorous, we might want to insist
  1634. # that the command was checked for all the basic commands
  1635. # like gcc, etc. For this reason we don't have an includes
  1636. # method.
  1637. # Call this to get the command line script: an array of
  1638. # fully substituted commands.
  1639. sub getcoms {
  1640. my($self, $env, $tgt) = @_;
  1641. my(@coms);
  1642. my $com;
  1643. my @allcoms = ();
  1644. my $cmd = $self->{'cmd'};
  1645. push @allcoms, ref $cmd ? @{$cmd} : split(/\n/, $cmd);
  1646. for $com (@allcoms) {
  1647. my(@src) = (undef, @{$tgt->{sources}});
  1648. my(@src1) = @src;
  1649. next if $com =~ /^\s*$/;
  1650. # NOTE: we used to have a more elegant s//.../e solution
  1651. # for the items below, but this caused a bus error...
  1652. # Remove %( and %) -- those are only used to bracket parts
  1653. # of the command that we don't depend on.
  1654. $com =~ s/%[()]//g;
  1655. # Deal with %n, n=1,9 and variants.
  1656. while ($com =~ /%([1-9])(:([$_varletters]?))?/o) {
  1657. my($match) = $&;
  1658. my($src) = $src1[$1];
  1659. my($subst) = _variant($3, $src1[$1]->rfile);
  1660. undef $src[$1];
  1661. $com =~ s/$match/$subst/;
  1662. }
  1663. # Deal with %0 aka %> and variants.
  1664. while ($com =~ /%[0>](:([$_varletters]?))?/o) {
  1665. my($match) = $&;
  1666. my($subst) = _variant($2, $tgt);
  1667. $com =~ s/$match/$subst/;
  1668. }
  1669. # Deal with %< (all sources except %n's already used)
  1670. while ($com =~ /%<(:([$_varletters]?))?/o) {
  1671. my($match) = $&;
  1672. my @list = ();
  1673. foreach (@src) {
  1674. push(@list, _variant($2, $_->rfile)) if $_;
  1675. }
  1676. my($subst) = join(' ', @list);
  1677. $com =~ s/$match/$subst/;
  1678. }
  1679. # Deal with %[ %].
  1680. $com =~ s{%\[(.*?)%\]}{
  1681. my($func, @args) = grep { $_ ne '' } split(/\s+/, $1);
  1682. die("$0: \"$func\" is not defined.\n")
  1683. unless ($env->{$func});
  1684. &{$env->{$func}}(@args);
  1685. }gex;
  1686. # Convert left-over %% into %.
  1687. $com =~ s/%%/%/g;
  1688. # White space cleanup. XXX NO WAY FOR USER TO HAVE QUOTED SPACES
  1689. $com = join(' ', split(' ', $com));
  1690. next if $com =~ /^:/ && $com !~ /^:\S/;
  1691. push(@coms, $com);
  1692. }
  1693. @coms
  1694. }
  1695. # Build the target using the previously specified commands.
  1696. sub execute {
  1697. my($self, $env, $tgt, $package) = @_;
  1698. if ($param::build) {
  1699. futil::mkdir($tgt->{dir});
  1700. unlink($tgt->path) if ! $tgt->precious;
  1701. }
  1702. # Set environment.
  1703. map(delete $ENV{$_}, keys %ENV);
  1704. %ENV = %{$env->{ENV}};
  1705. # Handle multi-line commands.
  1706. my $com;
  1707. for $com ($self->getcoms($env, $tgt)) {
  1708. if ($com !~ s/^\@\s*//) {
  1709. main::showcom($com);
  1710. }
  1711. next if ! $param::build;
  1712. if ($com =~ /^\[perl\]\s*/) {
  1713. my $perlcmd = $';
  1714. my $status;
  1715. {
  1716. # Restore the script package variables that were defined
  1717. # in the Conscript file that defined this [perl] build,
  1718. # so the code executes with the expected variables.
  1719. # Then actually execute (eval) the [perl] command to build
  1720. # the target, followed by cleaning up the name space
  1721. # by deleting the package variables we just restored.
  1722. my($pkgvars) = $tgt->{conscript}->{pkgvars};
  1723. NameSpace::restore($package, $pkgvars) if $pkgvars;
  1724. $status = eval "package $package; $perlcmd";
  1725. NameSpace::remove($package, keys %$pkgvars) if $pkgvars;
  1726. }
  1727. if (!defined($status)) {
  1728. warn "$0: *** Error during perl command eval: $@.\n";
  1729. return undef;
  1730. } elsif ($status == 0) {
  1731. warn "$0: *** Perl command returned $status "
  1732. . "(this indicates an error).\n";
  1733. return undef;
  1734. }
  1735. next;
  1736. }
  1737. if (! $self->do_command($com, $tgt->path)) {
  1738. return undef;
  1739. }
  1740. }
  1741. # success.
  1742. return 1;
  1743. }
  1744. sub show {
  1745. my($self, $env, $tgt) = @_;
  1746. my $com;
  1747. for $com ($self->getcoms($env, $tgt)) {
  1748. if ($com !~ /^\@\s*/) {
  1749. main::showcom($com);
  1750. }
  1751. }
  1752. }
  1753. package action::command::unix;
  1754. sub do_command {
  1755. my($class, $com, $path) = @_;
  1756. my($pid) = fork();
  1757. die("$0: unable to fork child process ($!)\n") if !defined $pid;
  1758. if (!$pid) {
  1759. # This is the child. We eval the command to suppress -w
  1760. # warnings about not reaching the statements afterwards.
  1761. eval 'exec($com)';
  1762. $com =~ s/\s.*//;
  1763. die qq($0: failed to execute "$com" ($!). )
  1764. . qq(Is this an executable on path "$ENV{PATH}"?\n);
  1765. }
  1766. for (;;) {
  1767. do {} until wait() == $pid;
  1768. my ($b0, $b1) = ($? & 0xFF, $? >> 8);
  1769. # Don't actually see 0177 on stopped process; is this necessary?
  1770. next if $b0 == 0177; # process stopped; we can wait.
  1771. if ($b0) {
  1772. my($core, $sig) = ($b0 & 0200, $b0 & 0177);
  1773. my($coremsg) = $core ? "; core dumped" : "";
  1774. $com =~ s/\s.*//;
  1775. my $err = "$0: *** \[$path\] $com terminated by signal " .
  1776. "$sig$coremsg\n";
  1777. warn $err;
  1778. return undef;
  1779. }
  1780. if ($b1) {
  1781. warn qq($0: *** [$path] Error $b1\n); # trying to be like make.
  1782. return undef;
  1783. }
  1784. last;
  1785. }
  1786. return 1;
  1787. }
  1788. package action::command::win32;
  1789. sub do_command {
  1790. my($class, $com, $path) = @_;
  1791. system($com);
  1792. if ($?) {
  1793. my ($b0, $b1) = ($? & 0xFF, $? >> 8);
  1794. my $err = $b1 || $?;
  1795. my $warn = qq($0: *** [$path] Error $err);
  1796. $warn .= " (executable not found in path?)" if $b1 == 0xFF;
  1797. warn "$warn\n";
  1798. return undef;
  1799. }
  1800. return 1;
  1801. }
  1802. package action::perl;
  1803. # THIS IS AN EXPERIMENTAL PACKAGE. It's entirely possible that the
  1804. # interface may change as this gets completed, so use at your own risk.
  1805. #
  1806. # There are (at least) two issues that need to be solved before blessing
  1807. # this as a real, fully-supported feature:
  1808. #
  1809. # -- We need to calculate a signature value for a Perl code ref, in
  1810. # order to rebuild the target if there's a change to the Perl code
  1811. # used to generate it.
  1812. #
  1813. # This is not straightforward. A B::Deparse package exists that
  1814. # decompiles a coderef into text. It's reportedly not completely
  1815. # reliable for closures; it misses which variables are global, and
  1816. # the values of private lexicals. Nevertheless, it'd probably
  1817. # be perfect for our purposes, except that it wasn't added until
  1818. # some time between Perl 5.00502 and 5.00554, and doesn't seem to
  1819. # really work until Perl 5.6.0, so by relying on it, we'd lose
  1820. # support for Perl versions back to 5.003*.
  1821. #
  1822. # -- Ideally, a code ref should be able to use something like
  1823. # $env->_subst to fetch values from the construction environment
  1824. # to modify its behavior without having to cut-and-paste code.
  1825. # (Actually, since we pass the environment to the executed code
  1826. # ref, there's no reason you can't do this with the code as it
  1827. # stands today.) But this REALLY complicates the signature
  1828. # calculation, because now the actual signature would depend not
  1829. # just on the code contents, but on the construction variables (or
  1830. # maybe just the environment).
  1831. #
  1832. # A potentially valid workaround would be to use the contents of the
  1833. # Conscript file in which the code reference is defined as the code
  1834. # ref's signature. This has the drawback of causing a recompilation of
  1835. # the target file even in response to unrelated changes in the Conscript
  1836. # file, but it would ensure correct builds without having to solve the
  1837. # messy issues of generating a signature directly from a code ref.
  1838. #
  1839. # Nevertheless, this seemed a useful enough skeleton of a feature that
  1840. # it made sense to release it in hopes that some practical experience
  1841. # will encourage someone to figure out how to solve the signature
  1842. # issues. Or maybe we'll discover these aren't big issues in practice
  1843. # and end up blessing it as is.
  1844. use vars qw( %code );
  1845. sub new {
  1846. my($class, $cref) = @_;
  1847. $code{$cref} || do {
  1848. my $sig = '';
  1849. # Generating a code signature using B::Deparse doesn't really
  1850. # work for us until Perl 5.6.0. Here's the code in case
  1851. # someone wants to use it.
  1852. #use B::Deparse;
  1853. #my $deparse = B::Deparse->new();
  1854. #my $body = $deparse->coderef2text($cref);
  1855. #$sig = $body; # should be an MD5 sig
  1856. my($self) = { cref => $cref, crefsig => $sig };
  1857. $code{$cref} = bless $self, $class;
  1858. }
  1859. }
  1860. sub scriptsig {
  1861. $_[0]->{crefsig}
  1862. }
  1863. sub execute {
  1864. my($self, $env, $tgt) = @_;
  1865. if ($param::build) {
  1866. futil::mkdir($tgt->{dir});
  1867. unlink($tgt->path) if ! $tgt->precious;
  1868. my($cref) = $self->{cref};
  1869. &$cref($env, $tgt->path, map($_->rpath, @{$tgt->{sources}}));
  1870. }
  1871. }
  1872. sub commands {
  1873. return ();
  1874. }
  1875. # Generic scanning module.
  1876. package scan;
  1877. # Returns the signature of files included by the specified files on
  1878. # behalf of the associated target. Any errors in handling the included
  1879. # files are propagated to the target on whose behalf this processing
  1880. # is being done. Signatures are cached for each unique file/scanner
  1881. # pair.
  1882. sub includes {
  1883. my($self, $tgt, @files) = @_;
  1884. my(%files, $file);
  1885. my($inc) = $self->{includes} || ($self->{includes} = {});
  1886. while ($file = pop @files) {
  1887. next if exists $files{$file};
  1888. if ($inc->{$file}) {
  1889. push(@files, @{$inc->{$file}});
  1890. $files{$file} = 'sig'->signature($file->rfile);
  1891. } else {
  1892. if ((build $file) eq 'errors') {
  1893. $tgt->{status} = 'errors'; # tgt inherits build status
  1894. return ();
  1895. }
  1896. $files{$file} = 'sig'->signature($file->rfile);
  1897. my(@includes) = $self->scan($file);
  1898. $inc->{$file} = \@includes;
  1899. push(@files, @includes);
  1900. }
  1901. }
  1902. 'sig'->collect(sort values %files)
  1903. }
  1904. # A simple scanner. This is used by the QuickScanfunction, to setup
  1905. # one-time target and environment-independent scanning for a source
  1906. # file. Only used for commands run by the Command method.
  1907. package scan::quickscan;
  1908. use vars qw( @ISA %scanner );
  1909. BEGIN { @ISA = qw(scan) }
  1910. sub find {
  1911. my($class, $code, $env, $pdirs) = @_;
  1912. if (! defined $pdirs) {
  1913. $pdirs = [ ] ;
  1914. } elsif (ref($pdirs) ne 'ARRAY') {
  1915. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1916. }
  1917. my(@path) = map { $dir::cwd->lookupdir($_) } @$pdirs;
  1918. my($spath) = "@path";
  1919. $scanner{$code,$env,$spath} || do {
  1920. my($self) = { code => $code, env => $env, path => \@path };
  1921. $scanner{$code,$env,$spath} = bless $self;
  1922. }
  1923. }
  1924. # Scan the specified file for included file names.
  1925. sub scan {
  1926. my($self, $file) = @_;
  1927. my($code) = $self->{code};
  1928. my(@includes);
  1929. # File should have been built by now. If not, we'll ignore it.
  1930. return () unless open(SCAN, $file->rpath);
  1931. while(<SCAN>) {
  1932. push(@includes, grep($_ ne '', &$code));
  1933. }
  1934. close(SCAN);
  1935. my($wd) = $file->{dir};
  1936. my(@files);
  1937. my $name;
  1938. for $name (@includes) {
  1939. my $dir;
  1940. for $dir ($file->{dir}, @{$self->{path}}) {
  1941. my($include) = $dir->lookup_accessible($name);
  1942. if ($include) {
  1943. push(@files, $include) unless $include->ignore;
  1944. last;
  1945. }
  1946. }
  1947. }
  1948. @files
  1949. }
  1950. # CPP (C preprocessor) scanning module
  1951. package scan::cpp;
  1952. use vars qw( @ISA %scanner );
  1953. BEGIN { @ISA = qw(scan) }
  1954. # For this constructor, provide the include path argument (colon
  1955. # separated). Each path is taken relative to the provided directory.
  1956. # Note: a particular scanning object is assumed to always return the
  1957. # same result for the same input. This is why the search path is a
  1958. # parameter to the constructor for a CPP scanning object. We go to
  1959. # some pains to make sure that we return the same scanner object
  1960. # for the same path: otherwise we will unecessarily scan files.
  1961. sub find {
  1962. my($class, $dir, $pdirs) = @_;
  1963. if (! defined $pdirs) {
  1964. $pdirs = [ ];
  1965. } elsif (ref($pdirs) ne 'ARRAY') {
  1966. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1967. }
  1968. my @path = map($dir->lookupdir($_), @$pdirs);
  1969. my($spath) = "@path";
  1970. $scanner{$spath} || do {
  1971. my($self) = {'path' => \@path};
  1972. $scanner{$spath} = bless $self;
  1973. }
  1974. }
  1975. # Scan the specified file for include lines.
  1976. sub scan {
  1977. my($self, $file) = @_;
  1978. my($angles, $quotes);
  1979. if (exists $file->{angles}) {
  1980. $angles = $file->{angles};
  1981. $quotes = $file->{quotes};
  1982. } else {
  1983. my(@anglenames, @quotenames);
  1984. return () unless open(SCAN, $file->rpath);
  1985. while (<SCAN>) {
  1986. next unless /^\s*#/;
  1987. if (/^\s*#\s*include\s*([<"])(.*?)[>"]/) {
  1988. if ($1 eq "<") {
  1989. push(@anglenames, $2);
  1990. } else {
  1991. push(@quotenames, $2);
  1992. }
  1993. }
  1994. }
  1995. close(SCAN);
  1996. $angles = $file->{angles} = \@anglenames;
  1997. $quotes = $file->{quotes} = \@quotenames;
  1998. }
  1999. my(@shortpath) = @{$self->{path}}; # path for <> style includes
  2000. my(@longpath) = ($file->{dir}, @shortpath); # path for "" style includes
  2001. my(@includes);
  2002. my $name;
  2003. for $name (@$angles) {
  2004. my $dir;
  2005. for $dir (@shortpath) {
  2006. my($include) = $dir->lookup_accessible($name);
  2007. if ($include) {
  2008. push(@includes, $include) unless $include->ignore;
  2009. last;
  2010. }
  2011. }
  2012. }
  2013. for $name (@$quotes) {
  2014. my $dir;
  2015. for $dir(@longpath) {
  2016. my($include) = $dir->lookup_accessible($name);
  2017. if ($include) {
  2018. push(@includes, $include) unless $include->ignore;
  2019. last;
  2020. }
  2021. }
  2022. }
  2023. return @includes
  2024. }
  2025. # Return the include flags that would be used for a C Compile.
  2026. sub iflags {
  2027. my($self, $env) = @_;
  2028. my($iflags) = '';
  2029. my($dir, $dpath);
  2030. for $dir (@{$self->{path}}) {
  2031. $dpath = $dir->path;
  2032. # Add the (presumably local) directory to the -I flags
  2033. # if we're not using repositories, the directory exists,
  2034. # or it's Linked to a source directory (that is, it *will*
  2035. # exist by the time the compilation occurs).
  2036. $iflags .= " ".$env->{INCDIRPREFIX}.$dpath.$env->{INCDIRSUFFIX}
  2037. if ! @param::rpath || -d $dpath || $dir->is_linked;
  2038. next if File::Spec->file_name_is_absolute($dpath);
  2039. if (@param::rpath) {
  2040. my $d;
  2041. if ($dpath eq $dir::CURDIR) {
  2042. foreach $d (map($_->path, @param::rpath)) {
  2043. $iflags .= " ".$env->{INCDIRPREFIX}.$d.$env->{INCDIRSUFFIX};
  2044. }
  2045. } else {
  2046. my($rpath);
  2047. foreach $d (map($_->path, @param::rpath)) {
  2048. $rpath = File::Spec->catfile($d, $dpath);
  2049. $iflags .= " ".$env->{INCDIRPREFIX}.$rpath.$env->{INCDIRSUFFIX}
  2050. if -d $rpath;
  2051. }
  2052. }
  2053. }
  2054. }
  2055. $iflags
  2056. }
  2057. package File::Spec;
  2058. use vars qw( $_SEP $_MATCH_SEP $_MATCH_VOL );
  2059. # Cons is migrating to using File::Spec for portable path name
  2060. # manipulation. This is the right long-term direction, but there are
  2061. # some problems with making the transition:
  2062. #
  2063. # For multi-volume support, we need to use newer interfaces
  2064. # (splitpath, catpath, splitdir) that are only available in
  2065. # File::Spec 0.8.
  2066. #
  2067. # File::Spec 0.8 doesn't work with Perl 5.00[34] due to
  2068. # regular expression incompatibilities (use of \z).
  2069. #
  2070. # Forcing people to use a new version of a module is painful
  2071. # because (in the workplace) their administrators aren't
  2072. # always going to agree to install it everywhere.
  2073. #
  2074. # As a middle ground, we provide our own versions of all the File::Spec
  2075. # methods we use, supporting both UNIX and Win32. Some of these methods
  2076. # are home brew, some are cut-and-pasted from the real File::Spec methods.
  2077. # This way, we're not reinventing the whole wheel, at least.
  2078. #
  2079. # We can (and should) get rid of this class whenever 5.00[34] and
  2080. # versions of File::Spec prior to 0.9 (?) have faded sufficiently.
  2081. # We also may need to revisit whenever someone first wants to use
  2082. # Cons on some platform other than UNIX or Win32.
  2083. BEGIN {
  2084. if ($main::_WIN32) {
  2085. $_SEP = '\\';
  2086. $_MATCH_SEP = "[\Q/$_SEP\E]";
  2087. $_MATCH_VOL = "([a-z]:)?$_MATCH_SEP";
  2088. } else {
  2089. $_SEP = '/';
  2090. $_MATCH_SEP = "\Q$_SEP\E";
  2091. $_MATCH_VOL = $_MATCH_SEP;
  2092. }
  2093. }
  2094. sub canonpath {
  2095. my ($self, $path) = @_;
  2096. if ($main::_WIN32) {
  2097. $path =~ s/^([a-z]:)/\u$1/s;
  2098. $path =~ s|/|\\|g;
  2099. $path =~ s|([^\\])\\+|$1\\|g; # xx////xx -> xx/xx
  2100. $path =~ s|(\\\.)+\\|\\|g; # xx/././xx -> xx/xx
  2101. $path =~ s|^(\.\\)+||s unless $path eq ".\\"; # ./xx -> xx
  2102. $path =~ s|\\$||
  2103. unless $path =~ m#^([A-Z]:)?\\$#s; # xx/ -> xx
  2104. } else {
  2105. $path =~ s|/+|/|g unless($^O eq 'cygwin'); # xx////xx -> xx/xx
  2106. $path =~ s|(/\.)+/|/|g; # xx/././xx -> xx/xx
  2107. $path =~ s|^(\./)+||s unless $path eq "./"; # ./xx -> xx
  2108. $path =~ s|^/(\.\./)+|/|s; # /../../xx -> xx
  2109. $path =~ s|/$|| unless $path eq "/"; # xx/ -> xx
  2110. }
  2111. return $path;
  2112. }
  2113. sub catdir {
  2114. my $self = shift;
  2115. my @args = @_;
  2116. foreach (@args) {
  2117. # append a slash to each argument unless it has one there
  2118. $_ .= $_SEP if $_ eq '' || substr($_,-1) ne $_SEP;
  2119. }
  2120. return $self->canonpath(join('', @args));
  2121. }
  2122. sub catfile {
  2123. my $self = shift;
  2124. my $file = pop @_;
  2125. return $file unless @_;
  2126. my $dir = $self->catdir(@_);
  2127. $dir .= $_SEP unless substr($dir,-1) eq $_SEP;
  2128. $file = '' if ! defined($file);
  2129. return $dir.$file;
  2130. }
  2131. sub catpath {
  2132. my $path = $_[1] . $_[0]->catfile(@_[2..$#_]);
  2133. $path =~ s/(.)$_MATCH_SEP*$/$1/;
  2134. $path;
  2135. }
  2136. sub curdir {
  2137. '.'
  2138. }
  2139. sub file_name_is_absolute {
  2140. my ($self, $file) = @_;
  2141. return scalar($file =~ m{^$_MATCH_VOL}is);
  2142. }
  2143. sub splitdir {
  2144. my @dirs = split(/$_MATCH_SEP/, $_[1], -1);
  2145. push(@dirs, '') if $dirs[$#dirs];
  2146. @dirs;
  2147. }
  2148. sub splitpath {
  2149. my ($self, $path) = @_;
  2150. my $vol = '';
  2151. my $sep = $_SEP;
  2152. if ($main::_WIN32) {
  2153. if ($path =~ s#^([A-Za-z]:|(?:\\\\|//)[^\\/]+[\\/][^\\/]+)([\\/])#$2#) {
  2154. $vol = $1;
  2155. $sep = $2;
  2156. }
  2157. }
  2158. my(@path) = split(/$_MATCH_SEP/, $path, -1);
  2159. my $file = pop @path;
  2160. my $dirs = join($sep, @path, '');
  2161. return ($vol, $dirs, $file);
  2162. }
  2163. sub updir {
  2164. '..'
  2165. }
  2166. sub case_tolerant {
  2167. return $main::_WIN32;
  2168. }
  2169. # Directory and file handling. Files/dirs are represented by objects.
  2170. # Other packages are welcome to add component-specific attributes.
  2171. package dir;
  2172. use vars qw( $SEPARATOR $MATCH_SEPARATOR $CURDIR $UPDIR
  2173. $cwd_vol %root $top $cwd );
  2174. BEGIN {
  2175. # A portable way of determing our directory separator.
  2176. $SEPARATOR = File::Spec->catdir('', '');
  2177. # A fast-path regular expression to match a directory separator
  2178. # anywhere in a path name.
  2179. if ($SEPARATOR eq '/') {
  2180. $MATCH_SEPARATOR = "\Q$SEPARATOR\E";
  2181. } else {
  2182. $MATCH_SEPARATOR = "[\Q/$SEPARATOR\E]";
  2183. }
  2184. # Cache these values so we don't have to make a method call
  2185. # every time we need them.
  2186. $CURDIR = File::Spec->curdir; # '.' on UNIX
  2187. $UPDIR = File::Spec->updir; # '..' on UNIX
  2188. #
  2189. $cwd_vol = '';
  2190. }
  2191. # Annotate a node (file or directory) with info about the
  2192. # method that created it.
  2193. sub creator {
  2194. my($self, @frame) = @_;
  2195. $self->{'creator'} = \@frame if @frame;
  2196. $self->{'creator'};
  2197. }
  2198. # Handle a file|dir type exception. We only die if we find we were
  2199. # invoked by something in a Conscript/Construct file, because
  2200. # dependencies created directly by Cons' analysis shouldn't cause
  2201. # an error.
  2202. sub _type_exception {
  2203. my($e) = @_;
  2204. my($line, $sub);
  2205. (undef, undef, $line, $sub) = script::caller_info;
  2206. if (defined $line) {
  2207. my $err = "\"${\$e->path}\" already in use as a " . ref($e) . " before $sub on line $line";
  2208. if ($e->{'creator'}) {
  2209. my $script;
  2210. (undef, $script, $line, $sub) = @{$e->{'creator'}};
  2211. $err = "\t" . $err . ",\n\t\tdefined by $sub in $script, line $line";
  2212. }
  2213. $err .= "\n";
  2214. die $err;
  2215. }
  2216. }
  2217. # This wraps up all the common File::Spec logic that we use for parsing
  2218. # directory separators in a path and turning it into individual
  2219. # subdirectories that we must create, as well as creation of root
  2220. # nodes for any new file system volumes we find. File::Spec doesn't have
  2221. # intuitively obvious interfaces, so this is heavily commented.
  2222. #
  2223. # Note: This is NOT an object or class method;
  2224. # it's just a utility subroutine.
  2225. sub _parse_path {
  2226. my($dir, $path) = @_;
  2227. # Convert all slashes to the native directory separator.
  2228. # This allows Construct files to always be written with good
  2229. # old POSIX path names, regardless of what we're running on.
  2230. $path = File::Spec->canonpath($path);
  2231. # File::Spec doesn't understand the Cons convention of
  2232. # an initial '#' for top-relative files. Strip it.
  2233. my($toprel) = $path =~ s/^#//;
  2234. # Let File::Spec do the heavy lifting of parsing the path name.
  2235. my($vol, $directories, $entry) = File::Spec->splitpath($path);
  2236. my @dirs = File::Spec->splitdir($directories);
  2237. # If there was a file entry on the end of the path, then the
  2238. # last @dirs element is '' and we don't need it. If there
  2239. # wasn't a file entry on the end (File::Spec->splitpath() knew
  2240. # the last component was a directory), then the last @dirs
  2241. # element becomes the entry we want to look up.
  2242. my($e) = pop @dirs;
  2243. $entry = $e if $entry eq '';
  2244. if (File::Spec->file_name_is_absolute($path)) {
  2245. # An absolute path name. If no volume was supplied,
  2246. # use the volume of our current directory.
  2247. $vol = $cwd_vol if $vol eq '';
  2248. $vol = uc($vol) if File::Spec->case_tolerant;
  2249. if (! defined $root{$vol}) {
  2250. # This is our first time looking up a path name
  2251. # on this volume, so create a root node for it.
  2252. # (On UNIX systems, $vol is always '', so '/'
  2253. # always maps to the $root{''} node.)
  2254. $root{$vol} = {path => $vol.$SEPARATOR,
  2255. prefix => $vol.$SEPARATOR,
  2256. srcpath => $vol.$SEPARATOR,
  2257. 'exists' => 1 };
  2258. $root{$vol}->{'srcdir'} = $root{$vol};
  2259. bless $root{$vol};
  2260. }
  2261. # We're at the top, so strip the blank entry from the front of
  2262. # the @dirs array since the initial '/' it represents will now
  2263. # be supplied by the root node we return.
  2264. shift @dirs;
  2265. $dir = $root{$vol};
  2266. } elsif ($toprel) {
  2267. $dir = $dir::top;
  2268. }
  2269. ($dir, \@dirs, $entry);
  2270. }
  2271. # Common subroutine for creating directory nodes.
  2272. sub _create_dirs {
  2273. my ($dir, @dirs) = @_;
  2274. my $e;
  2275. foreach $e (@dirs) {
  2276. my $d = $dir->{member}->{$e};
  2277. if (! defined $d) {
  2278. bless $d = { 'entry' => $e, 'dir' => $dir, }, 'dir';
  2279. $d->creator(script::caller_info);
  2280. $d->{member}->{$dir::CURDIR} = $d;
  2281. $d->{member}->{$dir::UPDIR} = $dir;
  2282. $dir->{member}->{$e} = $d;
  2283. } elsif (ref $d eq 'entry') {
  2284. bless $d, 'dir';
  2285. $d->{member}->{$dir::CURDIR} = $d;
  2286. $d->{member}->{$dir::UPDIR} = $dir;
  2287. } elsif (ref $d eq 'file') {
  2288. # This clause is to supply backwards compatibility,
  2289. # with a warning, for anyone that's used FilePath
  2290. # to refer to a directory. After people have using
  2291. # 1.8 have had time to adjust (sometime in version
  2292. # 1.9 or later), we should remove this entire clause.
  2293. my($script, $line, $sub);
  2294. (undef, $script, $line, $sub) = @{$d->{'creator'}};
  2295. if ($sub eq 'script::FilePath') {
  2296. print STDERR "$0: Warning: $sub used to refer to a directory\n"
  2297. . "\tat line $line of $script. Use DirPath instead.\n";
  2298. bless $d, 'dir';
  2299. } else {
  2300. _type_exception($d);
  2301. }
  2302. } elsif (ref $d ne 'dir') {
  2303. _type_exception($d);
  2304. }
  2305. $dir = $d;
  2306. }
  2307. $dir;
  2308. }
  2309. # Look up an entry in a directory. This method is for when we don't
  2310. # care whether a file or directory is returned, so if the entry already
  2311. # exists, it will simply be returned. If not, we create it as a
  2312. # generic "entry" which can be later turned into a file or directory
  2313. # by a more-specific lookup.
  2314. #
  2315. # The file entry may be specified as relative, absolute (starts with /),
  2316. # or top-relative (starts with #).
  2317. sub lookup {
  2318. my($dir, $entry) = @_;
  2319. if ($entry !~ m#$MATCH_SEPARATOR#o) {
  2320. # Fast path: simple entry name in a known directory.
  2321. if ($entry =~ s/^#//) {
  2322. # Top-relative names begin with #.
  2323. $dir = $dir::top;
  2324. } elsif ($entry =~ s/^!//) {
  2325. $dir = $dir::cwd->srcdir;
  2326. }
  2327. } else {
  2328. my $dirsref;
  2329. ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
  2330. $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
  2331. return if ! defined $dir;
  2332. return $dir if $entry eq '';
  2333. }
  2334. my $e = $dir->{member}->{$entry};
  2335. if (! defined $e) {
  2336. bless $e = { 'entry' => $entry, 'dir' => $dir, }, 'entry';
  2337. $e->creator(script::caller_info);
  2338. $dir->{member}->{$entry} = $e;
  2339. }
  2340. $e;
  2341. }
  2342. # Look up a file entry in a directory.
  2343. #
  2344. # The file entry may be specified as relative, absolute (starts with /),
  2345. # or top-relative (starts with #).
  2346. sub lookupfile {
  2347. my($dir, $entry) = @_;
  2348. if ($entry !~ m#$MATCH_SEPARATOR#o) {
  2349. # Fast path: simple entry name in a known directory.
  2350. if ($entry =~ s/^#//) {
  2351. # Top-relative names begin with #.
  2352. $dir = $dir::top;
  2353. } elsif ($entry =~ s/^!//) {
  2354. $dir = $dir::cwd->srcdir;
  2355. }
  2356. } else {
  2357. my $dirsref;
  2358. ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
  2359. $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
  2360. return undef if $entry eq '';
  2361. }
  2362. my $f = $dir->{member}->{$entry};
  2363. if (! defined $f) {
  2364. bless $f = { 'entry' => $entry, 'dir' => $dir, }, 'file';
  2365. $f->creator(script::caller_info);
  2366. $dir->{member}->{$entry} = $f;
  2367. } elsif (ref $f eq 'entry') {
  2368. bless $f, 'file';
  2369. } elsif (ref $f ne 'file') {
  2370. _type_exception($f);
  2371. }
  2372. $f;
  2373. }
  2374. # Look up a (sub-)directory entry in a directory.
  2375. #
  2376. # The (sub-)directory entry may be specified as relative, absolute
  2377. # (starts with /), or top-relative (starts with #).
  2378. sub lookupdir {
  2379. my($dir, $entry) = @_;
  2380. my $dirsref;
  2381. if ($entry !~ m#$MATCH_SEPARATOR#o) {
  2382. # Fast path: simple entry name in a known directory.
  2383. if ($entry =~ s/^#//) {
  2384. # Top-relative names begin with #.
  2385. $dir = $dir::top;
  2386. } elsif ($entry =~ s/^!//) {
  2387. $dir = $dir::cwd->srcdir;
  2388. }
  2389. } else {
  2390. ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
  2391. }
  2392. push(@$dirsref, $entry) if $entry ne '';
  2393. _create_dirs($dir, @$dirsref);
  2394. }
  2395. # Look up a file entry and return it if it's accessible.
  2396. sub lookup_accessible {
  2397. my $file = $_[0]->lookupfile($_[1]);
  2398. return ($file && $file->accessible) ? $file : undef;
  2399. }
  2400. # Return the parent directory without doing a lookupdir,
  2401. # which would create a parent if it doesn't already exist.
  2402. # A return value of undef (! $dir->up) indicates a root directory.
  2403. sub up {
  2404. $_[0]->{member}->{$dir::UPDIR};
  2405. }
  2406. # Return whether this is an entry somewhere underneath the
  2407. # specified directory.
  2408. sub is_under {
  2409. my $dir = $_[0];
  2410. while ($dir) {
  2411. return 1 if $_[1] == $dir;
  2412. $dir = $dir->up;
  2413. }
  2414. return undef;
  2415. }
  2416. # Return the relative path from the calling directory ($_[1])
  2417. # to the object. If the object is not under the directory, then
  2418. # we return it as a top-relative or absolute path name.
  2419. sub relpath {
  2420. my ($dir, $obj) = @_;
  2421. my @dirs;
  2422. my $o = $obj;
  2423. while ($o) {
  2424. if ($dir == $o) {
  2425. if (@dirs < 2) {
  2426. return $dirs[0] || '';
  2427. } else {
  2428. return File::Spec->catdir(@dirs);
  2429. }
  2430. }
  2431. unshift(@dirs, $o->{entry});
  2432. $o = $o->up;
  2433. }
  2434. # The object was not underneath the specified directory.
  2435. # Use the node's cached path, which is either top-relative
  2436. # (in which case we append '#' to the beginning) or
  2437. # absolute.
  2438. my $p = $obj->path;
  2439. $p = '#' . $p if ! File::Spec->file_name_is_absolute($p);
  2440. return $p;
  2441. }
  2442. # Return the path of the directory (file paths implemented
  2443. # separately, below).
  2444. sub path {
  2445. $_[0]->{path} ||
  2446. ($_[0]->{path} = $_[0]->{dir}->prefix . $_[0]->{entry});
  2447. }
  2448. # Return the pathname as a prefix to be concatenated with an entry.
  2449. sub prefix {
  2450. return $_[0]->{prefix} if exists $_[0]->{prefix};
  2451. $_[0]->{prefix} = $_[0]->path . $SEPARATOR;
  2452. }
  2453. # Return the related source path prefix.
  2454. sub srcprefix {
  2455. return $_[0]->{srcprefix} if exists $_[0]->{srcprefix};
  2456. my($srcdir) = $_[0]->srcdir;
  2457. $srcdir->{srcprefix} = $srcdir eq $_[0] ? $srcdir->prefix
  2458. : $srcdir->srcprefix;
  2459. }
  2460. # Return the related source directory.
  2461. sub srcdir {
  2462. $_[0]->{'srcdir'} ||
  2463. ($_[0]->{'srcdir'} = $_[0]->{dir}->srcdir->lookupdir($_[0]->{entry}))
  2464. }
  2465. # Return if the directory is linked to a separate source directory.
  2466. sub is_linked {
  2467. return $_[0]->{is_linked} if defined $_[0]->{is_linked};
  2468. $_[0]->{is_linked} = $_[0]->path ne $_[0]->srcdir->path;
  2469. }
  2470. sub link {
  2471. my(@paths) = @_;
  2472. my($srcdir) = $dir::cwd->lookupdir(pop @paths)->srcdir;
  2473. map($dir::cwd->lookupdir($_)->{'srcdir'} = $srcdir, @paths);
  2474. # make a reverse lookup for the link.
  2475. $srcdir->{links} = [] if ! $srcdir->{links};
  2476. push @{$srcdir->{links}}, @paths;
  2477. }
  2478. use vars qw( @tail ); # TODO: Why global ????
  2479. sub linked_targets {
  2480. my $tgt = shift;
  2481. my @targets = ();
  2482. my $dir;
  2483. if (ref $tgt eq 'dir') {
  2484. $dir = $tgt;
  2485. } else {
  2486. push @tail, $tgt;
  2487. $dir = $tgt->{dir};
  2488. }
  2489. while ($dir) {
  2490. if (defined $dir->{links} && @{$dir->{links}}) {
  2491. push @targets,
  2492. map(File::Spec->catdir($_, @tail), @{$dir->{links}});
  2493. #print STDERR "Found Link: ${\$dir->path} -> @{\$dir->{links}}\n";
  2494. }
  2495. unshift @tail, $dir->{entry};
  2496. $dir = $dir->up;
  2497. }
  2498. return map($dir::top->lookupdir($_), @targets);
  2499. }
  2500. sub accessible {
  2501. my $path = $_[0]->path;
  2502. my $err = "$0: you have attempted to use path \"$path\" both as a file " .
  2503. "and as a directory!\n";
  2504. die $err;
  2505. }
  2506. sub init {
  2507. my $path = Cwd::cwd();
  2508. # We know we can get away with passing undef to lookupdir
  2509. # as the directory because $dir is an absolute path.
  2510. $top = lookupdir(undef, $path);
  2511. $top->{'path'} = $top->{srcpath} = $dir::CURDIR;
  2512. $top->{'prefix'} = '';
  2513. $top->{'srcdir'} = $top;
  2514. $cwd = $top;
  2515. ($cwd_vol, undef, undef) = File::Spec->splitpath($path);
  2516. $cwd_vol = '' if ! defined $cwd_vol;
  2517. $cwd_vol = uc($cwd_vol) if File::Spec->case_tolerant;
  2518. }
  2519. package file;
  2520. use vars qw( @ISA $level );
  2521. BEGIN { @ISA = qw(dir); $level = 0 }
  2522. # Return the pathname of the file.
  2523. # Define this separately from dir::path because we don't want to
  2524. # cache all file pathnames (just directory pathnames).
  2525. sub path {
  2526. $_[0]->{dir}->prefix . $_[0]->{entry}
  2527. }
  2528. # Return the related source file path.
  2529. sub srcpath {
  2530. $_[0]->{dir}->srcprefix . $_[0]->{entry}
  2531. }
  2532. # Return if the file is (should be) linked to a separate source file.
  2533. sub is_linked {
  2534. $_[0]->{dir}->is_linked
  2535. }
  2536. # Repository file search. If the local file exists, that wins.
  2537. # Otherwise, return the first existing same-named file under a
  2538. # Repository directory. If there isn't anything with the same name
  2539. # under a Repository directory, return the local file name anyway
  2540. # so that some higher layer can try to construct it.
  2541. sub rfile {
  2542. return $_[0]->{rfile} if exists $_[0]->{rfile};
  2543. my($self) = @_;
  2544. my($rfile) = $self;
  2545. if (@param::rpath) {
  2546. my($path) = $self->path;
  2547. if (! File::Spec->file_name_is_absolute($path) && ! -f $path) {
  2548. my($dir);
  2549. foreach $dir (@param::rpath) {
  2550. my($t) = $dir->prefix . $path;
  2551. if (-f $t) {
  2552. $rfile = $_[0]->lookupfile($t);
  2553. $rfile->{'lfile'} = $self;
  2554. last;
  2555. }
  2556. }
  2557. }
  2558. }
  2559. $self->{rfile} = $rfile;
  2560. }
  2561. # Returns the local file for a repository file;
  2562. # returns self if it's already a local file.
  2563. sub lfile {
  2564. $_[0]->{'lfile'} || $_[0]
  2565. }
  2566. # returns the "precious" status of this file.
  2567. sub precious {
  2568. return $_[0]->{precious};
  2569. }
  2570. # "Erase" reference to a Repository file,
  2571. # making this a completely local file object
  2572. # by pointing it back to itself.
  2573. sub no_rfile {
  2574. $_[0]->{'rfile'} = $_[0];
  2575. }
  2576. # Return a path to the first existing file under a Repository directory,
  2577. # implicitly returning the current file's path if there isn't a
  2578. # same-named file under a Repository directory.
  2579. sub rpath {
  2580. $_[0]->{rpath} ||
  2581. ($_[0]->{rpath} = $_[0]->rfile->path)
  2582. }
  2583. # Return a path to the first linked srcpath file under a Repositoy
  2584. # directory, implicitly returning the current file's srcpath if there
  2585. # isn't a same-named file under a Repository directory.
  2586. sub rsrcpath {
  2587. return $_[0]->{rsrcpath} if exists $_[0]->{rsrcpath};
  2588. my($self) = @_;
  2589. my($path) = $self->{rsrcpath} = $self->srcpath;
  2590. if (@param::rpath && ! File::Spec->file_name_is_absolute($path) && ! -f $path) {
  2591. my($dir);
  2592. foreach $dir (@param::rpath) {
  2593. my($t) = $dir->prefix . $path;
  2594. if (-f $t) {
  2595. $self->{rsrcpath} = $t;
  2596. last;
  2597. }
  2598. }
  2599. }
  2600. $self->{rsrcpath};
  2601. }
  2602. # Return if a same-named file source file exists.
  2603. # This handles the interaction of Link and Repository logic.
  2604. # As a side effect, it will link a source file from its Linked
  2605. # directory (preferably local, but maybe in a repository)
  2606. # into a build directory from its proper Linked directory.
  2607. sub source_exists {
  2608. return $_[0]->{source_exists} if defined $_[0]->{source_exists};
  2609. my($self) = @_;
  2610. my($path) = $self->path;
  2611. my($mtime, $ctime) = (stat($path))[9,10];
  2612. if ($self->is_linked) {
  2613. # Linked directory, local logic.
  2614. my($srcpath) = $self->srcpath;
  2615. my($src_mtime, $src_ctime) = (stat($srcpath))[9,10];
  2616. if ($src_mtime) {
  2617. if (! $mtime || $src_mtime != $mtime || $src_ctime != $ctime) {
  2618. futil::install($srcpath, $self);
  2619. }
  2620. return $self->{source_exists} = 1;
  2621. }
  2622. # Linked directory, repository logic.
  2623. if (@param::rpath) {
  2624. if ($self != $self->rfile) {
  2625. return $self->{source_exists} = 1;
  2626. }
  2627. my($rsrcpath) = $self->rsrcpath;
  2628. if ($path ne $rsrcpath) {
  2629. my($rsrc_mtime, $rsrc_ctime) = (stat($rsrcpath))[9,10];
  2630. if ($rsrc_mtime) {
  2631. if (! $mtime || $rsrc_mtime != $mtime
  2632. || $rsrc_ctime != $ctime) {
  2633. futil::install($rsrcpath, $self);
  2634. }
  2635. return $self->{source_exists} = 1;
  2636. }
  2637. }
  2638. }
  2639. # There was no source file in any Linked directory
  2640. # under any Repository. If there's one in the local
  2641. # build directory, it no longer belongs there.
  2642. if ($mtime) {
  2643. unlink($path) || die("$0: couldn't unlink $path ($!)\n");
  2644. }
  2645. return $self->{source_exists} = '';
  2646. } else {
  2647. if ($mtime) {
  2648. return $self->{source_exists} = 1;
  2649. }
  2650. if (@param::rpath && $self != $self->rfile) {
  2651. return $self->{source_exists} = 1;
  2652. }
  2653. return $self->{source_exists} = '';
  2654. }
  2655. }
  2656. # Return if a same-named derived file exists under a Repository directory.
  2657. sub derived_exists {
  2658. $_[0]->{derived_exists} ||
  2659. ($_[0]->{derived_exists} = ($_[0] != $_[0]->rfile));
  2660. }
  2661. # Return if this file is somewhere under a Repository directory.
  2662. sub is_on_rpath {
  2663. defined $_[0]->{'lfile'};
  2664. }
  2665. sub local {
  2666. my($self, $arg) = @_;
  2667. if (defined $arg) {
  2668. $self->{'local'} = $arg;
  2669. }
  2670. $self->{'local'};
  2671. }
  2672. # Return the entry name of the specified file with the specified
  2673. # suffix appended. Leave it untouched if the suffix is already there.
  2674. # Differs from the addsuffix function, below, in that this strips
  2675. # the existing suffix (if any) before appending the desired one.
  2676. sub base_suf {
  2677. my($entry) = $_[0]->{entry};
  2678. if ($entry !~ m/$_[1]$/) {
  2679. $entry =~ s/\.[^\.]*$//;
  2680. $entry .= $_[1];
  2681. }
  2682. $entry;
  2683. }
  2684. # Return the suffix of the file; everything including and to the
  2685. # right of the last dot.
  2686. sub suffix {
  2687. my @pieces = split(/\./, $_[0]->{entry});
  2688. my $suffix = pop(@pieces);
  2689. return ".$suffix";
  2690. }
  2691. # Called as a simple function file::addsuffix(name, suffix)
  2692. sub addsuffix {
  2693. my($name, $suffix) = @_;
  2694. if ($suffix && substr($name, -length($suffix)) ne $suffix) {
  2695. return $name .= $suffix;
  2696. }
  2697. $name;
  2698. }
  2699. # Return true if the file is (or will be) accessible.
  2700. # That is, if we can build it, or if it is already present.
  2701. sub accessible {
  2702. (exists $_[0]->{builder}) || ($_[0]->source_exists);
  2703. }
  2704. # Return true if the file should be ignored for the purpose
  2705. # of computing dependency information (should not be considered
  2706. # as a dependency and, further, should not be scanned for
  2707. # dependencies).
  2708. sub ignore {
  2709. return 0 if !$param::ignore;
  2710. return $_[0]->{ignore} if exists $_[0]->{ignore};
  2711. $_[0]->{ignore} = $_[0]->path =~ /$param::ignore/o;
  2712. }
  2713. # Build the file, if necessary.
  2714. sub build {
  2715. return $_[0]->{status} if $_[0]->{status};
  2716. my($status) = &file::_build;
  2717. if ($_[0]->{after_build_func}) {
  2718. my($pkgvars) = $_[0]->{conscript}->{pkgvars};
  2719. NameSpace::restore('script', $pkgvars) if $pkgvars;
  2720. eval("package script; " . $_[0]->{after_build_func});
  2721. print "Error running AfterBuild for ${\$_[0]->path}: $@\n" if ($@);
  2722. NameSpace::remove('script', keys %$pkgvars) if $pkgvars;
  2723. }
  2724. return $status;
  2725. }
  2726. sub _build {
  2727. my($self) = @_;
  2728. print main::DEPFILE $self->path, "\n" if $param::depfile;
  2729. print((' ' x $level), "Checking ", $self->path, "\n") if $param::depends;
  2730. if (!exists $self->{builder}) {
  2731. # We don't know how to build the file. This is OK, if
  2732. # the file is present as a source file, under either the
  2733. # local tree or a Repository.
  2734. if ($self->source_exists) {
  2735. return $self->{status} = 'handled';
  2736. } else {
  2737. my($name) = $self->path;
  2738. print("$0: don't know how to construct \"$name\"\n");
  2739. exit(1) unless $param::kflag;
  2740. return $self->{status} = 'errors'; # xxx used to be 'unknown'
  2741. }
  2742. }
  2743. # An associated build object exists, so we know how to build
  2744. # the file. We first compute the signature of the file, based
  2745. # on its dependendencies, then only rebuild the file if the
  2746. # signature has changed.
  2747. my($builder) = $self->{builder};
  2748. $level += 2;
  2749. my(@deps) = (@{$self->{dep}}, @{$self->{sources}});
  2750. my($rdeps) = \@deps;
  2751. if ($param::random) {
  2752. # If requested, build in a random order, instead of the
  2753. # order that the dependencies were listed.
  2754. my(%rdeps);
  2755. map { $rdeps{$_,'*' x int(rand 10)} = $_ } @deps;
  2756. $rdeps = [values(%rdeps)];
  2757. }
  2758. $self->{status} = '';
  2759. my $dep;
  2760. for $dep (@$rdeps) {
  2761. if ((build $dep) eq 'errors') {
  2762. # Propagate dependent errors to target.
  2763. # but try to build all dependents regardless of errors.
  2764. $self->{status} = 'errors';
  2765. }
  2766. }
  2767. # If any dependents had errors, then we abort.
  2768. if ($self->{status} eq 'errors') {
  2769. $level -= 2;
  2770. return 'errors';
  2771. }
  2772. # Compute the final signature of the file, based on
  2773. # the static dependencies (in order), dynamic dependencies,
  2774. # output path name, and (non-substituted) build script.
  2775. my($sig) = 'sig'->collect(map('sig'->signature($_->rfile), @deps),
  2776. $builder->includes($self),
  2777. $builder->scriptsig);
  2778. # May have gotten errors during computation of dynamic
  2779. # dependency signature, above.
  2780. $level -= 2;
  2781. return 'errors' if $self->{status} eq 'errors';
  2782. if (@param::rpath && $self->derived_exists) {
  2783. # There is no local file of this name, but there is one
  2784. # under a Repository directory.
  2785. if ('sig'->current($self->rfile, $sig)) {
  2786. # The Repository copy is current (its signature matches
  2787. # our calculated signature).
  2788. if ($self->local) {
  2789. # ...but they want a local copy, so provide it.
  2790. main::showcom("Local copy of ${\$self->path} from " .
  2791. "${\$self->rpath}");
  2792. futil::install($self->rpath, $self);
  2793. 'sig'->bsig($self, $sig);
  2794. }
  2795. return $self->{status} = 'handled';
  2796. }
  2797. # The signatures don't match, implicitly because something
  2798. # on which we depend exists locally. Get rid of the reference
  2799. # to the Repository file; we'll build this (and anything that
  2800. # depends on it) locally.
  2801. $self->no_rfile;
  2802. }
  2803. # Then check for currency.
  2804. if (! 'sig'->current($self, $sig)) {
  2805. # We have to build/derive the file.
  2806. print((' ' x $level), "Rebuilding ", $self->path, ": out of date.\n")
  2807. if $param::depends;
  2808. # First check to see if the built file is cached.
  2809. if ($builder->cachin($self, $sig)) {
  2810. 'sig'->bsig($self, $sig);
  2811. return $self->{status} = 'built';
  2812. } elsif ($builder->action($self)) {
  2813. $builder->cachout($self, $sig);
  2814. 'sig'->bsig($self, $sig);
  2815. return $self->{status} = 'built';
  2816. } else {
  2817. die("$0: errors constructing ${\$self->path}\n")
  2818. unless $param::kflag;
  2819. return $self->{status} = 'errors';
  2820. }
  2821. } else {
  2822. # Push this out to the cache if we've been asked to (-C option).
  2823. # Don't normally do this because it slows us down.
  2824. # In a fully built system, no accesses to the cache directory
  2825. # are required to check any files. This is a win if cache is
  2826. # heavily shared. Enabling this option puts the directory in the
  2827. # loop. Useful only when you wish to recreate a cache from a build.
  2828. if ($param::cachesync) {
  2829. $builder->cachout($self, $sig);
  2830. 'sig'->bsig($self, $sig);
  2831. }
  2832. return $self->{status} = 'handled';
  2833. }
  2834. }
  2835. # Bind an action to a file, with the specified sources. No return value.
  2836. sub bind {
  2837. my($self, $builder, @sources) = @_;
  2838. if ($self->{builder} && !$self->{builder}->compatible($builder)) {
  2839. # Even if not "compatible", we can still check to see if the
  2840. # derivation is identical. It should be identical if the builder is
  2841. # the same and the sources are the same.
  2842. if ("$self->{builder} @{$self->{sources}}" ne "$builder @sources") {
  2843. $main::errors++;
  2844. my($_foo1, $script1, $line1, $sub1) = @{$self->creator};
  2845. my($_foo2, $script2, $line2, $sub2) = script::caller_info;
  2846. my $err = "\t${\$self->path}\n" .
  2847. "\tbuilt (at least) two different ways:\n" .
  2848. "\t\t$script1, line $line1: $sub1\n" .
  2849. "\t\t$script2, line $line2: $sub2\n";
  2850. die $err;
  2851. }
  2852. return;
  2853. }
  2854. if ($param::wflag) {
  2855. my($script, $line, $sub);
  2856. (undef, $script, $line, $sub) = script::caller_info;
  2857. $self->{script} = '' if ! defined $self->{script};
  2858. $self->{script} .= "; " if $self->{script};
  2859. $self->{script} .= qq($sub in "$script", line $line);
  2860. }
  2861. $self->{builder} = $builder;
  2862. push(@{$self->{sources}}, @sources);
  2863. @{$self->{dep}} = () if ! defined $self->{dep};
  2864. $self->{conscript} = $priv::self->{script};
  2865. }
  2866. sub is_under {
  2867. $_[0]->{dir}->is_under($_[1]);
  2868. }
  2869. sub relpath {
  2870. my $dirpath = $_[0]->relpath($_[1]->{dir});
  2871. if (! $dirpath) {
  2872. return $_[1]->{entry};
  2873. } else {
  2874. File::Spec->catfile($dirpath, $_[1]->{entry});
  2875. }
  2876. }
  2877. # Return the signature array for this file.
  2878. # This probably belongs in its own "sigarray" package,
  2879. # which would make it easier to optimize performance.
  2880. sub sigarray {
  2881. if ($_[0]->{sigaref}) {
  2882. return @{$_[0]->{sigaref}};
  2883. }
  2884. my $self = shift;
  2885. # glob2pat based on The Perl Cookbook, p. 180.
  2886. sub glob2pat {
  2887. my $globstr = shift;
  2888. my %patmap = (
  2889. '*' => '.*',
  2890. '?' => '.',
  2891. '[' => '[',
  2892. ']' => ']',
  2893. '/' => "\Q$dir::SEPARATOR", # Cons-specific modification
  2894. );
  2895. $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
  2896. return '^' . $globstr . '$';
  2897. }
  2898. my @sigarray;
  2899. my $default;
  2900. my $builder = $self->lfile->{builder};
  2901. if (! $builder) {
  2902. @sigarray = @$param::sourcesig;
  2903. $default = [qw(content)];
  2904. } else {
  2905. if ($builder->{env} && $builder->{env}->{SIGNATURE}) {
  2906. @sigarray = @{$builder->{env}->{SIGNATURE}};
  2907. } else {
  2908. my $class = ref $builder;
  2909. my $path = $self->path;
  2910. warn qq($0: Warning: Builder package $class did not record\n) .
  2911. qq(\tthe calling environment for '$path'.\n) .
  2912. qq(\tUnable to use any %SIGNATURE construction variable\n) .
  2913. qq(\tfor signature configuration.\n);
  2914. }
  2915. $default = [qw(build)];
  2916. }
  2917. my $path = $self->path;
  2918. while (@sigarray) {
  2919. my($glob, $aref) = splice(@sigarray, 0, 2);
  2920. my $re = glob2pat($glob);
  2921. if ($path =~ /$re/) {
  2922. $aref = [split(/\s+/, $aref)] if ! ref $aref;
  2923. $self->{sigaref} = $aref;
  2924. return @$aref;
  2925. }
  2926. }
  2927. $self->{sigaref} = $default;
  2928. return @{$self->{sigaref}}
  2929. }
  2930. # Decide if this file's signature should be the content or build signature.
  2931. sub sigtype {
  2932. if ($_[0]->{sigtype}) {
  2933. return $_[0]->{sigtype};
  2934. }
  2935. my $self = shift;
  2936. my @sigarray = $self->sigarray;
  2937. my $sigtype;
  2938. if (grep($_ eq "build", @sigarray)) {
  2939. $sigtype = 'bsig';
  2940. } elsif (grep($_ =~ /content$/, @sigarray)) {
  2941. $sigtype = 'csig';
  2942. }
  2943. return $self->{sigtype} = $sigtype;
  2944. }
  2945. # Return whether this file is configured to use stored
  2946. # signature values from the .consign file.
  2947. sub stored {
  2948. if (! defined $_[0]->{stored}) {
  2949. $_[0]->{stored} = grep($_ eq "stored-content", $_[0]->sigarray);
  2950. }
  2951. return $_[0]->{stored};
  2952. }
  2953. # Generic entry (file or directory) handling.
  2954. # This is an empty subclass for nodes that haven't
  2955. # quite decided whether they're files or dirs.
  2956. # Use file methods until someone blesses them one way or the other.
  2957. package entry;
  2958. use vars qw( @ISA );
  2959. BEGIN { @ISA = qw(file) }
  2960. # File utilities
  2961. package futil;
  2962. # Install one file as another.
  2963. # Links them if possible (hard link), otherwise copies.
  2964. # Don't ask why, but the source is a path, the tgt is a file obj.
  2965. sub install {
  2966. my($sp, $tgt) = @_;
  2967. my($tp) = $tgt->path;
  2968. return 1 if $tp eq $sp;
  2969. return 1 if eval { link($sp, $tp) };
  2970. unlink($tp);
  2971. if (! futil::mkdir($tgt->{dir})) {
  2972. return undef;
  2973. }
  2974. return 1 if eval { link($sp, $tp) };
  2975. futil::copy($sp, $tp);
  2976. }
  2977. # Copy one file to another. Arguments are actual file names.
  2978. # Returns undef on failure. Preserves mtime and mode.
  2979. sub copy {
  2980. my ($sp, $tp) = @_;
  2981. my ($mode, $length, $atime, $mtime) = (stat($sp))[2,7,8,9];
  2982. # Use Perl standard library module for file copying, which handles
  2983. # binary copies. <schwarze@isa.de> 1998-06-18
  2984. if (! File::Copy::copy($sp, $tp)) {
  2985. warn qq($0: can\'t install "$sp" to "$tp" ($!)\n); #'
  2986. return undef;
  2987. }
  2988. # The file has been created, so try both the chmod and utime,
  2989. # first making sure the copy is writable (because permissions
  2990. # affect the ability to modify file times on some operating
  2991. # systems), and then changing permissions back if necessary.
  2992. my $ret = 1;
  2993. my $wmode = $mode | 0700;
  2994. if (! chmod $wmode, $tp) {
  2995. warn qq($0: can\'t set mode $wmode on file "$tp" ($!)\n); #'
  2996. $ret = undef;
  2997. }
  2998. if (! utime $atime, $mtime, $tp) {
  2999. warn qq($0: can\'t set modification time for file "$tp" ($!)\n); #'
  3000. $ret = undef;
  3001. }
  3002. if ($mode != $wmode && ! chmod $mode, $tp) {
  3003. warn qq($0: can\'t set mode $mode on file "$tp" ($!)\n); #'
  3004. $ret = undef;
  3005. }
  3006. return $ret;
  3007. }
  3008. # Ensure that the specified directory exists.
  3009. # Aborts on failure.
  3010. sub mkdir {
  3011. return 1 if $_[0]->{'exists'};
  3012. if (! futil::mkdir($_[0]->{dir})) { # Recursively make parent.
  3013. return undef;
  3014. }
  3015. my($path) = $_[0]->path;
  3016. if (!-d $path && !mkdir($path, 0777)) {
  3017. warn qq($0: can't create directory $path ($!).\n); #'
  3018. return undef;
  3019. }
  3020. $_[0]->{'exists'} = 1;
  3021. }
  3022. # Signature package.
  3023. package sig::hash;
  3024. use vars qw( $called );
  3025. sub init {
  3026. my($dir) = @_;
  3027. my($consign) = $dir->prefix . ".consign";
  3028. my($dhash) = $dir->{consign} = {};
  3029. if (-f $consign) {
  3030. open(CONSIGN, $consign) || die("$0: can't open $consign ($!)\n");
  3031. while(<CONSIGN>) {
  3032. chop;
  3033. my ($file, $sig) = split(/:/,$_);
  3034. $dhash->{$file} = $sig;
  3035. }
  3036. close(CONSIGN);
  3037. }
  3038. $dhash
  3039. }
  3040. # Read the hash entry for a particular file.
  3041. sub in {
  3042. my($dir) = $_[0]->{dir};
  3043. ($dir->{consign} || init($dir))->{$_[0]->{entry}}
  3044. }
  3045. # Write the hash entry for a particular file.
  3046. sub out {
  3047. my($file, $sig) = @_;
  3048. my($dir) = $file->{dir};
  3049. ($dir->{consign} || init($dir))->{$file->{entry}} = $sig;
  3050. $sig::hash::dirty{$dir} = $dir;
  3051. }
  3052. # Eliminate the hash entry for a particular file.
  3053. sub clear {
  3054. my($file) = @_;
  3055. my($dir) = $file->{dir};
  3056. delete $dir->{consign}->{$file->{entry}} if $dir->{consign};
  3057. $sig::hash::dirty{$dir} = $dir;
  3058. }
  3059. # Flush hash entries. Called at end or via ^C interrupt.
  3060. sub END {
  3061. return if $called++; # May be called twice.
  3062. close(CONSIGN); # in case this came in via ^C.
  3063. my $dir;
  3064. for $dir (values %sig::hash::dirty) {
  3065. my($consign) = $dir->prefix . ".consign";
  3066. my($constemp) = $consign . ".$$";
  3067. if (! open(CONSIGN, ">$constemp")) {
  3068. die("$0: can't create $constemp ($!)\n");
  3069. }
  3070. my($entry, $sig);
  3071. while (($entry, $sig) = each %{$dir->{consign}}) {
  3072. if (! print CONSIGN "$entry:$sig\n") {
  3073. die("$0: error writing to $constemp ($!)\n");
  3074. }
  3075. }
  3076. close(CONSIGN);
  3077. if (! rename($constemp, $consign)) {
  3078. if (futil::copy($constemp, $consign)) {
  3079. unlink($constemp);
  3080. } else {
  3081. die("$0: couldn't rename or copy $constemp to $consign " .
  3082. "($!)\n");
  3083. }
  3084. }
  3085. }
  3086. }
  3087. # Derived file caching.
  3088. package cache;
  3089. # Find a file in the cache. Return non-null if the file is in the cache.
  3090. sub in {
  3091. return undef unless $param::cache;
  3092. my($file, $sig) = @_;
  3093. # Add the path to the signature, to make it unique.
  3094. $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
  3095. my($dir) = substr($sig, 0, 1);
  3096. my($cp) = File::Spec->catfile($param::cache, $dir, $sig);
  3097. return -f $cp && futil::install($cp, $file);
  3098. }
  3099. # Try to flush a file to the cache, if not already there.
  3100. # If it doesn't make it out, due to an error, then that doesn't
  3101. # really matter.
  3102. sub out {
  3103. return unless $param::cache;
  3104. my($file, $sig) = @_;
  3105. # Add the path to the signature, to make it unique.
  3106. $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
  3107. my($dir) = substr($sig, 0, 1);
  3108. my($sp) = $file->path;
  3109. my($cp) = File::Spec->catfile($param::cache, $dir, $sig);
  3110. my($cdir) = File::Spec->catfile($param::cache, $dir);
  3111. if (! -d $cdir) {
  3112. mkdir($cdir, 0777) ||
  3113. die("$0: can't create cache directory $cdir ($!).\n");
  3114. } elsif (-f $cp) {
  3115. # Already cached: try to use that instead, to save space.
  3116. # This can happen if the -cs option is used on a previously
  3117. # uncached build, or if two builds occur simultaneously.
  3118. my($lp) = ".$sig";
  3119. unlink($lp);
  3120. return if ! eval { link($cp, $lp) };
  3121. rename($lp, $sp);
  3122. # Unix98 says, "If the old argument and the new argument both
  3123. # [refer] to the same existing file, the rename() function
  3124. # returns successfully and performs no other action." So, if
  3125. # $lp and $sp are links (i.e., $cp and $sp are links), $lp is
  3126. # left, and we must unlink it ourselves. If the rename failed
  3127. # for any reason, it is also good form to unlink the temporary
  3128. # $lp. Otherwise $lp no longer exists and, barring some race,
  3129. # the unlink fails silently.
  3130. unlink($lp);
  3131. return;
  3132. }
  3133. return if eval { link($sp, $cp) };
  3134. return if ! -f $sp; # if nothing to cache.
  3135. if (futil::copy($sp, "$cp.new")) {
  3136. rename("$cp.new", $cp);
  3137. }
  3138. }
  3139. # Generic signature handling package.
  3140. # This handles the higher-layer distinction between content and build
  3141. # signatures, relying on an underlying calculation package like
  3142. # "sig::md5"" to provide the signature values themselves.
  3143. package sig;
  3144. use vars qw( @ISA );
  3145. # Select the underlying package to be used for signature calculation.
  3146. # We play a few namespace games here. Specifically, we append
  3147. # "sig::" to the beginning of the subclass we're passed. Then,
  3148. # if the package ends in "::debug", we actually subclass the
  3149. # "sig::debug" package and as a wrapper around the underlying
  3150. # (e.g.) "sig::md5" package that's doing the real calculation.
  3151. sub select {
  3152. my($package, $subclass) = @_;
  3153. my $p = $package . "::" . $subclass;
  3154. my $sigpkg = $p;
  3155. if ($p =~ /(.*)::debug$/) {
  3156. $sigpkg = $1;
  3157. $p = 'sig::debug';
  3158. }
  3159. @ISA = ($p);
  3160. $p->init($sigpkg);
  3161. };
  3162. # Set or return the build signature of a file.
  3163. # This is computed elsewhere and passed in to us.
  3164. sub bsig {
  3165. my($self, $file, $sig) = @_;
  3166. if (defined $sig) {
  3167. $file->{'bsig'} = $sig;
  3168. $self->set($file);
  3169. } elsif (! defined $file->{'bsig'}) {
  3170. $file->{'bsig'} = '';
  3171. }
  3172. $file->{'bsig'}
  3173. }
  3174. # Determine the content signature of a file.
  3175. # This also sets the .consign entry unless the file is in a
  3176. # repository; we don't write into repositories, only read from them.
  3177. sub csig {
  3178. my($self, $file) = @_;
  3179. if (! $file->{'csig'}) {
  3180. $file->{'csig'} = $self->srcsig($file->path);
  3181. $self->set($file) if ! $file->is_on_rpath;
  3182. }
  3183. $_[1]->{'csig'}
  3184. }
  3185. # Determine the current signature of an already-existing or
  3186. # non-existant file. Unless a specific signature type (bsig
  3187. # or csig) is requested, this consults the file's signature
  3188. # array to decide whether to return content or build signature,
  3189. # and whether to use a cached value from a .consign file.
  3190. sub signature {
  3191. my($self, $file, $sigtype) = @_;
  3192. $sigtype = $file->sigtype if ! $sigtype;
  3193. #open(TTY, ">/dev/tty");
  3194. #print TTY $file->path, ": $sigtype\n";
  3195. #close(TTY);
  3196. my($path) = $file->path;
  3197. my($time) = (stat($path))[9];
  3198. if ($time) {
  3199. if ($file->{$sigtype}) {
  3200. return $file->{$sigtype};
  3201. }
  3202. if ($file->is_on_rpath || $file->stored) {
  3203. if ('sig'->fetch($file) && $file->{$sigtype}) {
  3204. if ($file->{'sigtime'} == $time ||
  3205. ! $param::rep_sig_times_ok
  3206. && $file->is_on_rpath) {
  3207. return $file->{$sigtype};
  3208. }
  3209. }
  3210. $file->{$sigtype} = undef;
  3211. }
  3212. if ($file->is_on_rpath || ! File::Spec->file_name_is_absolute($path)) {
  3213. my $sig = '';
  3214. if ($sigtype eq 'bsig') { $sig = $self->bsig($file); }
  3215. elsif ($sigtype eq 'csig') { $sig = $self->csig($file); }
  3216. return $sig;
  3217. }
  3218. # This file is not in a repository or under the local directory
  3219. # structure. In the canonical case, it's a utility that will be
  3220. # executed by a command. Historically, Cons has returned the
  3221. # name of the command concatenated with the modification time.
  3222. # Note that this is *not* the path ("cc" not "/bin/cc"), so it
  3223. # would lose in the unlikely event that a different copy of the
  3224. # utility was used that happened to have the same modification
  3225. # time (due to living in a different directory on the PATH, for
  3226. # example). The obvious "fix" of using the path like so, however:
  3227. # return $path . $time;
  3228. # is wrong. In a multi-machine build environment, different
  3229. # systems may have the same utility in different locations (due
  3230. # to different NFS mount points, for example), which would
  3231. # cause a lot of unnecessary builds if we used the full path.
  3232. # A better solution to strengthen this signature would be to
  3233. # also concatenate the size of the file, but that would cause
  3234. # unnecessary rebuilds when coming from .consign files that used
  3235. # the old scheme. All of which is to merely explain why we're
  3236. # leaving this as it has been, but documenting it here in case
  3237. # there's reason to change it in the future.
  3238. return $file->{entry} . $time;
  3239. }
  3240. return $file->{$sigtype} = '';
  3241. }
  3242. sub bsignature {
  3243. my($self, $file) = @_;
  3244. my($path) = $file->path;
  3245. my($time) = (stat($path))[9];
  3246. if ($time) {
  3247. if ($file->{'bsig'}) {
  3248. return $file->{'bsig'};
  3249. }
  3250. if ('sig'->fetch($file, 'bsig') && $file->{'bsig'}) {
  3251. if ($file->{'sigtime'} == $time ||
  3252. ! $param::rep_sig_times_ok
  3253. && $file->is_on_rpath) {
  3254. return $file->{'bsig'};
  3255. }
  3256. }
  3257. if ($file->is_on_rpath || ! File::Spec->file_name_is_absolute($path)) {
  3258. return $self->bsig($file);
  3259. }
  3260. return $path . $time;
  3261. }
  3262. return $file->{'bsig'} = '';
  3263. }
  3264. # Invalidate a file's signature, also clearing its .consign entry.
  3265. sub invalidate {
  3266. my($self, $file) = @_;
  3267. delete $file->{'sigtime'};
  3268. delete $file->{'bsig'};
  3269. delete $file->{'csig'};
  3270. sig::hash::clear($file);
  3271. }
  3272. # Store the signature for a file.
  3273. sub set {
  3274. my($self, $file) = @_;
  3275. my $sig = (stat($file->path))[9];
  3276. $sig .= " " . ($file->{'bsig'} || '-');
  3277. $sig .= " " . $file->{'csig'} if $file->{'csig'};
  3278. sig::hash::out($file, $sig);
  3279. }
  3280. # Fetch the signature(s) for a file.
  3281. # Returns whether there was a signature to fetch.
  3282. sub fetch {
  3283. my($self, $file, @kw) = @_;
  3284. @kw = ('bsig', 'csig') if ! @kw;
  3285. my $sig = sig::hash::in($file) || '';
  3286. my($sigtime, $bsig, $csig) = split(/ /, $sig);
  3287. $file->{'sigtime'} = $sigtime;
  3288. $file->{'bsig'} = $bsig || '' if grep($_ eq 'bsig', @kw);
  3289. $file->{'csig'} = $csig || '' if grep($_ eq 'csig', @kw);
  3290. $file->{'bsig'} = '' if $file->{'bsig'} eq '-';
  3291. return $sig ne '';
  3292. }
  3293. # MD5-based signature package.
  3294. package sig::md5;
  3295. use vars qw( $md5 );
  3296. # Initialize MD5 signature calculation by finding an appropriate
  3297. # module and creating the proper object.
  3298. sub init {
  3299. my $self = shift;
  3300. my @md5_modules = qw(Digest::MD5 MD5 Digest::Perl::MD5);
  3301. # We used to find the right module more simply, using $_ as the
  3302. # loop iterator and just doing:
  3303. #
  3304. # eval "use $_";
  3305. # $module = $_, $last if ! $@;
  3306. #
  3307. # in the loop. Empirically, though, this doesn't pass back the
  3308. # right value in $module on some ActiveState versions. (Maybe
  3309. # it's something to do with the eval in a for loop, I dunno.)
  3310. # Work around it by using $_ to pass the value out of the loop,
  3311. # which seems to work everywhere.
  3312. my $module;
  3313. for $module (@md5_modules) {
  3314. eval "use $module";
  3315. $_ = $module, last if ! $@;
  3316. }
  3317. $module = $_;
  3318. die "Cannot find any MD5 module from: @md5_modules" if $@;
  3319. $md5 = new $module;
  3320. }
  3321. # Is the provided signature equal to the signature of the current
  3322. # instantiation of the target (and does the target exist)?
  3323. sub current {
  3324. my($self, $file, $sig, $sigtype) = @_;
  3325. $self->bsignature($file) eq $sig;
  3326. }
  3327. # Return an aggregate signature for a list of signature values.
  3328. sub collect {
  3329. my($self, @sigs) = @_;
  3330. # The following sequence is faster than calling the hex interface.
  3331. $md5->reset();
  3332. $md5->add(join('', $param::salt, @sigs));
  3333. unpack("H*", $md5->digest());
  3334. }
  3335. # Directly compute a file signature as the MD5 checksum of the
  3336. # bytes in the file.
  3337. sub srcsig {
  3338. my($self, $path) = @_;
  3339. $md5->reset();
  3340. open(FILE, $path) || return '';
  3341. binmode(FILE);
  3342. $md5->addfile(\*FILE);
  3343. close(FILE);
  3344. unpack("H*", $md5->digest());
  3345. }
  3346. # Compute the signature of a command string.
  3347. # For MD5, this is just the string itself, since MD5 will condense
  3348. # the string contents into the ultimate signature. Other signature
  3349. # schemes may need to figure this out differently.
  3350. sub cmdsig {
  3351. my($self, $sig) = @_;
  3352. return $sig
  3353. }
  3354. # Generic debug package for signature calculation.
  3355. # Because of the way we're called by sig::select() and then use
  3356. # the specified value to set up @ISA, this package is essentially a
  3357. # factory that creates packages like sig::md5::debug, etc., on the fly.
  3358. package sig::debug;
  3359. use vars qw( @ISA $sigpkg $outfh );
  3360. local *FH;
  3361. sub init {
  3362. my $self = shift;
  3363. $sigpkg = shift;
  3364. @ISA = ($sigpkg);
  3365. $sigpkg->init();
  3366. my $file = $ENV{CONS_SIG_DEBUG};
  3367. if ($file) {
  3368. if (! open(FH, ">$file")) {
  3369. die "Cannot open $file: $!";
  3370. }
  3371. $outfh = \*FH;
  3372. } else {
  3373. $outfh = \*STDOUT;
  3374. }
  3375. }
  3376. sub current {
  3377. my($self, $file, $sig, $sigtype) = @_;
  3378. my $fsig = $self->bsignature($file);
  3379. my $sub = "${sigpkg}::current";
  3380. my $sep = "\n" . ' ' x (length($sub) + 1 - 3);
  3381. print $outfh "$sub(|$fsig|${sep}eq |$sig|)\n";
  3382. return $fsig eq $sig;
  3383. }
  3384. sub collect {
  3385. my($self, @sigs) = @_;
  3386. my $sig = $sigpkg->collect(@sigs);
  3387. my $sub = "${sigpkg}::collect";
  3388. my $sep = ",\n" . ' ' x (length($sub) + 1);
  3389. my $buf = join($sep, @sigs);
  3390. $buf = $param::salt . $sep . $buf if $param::salt;
  3391. print $outfh "$sub($buf)\n\t=> |$sig|\n";
  3392. return $sig;
  3393. }
  3394. sub srcsig {
  3395. my($self, $path) = @_;
  3396. my $sig = $sigpkg->srcsig($path);
  3397. print $outfh "${sigpkg}::srcsig($path)\n\t=> |$sig|\n";
  3398. return $sig;
  3399. }
  3400. __END__;
  3401. =head1 NAME
  3402. Cons - A Software Construction System
  3403. =head1 DESCRIPTION
  3404. A guide and reference for version 2.3.1
  3405. Copyright (c) 1996-2001 Free Software Foundation, Inc.
  3406. This program is free software; you can redistribute it and/or modify
  3407. it under the terms of the GNU General Public License as published by
  3408. the Free Software Foundation; either version 2 of the License, or
  3409. (at your option) any later version.
  3410. This program is distributed in the hope that it will be useful,
  3411. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3412. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3413. GNU General Public License for more details.
  3414. You should have received a copy of the GNU General Public License
  3415. along with this program; see the file COPYING. If not, write to
  3416. the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  3417. Boston, MA 02111-1307, USA.
  3418. =head1 Introduction
  3419. B<Cons> is a system for constructing, primarily, software, but is quite
  3420. different from previous software construction systems. Cons was designed
  3421. from the ground up to deal easily with the construction of software spread
  3422. over multiple source directories. Cons makes it easy to create build scripts
  3423. that are simple, understandable and maintainable. Cons ensures that complex
  3424. software is easily and accurately reproducible.
  3425. Cons uses a number of techniques to accomplish all of this. Construction
  3426. scripts are just Perl scripts, making them both easy to comprehend and very
  3427. flexible. Global scoping of variables is replaced with an import/export
  3428. mechanism for sharing information between scripts, significantly improving
  3429. the readability and maintainability of each script. B<Construction
  3430. environments> are introduced: these are Perl objects that capture the
  3431. information required for controlling the build process. Multiple
  3432. environments are used when different semantics are required for generating
  3433. products in the build tree. Cons implements automatic dependency analysis
  3434. and uses this to globally sequence the entire build. Variant builds are
  3435. easily produced from a single source tree. Intelligent build subsetting is
  3436. possible, when working on localized changes. Overrides can be setup to
  3437. easily override build instructions without modifying any scripts. MD5
  3438. cryptographic B<signatures> are associated with derived files, and are used
  3439. to accurately determine whether a given file needs to be rebuilt.
  3440. While offering all of the above, and more, Cons remains simple and easy to
  3441. use. This will, hopefully, become clear as you read the remainder of this
  3442. document.
  3443. =head1 Why Cons? Why not Make?
  3444. Cons is a B<make> replacement. In the following paragraphs, we look at a few
  3445. of the undesirable characteristics of make--and typical build environments
  3446. based on make--that motivated the development of Cons.
  3447. =head2 Build complexity
  3448. Traditional make-based systems of any size tend to become quite complex. The
  3449. original make utility and its derivatives have contributed to this tendency
  3450. in a number of ways. Make is not good at dealing with systems that are
  3451. spread over multiple directories. Various work-arounds are used to overcome
  3452. this difficulty; the usual choice is for make to invoke itself recursively
  3453. for each sub-directory of a build. This leads to complicated code, in which
  3454. it is often unclear how a variable is set, or what effect the setting of a
  3455. variable will have on the build as a whole. The make scripting language has
  3456. gradually been extended to provide more possibilities, but these have
  3457. largely served to clutter an already overextended language. Often, builds
  3458. are done in multiple passes in order to provide appropriate products from
  3459. one directory to another directory. This represents a further increase in
  3460. build complexity.
  3461. =head2 Build reproducibility
  3462. The bane of all makes has always been the correct handling of
  3463. dependencies. Most often, an attempt is made to do a reasonable job of
  3464. dependencies within a single directory, but no serious attempt is made to do
  3465. the job between directories. Even when dependencies are working correctly,
  3466. make's reliance on a simple time stamp comparison to determine whether a
  3467. file is out of date with respect to its dependents is not, in general,
  3468. adequate for determining when a file should be rederived. If an external
  3469. library, for example, is rebuilt and then ``snapped'' into place, the
  3470. timestamps on its newly created files may well be earlier than the last
  3471. local build, since it was built before it became visible.
  3472. =head2 Variant builds
  3473. Make provides only limited facilities for handling variant builds. With the
  3474. proliferation of hardware platforms and the need for debuggable
  3475. vs. optimized code, the ability to easily create these variants is
  3476. essential. More importantly, if variants are created, it is important to
  3477. either be able to separate the variants or to be able to reproduce the
  3478. original or variant at will. With make it is very difficult to separate the
  3479. builds into multiple build directories, separate from the source. And if
  3480. this technique isn't used, it's also virtually impossible to guarantee at
  3481. any given time which variant is present in the tree, without resorting to a
  3482. complete rebuild.
  3483. =head2 Repositories
  3484. Make provides only limited support for building software from code that
  3485. exists in a central repository directory structure. The VPATH feature of
  3486. GNU make (and some other make implementations) is intended to provide this,
  3487. but doesn't work as expected: it changes the path of target file to the
  3488. VPATH name too early in its analysis, and therefore searches for all
  3489. dependencies in the VPATH directory. To ensure correct development builds,
  3490. it is important to be able to create a file in a local build directory and
  3491. have any files in a code repository (a VPATH directory, in make terms) that
  3492. depend on the local file get rebuilt properly. This isn't possible with
  3493. VPATH, without coding a lot of complex repository knowledge directly into
  3494. the makefiles.
  3495. =head1 Keeping it simple
  3496. A few of the difficulties with make have been cited above. In this and
  3497. subsequent sections, we shall introduce Cons and show how these issues are
  3498. addressed.
  3499. =head2 Perl scripts
  3500. Cons is Perl-based. That is, Cons scripts--F<Conscript> and F<Construct>
  3501. files, the equivalent to F<Makefile> or F<makefile>--are all written in
  3502. Perl. This provides an immediate benefit: the language for writing scripts
  3503. is a familiar one. Even if you don't happen to be a Perl programmer, it
  3504. helps to know that Perl is basically just a simple declarative language,
  3505. with a well-defined flow of control, and familiar semantics. It has
  3506. variables that behave basically the way you would expect them to,
  3507. subroutines, flow of control, and so on. There is no special syntax
  3508. introduced for Cons. The use of Perl as a scripting language simplifies
  3509. the task of expressing the appropriate solution to the often complex
  3510. requirements of a build.
  3511. =head2 Hello, World!
  3512. To ground the following discussion, here's how you could build the B<Hello,
  3513. World!> C application with Cons:
  3514. $env = new cons();
  3515. Program $env 'hello', 'hello.c';
  3516. If you install this script in a directory, naming the script F<Construct>,
  3517. and create the F<hello.c> source file in the same directory, then you can
  3518. type C<cons hello> to build the application:
  3519. % cons hello
  3520. cc -c hello.c -o hello.o
  3521. cc -o hello hello.o
  3522. =head2 Construction environments
  3523. A key simplification of Cons is the idea of a B<construction environment>. A
  3524. construction environment is an B<object> characterized by a set of key/value
  3525. pairs and a set of B<methods>. In order to tell Cons how to build something,
  3526. you invoke the appropriate method via an appropriate construction
  3527. environment. Consider the following example:
  3528. $env = new cons(
  3529. CC => 'gcc',
  3530. LIBS => 'libworld.a'
  3531. );
  3532. Program $env 'hello', 'hello.c';
  3533. In this case, rather than using the default construction environment, as is,
  3534. we have overridden the value of C<CC> so that the GNU C Compiler equivalent
  3535. is used, instead. Since this version of B<Hello, World!> requires a library,
  3536. F<libworld.a>, we have specified that any program linked in this environment
  3537. should be linked with that library. If the library exists already, well and
  3538. good, but if not, then we'll also have to include the statement:
  3539. Library $env 'libworld', 'world.c';
  3540. Now if you type C<cons hello>, the library will be built before the program
  3541. is linked, and, of course, C<gcc> will be used to compile both modules:
  3542. % cons hello
  3543. gcc -c hello.c -o hello.o
  3544. gcc -c world.c -o world.o
  3545. ar r libworld.a world.o
  3546. ar: creating libworld.a
  3547. ranlib libworld.a
  3548. gcc -o hello hello.o libworld.a
  3549. =head2 Automatic and complete dependency analysis
  3550. With Cons, dependencies are handled automatically. Continuing the previous
  3551. example, note that when we modify F<world.c>, F<world.o> is recompiled,
  3552. F<libworld.a> recreated, and F<hello> relinked:
  3553. % vi world.c
  3554. [EDIT]
  3555. % cons hello
  3556. gcc -c world.c -o world.o
  3557. ar r libworld.a world.o
  3558. ar: creating libworld.a
  3559. ranlib libworld.a
  3560. gcc -o hello hello.o libworld.a
  3561. This is a relatively simple example: Cons ``knows'' F<world.o> depends upon
  3562. F<world.c>, because the dependency is explicitly set up by the C<Library>
  3563. method. It also knows that F<libworld.a> depends upon F<world.o> and that
  3564. F<hello> depends upon F<libworld.a>, all for similar reasons.
  3565. Now it turns out that F<hello.c> also includes the interface definition
  3566. file, F<world.h>:
  3567. % emacs world.h
  3568. [EDIT]
  3569. % cons hello
  3570. gcc -c hello.c -o hello.o
  3571. gcc -o hello hello.o libworld.a
  3572. How does Cons know that F<hello.c> includes F<world.h>, and that F<hello.o>
  3573. must therefore be recompiled? For now, suffice it to say that when
  3574. considering whether or not F<hello.o> is up-to-date, Cons invokes a scanner
  3575. for its dependency, F<hello.c>. This scanner enumerates the files included
  3576. by F<hello.c> to come up with a list of further dependencies, beyond those
  3577. made explicit by the Cons script. This process is recursive: any files
  3578. included by included files will also be scanned.
  3579. Isn't this expensive? The answer is--it depends. If you do a full build of a
  3580. large system, the scanning time is insignificant. If you do a rebuild of a
  3581. large system, then Cons will spend a fair amount of time thinking about it
  3582. before it decides that nothing has to be done (although not necessarily more
  3583. time than make!). The good news is that Cons makes it very easy to
  3584. intelligently subset your build, when you are working on localized changes.
  3585. =head2 Automatic global build sequencing
  3586. Because Cons does full and accurate dependency analysis, and does this
  3587. globally, for the entire build, Cons is able to use this information to take
  3588. full control of the B<sequencing> of the build. This sequencing is evident
  3589. in the above examples, and is equivalent to what you would expect for make,
  3590. given a full set of dependencies. With Cons, this extends trivially to
  3591. larger, multi-directory builds. As a result, all of the complexity involved
  3592. in making sure that a build is organized correctly--including multi-pass
  3593. hierarchical builds--is eliminated. We'll discuss this further in the next
  3594. sections.
  3595. =head1 Building large trees--still just as simple
  3596. =head2 A hierarchy of build scripts
  3597. A larger build, in Cons, is organized by creating a hierarchy of B<build
  3598. scripts>. At the top of the tree is a script called F<Construct>. The rest
  3599. of the scripts, by convention, are each called F<Conscript>. These scripts
  3600. are connected together, very simply, by the C<Build>, C<Export>, and
  3601. C<Import> commands.
  3602. =head2 The Build command
  3603. The C<Build> command takes a list of F<Conscript> file names, and arranges
  3604. for them to be included in the build. For example:
  3605. Build qw(
  3606. drivers/display/Conscript
  3607. drivers/mouse/Conscript
  3608. parser/Conscript
  3609. utilities/Conscript
  3610. );
  3611. This is a simple two-level hierarchy of build scripts: all the subsidiary
  3612. F<Conscript> files are mentioned in the top-level F<Construct> file. Notice
  3613. that not all directories in the tree necessarily have build scripts
  3614. associated with them.
  3615. This could also be written as a multi-level script. For example, the
  3616. F<Construct> file might contain this command:
  3617. Build qw(
  3618. parser/Conscript
  3619. drivers/Conscript
  3620. utilities/Conscript
  3621. );
  3622. and the F<Conscript> file in the F<drivers> directory might contain this:
  3623. Build qw(
  3624. display/Conscript
  3625. mouse/Conscript
  3626. );
  3627. Experience has shown that the former model is a little easier to understand,
  3628. since the whole construction tree is laid out in front of you, at the
  3629. top-level. Hybrid schemes are also possible. A separately maintained
  3630. component that needs to be incorporated into a build tree, for example,
  3631. might hook into the build tree in one place, but define its own construction
  3632. hierarchy.
  3633. By default, Cons does not change its working directory to the directory
  3634. containing a subsidiary F<Conscript> file it is including. This behavior
  3635. can be enabled for a build by specifying, in the top-level F<Construct>
  3636. file:
  3637. Conscript_chdir 1;
  3638. When enabled, Cons will change to the subsidiary F<Conscript> file's
  3639. containing directory while reading in that file, and then change back
  3640. to the top-level directory once the file has been processed.
  3641. It is expected that this behavior will become the default in some future
  3642. version of Cons. To prepare for this transition, builds that expect
  3643. Cons to remain at the top of the build while it reads in a subsidiary
  3644. F<Conscript> file should explicitly disable this feature as follows:
  3645. Conscript_chdir 0;
  3646. =head2 Relative, top-relative, and absolute file names
  3647. You may have noticed that the file names specified to the Build command are
  3648. relative to the location of the script it is invoked from. This is generally
  3649. true for other filename arguments to other commands, too, although we might
  3650. as well mention here that if you begin a file name with a hash mark, ``#'',
  3651. then that file is interpreted relative to the top-level directory (where the
  3652. F<Construct> file resides). And, not surprisingly, if you begin it with ``/'',
  3653. then it is considered to be an absolute pathname. This is true even on
  3654. systems which use a back slash rather than a forward slash to name absolute
  3655. paths.
  3656. (There is another file prefix, ``!'', that is interpreted specially by
  3657. Cons. See discussion of the C<Link> command, below, for details.)
  3658. =head2 Using modules in build scripts
  3659. You may pull modules into each F<Conscript> file using the normal Perl
  3660. C<use> or C<require> statements:
  3661. use English;
  3662. require My::Module;
  3663. Each C<use> or C<require> only affects the one F<Conscript> file in which
  3664. it appears. To use a module in multiple F<Conscript> files, you must
  3665. put a C<use> or C<require> statement in each one that needs the module.
  3666. =head2 Scope of variables
  3667. The top-level F<Construct> file and all F<Conscript> files begin life in
  3668. a common, separate Perl package. B<Cons> controls the symbol table for
  3669. the package so that, the symbol table for each script is empty, except
  3670. for the F<Construct> file, which gets some of the command line arguments.
  3671. All of the variables that are set or used, therefore, are set by the
  3672. script itself--not by some external script.
  3673. Variables can be explicitly B<imported> by a script from its parent
  3674. script. To import a variable, it must have been B<exported> by the parent
  3675. and initialized (otherwise an error will occur).
  3676. =head2 The Export command
  3677. The C<Export> command is used as in the following example:
  3678. $env = new cons();
  3679. $INCLUDE = "#export/include";
  3680. $LIB = "#export/lib";
  3681. Export qw( env INCLUDE LIB );
  3682. Build qw( util/Conscript );
  3683. The values of the simple variables mentioned in the C<Export> list will be
  3684. squirreled away by any subsequent C<Build> commands. The C<Export> command
  3685. will only export Perl B<scalar> variables, that is, variables whose name
  3686. begins with C<$>. Other variables, objects, etc. can be exported by
  3687. reference--but all scripts will refer to the same object, and this object
  3688. should be considered to be read-only by the subsidiary scripts and by the
  3689. original exporting script. It's acceptable, however, to assign a new value
  3690. to the exported scalar variable--that won't change the underlying variable
  3691. referenced. This sequence, for example, is OK:
  3692. $env = new cons();
  3693. Export qw( env INCLUDE LIB );
  3694. Build qw( util/Conscript );
  3695. $env = new cons(CFLAGS => '-O');
  3696. Build qw( other/Conscript );
  3697. It doesn't matter whether the variable is set before or after the C<Export>
  3698. command. The important thing is the value of the variable at the time the
  3699. C<Build> command is executed. This is what gets squirreled away. Any
  3700. subsequent C<Export> commands, by the way, invalidate the first: you must
  3701. mention all the variables you wish to export on each C<Export> command.
  3702. =head2 The Import command
  3703. Variables exported by the C<Export> command can be imported into subsidiary
  3704. scripts by the C<Import> command. The subsidiary script always imports
  3705. variables directly from the superior script. Consider this example:
  3706. Import qw( env INCLUDE );
  3707. This is only legal if the parent script exported both C<$env> and
  3708. C<$INCLUDE>. It also must have given each of these variables values. It is
  3709. OK for the subsidiary script to only import a subset of the exported
  3710. variables (in this example, C<$LIB>, which was exported by the previous
  3711. example, is not imported).
  3712. All the imported variables are automatically re-exported, so the sequence:
  3713. Import qw ( env INCLUDE );
  3714. Build qw ( beneath-me/Conscript );
  3715. will supply both C<$env> and C<$INCLUDE> to the subsidiary file. If only
  3716. C<$env> is to be exported, then the following will suffice:
  3717. Import qw ( env INCLUDE );
  3718. Export qw ( env );
  3719. Build qw ( beneath-me/Conscript );
  3720. Needless to say, the variables may be modified locally before invoking
  3721. C<Build> on the subsidiary script.
  3722. =head2 Build script evaluation order
  3723. The only constraint on the ordering of build scripts is that superior
  3724. scripts are evaluated before their inferior scripts. The top-level
  3725. F<Construct> file, for instance, is evaluated first, followed by any
  3726. inferior scripts. This is all you really need to know about the evaluation
  3727. order, since order is generally irrelevant. Consider the following C<Build>
  3728. command:
  3729. Build qw(
  3730. drivers/display/Conscript
  3731. drivers/mouse/Conscript
  3732. parser/Conscript
  3733. utilities/Conscript
  3734. );
  3735. We've chosen to put the script names in alphabetical order, simply because
  3736. that's the most convenient for maintenance purposes. Changing the order will
  3737. make no difference to the build.
  3738. =head1 A Model for sharing files
  3739. =head2 Some simple conventions
  3740. In any complex software system, a method for sharing build products needs to
  3741. be established. We propose a simple set of conventions which are trivial to
  3742. implement with Cons, but very effective.
  3743. The basic rule is to require that all build products which need to be shared
  3744. between directories are shared via an intermediate directory. We have
  3745. typically called this F<export>, and, in a C environment, provided
  3746. conventional sub-directories of this directory, such as F<include>, F<lib>,
  3747. F<bin>, etc.
  3748. These directories are defined by the top-level F<Construct> file. A simple
  3749. F<Construct> file for a B<Hello, World!> application, organized using
  3750. multiple directories, might look like this:
  3751. # Construct file for Hello, World!
  3752. # Where to put all our shared products.
  3753. $EXPORT = '#export';
  3754. Export qw( CONS INCLUDE LIB BIN );
  3755. # Standard directories for sharing products.
  3756. $INCLUDE = "$EXPORT/include";
  3757. $LIB = "$EXPORT/lib";
  3758. $BIN = "$EXPORT/bin";
  3759. # A standard construction environment.
  3760. $CONS = new cons (
  3761. CPPPATH => $INCLUDE, # Include path for C Compilations
  3762. LIBPATH => $LIB, # Library path for linking programs
  3763. LIBS => '-lworld', # List of standard libraries
  3764. );
  3765. Build qw(
  3766. hello/Conscript
  3767. world/Conscript
  3768. );
  3769. The F<world> directory's F<Conscript> file looks like this:
  3770. # Conscript file for directory world
  3771. Import qw( CONS INCLUDE LIB );
  3772. # Install the products of this directory
  3773. Install $CONS $LIB, 'libworld.a';
  3774. Install $CONS $INCLUDE, 'world.h';
  3775. # Internal products
  3776. Library $CONS 'libworld.a', 'world.c';
  3777. and the F<hello> directory's F<Conscript> file looks like this:
  3778. # Conscript file for directory hello
  3779. Import qw( CONS BIN );
  3780. # Exported products
  3781. Install $CONS $BIN, 'hello';
  3782. # Internal products
  3783. Program $CONS 'hello', 'hello.c';
  3784. To construct a B<Hello, World!> program with this directory structure, go to
  3785. the top-level directory, and invoke C<cons> with the appropriate
  3786. arguments. In the following example, we tell Cons to build the directory
  3787. F<export>. To build a directory, Cons recursively builds all known products
  3788. within that directory (only if they need rebuilding, of course). If any of
  3789. those products depend upon other products in other directories, then those
  3790. will be built, too.
  3791. % cons export
  3792. Install world/world.h as export/include/world.h
  3793. cc -Iexport/include -c hello/hello.c -o hello/hello.o
  3794. cc -Iexport/include -c world/world.c -o world/world.o
  3795. ar r world/libworld.a world/world.o
  3796. ar: creating world/libworld.a
  3797. ranlib world/libworld.a
  3798. Install world/libworld.a as export/lib/libworld.a
  3799. cc -o hello/hello hello/hello.o -Lexport/lib -lworld
  3800. Install hello/hello as export/bin/hello
  3801. =head2 Clean, understandable, location-independent scripts
  3802. You'll note that the two F<Conscript> files are very clean and
  3803. to-the-point. They simply specify products of the directory and how to build
  3804. those products. The build instructions are minimal: they specify which
  3805. construction environment to use, the name of the product, and the name of
  3806. the inputs. Note also that the scripts are location-independent: if you wish
  3807. to reorganize your source tree, you are free to do so: you only have to
  3808. change the F<Construct> file (in this example), to specify the new locations
  3809. of the F<Conscript> files. The use of an export tree makes this goal easy.
  3810. Note, too, how Cons takes care of little details for you. All the F<export>
  3811. directories, for example, were made automatically. And the installed files
  3812. were really hard-linked into the respective export directories, to save
  3813. space and time. This attention to detail saves considerable work, and makes
  3814. it even easier to produce simple, maintainable scripts.
  3815. =head1 Separating source and build trees
  3816. It's often desirable to keep any derived files from the build completely
  3817. separate from the source files. This makes it much easier to keep track of
  3818. just what is a source file, and also makes it simpler to handle B<variant>
  3819. builds, especially if you want the variant builds to co-exist.
  3820. =head2 Separating build and source directories using the Link command
  3821. Cons provides a simple mechanism that handles all of these requirements. The
  3822. C<Link> command is invoked as in this example:
  3823. Link 'build' => 'src';
  3824. The specified directories are ``linked'' to the specified source
  3825. directory. Let's suppose that you setup a source directory, F<src>, with the
  3826. sub-directories F<world> and F<hello> below it, as in the previous
  3827. example. You could then substitute for the original build lines the
  3828. following:
  3829. Build qw(
  3830. build/world/Conscript
  3831. build/hello/Conscript
  3832. );
  3833. Notice that you treat the F<Conscript> file as if it existed in the build
  3834. directory. Now if you type the same command as before, you will get the
  3835. following results:
  3836. % cons export
  3837. Install build/world/world.h as export/include/world.h
  3838. cc -Iexport/include -c build/hello/hello.c -o build/hello/hello.o
  3839. cc -Iexport/include -c build/world/world.c -o build/world/world.o
  3840. ar r build/world/libworld.a build/world/world.o
  3841. ar: creating build/world/libworld.a
  3842. ranlib build/world/libworld.a
  3843. Install build/world/libworld.a as export/lib/libworld.a
  3844. cc -o build/hello/hello build/hello/hello.o -Lexport/lib -lworld
  3845. Install build/hello/hello as export/bin/hello
  3846. Again, Cons has taken care of the details for you. In particular, you will
  3847. notice that all the builds are done using source files and object files from
  3848. the build directory. For example, F<build/world/world.o> is compiled from
  3849. F<build/world/world.c>, and F<export/include/world.h> is installed from
  3850. F<build/world/world.h>. This is accomplished on most systems by the simple
  3851. expedient of ``hard'' linking the required files from each source directory
  3852. into the appropriate build directory.
  3853. The links are maintained correctly by Cons, no matter what you do to the
  3854. source directory. If you modify a source file, your editor may do this ``in
  3855. place'' or it may rename it first and create a new file. In the latter case,
  3856. any hard link will be lost. Cons will detect this condition the next time
  3857. the source file is needed, and will relink it appropriately.
  3858. You'll also notice, by the way, that B<no> changes were required to the
  3859. underlying F<Conscript> files. And we can go further, as we shall see in the
  3860. next section.
  3861. =head2 Explicit references to the source directory
  3862. When using the C<Link> command on some operating systems or with some
  3863. tool chains, it's sometimes useful to have a command actually use
  3864. the path name to the source directory, not the build directory. For
  3865. example, on systems that must copy, not "hard link," the F<src/> and
  3866. F<build/> copies of C<Linked> files, using the F<src/> path of a file
  3867. name might make an editor aware that a syntax error must be fixed in the
  3868. source directory, not the build directory.
  3869. You can tell Cons that you want to use the "source path" for a file by
  3870. preceding the file name with a ``!'' (exclamation point). For example,
  3871. if we add a ``!'' to the beginning of a source file:
  3872. Program $env "foo", "!foo.c"; # Notice initial ! on foo.c
  3873. Cons will compile the target as follows:
  3874. cc -c src/foo.c -o build/foo.o
  3875. cc -o build/foo build/foo.o
  3876. Notice that Cons has compiled the program from the the F<src/foo.c>
  3877. source file. Without the initial ``!'', Cons would have compiled the
  3878. program using the F<build/foo.c> path name.
  3879. =head1 Variant builds
  3880. =head2 Hello, World! for baNaNa and peAcH OS's
  3881. Variant builds require just another simple extension. Let's take as an
  3882. example a requirement to allow builds for both the baNaNa and peAcH
  3883. operating systems. In this case, we are using a distributed file system,
  3884. such as NFS to access the particular system, and only one or the other of
  3885. the systems has to be compiled for any given invocation of C<cons>. Here's
  3886. one way we could set up the F<Construct> file for our B<Hello, World!>
  3887. application:
  3888. # Construct file for Hello, World!
  3889. die qq(OS must be specified) unless $OS = $ARG{OS};
  3890. die qq(OS must be "peach" or "banana")
  3891. if $OS ne "peach" && $OS ne "banana";
  3892. # Where to put all our shared products.
  3893. $EXPORT = "#export/$OS";
  3894. Export qw( CONS INCLUDE LIB BIN );
  3895. # Standard directories for sharing products.
  3896. $INCLUDE = "$EXPORT/include";
  3897. $LIB = "$EXPORT/lib";
  3898. $BIN = "$EXPORT/bin";
  3899. # A standard construction environment.
  3900. $CONS = new cons (
  3901. CPPPATH => $INCLUDE, # Include path for C Compilations
  3902. LIBPATH => $LIB, # Library path for linking programs
  3903. LIBS => '-lworld', # List of standard libraries
  3904. );
  3905. # $BUILD is where we will derive everything.
  3906. $BUILD = "#build/$OS";
  3907. # Tell cons where the source files for $BUILD are.
  3908. Link $BUILD => 'src';
  3909. Build (
  3910. "$BUILD/hello/Conscript",
  3911. "$BUILD/world/Conscript",
  3912. );
  3913. Now if we login to a peAcH system, we can build our B<Hello, World!>
  3914. application for that platform:
  3915. % cons export OS=peach
  3916. Install build/peach/world/world.h as export/peach/include/world.h
  3917. cc -Iexport/peach/include -c build/peach/hello/hello.c -o build/peach/hello/hello.o
  3918. cc -Iexport/peach/include -c build/peach/world/world.c -o build/peach/world/world.o
  3919. ar r build/peach/world/libworld.a build/peach/world/world.o
  3920. ar: creating build/peach/world/libworld.a
  3921. ranlib build/peach/world/libworld.a
  3922. Install build/peach/world/libworld.a as export/peach/lib/libworld.a
  3923. cc -o build/peach/hello/hello build/peach/hello/hello.o -Lexport/peach/lib -lworld
  3924. Install build/peach/hello/hello as export/peach/bin/hello
  3925. =head2 Variations on a theme
  3926. Other variations of this model are possible. For example, you might decide
  3927. that you want to separate out your include files into platform dependent and
  3928. platform independent files. In this case, you'd have to define an
  3929. alternative to C<$INCLUDE> for platform-dependent files. Most F<Conscript>
  3930. files, generating purely platform-independent include files, would not have
  3931. to change.
  3932. You might also want to be able to compile your whole system with debugging
  3933. or profiling, for example, enabled. You could do this with appropriate
  3934. command line options, such as C<DEBUG=on>. This would then be translated
  3935. into the appropriate platform-specific requirements to enable debugging
  3936. (this might include turning off optimization, for example). You could
  3937. optionally vary the name space for these different types of systems, but, as
  3938. we'll see in the next section, it's not B<essential> to do this, since Cons
  3939. is pretty smart about rebuilding things when you change options.
  3940. =head1 Signatures
  3941. Cons uses file B<signatures> to decide if a derived file is out-of-date
  3942. and needs rebuilding. In essence, if the contents of a file change,
  3943. or the manner in which the file is built changes, the file's signature
  3944. changes as well. This allows Cons to decide with certainty when a file
  3945. needs rebuilding, because Cons can detect, quickly and reliably, whether
  3946. any of its dependency files have been changed.
  3947. =head2 MD5 content and build signatures
  3948. Cons uses the B<MD5> (B<Message Digest 5>) algorithm to compute file
  3949. signatures. The MD5 algorithm computes a strong cryptographic checksum
  3950. for any given input string. Cons can, based on configuration, use two
  3951. different MD5 signatures for a given file:
  3952. The B<content signature> of a file is an MD5 checksum of the file's
  3953. contents. Consequently, when the contents of a file change, its content
  3954. signature changes as well.
  3955. The B<build signature> of a file is a combined MD5 checksum of:
  3956. =over 4
  3957. the signatures of all the input files used to build the file
  3958. the signatures of all dependency files discovered by source scanners
  3959. (for example, C<.h> files)
  3960. the signatures of all dependency files specified explicitly via the
  3961. C<Depends> method)
  3962. the command-line string used to build the file
  3963. =back
  3964. The build signature is, in effect, a digest of all the dependency
  3965. information for the specified file. Consequently, a file's build
  3966. signature changes whenever any part of its dependency information
  3967. changes: a new file is added, the contents of a file on which it depends
  3968. change, there's a change to the command line used to build the file (or
  3969. any of its dependency files), etc.
  3970. For example, in the previous section, the build signature of the
  3971. F<world.o> file will include:
  3972. =over 4
  3973. the signature of the F<world.c> file
  3974. the signatures of any header files that Cons detects are included,
  3975. directly or indirectly, by F<world.c>
  3976. the text of the actual command line was used to generate F<world.o>
  3977. =back
  3978. Similarly, the build signature of the F<libworld.a> file will include
  3979. all the signatures of its constituents (and hence, transitively, the
  3980. signatures of B<their> constituents), as well as the command line that
  3981. created the file.
  3982. Note that there is no need for a derived file to depend upon any
  3983. particular F<Construct> or F<Conscript> file. If changes to these files
  3984. affect a file, then this will be automatically reflected in its build
  3985. signature, since relevant parts of the command line are included in the
  3986. signature. Unrelated F<Construct> or F<Conscript> changes will have no
  3987. effect.
  3988. =head2 Storing signatures in .consign files
  3989. Before Cons exits, it stores the calculated signatures for all of the
  3990. files it built or examined in F<.consign> files, one per directory.
  3991. Cons uses this stored information on later invocations to decide if
  3992. derived files need to be rebuilt.
  3993. After the previous example was compiled, the F<.consign> file in the
  3994. F<build/peach/world> directory looked like this:
  3995. world.h:985533370 - d181712f2fdc07c1f05d97b16bfad904
  3996. world.o:985533372 2a0f71e0766927c0532977b0d2158981
  3997. world.c:985533370 - c712f77189307907f4189b5a7ab62ff3
  3998. libworld.a:985533374 69e568fc5241d7d25be86d581e1fb6aa
  3999. After the file name and colon, the first number is a timestamp of the
  4000. file's modification time (on UNIX systems, this is typically the number
  4001. of seconds since January 1st, 1970). The second value is the build
  4002. signature of the file (or ``-'' in the case of files with no build
  4003. signature--that is, source files). The third value, if any, is the
  4004. content signature of the file.
  4005. =head2 Using build signatures to decide when to rebuild files
  4006. When Cons is deciding whether to build or rebuild a derived file, it
  4007. first computes the file's current build signature. If the file doesn't
  4008. exist, it must obviously be built.
  4009. If, however, the file already exists, Cons next compares the
  4010. modification timestamp of the file against the timestamp value in
  4011. the F<.consign> file. If the timestamps match, Cons compares the
  4012. newly-computed build signature against the build signature in the
  4013. F<.consign> file. If the timestamps do not match or the build
  4014. signatures do not match, the derived file is rebuilt.
  4015. After the file is built or rebuilt, Cons arranges to store the
  4016. newly-computed build signature in the F<.consign> file when it exits.
  4017. =head2 Signature example
  4018. The use of these signatures is an extremely simple, efficient, and
  4019. effective method of improving--dramatically--the reproducibility of a
  4020. system.
  4021. We'll demonstrate this with a simple example:
  4022. # Simple "Hello, World!" Construct file
  4023. $CFLAGS = '-g' if $ARG{DEBUG} eq 'on';
  4024. $CONS = new cons(CFLAGS => $CFLAGS);
  4025. Program $CONS 'hello', 'hello.c';
  4026. Notice how Cons recompiles at the appropriate times:
  4027. % cons hello
  4028. cc -c hello.c -o hello.o
  4029. cc -o hello hello.o
  4030. % cons hello
  4031. cons: "hello" is up-to-date.
  4032. % cons DEBUG=on hello
  4033. cc -g -c hello.c -o hello.o
  4034. cc -o hello hello.o
  4035. % cons DEBUG=on hello
  4036. cons: "hello" is up-to-date.
  4037. % cons hello
  4038. cc -c hello.c -o hello.o
  4039. cc -o hello hello.o
  4040. =head2 Source-file signature configuration
  4041. Cons provides a C<SourceSignature> method that allows you to configure
  4042. how the signature should be calculated for any source file when its
  4043. signature is being used to decide if a dependent file is up-to-date.
  4044. The arguments to the C<SourceSignature> method consist of one or more
  4045. pairs of strings:
  4046. SourceSignature 'auto/*.c' => 'content',
  4047. '*' => 'stored-content';
  4048. The first string in each pair is a pattern to match against derived file
  4049. path names. The pattern is a file-globbing pattern, not a Perl regular
  4050. expression; the pattern <*.l> will match all Lex source files. The C<*>
  4051. wildcard will match across directory separators; the pattern C<foo/*.c>
  4052. would match all C source files in any subdirectory underneath the C<foo>
  4053. subdirectory.
  4054. The second string in each pair contains one of the following keywords to
  4055. specify how signatures should be calculated for source files that match
  4056. the pattern. The available keywords are:
  4057. =over 4
  4058. =item content
  4059. Use the content signature of the source file when calculating signatures
  4060. of files that depend on it. This guarantees correct calculation of the
  4061. file's signature for all builds, by telling Cons to read the contents of
  4062. a source file to calculate its content signature each time it is run.
  4063. =item stored-content
  4064. Use the source file's content signature as stored in the F<.consign>
  4065. file, provided the file's timestamp matches the cached timestamp value
  4066. in the F<.consign> file. This optimizes performance, with the slight
  4067. risk of an incorrect build if a source file's contents have been changed
  4068. so quickly after its previous update that the timestamp still matches
  4069. the stored timestamp in the F<.consign> file even though the contents
  4070. have changed.
  4071. =back
  4072. The Cons default behavior of always calculating a source file's
  4073. signature from the file's contents is equivalent to specifying:
  4074. SourceSignature '*' => 'content';
  4075. The C<*> will match all source files. The C<content> keyword
  4076. specifies that Cons will read the contents of a source file to calculate
  4077. its signature each time it is run.
  4078. A useful global performance optimization is:
  4079. SourceSignature '*' => 'stored-content';
  4080. This specifies that Cons will use pre-computed content signatures
  4081. from F<.consign> files, when available, rather than re-calculating a
  4082. signature from the the source file's contents each time Cons is run. In
  4083. practice, this is safe for most build situations, and only a problem
  4084. when source files are changed automatically (by scripts, for example).
  4085. The Cons default, however, errs on the side of guaranteeing a correct
  4086. build in all situations.
  4087. Cons tries to match source file path names against the patterns in the
  4088. order they are specified in the C<SourceSignature> arguments:
  4089. SourceSignature '/usr/repository/objects/*' => 'stored-content',
  4090. '/usr/repository/*' => 'content',
  4091. '*.y' => 'content',
  4092. '*' => 'stored-content';
  4093. In this example, all source files under the F</usr/repository/objects>
  4094. directory will use F<.consign> file content signatures, source files
  4095. anywhere else underneath F</usr/repository> will not use F<.consign>
  4096. signature values, all Yacc source files (C<*.y>) anywhere else will not
  4097. use F<.consign> signature values, and any other source file will use
  4098. F<.consign> signature values.
  4099. =head2 Derived-file signature configuration
  4100. Cons provides a C<SIGNATURE> construction variable that allows you to
  4101. configure how signatures are calculated for any derived file when its
  4102. signature is being used to decide if a dependent file is up-to-date.
  4103. The value of the C<SIGNATURE> construction variable is a Perl array
  4104. reference that holds one or more pairs of strings, like the arguments to
  4105. the C<SourceSignature> method.
  4106. The first string in each pair is a pattern to match against derived file
  4107. path names. The pattern is a file-globbing pattern, not a Perl regular
  4108. expression; the pattern `*.obj' will match all (Win32) object files.
  4109. The C<*> wildcard will match across directory separators; the pattern
  4110. `foo/*.a' would match all (UNIX) library archives in any subdirectory
  4111. underneath the foo subdirectory.
  4112. The second string in each pair contains one of the following keywords
  4113. to specify how signatures should be calculated for derived files that
  4114. match the pattern. The available keywords are the same as for the
  4115. C<SourceSignature> method, with an additional keyword:
  4116. =over 4
  4117. =item build
  4118. Use the build signature of the derived file when calculating signatures
  4119. of files that depend on it. This guarantees correct builds by forcing
  4120. Cons to rebuild any and all files that depend on the derived file.
  4121. =item content
  4122. Use the content signature of the derived file when calculating signatures
  4123. of files that depend on it. This guarantees correct calculation of the
  4124. file's signature for all builds, by telling Cons to read the contents of
  4125. a derived file to calculate its content signature each time it is run.
  4126. =item stored-content
  4127. Use the derived file's content signature as stored in the F<.consign>
  4128. file, provided the file's timestamp matches the cached timestamp value
  4129. in the F<.consign> file. This optimizes performance, with the slight
  4130. risk of an incorrect build if a derived file's contents have been
  4131. changed so quickly after a Cons build that the file's timestamp still
  4132. matches the stored timestamp in the F<.consign> file.
  4133. =back
  4134. The Cons default behavior (as previously described) for using
  4135. derived-file signatures is equivalent to:
  4136. $env = new cons(SIGNATURE => ['*' => 'build']);
  4137. The C<*> will match all derived files. The C<build> keyword specifies
  4138. that all derived files' build signatures will be used when calculating
  4139. whether a dependent file is up-to-date.
  4140. A useful alternative default C<SIGNATURE> configuration for many sites:
  4141. $env = new cons(SIGNATURE => ['*' => 'content']);
  4142. In this configuration, derived files have their signatures calculated
  4143. from the file contents. This adds slightly to Cons' workload, but has
  4144. the useful effect of "stopping" further rebuilds if a derived file is
  4145. rebuilt to exactly the same file contents as before, which usually
  4146. outweighs the additional computation Cons must perform.
  4147. For example, changing a comment in a C file and recompiling should
  4148. generate the exact same object file (assuming the compiler doesn't
  4149. insert a timestamp in the object file's header). In that case,
  4150. specifying C<content> or C<stored-content> for the signature calculation
  4151. will cause Cons to recognize that the object file did not actually
  4152. change as a result of being rebuilt, and libraries or programs that
  4153. include the object file will not be rebuilt. When C<build> is
  4154. specified, however, Cons will only "know" that the object file was
  4155. rebuilt, and proceed to rebuild any additional files that include the
  4156. object file.
  4157. Note that Cons tries to match derived file path names against the
  4158. patterns in the order they are specified in the C<SIGNATURE> array
  4159. reference:
  4160. $env = new cons(SIGNATURE => ['foo/*.o' => 'build',
  4161. '*.o' => 'content',
  4162. '*.a' => 'stored-content',
  4163. '*' => 'content']);
  4164. In this example, all object files underneath the F<foo> subdirectory
  4165. will use build signatures, all other object files (including object
  4166. files underneath other subdirectories!) will use F<.consign> file
  4167. content signatures, libraries will use F<.consign> file build
  4168. signatures, and all other derived files will use content signatures.
  4169. =head2 Debugging signature calculation
  4170. Cons provides a C<-S> option that can be used to specify what internal
  4171. Perl package Cons should use to calculate signatures. The default Cons
  4172. behavior is equivalent to specifying C<-S md5> on the command line.
  4173. The only other package (currently) available is an C<md5::debug>
  4174. package that prints out detailed information about the MD5 signature
  4175. calculations performed by Cons:
  4176. % cons -S md5::debug hello
  4177. sig::md5::srcsig(hello.c)
  4178. => |52d891204c62fe93ecb95281e1571938|
  4179. sig::md5::collect(52d891204c62fe93ecb95281e1571938)
  4180. => |fb0660af4002c40461a2f01fbb5ffd03|
  4181. sig::md5::collect(52d891204c62fe93ecb95281e1571938,
  4182. fb0660af4002c40461a2f01fbb5ffd03,
  4183. cc -c %< -o %>)
  4184. => |f7128da6c3fe3c377dc22ade70647b39|
  4185. sig::md5::current(||
  4186. eq |f7128da6c3fe3c377dc22ade70647b39|)
  4187. cc -c hello.c -o hello.o
  4188. sig::md5::collect()
  4189. => |d41d8cd98f00b204e9800998ecf8427e|
  4190. sig::md5::collect(f7128da6c3fe3c377dc22ade70647b39,
  4191. d41d8cd98f00b204e9800998ecf8427e,
  4192. cc -o %> %< )
  4193. => |a0bdce7fd09e0350e7efbbdb043a00b0|
  4194. sig::md5::current(||
  4195. eq |a0bdce7fd09e0350e7efbbdb043a00b0|)
  4196. cc -o hello, hello.o
  4197. =head1 Code Repositories
  4198. Many software development organizations will have one or more central
  4199. repository directory trees containing the current source code for one or
  4200. more projects, as well as the derived object files, libraries, and
  4201. executables. In order to reduce unnecessary recompilation, it is useful to
  4202. use files from the repository to build development software--assuming, of
  4203. course, that no newer dependency file exists in the local build tree.
  4204. =head2 Repository
  4205. Cons provides a mechanism to specify a list of code repositories that will
  4206. be searched, in-order, for source files and derived files not found in the
  4207. local build directory tree.
  4208. The following lines in a F<Construct> file will instruct Cons to look first
  4209. under the F</usr/experiment/repository> directory and then under the
  4210. F</usr/product/repository> directory:
  4211. Repository qw (
  4212. /usr/experiment/repository
  4213. /usr/product/repository
  4214. );
  4215. The repository directories specified may contain source files, derived files
  4216. (objects, libraries and executables), or both. If there is no local file
  4217. (source or derived) under the directory in which Cons is executed, then the
  4218. first copy of a same-named file found under a repository directory will be
  4219. used to build any local derived files.
  4220. Cons maintains one global list of repositories directories. Cons will
  4221. eliminate the current directory, and any non-existent directories, from the
  4222. list.
  4223. =head2 Finding the Construct file in a Repository
  4224. Cons will also search for F<Construct> and F<Conscript> files in the
  4225. repository tree or trees. This leads to a chicken-and-egg situation,
  4226. though: how do you look in a repository tree for a F<Construct> file if the
  4227. F<Construct> file tells you where the repository is? To get around this,
  4228. repositories may be specified via C<-R> options on the command line:
  4229. % cons -R /usr/experiment/repository -R /usr/product/repository .
  4230. Any repository directories specified in the F<Construct> or F<Conscript>
  4231. files will be appended to the repository directories specified by
  4232. command-line C<-R> options.
  4233. =head2 Repository source files
  4234. If the source code (include the F<Conscript> file) for the library version
  4235. of the I<Hello, World!> C application is in a repository (with no derived
  4236. files), Cons will use the repository source files to create the local object
  4237. files and executable file:
  4238. % cons -R /usr/src_only/repository hello
  4239. gcc -c /usr/src_only/repository/hello.c -o hello.o
  4240. gcc -c /usr/src_only/repository/world.c -o world.o
  4241. ar r libworld.a world.o
  4242. ar: creating libworld.a
  4243. ranlib libworld.a
  4244. gcc -o hello hello.o libworld.a
  4245. Creating a local source file will cause Cons to rebuild the appropriate
  4246. derived file or files:
  4247. % pico world.c
  4248. [EDIT]
  4249. % cons -R /usr/src_only/repository hello
  4250. gcc -c world.c -o world.o
  4251. ar r libworld.a world.o
  4252. ar: creating libworld.a
  4253. ranlib libworld.a
  4254. gcc -o hello hello.o libworld.a
  4255. And removing the local source file will cause Cons to revert back to
  4256. building the derived files from the repository source:
  4257. % rm world.c
  4258. % cons -R /usr/src_only/repository hello
  4259. gcc -c /usr/src_only/repository/world.c -o world.o
  4260. ar r libworld.a world.o
  4261. ar: creating libworld.a
  4262. ranlib libworld.a
  4263. gcc -o hello hello.o libworld.a
  4264. =head2 Repository derived files
  4265. If a repository tree contains derived files (usually object files,
  4266. libraries, or executables), Cons will perform its normal signature
  4267. calculation to decide whether the repository file is up-to-date or a derived
  4268. file must be built locally. This means that, in order to ensure correct
  4269. signature calculation, a repository tree must also contain the F<.consign>
  4270. files that were created by Cons when generating the derived files.
  4271. This would usually be accomplished by building the software in the
  4272. repository (or, alternatively, in a build directory, and then copying the
  4273. result to the repository):
  4274. % cd /usr/all/repository
  4275. % cons hello
  4276. gcc -c hello.c -o hello.o
  4277. gcc -c world.c -o world.o
  4278. ar r libworld.a world.o
  4279. ar: creating libworld.a
  4280. ranlib libworld.a
  4281. gcc -o hello hello.o libworld.a
  4282. (This is safe even if the F<Construct> file lists the F</usr/all/repository>
  4283. directory in a C<Repository> command because Cons will remove the current
  4284. directory from the repository list.)
  4285. Now if we want to build a copy of the application with our own F<hello.c>
  4286. file, we only need to create the one necessary source file, and use the
  4287. C<-R> option to have Cons use other files from the repository:
  4288. % mkdir $HOME/build1
  4289. % cd $HOME/build1
  4290. % ed hello.c
  4291. [EDIT]
  4292. % cons -R /usr/all/repository hello
  4293. gcc -c hello.c -o hello.o
  4294. gcc -o hello hello.o /usr/all/repository/libworld.a
  4295. Notice that Cons has not bothered to recreate a local F<libworld.a> library
  4296. (or recompile the F<world.o> module), but instead uses the already-compiled
  4297. version from the repository.
  4298. Because the MD5 signatures that Cons puts in the F<.consign> file contain
  4299. timestamps for the derived files, the signature timestamps must match the
  4300. file timestamps for a signature to be considered valid.
  4301. Some software systems may alter the timestamps on repository files (by
  4302. copying them, e.g.), in which case Cons will, by default, assume the
  4303. repository signatures are invalid and rebuild files unnecessarily. This
  4304. behavior may be altered by specifying:
  4305. Repository_Sig_Times_OK 0;
  4306. This tells Cons to ignore timestamps when deciding whether a signature is
  4307. valid. (Note that avoiding this sanity check means there must be proper
  4308. control over the repository tree to ensure that the derived files cannot be
  4309. modified without updating the F<.consign> signature.)
  4310. =head2 Local copies of files
  4311. If the repository tree contains the complete results of a build, and we try
  4312. to build from the repository without any files in our local tree, something
  4313. moderately surprising happens:
  4314. % mkdir $HOME/build2
  4315. % cd $HOME/build2
  4316. % cons -R /usr/all/repository hello
  4317. cons: "hello" is up-to-date.
  4318. Why does Cons say that the F<hello> program is up-to-date when there is no
  4319. F<hello> program in the local build directory? Because the repository (not
  4320. the local directory) contains the up-to-date F<hello> program, and Cons
  4321. correctly determines that nothing needs to be done to rebuild this
  4322. up-to-date copy of the file.
  4323. There are, however, many times in which it is appropriate to ensure that a
  4324. local copy of a file always exists. A packaging or testing script, for
  4325. example, may assume that certain generated files exist locally. Instead of
  4326. making these subsidiary scripts aware of the repository directory, the
  4327. C<Local> command may be added to a F<Construct> or F<Conscript> file to
  4328. specify that a certain file or files must appear in the local build
  4329. directory:
  4330. Local qw(
  4331. hello
  4332. );
  4333. Then, if we re-run the same command, Cons will make a local copy of the
  4334. program from the repository copy (telling you that it is doing so):
  4335. % cons -R /usr/all/repository hello
  4336. Local copy of hello from /usr/all/repository/hello
  4337. cons: "hello" is up-to-date.
  4338. Notice that, because the act of making the local copy is not considered a
  4339. "build" of the F<hello> file, Cons still reports that it is up-to-date.
  4340. Creating local copies is most useful for files that are being installed into
  4341. an intermediate directory (for sharing with other directories) via the
  4342. C<Install> command. Accompanying the C<Install> command for a file with a
  4343. companion C<Local> command is so common that Cons provides a
  4344. C<Install_Local> command as a convenient way to do both:
  4345. Install_Local $env, '#export', 'hello';
  4346. is exactly equivalent to:
  4347. Install $env '#export', 'hello';
  4348. Local '#export/hello';
  4349. Both the C<Local> and C<Install_Local> commands update the local F<.consign>
  4350. file with the appropriate file signatures, so that future builds are
  4351. performed correctly.
  4352. =head2 Repository dependency analysis
  4353. Due to its built-in scanning, Cons will search the specified repository
  4354. trees for included F<.h> files. Unless the compiler also knows about the
  4355. repository trees, though, it will be unable to find F<.h> files that only
  4356. exist in a repository. If, for example, the F<hello.c> file includes the
  4357. F<hello.h> file in its current directory:
  4358. % cons -R /usr/all/repository hello
  4359. gcc -c /usr/all/repository/hello.c -o hello.o
  4360. /usr/all/repository/hello.c:1: hello.h: No such file or directory
  4361. Solving this problem forces some requirements onto the way construction
  4362. environments are defined and onto the way the C C<#include> preprocessor
  4363. directive is used to include files.
  4364. In order to inform the compiler about the repository trees, Cons will add
  4365. appropriate C<-I> flags to the compilation commands. This means that the
  4366. C<CPPPATH> variable in the construction environment must explicitly specify
  4367. all subdirectories which are to be searched for included files, including the
  4368. current directory. Consequently, we can fix the above example by changing
  4369. the environment creation in the F<Construct> file as follows:
  4370. $env = new cons(
  4371. CC => 'gcc',
  4372. CPPPATH => '.',
  4373. LIBS => 'libworld.a',
  4374. );
  4375. Due to the definition of the C<CPPPATH> variable, this yields, when we
  4376. re-execute the command:
  4377. % cons -R /usr/all/repository hello
  4378. gcc -c -I. -I/usr/all/repository /usr/all/repository/hello.c -o hello.o
  4379. gcc -o hello hello.o /usr/all/repository/libworld.a
  4380. The order of the C<-I> flags replicates, for the C preprocessor, the same
  4381. repository-directory search path that Cons uses for its own dependency
  4382. analysis. If there are multiple repositories and multiple C<CPPPATH>
  4383. directories, Cons will append the repository directories to the beginning of
  4384. each C<CPPPATH> directory, rapidly multiplying the number of C<-I> flags.
  4385. As an extreme example, a F<Construct> file containing:
  4386. Repository qw(
  4387. /u1
  4388. /u2
  4389. );
  4390. $env = new cons(
  4391. CPPPATH => 'a:b:c',
  4392. );
  4393. Would yield a compilation command of:
  4394. cc -Ia -I/u1/a -I/u2/a -Ib -I/u1/b -I/u2/b -Ic -I/u1/c -I/u2/c -c hello.c -o hello.o
  4395. In order to shorten the command lines as much as possible, Cons will
  4396. remove C<-I> flags for any directories, locally or in the repositories,
  4397. which do not actually exist. (Note that the C<-I> flags are not included
  4398. in the MD5 signature calculation for the target file, so the target will
  4399. not be recompiled if the compilation command changes due to a directory
  4400. coming into existence.)
  4401. Because Cons relies on the compiler's C<-I> flags to communicate the
  4402. order in which repository directories must be searched, Cons' handling
  4403. of repository directories is fundamentally incompatible with using
  4404. double-quotes on the C<#include> directives in any C source code that
  4405. you plan to modify:
  4406. #include "file.h" /* DON'T USE DOUBLE-QUOTES LIKE THIS */
  4407. This is because most C preprocessors, when faced with such a directive, will
  4408. always first search the directory containing the source file. This
  4409. undermines the elaborate C<-I> options that Cons constructs to make the
  4410. preprocessor conform to its preferred search path.
  4411. Consequently, when using repository trees in Cons, B<always> use
  4412. angle-brackets for included files in any C source (.c or .h) files that
  4413. you plan to modify locally:
  4414. #include <file.h> /* USE ANGLE-BRACKETS INSTEAD */
  4415. Code that will not change can still safely use double quotes on #include
  4416. lines.
  4417. =head2 Repository_List
  4418. Cons provides a C<Repository_List> command to return a list of all
  4419. repository directories in their current search order. This can be used for
  4420. debugging, or to do more complex Perl stuff:
  4421. @list = Repository_List;
  4422. print join(' ', @list), "\n";
  4423. =head2 Repository interaction with other Cons features
  4424. Cons' handling of repository trees interacts correctly with other Cons
  4425. features--which is to say, it generally does what you would expect.
  4426. Most notably, repository trees interact correctly, and rather powerfully,
  4427. with the 'Link' command. A repository tree may contain one or more
  4428. subdirectories for version builds established via C<Link> to a source
  4429. subdirectory. Cons will search for derived files in the appropriate build
  4430. subdirectories under the repository tree.
  4431. =head1 Default targets
  4432. Until now, we've demonstrated invoking Cons with an explicit target
  4433. to build:
  4434. % cons hello
  4435. Normally, Cons does not build anything unless a target is specified,
  4436. but specifying '.' (the current directory) will build everything:
  4437. % cons # does not build anything
  4438. % cons . # builds everything under the top-level directory
  4439. Adding the C<Default> method to any F<Construct> or F<Conscript> file will add
  4440. the specified targets to a list of default targets. Cons will build
  4441. these defaults if there are no targets specified on the command line.
  4442. So adding the following line to the top-level F<Construct> file will mimic
  4443. Make's typical behavior of building everything by default:
  4444. Default '.';
  4445. The following would add the F<hello> and F<goodbye> commands (in the
  4446. same directory as the F<Construct> or F<Conscript> file) to the default list:
  4447. Default qw(
  4448. hello
  4449. goodbye
  4450. );
  4451. The C<Default> method may be used more than once to add targets to the
  4452. default list.
  4453. =head1 Selective builds
  4454. Cons provides two methods for reducing the size of given build. The first is
  4455. by specifying targets on the command line, and the second is a method for
  4456. pruning the build tree. We'll consider target specification first.
  4457. =head2 Selective targeting
  4458. Like make, Cons allows the specification of ``targets'' on the command
  4459. line. Cons targets may be either files or directories. When a directory is
  4460. specified, this is simply a short-hand notation for every derivable
  4461. product--that Cons knows about--in the specified directory and below. For
  4462. example:
  4463. % cons build/hello/hello.o
  4464. means build F<hello.o> and everything that F<hello.o> might need. This is
  4465. from a previous version of the B<Hello, World!> program in which F<hello.o>
  4466. depended upon F<export/include/world.h>. If that file is not up-to-date
  4467. (because someone modified F<src/world/world.h)>, then it will be rebuilt,
  4468. even though it is in a directory remote from F<build/hello>.
  4469. In this example:
  4470. % cons build
  4471. Everything in the F<build> directory is built, if necessary. Again, this may
  4472. cause more files to be built. In particular, both F<export/include/world.h>
  4473. and F<export/lib/libworld.a> are required by the F<build/hello> directory,
  4474. and so they will be built if they are out-of-date.
  4475. If we do, instead:
  4476. % cons export
  4477. then only the files that should be installed in the export directory will be
  4478. rebuilt, if necessary, and then installed there. Note that C<cons build>
  4479. might build files that C<cons export> doesn't build, and vice-versa.
  4480. =head2 No ``special'' targets
  4481. With Cons, make-style ``special'' targets are not required. The simplest
  4482. analog with Cons is to use special F<export> directories, instead. Let's
  4483. suppose, for example, that you have a whole series of unit tests that are
  4484. associated with your code. The tests live in the source directory near the
  4485. code. Normally, however, you don't want to build these tests. One solution
  4486. is to provide all the build instructions for creating the tests, and then to
  4487. install the tests into a separate part of the tree. If we install the tests
  4488. in a top-level directory called F<tests>, then:
  4489. % cons tests
  4490. will build all the tests.
  4491. % cons export
  4492. will build the production version of the system (but not the tests), and:
  4493. % cons build
  4494. should probably be avoided (since it will compile tests unnecessarily).
  4495. If you want to build just a single test, then you could explicitly name the
  4496. test (in either the F<tests> directory or the F<build> directory). You could
  4497. also aggregate the tests into a convenient hierarchy within the tests
  4498. directory. This hierarchy need not necessarily match the source hierarchy,
  4499. in much the same manner that the include hierarchy probably doesn't match
  4500. the source hierarchy (the include hierarchy is unlikely to be more than two
  4501. levels deep, for C programs).
  4502. If you want to build absolutely everything in the tree (subject to whatever
  4503. options you select), you can use:
  4504. % cons .
  4505. This is not particularly efficient, since it will redundantly walk all the
  4506. trees, including the source tree. The source tree, of course, may have
  4507. buildable objects in it--nothing stops you from doing this, even if you
  4508. normally build in a separate build tree.
  4509. =head1 Build Pruning
  4510. In conjunction with target selection, B<build pruning> can be used to reduce
  4511. the scope of the build. In the previous peAcH and baNaNa example, we have
  4512. already seen how script-driven build pruning can be used to make only half
  4513. of the potential build available for any given invocation of C<cons>. Cons
  4514. also provides, as a convenience, a command line convention that allows you
  4515. to specify which F<Conscript> files actually get ``built''--that is,
  4516. incorporated into the build tree. For example:
  4517. % cons build +world
  4518. The C<+> argument introduces a Perl regular expression. This must, of
  4519. course, be quoted at the shell level if there are any shell meta-characters
  4520. within the expression. The expression is matched against each F<Conscript>
  4521. file which has been mentioned in a C<Build> statement, and only those
  4522. scripts with matching names are actually incorporated into the build
  4523. tree. Multiple such arguments are allowed, in which case a match against any
  4524. of them is sufficient to cause a script to be included.
  4525. In the example, above, the F<hello> program will not be built, since Cons
  4526. will have no knowledge of the script F<hello/Conscript>. The F<libworld.a>
  4527. archive will be built, however, if need be.
  4528. There are a couple of uses for build pruning via the command line. Perhaps
  4529. the most useful is the ability to make local changes, and then, with
  4530. sufficient knowledge of the consequences of those changes, restrict the size
  4531. of the build tree in order to speed up the rebuild time. A second use for
  4532. build pruning is to actively prevent the recompilation of certain files that
  4533. you know will recompile due to, for example, a modified header file. You may
  4534. know that either the changes to the header file are immaterial, or that the
  4535. changes may be safely ignored for most of the tree, for testing
  4536. purposes.With Cons, the view is that it is pragmatic to admit this type of
  4537. behavior, with the understanding that on the next full build everything that
  4538. needs to be rebuilt will be. There is no equivalent to a ``make touch''
  4539. command, to mark files as permanently up-to-date. So any risk that is
  4540. incurred by build pruning is mitigated. For release quality work, obviously,
  4541. we recommend that you do not use build pruning (it's perfectly OK to use
  4542. during integration, however, for checking compilation, etc. Just be sure to
  4543. do an unconstrained build before committing the integration).
  4544. =head1 Temporary overrides
  4545. Cons provides a very simple mechanism for overriding aspects of a build. The
  4546. essence is that you write an override file containing one or more
  4547. C<Override> commands, and you specify this on the command line, when you run
  4548. C<cons>:
  4549. % cons -o over export
  4550. will build the F<export> directory, with all derived files subject to the
  4551. overrides present in the F<over> file. If you leave out the C<-o> option,
  4552. then everything necessary to remove all overrides will be rebuilt.
  4553. =head2 Overriding environment variables
  4554. The override file can contain two types of overrides. The first is incoming
  4555. environment variables. These are normally accessible by the F<Construct>
  4556. file from the C<%ENV> hash variable. These can trivially be overridden in
  4557. the override file by setting the appropriate elements of C<%ENV> (these
  4558. could also be overridden in the user's environment, of course).
  4559. =head2 The Override command
  4560. The second type of override is accomplished with the C<Override> command,
  4561. which looks like this:
  4562. Override <regexp>, <var1> => <value1>, <var2> => <value2>, ...;
  4563. The regular expression I<regexp> is matched against every derived file that
  4564. is a candidate for the build. If the derived file matches, then the
  4565. variable/value pairs are used to override the values in the construction
  4566. environment associated with the derived file.
  4567. Let's suppose that we have a construction environment like this:
  4568. $CONS = new cons(
  4569. COPT => '',
  4570. CDBG => '-g',
  4571. CFLAGS => '%COPT %CDBG',
  4572. );
  4573. Then if we have an override file F<over> containing this command:
  4574. Override '\.o$', COPT => '-O', CDBG => '';
  4575. then any C<cons> invocation with C<-o over> that creates F<.o> files via
  4576. this environment will cause them to be compiled with C<-O >and no C<-g>. The
  4577. override could, of course, be restricted to a single directory by the
  4578. appropriate selection of a regular expression.
  4579. Here's the original version of the Hello, World! program, built with this
  4580. environment. Note that Cons rebuilds the appropriate pieces when the
  4581. override is applied or removed:
  4582. % cons hello
  4583. cc -g -c hello.c -o hello.o
  4584. cc -o hello hello.o
  4585. % cons -o over hello
  4586. cc -O -c hello.c -o hello.o
  4587. cc -o hello hello.o
  4588. % cons -o over hello
  4589. cons: "hello" is up-to-date.
  4590. % cons hello
  4591. cc -g -c hello.c -o hello.o
  4592. cc -o hello hello.o
  4593. It's important that the C<Override> command only be used for temporary,
  4594. on-the-fly overrides necessary for development because the overrides are not
  4595. platform independent and because they rely too much on intimate knowledge of
  4596. the workings of the scripts. For temporary use, however, they are exactly
  4597. what you want.
  4598. Note that it is still useful to provide, say, the ability to create a fully
  4599. optimized version of a system for production use--from the F<Construct> and
  4600. F<Conscript> files. This way you can tailor the optimized system to the
  4601. platform. Where optimizer trade-offs need to be made (particular files may
  4602. not be compiled with full optimization, for example), then these can be
  4603. recorded for posterity (and reproducibility) directly in the scripts.
  4604. =head1 More on construction environments
  4605. As previously mentioned, a B<construction environment> is an object that
  4606. has a set of keyword/value pairs and a set of methods, and which is used
  4607. to tell Cons how target files should be built. This section describes
  4608. how Cons uses and expands construction environment values to control its
  4609. build behavior.
  4610. =head2 Construction variable expansion
  4611. Construction variables from a construction environment are expanded
  4612. by preceding the keyword with a C<%> (percent sign):
  4613. Construction variables:
  4614. XYZZY => 'abracadabra',
  4615. The string: "The magic word is: %XYZZY!"
  4616. expands to: "The magic word is: abracadabra!"
  4617. A construction variable name may be surrounded by C<{> and C<}> (curly
  4618. braces), which are stripped as part of the expansion. This can
  4619. sometimes be necessary to separate a variable expansion from trailing
  4620. alphanumeric characters:
  4621. Construction variables:
  4622. OPT => 'value1',
  4623. OPTION => 'value2',
  4624. The string: "%OPT %{OPT}ION %OPTION %{OPTION}"
  4625. expands to: "value1 value1ION value2 value2"
  4626. Construction variable expansion is recursive--that is, a string
  4627. containing C<%->expansions after substitution will be re-expanded until
  4628. no further substitutions can be made:
  4629. Construction variables:
  4630. STRING => 'The result is: %FOO',
  4631. FOO => '%BAR',
  4632. BAR => 'final value',
  4633. The string: "The string says: %STRING"
  4634. expands to: "The string says: The result is: final value"
  4635. If a construction variable is not defined in an environment, then the
  4636. null string is substituted:
  4637. Construction variables:
  4638. FOO => 'value1',
  4639. BAR => 'value2',
  4640. The string: "%FOO <%NO_VARIABLE> %BAR"
  4641. expands to: "value1 <> value2"
  4642. A doubled C<%%> will be replaced by a single C<%>:
  4643. The string: "Here is a percent sign: %%"
  4644. expands to: "Here is a percent sign: %"
  4645. =head2 Default construction variables
  4646. When you specify no arguments when creating a new construction
  4647. environment:
  4648. $env = new cons();
  4649. Cons creates a reference to a new, default construction
  4650. environment. This contains a number of construction variables and some
  4651. methods. At the present writing, the default construction variables on a
  4652. UNIX system are:
  4653. CC => 'cc',
  4654. CFLAGS => '',
  4655. CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
  4656. CXX => '%CC',
  4657. CXXFLAGS => '%CFLAGS',
  4658. CXXCOM => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
  4659. INCDIRPREFIX => '-I',
  4660. INCDIRSUFFIX => '',
  4661. LINK => '%CXX',
  4662. LINKCOM => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
  4663. LINKMODULECOM => '%LD -r -o %> %<',
  4664. LIBDIRPREFIX => '-L',
  4665. LIBDIRSUFFIX => '',
  4666. AR => 'ar',
  4667. ARFLAGS => 'r',
  4668. ARCOM => ['%AR %ARFLAGS %> %<', '%RANLIB %>'],
  4669. RANLIB => 'ranlib',
  4670. AS => 'as',
  4671. ASFLAGS => '',
  4672. ASCOM => '%AS %ASFLAGS %< -o %>',
  4673. LD => 'ld',
  4674. LDFLAGS => '',
  4675. PREFLIB => 'lib',
  4676. SUFLIB => '.a',
  4677. SUFLIBS => '.so:.a',
  4678. SUFOBJ => '.o',
  4679. SIGNATURE => [ '*' => 'build' ],
  4680. ENV => { 'PATH' => '/bin:/usr/bin' },
  4681. And on a Win32 system (Windows NT), the default construction variables
  4682. are (unless the default rule style is set using the B<DefaultRules>
  4683. method):
  4684. CC => 'cl',
  4685. CFLAGS => '/nologo',
  4686. CCCOM => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
  4687. CXXCOM => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
  4688. INCDIRPREFIX => '/I',
  4689. INCDIRSUFFIX => '',
  4690. LINK => 'link',
  4691. LINKCOM => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
  4692. LINKMODULECOM => '%LD /r /o %> %<',
  4693. LIBDIRPREFIX => '/LIBPATH:',
  4694. LIBDIRSUFFIX => '',
  4695. AR => 'lib',
  4696. ARFLAGS => '/nologo ',
  4697. ARCOM => "%AR %ARFLAGS /out:%> %<",
  4698. RANLIB => '',
  4699. LD => 'link',
  4700. LDFLAGS => '/nologo ',
  4701. PREFLIB => '',
  4702. SUFEXE => '.exe',
  4703. SUFLIB => '.lib',
  4704. SUFLIBS => '.dll:.lib',
  4705. SUFOBJ => '.obj',
  4706. SIGNATURE => [ '*' => 'build' ],
  4707. These variables are used by the various methods associated with the
  4708. environment. In particular, any method that ultimately invokes an external
  4709. command will substitute these variables into the final command, as
  4710. appropriate. For example, the C<Objects> method takes a number of source
  4711. files and arranges to derive, if necessary, the corresponding object
  4712. files:
  4713. Objects $env 'foo.c', 'bar.c';
  4714. This will arrange to produce, if necessary, F<foo.o> and F<bar.o>. The
  4715. command invoked is simply C<%CCCOM>, which expands, through substitution,
  4716. to the appropriate external command required to build each object. The
  4717. substitution rules will be discussed in detail in the next section.
  4718. The construction variables are also used for other purposes. For example,
  4719. C<CPPPATH> is used to specify a colon-separated path of include
  4720. directories. These are intended to be passed to the C preprocessor and are
  4721. also used by the C-file scanning machinery to determine the dependencies
  4722. involved in a C Compilation.
  4723. Variables beginning with underscore are created by various methods,
  4724. and should normally be considered ``internal'' variables. For example,
  4725. when a method is called which calls for the creation of an object from
  4726. a C source, the variable C<_IFLAGS> is created: this corresponds to the
  4727. C<-I> switches required by the C compiler to represent the directories
  4728. specified by C<CPPPATH>.
  4729. Note that, for any particular environment, the value of a variable is set
  4730. once, and then never reset (to change a variable, you must create a new
  4731. environment. Methods are provided for copying existing environments for this
  4732. purpose). Some internal variables, such as C<_IFLAGS> are created on demand,
  4733. but once set, they remain fixed for the life of the environment.
  4734. The C<CFLAGS>, C<LDFLAGS>, and C<ARFLAGS> variables all supply a place
  4735. for passing options to the compiler, loader, and archiver, respectively.
  4736. The C<INCDIRPREFIX> and C<INCDIRSUFFIX> variables specify option
  4737. strings to be appended to the beginning and end, respectively, of each
  4738. include directory so that the compiler knows where to find F<.h> files.
  4739. Similarly, the C<LIBDIRPREFIX> and C<LIBDIRSUFFIX> variables specify the
  4740. option string to be appended to the beginning of and end, respectively,
  4741. of each directory that the linker should search for libraries.
  4742. Another variable, C<ENV>, is used to determine the system environment during
  4743. the execution of an external command. By default, the only environment
  4744. variable that is set is C<PATH>, which is the execution path for a UNIX
  4745. command. For the utmost reproducibility, you should really arrange to set
  4746. your own execution path, in your top-level F<Construct> file (or perhaps by
  4747. importing an appropriate construction package with the Perl C<use>
  4748. command). The default variables are intended to get you off the ground.
  4749. =head2 Expanding variables in construction commands
  4750. Within a construction command, construction variables will be expanded
  4751. according to the rules described above. In addition to normal variable
  4752. expansion from the construction environment, construction commands also
  4753. expand the following pseudo-variables to insert the specific input and
  4754. output files in the command line that will be executed:
  4755. =over 10
  4756. =item %>
  4757. The target file name. In a multi-target command, this expands to the
  4758. first target mentioned.)
  4759. =item %0
  4760. Same as C<%E<gt>>.
  4761. =item %1, %2, ..., %9
  4762. These refer to the first through ninth input file, respectively.
  4763. =item %E<lt>
  4764. The full set of input file names. If any of these have been used
  4765. anywhere else in the current command line (via C<%1>, C<%2>, etc.), then
  4766. those will be deleted from the list provided by C<%E<lt>>. Consider the
  4767. following command found in a F<Conscript> file in the F<test> directory:
  4768. Command $env 'tgt', qw(foo bar baz), qq(
  4769. echo %< -i %1 > %>
  4770. echo %< -i %2 >> %>
  4771. echo %< -i %3 >> %>
  4772. );
  4773. If F<tgt> needed to be updated, then this would result in the execution of
  4774. the following commands, assuming that no remapping has been established for
  4775. the F<test> directory:
  4776. echo test/bar test/baz -i test/foo > test/tgt
  4777. echo test/foo test/baz -i test/bar >> test/tgt
  4778. echo test/foo test/bar -i test/baz >> test/tgt
  4779. =back
  4780. Any of the above pseudo-variables may be followed immediately by one of
  4781. the following suffixes to select a portion of the expanded path name:
  4782. :a the absolute path to the file name
  4783. :b the directory plus the file name stripped of any suffix
  4784. :d the directory
  4785. :f the file name
  4786. :s the file name suffix
  4787. :F the file name stripped of any suffix
  4788. :S the absolute path path to a Linked source file
  4789. Continuing with the above example, C<%E<lt>:f> would expand to C<foo bar baz>,
  4790. and C<%E<gt>:d> would expand to C<test>.
  4791. There are additional C<%> elements which affect the command line(s):
  4792. =over 10
  4793. =item %[ %]
  4794. It is possible to programmatically rewrite part of the command by
  4795. enclosing part of it between C<%[> and C<%]>. This will call the
  4796. construction variable named as the first word enclosed in the brackets
  4797. as a Perl code reference; the results of this call will be used to
  4798. replace the contents of the brackets in the command line. For example,
  4799. given an existing input file named F<tgt.in>:
  4800. @keywords = qw(foo bar baz);
  4801. $env = new cons(X_COMMA => sub { join(",", @_) });
  4802. Command $env 'tgt', 'tgt.in', qq(
  4803. echo '# Keywords: %[X_COMMA @keywords %]' > %>
  4804. cat %< >> %>
  4805. );
  4806. This will execute:
  4807. echo '# Keywords: foo,bar,baz' > tgt
  4808. cat tgt.in >> tgt
  4809. =item %( %)
  4810. Cons includes the text of the command line in the MD5 signature for a
  4811. build, so that targets get rebuilt if you change the command line (to
  4812. add or remove an option, for example). Command-line text in between
  4813. C<%(> and C<%)>, however, will be ignored for MD5 signature calculation.
  4814. Internally, Cons uses C<%(> and C<%)> around include and library
  4815. directory options (C<-I> and C<-L> on UNIX systems, C</I> and
  4816. C</LIBPATH> on Windows NT) to avoid rebuilds just because the directory
  4817. list changes. Rebuilds occur only if the changed directory list causes
  4818. any included I<files> to change, and a changed include file is detected
  4819. by the MD5 signature calculation on the actual file contents.
  4820. =back
  4821. =head2 Expanding construction variables in file names
  4822. Cons expands construction variables in the source and target file names
  4823. passed to the various construction methods according to the expansion
  4824. rules described above:
  4825. $env = new cons(
  4826. DESTDIR => 'programs',
  4827. SRCDIR => 'src',
  4828. );
  4829. Program $env '%DESTDIR/hello', '%SRCDIR/hello.c';
  4830. This allows for flexible configuration, through the construction
  4831. environment, of directory names, suffixes, etc.
  4832. =head1 Build actions
  4833. Cons supports several types of B<build actions> that can be performed
  4834. to construct one or more target files. Usually, a build action is
  4835. a construction command--that is, a command-line string that invokes
  4836. an external command. Cons can also execute Perl code embedded in a
  4837. command-line string, and even supports an experimental ability to build
  4838. a target file by executing a Perl code reference directly.
  4839. A build action is usually specified as the value of a construction
  4840. variable:
  4841. $env = new cons(
  4842. CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
  4843. LINKCOM => '[perl] &link_executable("%>", "%<")',
  4844. ARCOM => sub { my($env, $target, @sources) = @_;
  4845. # code to create an archive
  4846. }
  4847. );
  4848. A build action may be associated directly with one or more target files
  4849. via the C<Command> method; see below.
  4850. =head2 Construction commands
  4851. A construction command goes through expansion of construction variables
  4852. and C<%-> pseudo-variables, as described above, to create the actual
  4853. command line that Cons will execute to generate the target file or
  4854. files.
  4855. After substitution occurs, strings of white space are converted into
  4856. single blanks, and leading and trailing white space is eliminated. It
  4857. is therefore currently not possible to introduce variable length white
  4858. space in strings passed into a command.
  4859. If a multi-line command string is provided, the commands are executed
  4860. sequentially. If any of the commands fails, then none of the rest are
  4861. executed, and the target is not marked as updated, i.e. a new signature is
  4862. not stored for the target.
  4863. Normally, if all the commands succeed, and return a zero status (or whatever
  4864. platform-specific indication of success is required), then a new signature
  4865. is stored for the target. If a command erroneously reports success even
  4866. after a failure, then Cons will assume that the target file created by that
  4867. command is accurate and up-to-date.
  4868. The first word of each command string, after expansion, is assumed to be an
  4869. executable command looked up on the C<PATH> environment variable (which is,
  4870. in turn, specified by the C<ENV> construction variable). If this command is
  4871. found on the path, then the target will depend upon it: the command will
  4872. therefore be automatically built, as necessary. It's possible to write
  4873. multi-part commands to some shells, separated by semi-colons. Only the first
  4874. command word will be depended upon, however, so if you write your command
  4875. strings this way, you must either explicitly set up a dependency (with the
  4876. C<Depends> method), or be sure that the command you are using is a system
  4877. command which is expected to be available. If it isn't available, you will,
  4878. of course, get an error.
  4879. Cons normally prints a command before executing it. This behavior is
  4880. suppressed if the first character of the command is C<@>. Note that
  4881. you may need to separate the C<@> from the command name or escape it to
  4882. prevent C<@cmd> from looking like an array to Perl quote operators that
  4883. perform interpolation:
  4884. # The first command line is incorrect,
  4885. # because "@cp" looks like an array
  4886. # to the Perl qq// function.
  4887. # Use the second form instead.
  4888. Command $env 'foo', 'foo.in', qq(
  4889. @cp %< tempfile
  4890. @ cp tempfile %>
  4891. );
  4892. If there are shell meta characters anywhere in the expanded command line,
  4893. such as C<E<lt>>, C<E<gt>>, quotes, or semi-colon, then the command
  4894. will actually be executed by invoking a shell. This means that a command
  4895. such as:
  4896. cd foo
  4897. alone will typically fail, since there is no command C<cd> on the path. But
  4898. the command string:
  4899. cd $<:d; tar cf $>:f $<:f
  4900. when expanded will still contain the shell meta character semi-colon, and a
  4901. shell will be invoked to interpret the command. Since C<cd> is interpreted
  4902. by this sub-shell, the command will execute as expected.
  4903. =head2 Perl expressions
  4904. If any command (even one within a multi-line command) begins with
  4905. C<[perl]>, the remainder of that command line will be evaluated by the
  4906. running Perl instead of being forked by the shell. If an error occurs
  4907. in parsing the Perl code, or if the Perl expression returns 0 or undef,
  4908. the command will be considered to have failed. For example, here is a
  4909. simple command which creates a file C<foo> directly from Perl:
  4910. $env = new cons();
  4911. Command $env 'foo',
  4912. qq([perl] open(FOO,'>foo');print FOO "hi\\n"; close(FOO); 1);
  4913. Note that when the command is executed, you are in the same package as
  4914. when the F<Construct> or F<Conscript> file was read, so you can call
  4915. Perl functions you've defined in the same F<Construct> or F<Conscript>
  4916. file in which the C<Command> appears:
  4917. $env = new cons();
  4918. sub create_file {
  4919. my $file = shift;
  4920. open(FILE, ">$file");
  4921. print FILE "hi\n";
  4922. close(FILE);
  4923. return 1;
  4924. }
  4925. Command $env 'foo', "[perl] &create_file('%>')";
  4926. The Perl string will be used to generate the signature for the derived
  4927. file, so if you change the string, the file will be rebuilt. The contents
  4928. of any subroutines you call, however, are not part of the signature,
  4929. so if you modify a called subroutine such as C<create_file> above,
  4930. the target will I<not> be rebuilt. Caveat user.
  4931. =head2 Perl code references [EXPERIMENTAL]
  4932. Cons supports the ability to create a derived file by directly executing
  4933. a Perl code reference. This feature is considered EXPERIMENTAL and
  4934. subject to change in the future.
  4935. A code reference may either be a named subroutine referenced by the
  4936. usual C<\&> syntax:
  4937. sub build_output {
  4938. my($env, $target, @sources) = @_;
  4939. print "build_output building $target\n";
  4940. open(OUT, ">$target");
  4941. foreach $src (@sources) {
  4942. if (! open(IN, "<$src")) {
  4943. print STDERR "cannot open '$src': $!\n";
  4944. return undef;
  4945. }
  4946. print OUT, <IN>;
  4947. }
  4948. close(OUT);
  4949. return 1;
  4950. }
  4951. Command $env 'output', \&build_output;
  4952. or the code reference may be an anonymous subroutine:
  4953. Command $env 'output', sub {
  4954. my($env, $target, @sources) = @_;
  4955. print "building $target\n";
  4956. open(FILE, ">$target");
  4957. print FILE "hello\n";
  4958. close(FILE);
  4959. return 1;
  4960. };
  4961. To build the target file, the referenced subroutine is passed, in order:
  4962. the construction environment used to generate the target; the path
  4963. name of the target itself; and the path names of all the source files
  4964. necessary to build the target file.
  4965. The code reference is expected to generate the target file, of course,
  4966. but may manipulate the source and target files in any way it chooses.
  4967. The code reference must return a false value (C<undef> or C<0>) if
  4968. the build of the file failed. Any true value indicates a successful
  4969. build of the target.
  4970. Building target files using code references is considered EXPERIMENTAL
  4971. due to the following current limitations:
  4972. =over 4
  4973. Cons does I<not> print anything to indicate the code reference is being
  4974. called to build the file. The only way to give the user any indication
  4975. is to have the code reference explicitly print some sort of "building"
  4976. message, as in the above examples.
  4977. Cons does not generate any signatures for code references, so if the
  4978. code in the reference changes, the target will I<not> be rebuilt.
  4979. Cons has no public method to allow a code reference to extract
  4980. construction variables. This would be good to allow generalization of
  4981. code references based on the current construction environment, but would
  4982. also complicate the problem of generating meaningful signatures for code
  4983. references.
  4984. =back
  4985. Support for building targets via code references has been released in
  4986. this version to encourage experimentation and the seeking of possible
  4987. solutions to the above limitations.
  4988. =head1 Default construction methods
  4989. The list of default construction methods includes the following:
  4990. =head2 The C<new> constructor
  4991. The C<new> method is a Perl object constructor. That is, it is not invoked
  4992. via a reference to an existing construction environment B<reference>, but,
  4993. rather statically, using the name of the Perl B<package> where the
  4994. constructor is defined. The method is invoked like this:
  4995. $env = new cons(<overrides>);
  4996. The environment you get back is blessed into the package C<cons>, which
  4997. means that it will have associated with it the default methods described
  4998. below. Individual construction variables can be overridden by providing
  4999. name/value pairs in an override list. Note that to override any command
  5000. environment variable (i.e. anything under C<ENV>), you will have to override
  5001. all of them. You can get around this difficulty by using the C<copy> method
  5002. on an existing construction environment.
  5003. =head2 The C<clone> method
  5004. The C<clone> method creates a clone of an existing construction environment,
  5005. and can be called as in the following example:
  5006. $env2 = $env1->clone(<overrides>);
  5007. You can provide overrides in the usual manner to create a different
  5008. environment from the original. If you just want a new name for the same
  5009. environment (which may be helpful when exporting environments to existing
  5010. components), you can just use simple assignment.
  5011. =head2 The C<copy> method
  5012. The C<copy> method extracts the externally defined construction variables
  5013. from an environment and returns them as a list of name/value
  5014. pairs. Overrides can also be provided, in which case, the overridden values
  5015. will be returned, as appropriate. The returned list can be assigned to a
  5016. hash, as shown in the prototype, below, but it can also be manipulated in
  5017. other ways:
  5018. %env = $env1->copy(<overrides>);
  5019. The value of C<ENV>, which is itself a hash, is also copied to a new hash,
  5020. so this may be changed without fear of affecting the original
  5021. environment. So, for example, if you really want to override just the
  5022. C<PATH> variable in the default environment, you could do the following:
  5023. %cons = new cons()->copy();
  5024. $cons{ENV}{PATH} = "<your path here>";
  5025. $cons = new cons(%cons);
  5026. This will leave anything else that might be in the default execution
  5027. environment undisturbed.
  5028. =head2 The C<Install> method
  5029. The C<Install> method arranges for the specified files to be installed in
  5030. the specified directory. The installation is optimized: the file is not
  5031. copied if it can be linked. If this is not the desired behavior, you will
  5032. need to use a different method to install the file. It is called as follows:
  5033. Install $env <directory>, <names>;
  5034. Note that, while the files to be installed may be arbitrarily named,
  5035. only the last component of each name is used for the installed target
  5036. name. So, for example, if you arrange to install F<foo/bar> in F<baz>,
  5037. this will create a F<bar> file in the F<baz> directory (not F<foo/bar>).
  5038. =head2 The C<InstallAs> method
  5039. The C<InstallAs> method arranges for the specified source file(s) to be
  5040. installed as the specified target file(s). Multiple files should be
  5041. specified as a file list. The installation is optimized: the file is not
  5042. copied if it can be linked. If this is not the desired behavior, you will
  5043. need to use a different method to install the file. It is called as follows:
  5044. C<InstallAs> works in two ways:
  5045. Single file install:
  5046. InstallAs $env TgtFile, SrcFile;
  5047. Multiple file install:
  5048. InstallAs $env ['tgt1', 'tgt2'], ['src1', 'src2'];
  5049. Or, even as:
  5050. @srcs = qw(src1 src2 src3);
  5051. @tgts = qw(tgt1 tgt2 tgt3);
  5052. InstallAs $env [@tgts], [@srcs];
  5053. Both the target and the sources lists should be of the same length.
  5054. =head2 The C<Precious> method
  5055. The C<Precious> method asks cons not to delete the specified file or
  5056. list of files before building them again. It is invoked as:
  5057. Precious <files>;
  5058. This is especially useful for allowing incremental updates to libraries
  5059. or debug information files which are updated rather than rebuilt anew each
  5060. time. Cons will still delete the files when the C<-r> flag is specified.
  5061. =head2 The C<AfterBuild> method
  5062. The C<AfterBuild> method evaluates the specified perl string after
  5063. building the given file or files (or finding that they are up to date).
  5064. The eval will happen once per specified file. C<AfterBuild> is called
  5065. as follows:
  5066. AfterBuild $env 'foo.o', qq(print "foo.o is up to date!\n");
  5067. The perl string is evaluated in the C<script> package, and has access
  5068. to all variables and subroutines defined in the F<Conscript> file in
  5069. which the C<AfterBuild> method is called.
  5070. =head2 The C<Command> method
  5071. The C<Command> method is a catchall method which can be used to arrange for
  5072. any build action to be executed to update the target. For this command, a
  5073. target file and list of inputs is provided. In addition, a build action
  5074. is specified as the last argument. The build action is typically a
  5075. command line or lines, but may also contain Perl code to be executed;
  5076. see the section above on build actions for details.
  5077. The C<Command> method is called as follows:
  5078. Command $env <target>, <inputs>, <build action>;
  5079. The target is made dependent upon the list of input files specified, and the
  5080. inputs must be built successfully or Cons will not attempt to build the
  5081. target.
  5082. To specify a command with multiple targets, you can specify a reference to a
  5083. list of targets. In Perl, a list reference can be created by enclosing a
  5084. list in square brackets. Hence the following command:
  5085. Command $env ['foo.h', 'foo.c'], 'foo.template', q(
  5086. gen %1
  5087. );
  5088. could be used in a case where the command C<gen> creates two files, both
  5089. F<foo.h> and F<foo.c>.
  5090. =head2 The C<Objects> method
  5091. The C<Objects> method arranges to create the object files that correspond to
  5092. the specified source files. It is invoked as shown below:
  5093. @files = Objects $env <source or object files>;
  5094. Under Unix, source files ending in F<.s> and F<.c> are currently
  5095. supported, and will be compiled into a name of the same file ending
  5096. in F<.o>. By default, all files are created by invoking the external
  5097. command which results from expanding the C<CCCOM> construction variable,
  5098. with C<%E<lt>> and C<%E<gt>> set to the source and object files,
  5099. respectively. (See the section above on construction variable expansion
  5100. for details). The variable C<CPPPATH> is also used when scanning source
  5101. files for dependencies. This is a colon separated list of pathnames, and
  5102. is also used to create the construction variable C<_IFLAGS,> which will
  5103. contain the appropriate list of -C<I> options for the compilation. Any
  5104. relative pathnames in C<CPPPATH> is interpreted relative to the
  5105. directory in which the associated construction environment was created
  5106. (absolute and top-relative names may also be used). This variable is
  5107. used by C<CCCOM>. The behavior of this command can be modified by
  5108. changing any of the variables which are interpolated into C<CCCOM>, such
  5109. as C<CC>, C<CFLAGS>, and, indirectly, C<CPPPATH>. It's also possible
  5110. to replace the value of C<CCCOM>, itself. As a convenience, this file
  5111. returns the list of object filenames.
  5112. =head2 The C<Program> method
  5113. The C<Program> method arranges to link the specified program with the
  5114. specified object files. It is invoked in the following manner:
  5115. Program $env <program name>, <source or object files>;
  5116. The program name will have the value of the C<SUFEXE> construction
  5117. variable appended (by default, C<.exe> on Win32 systems, nothing on Unix
  5118. systems) if the suffix is not already present.
  5119. Source files may be specified in place of objects files--the C<Objects>
  5120. method will be invoked to arrange the conversion of all the files into
  5121. object files, and hence all the observations about the C<Objects> method,
  5122. above, apply to this method also.
  5123. The actual linking of the program will be handled by an external command
  5124. which results from expanding the C<LINKCOM> construction variable, with
  5125. C<%E<lt>> set to the object files to be linked (in the order presented),
  5126. and C<%E<gt>> set to the target. (See the section above on construction
  5127. variable expansion for details.) The user may set additional variables
  5128. in the construction environment, including C<LINK>, to define which
  5129. program to use for linking, C<LIBPATH>, a colon-separated list of
  5130. library search paths, for use with library specifications of the form
  5131. I<-llib>, and C<LIBS>, specifying the list of libraries to link against
  5132. (in either I<-llib> form or just as pathnames. Relative pathnames in
  5133. both C<LIBPATH> and C<LIBS> are interpreted relative to the directory
  5134. in which the associated construction environment is created (absolute
  5135. and top-relative names may also be used). Cons automatically sets up
  5136. dependencies on any libraries mentioned in C<LIBS>: those libraries will
  5137. be built before the command is linked.
  5138. =head2 The C<Library> method
  5139. The C<Library> method arranges to create the specified library from the
  5140. specified object files. It is invoked as follows:
  5141. Library $env <library name>, <source or object files>;
  5142. The library name will have the value of the C<SUFLIB> construction
  5143. variable appended (by default, C<.lib> on Win32 systems, C<.a> on Unix
  5144. systems) if the suffix is not already present.
  5145. Source files may be specified in place of objects files--the C<Objects>
  5146. method will be invoked to arrange the conversion of all the files into
  5147. object files, and hence all the observations about the C<Objects> method,
  5148. above, apply to this method also.
  5149. The actual creation of the library will be handled by an external
  5150. command which results from expanding the C<ARCOM> construction variable,
  5151. with C<%E<lt>> set to the library members (in the order presented),
  5152. and C<%E<gt>> to the library to be created. (See the section above
  5153. on construction variable expansion for details.) The user may set
  5154. variables in the construction environment which will affect the
  5155. operation of the command. These include C<AR>, the archive program
  5156. to use, C<ARFLAGS>, which can be used to modify the flags given to
  5157. the program specified by C<AR>, and C<RANLIB>, the name of a archive
  5158. index generation program, if needed (if the particular need does not
  5159. require the latter functionality, then C<ARCOM> must be redefined to not
  5160. reference C<RANLIB>).
  5161. The C<Library> method allows the same library to be specified in multiple
  5162. method invocations. All of the contributing objects from all the invocations
  5163. (which may be from different directories) are combined and generated by a
  5164. single archive command. Note, however, that if you prune a build so that
  5165. only part of a library is specified, then only that part of the library will
  5166. be generated (the rest will disappear!).
  5167. =head2 The C<Module> method
  5168. The C<Module> method is a combination of the C<Program> and C<Command>
  5169. methods. Rather than generating an executable program directly, this command
  5170. allows you to specify your own command to actually generate a module. The
  5171. method is invoked as follows:
  5172. Module $env <module name>, <source or object files>, <construction command>;
  5173. This command is useful in instances where you wish to create, for example,
  5174. dynamically loaded modules, or statically linked code libraries.
  5175. =head2 The C<Depends> method
  5176. The C<Depends> method allows you to specify additional dependencies for a
  5177. target. It is invoked as follows:
  5178. Depends $env <target>, <dependencies>;
  5179. This may be occasionally useful, especially in cases where no scanner exists
  5180. (or is writable) for particular types of files. Normally, dependencies are
  5181. calculated automatically from a combination of the explicit dependencies set
  5182. up by the method invocation or by scanning source files.
  5183. A set of identical dependencies for multiple targets may be specified
  5184. using a reference to a list of targets. In Perl, a list reference can
  5185. be created by enclosing a list in square brackets. Hence the following
  5186. command:
  5187. Depends $env ['foo', 'bar'], 'input_file_1', 'input_file_2';
  5188. specifies that both the F<foo> and F<bar> files depend on the listed
  5189. input files.
  5190. =head2 The C<RuleSet> method
  5191. The C<RuleSet> method returns the construction variables for building
  5192. various components with one of the rule sets supported by Cons. The
  5193. currently supported rule sets are:
  5194. =over 4
  5195. =item msvc
  5196. Rules for the Microsoft Visual C++ compiler suite.
  5197. =item unix
  5198. Generic rules for most UNIX-like compiler suites.
  5199. =back
  5200. On systems with more than one available compiler suite, this allows you
  5201. to easily create side-by-side environments for building software with
  5202. multiple tools:
  5203. $msvcenv = new cons(RuleSet("msvc"));
  5204. $cygnusenv = new cons(RuleSet("unix"));
  5205. In the future, this could also be extended to other platforms that
  5206. have different default rule sets.
  5207. =head2 The C<DefaultRules> method
  5208. The C<DefaultRules> method sets the default construction variables that
  5209. will be returned by the C<new> method to the specified arguments:
  5210. DefaultRules(CC => 'gcc',
  5211. CFLAGS => '',
  5212. CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>');
  5213. $env = new cons();
  5214. # $env now contains *only* the CC, CFLAGS,
  5215. # and CCCOM construction variables
  5216. Combined with the C<RuleSet> method, this also provides an easy way
  5217. to set explicitly the default build environment to use some supported
  5218. toolset other than the Cons defaults:
  5219. # use a UNIX-like tool suite (like cygwin) on Win32
  5220. DefaultRules(RuleSet('unix'));
  5221. $env = new cons();
  5222. Note that the C<DefaultRules> method completely replaces the default
  5223. construction environment with the specified arguments, it does not
  5224. simply override the existing defaults. To override one or more
  5225. variables in a supported C<RuleSet>, append the variables and values:
  5226. DefaultRules(RuleSet('unix'), CFLAGS => '-O3');
  5227. $env1 = new cons();
  5228. $env2 = new cons();
  5229. # both $env1 and $env2 have 'unix' defaults
  5230. # with CFLAGS set to '-O3'
  5231. =head2 The C<Ignore> method
  5232. The C<Ignore> method allows you to ignore explicitly dependencies that
  5233. Cons infers on its own. It is invoked as follows:
  5234. Ignore <patterns>;
  5235. This can be used to avoid recompilations due to changes in system header
  5236. files or utilities that are known to not affect the generated targets.
  5237. If, for example, a program is built in an NFS-mounted directory on
  5238. multiple systems that have different copies of F<stdio.h>, the differences
  5239. will affect the signatures of all derived targets built from source files
  5240. that C<#include E<lt>stdio.hE<gt>>. This will cause all those targets to
  5241. be rebuilt when changing systems. If this is not desirable behavior, then
  5242. the following line will remove the dependencies on the F<stdio.h> file:
  5243. Ignore '^/usr/include/stdio\.h$';
  5244. Note that the arguments to the C<Ignore> method are regular expressions,
  5245. so special characters must be escaped and you may wish to anchor the
  5246. beginning or end of the expression with C<^> or C<$> characters.
  5247. =head2 The C<Salt> method
  5248. The C<Salt> method adds a constant value to the signature calculation
  5249. for every derived file. It is invoked as follows:
  5250. Salt $string;
  5251. Changing the Salt value will force a complete rebuild of every derived
  5252. file. This can be used to force rebuilds in certain desired
  5253. circumstances. For example,
  5254. Salt `uname -s`;
  5255. Would force a complete rebuild of every derived file whenever the
  5256. operating system on which the build is performed (as reported by C<uname
  5257. -s>) changes.
  5258. =head2 The C<UseCache> method
  5259. The C<UseCache> method instructs Cons to maintain a cache of derived
  5260. files, to be shared among separate build trees of the same project.
  5261. UseCache("cache/<buildname>") || warn("cache directory not found");
  5262. =head2 The C<SourcePath> method
  5263. The C<SourcePath> mathod returns the real source path name of a file,
  5264. as opposed to the path name within a build directory. It is invoked
  5265. as follows:
  5266. $path = SourcePath <buildpath>;
  5267. =head2 The C<ConsPath> method
  5268. The C<ConsPath> method returns true if the supplied path is a derivable
  5269. file, and returns undef (false) otherwise.
  5270. It is invoked as follows:
  5271. $result = ConsPath <path>;
  5272. =head2 The C<SplitPath> method
  5273. The C<SplitPath> method looks up multiple path names in a string separated
  5274. by the default path separator for the operating system (':' on UNIX
  5275. systems, ';' on Windows NT), and returns the fully-qualified names.
  5276. It is invoked as follows:
  5277. @paths = SplitPath <pathlist>;
  5278. The C<SplitPath> method will convert names prefixed '#' to the
  5279. appropriate top-level build name (without the '#') and will convert
  5280. relative names to top-level names.
  5281. =head2 The C<DirPath> method
  5282. The C<DirPath> method returns the build path name(s) of a directory or
  5283. list of directories. It is invoked as follows:
  5284. $cwd = DirPath <paths>;
  5285. The most common use for the C<DirPath> method is:
  5286. $cwd = DirPath '.';
  5287. to fetch the path to the current directory of a subsidiary F<Conscript>
  5288. file.
  5289. =head2 The C<FilePath> method
  5290. The C<FilePath> method returns the build path name(s) of a file or
  5291. list of files. It is invoked as follows:
  5292. $file = FilePath <path>;
  5293. =head2 The C<Help> method
  5294. The C<Help> method specifies help text that will be displayed when the
  5295. user invokes C<cons -h>. This can be used to provide documentation
  5296. of specific targets, values, build options, etc. for the build tree.
  5297. It is invoked as follows:
  5298. Help <helptext>;
  5299. The C<Help> method may only be called once, and should typically be
  5300. specified in the top-level F<Construct> file.
  5301. =head1 Extending Cons
  5302. =head2 Overriding construction variables
  5303. There are several ways of extending Cons, which vary in degree of
  5304. difficulty. The simplest method is to define your own construction
  5305. environment, based on the default environment, but modified to reflect your
  5306. particular needs. This will often suffice for C-based applications. You can
  5307. use the C<new> constructor, and the C<clone> and C<copy> methods to create
  5308. hybrid environments. These changes can be entirely transparent to the
  5309. underlying F<Conscript> files.
  5310. =head2 Adding new methods
  5311. For slightly more demanding changes, you may wish to add new methods to the
  5312. C<cons> package. Here's an example of a very simple extension,
  5313. C<InstallScript>, which installs a tcl script in a requested location, but
  5314. edits the script first to reflect a platform-dependent path that needs to be
  5315. installed in the script:
  5316. # cons::InstallScript - Create a platform dependent version of a shell
  5317. # script by replacing string ``#!your-path-here'' with platform specific
  5318. # path $BIN_DIR.
  5319. sub cons::InstallScript {
  5320. my ($env, $dst, $src) = @_;
  5321. Command $env $dst, $src, qq(
  5322. sed s+your-path-here+$BIN_DIR+ %< > %>
  5323. chmod oug+x %>
  5324. );
  5325. }
  5326. Notice that this method is defined directly in the C<cons> package (by
  5327. prefixing the name with C<cons::>). A change made in this manner will be
  5328. globally visible to all environments, and could be called as in the
  5329. following example:
  5330. InstallScript $env "$BIN/foo", "foo.tcl";
  5331. For a small improvement in generality, the C<BINDIR> variable could be
  5332. passed in as an argument or taken from the construction environment--as
  5333. C<%BINDIR>.
  5334. =head2 Overriding methods
  5335. Instead of adding the method to the C<cons> name space, you could define a
  5336. new package which inherits existing methods from the C<cons> package and
  5337. overrides or adds others. This can be done using Perl's inheritance
  5338. mechanisms.
  5339. The following example defines a new package C<cons::switch> which
  5340. overrides the standard C<Library> method. The overridden method builds
  5341. linked library modules, rather than library archives. A new
  5342. constructor is provided. Environments created with this constructor
  5343. will have the new library method; others won't.
  5344. package cons::switch;
  5345. BEGIN {@ISA = 'cons'}
  5346. sub new {
  5347. shift;
  5348. bless new cons(@_);
  5349. }
  5350. sub Library {
  5351. my($env) = shift;
  5352. my($lib) = shift;
  5353. my(@objs) = Objects $env @_;
  5354. Command $env $lib, @objs, q(
  5355. %LD -r %LDFLAGS %< -o %>
  5356. );
  5357. }
  5358. This functionality could be invoked as in the following example:
  5359. $env = new cons::switch(@overrides);
  5360. ...
  5361. Library $env 'lib.o', 'foo.c', 'bar.c';
  5362. =head1 Invoking Cons
  5363. The C<cons> command is usually invoked from the root of the build tree. A
  5364. F<Construct> file must exist in that directory. If the C<-f> argument is
  5365. used, then an alternate F<Construct> file may be used (and, possibly, an
  5366. alternate root, since C<cons> will cd to F<Construct> file's containing
  5367. directory).
  5368. If C<cons> is invoked from a child of the root of the build tree with
  5369. the C<-t> argument, it will walk up the directory hierarchy looking for a
  5370. F<Construct> file. (An alternate name may still be specified with C<-f>.)
  5371. The targets supplied on the command line will be modified to be relative
  5372. to the discovered F<Construct> file. For example, from a directory
  5373. containing a top-level F<Construct> file, the following invocation:
  5374. % cd libfoo/subdir
  5375. % cons -t target
  5376. is exactly equivalent to:
  5377. % cons libfoo/subdir/target
  5378. If there are any C<Default> targets specified in the directory hierarchy's
  5379. F<Construct> or F<Conscript> files, only the default targets at or below
  5380. the directory from which C<cons -t> was invoked will be built.
  5381. The command is invoked as follows:
  5382. cons <arguments> -- <construct-args>
  5383. where I<arguments> can be any of the following, in any order:
  5384. =over 10
  5385. =item I<target>
  5386. Build the specified target. If I<target> is a directory, then recursively
  5387. build everything within that directory.
  5388. =item I<+pattern>
  5389. Limit the F<Conscript> files considered to just those that match I<pattern>,
  5390. which is a Perl regular expression. Multiple C<+> arguments are accepted.
  5391. =item I<name>=<val>
  5392. Sets I<name> to value I<val> in the C<ARG> hash passed to the top-level
  5393. F<Construct> file.
  5394. =item C<-cc>
  5395. Show command that would have been executed, when retrieving from cache. No
  5396. indication that the file has been retrieved is given; this is useful for
  5397. generating build logs that can be compared with real build logs.
  5398. =item C<-cd>
  5399. Disable all caching. Do not retrieve from cache nor flush to cache.
  5400. =item C<-cr>
  5401. Build dependencies in random order. This is useful when building multiple
  5402. similar trees with caching enabled.
  5403. =item C<-cs>
  5404. Synchronize existing build targets that are found to be up-to-date with
  5405. cache. This is useful if caching has been disabled with -cc or just recently
  5406. enabled with UseCache.
  5407. =item C<-d>
  5408. Enable dependency debugging.
  5409. =item C<-f> <file>
  5410. Use the specified file instead of F<Construct> (but first change to
  5411. containing directory of I<file>).
  5412. =item C<-h>
  5413. Show a help message local to the current build if one such is defined, and
  5414. exit.
  5415. =item C<-k>
  5416. Keep going as far as possible after errors.
  5417. =item C<-o> <file>
  5418. Read override file I<file>.
  5419. =item C<-p>
  5420. Show construction products in specified trees. No build is attempted.
  5421. =item C<-pa>
  5422. Show construction products and associated actions. No build is attempted.
  5423. =item C<-pw>
  5424. Show products and where they are defined. No build is attempted.
  5425. =item C<-q>
  5426. Make the build quiet. Multiple C<-q> options may be specified.
  5427. A single C<-q> options suppress messages about Installing and Removing
  5428. targets.
  5429. Two C<-q> options suppress build command lines and target up-to-date
  5430. messages.
  5431. =item C<-r>
  5432. Remove construction products associated with <targets>. No build is
  5433. attempted.
  5434. =item C<-R> <repos>
  5435. Search for files in I<repos>. Multiple B<-R> I<repos> directories are
  5436. searched in the order specified.
  5437. =item C<-S> <pkg>
  5438. Use the sig::<pkg> package to calculate. Supported <pkg> values
  5439. include "md5" for MD5 signature calculation and "md5::debug" for debug
  5440. information about MD5 signature calculation.
  5441. If the specified package ends in <::debug>, signature debug information
  5442. will be printed to the file name specified in the C<CONS_SIG_DEBUG>
  5443. environment variable, or to standard output if the environment variable
  5444. is not set.
  5445. =item C<-t>
  5446. Traverse up the directory hierarchy looking for a F<Construct> file,
  5447. if none exists in the current directory. Targets will be modified to
  5448. be relative to the F<Construct> file.
  5449. Internally, C<cons> will change its working directory to the directory
  5450. which contains the top-level F<Construct> file and report:
  5451. cons: Entering directory `top-level-directory'
  5452. This message indicates to an invoking editor (such as emacs) or build
  5453. environment that Cons will now report all file names relative to the
  5454. top-level directory. This message can not be suppressed with the C<-q>
  5455. option.
  5456. =item C<-v>
  5457. Show C<cons> version and continue processing.
  5458. =item C<-V>
  5459. Show C<cons> version and exit.
  5460. =item C<-wf> <file>
  5461. Write all filenames considered into I<file>.
  5462. =item C<-x>
  5463. Show a help message similar to this one, and exit.
  5464. =back
  5465. And I<construct-args> can be any arguments that you wish to process in the
  5466. F<Construct> file. Note that there should be a B<--> separating the arguments
  5467. to cons and the arguments that you wish to process in the F<Construct> file.
  5468. Processing of I<construct-args> can be done by any standard package like
  5469. B<Getopt> or its variants, or any user defined package. B<cons> will pass in
  5470. the I<construct-args> as B<@ARGV> and will not attempt to interpret anything
  5471. after the B<-->.
  5472. % cons -R /usr/local/repository -d os=solaris +driver -- -c test -f DEBUG
  5473. would pass the following to cons
  5474. -R /usr/local/repository -d os=solaris +driver
  5475. and the following, to the top level F<Construct> file as B<@ARGV>
  5476. -c test -f DEBUG
  5477. Note that C<cons -r .> is equivalent to a full recursive C<make clean>,
  5478. but requires no support in the F<Construct> file or any F<Conscript>
  5479. files. This is most useful if you are compiling files into source
  5480. directories (if you separate the F<build> and F<export> directories,
  5481. then you can just remove the directories).
  5482. The options C<-p>, C<-pa>, and C<-pw> are extremely useful for use as an aid
  5483. in reading scripts or debugging them. If you want to know what script
  5484. installs F<export/include/foo.h>, for example, just type:
  5485. % cons -pw export/include/foo.h
  5486. =head1 Using and writing dependency scanners
  5487. QuickScan allows simple target-independent scanners to be set up for
  5488. source files. Only one QuickScan scanner may be associated with any given
  5489. source file and environment, although the same scanner may (and should)
  5490. be used for multiple files of a given type.
  5491. A QuickScan scanner is only ever invoked once for a given source file,
  5492. and it is only invoked if the file is used by some target in the tree
  5493. (i.e., there is a dependency on the source file).
  5494. QuickScan is invoked as follows:
  5495. QuickScan CONSENV CODEREF, FILENAME [, PATH]
  5496. The subroutine referenced by CODEREF is expected to return a list of
  5497. filenames included directly by FILE. These filenames will, in turn, be
  5498. scanned. The optional PATH argument supplies a lookup path for finding
  5499. FILENAME and/or files returned by the user-supplied subroutine. The PATH
  5500. may be a reference to an array of lookup-directory names, or a string of
  5501. names separated by the system's separator character (':' on UNIX systems,
  5502. ';' on Windows NT).
  5503. The subroutine is called once for each line in the file, with $_ set to the
  5504. current line. If the subroutine needs to look at additional lines, or, for
  5505. that matter, the entire file, then it may read them itself, from the
  5506. filehandle SCAN. It may also terminate the loop, if it knows that no further
  5507. include information is available, by closing the filehandle.
  5508. Whether or not a lookup path is provided, QuickScan first tries to lookup
  5509. the file relative to the current directory (for the top-level file
  5510. supplied directly to QuickScan), or from the directory containing the
  5511. file which referenced the file. This is not very general, but seems good
  5512. enough--especially if you have the luxury of writing your own utilities
  5513. and can control the use of the search path in a standard way.
  5514. Here's a real example, taken from a F<Construct> file here:
  5515. sub cons::SMFgen {
  5516. my($env, @tables) = @_;
  5517. foreach $t (@tables) {
  5518. $env->QuickScan(sub { /\b\S*?\.smf\b/g }, "$t.smf",
  5519. $env->{SMF_INCLUDE_PATH});
  5520. $env->Command(["$t.smdb.cc","$t.smdb.h","$t.snmp.cc",
  5521. "$t.ami.cc", "$t.http.cc"], "$t.smf",
  5522. q(smfgen %( %SMF_INCLUDE_OPT %) %<));
  5523. }
  5524. }
  5525. The subroutine above finds all names of the form <name>.smf in the
  5526. file. It will return the names even if they're found within comments,
  5527. but that's OK (the mechanism is forgiving of extra files; they're just
  5528. ignored on the assumption that the missing file will be noticed when
  5529. the program, in this example, smfgen, is actually invoked).
  5530. [NOTE that the form C<$env-E<gt>QuickScan ...> and C<$env-E<gt>Command
  5531. ...> should not be necessary, but, for some reason, is required
  5532. for this particular invocation. This appears to be a bug in Perl or
  5533. a misunderstanding on my part; this invocation style does not always
  5534. appear to be necessary.]
  5535. Here is another way to build the same scanner. This one uses an
  5536. explicit code reference, and also (unnecessarily, in this case) reads
  5537. the whole file itself:
  5538. sub myscan {
  5539. my(@includes);
  5540. do {
  5541. push(@includes, /\b\S*?\.smf\b/g);
  5542. } while <SCAN>;
  5543. @includes
  5544. }
  5545. Note that the order of the loop is reversed, with the loop test at the
  5546. end. This is because the first line is already read for you. This scanner
  5547. can be attached to a source file by:
  5548. QuickScan $env \&myscan, "$_.smf";
  5549. This final example, which scans a different type of input file, takes
  5550. over the file scanning rather than being called for each input line:
  5551. $env->QuickScan(
  5552. sub { my(@includes) = ();
  5553. do {
  5554. push(@includes, $3)
  5555. if /^(#include|import)\s+(\")(.+)(\")/ && $3
  5556. } while <SCAN>;
  5557. @includes
  5558. },
  5559. "$idlFileName",
  5560. "$env->{CPPPATH};$BUILD/ActiveContext/ACSCLientInterfaces"
  5561. );
  5562. =head1 SUPPORT AND SUGGESTIONS
  5563. Cons is maintained by the user community. To subscribe, send mail to
  5564. B<cons-discuss-request@gnu.org> with body B<subscribe>.
  5565. Please report any suggestions through the B<cons-discuss@gnu.org> mailing
  5566. list.
  5567. =head1 BUGS
  5568. Sure to be some. Please report any bugs through the B<bug-cons@gnu.org>
  5569. mailing list.
  5570. =head1 INFORMATION ABOUT CONS
  5571. Information about CONS can be obtained from the official cons web site
  5572. B<http://www.dsmit.com/cons/> or its mirrors listed there.
  5573. The cons maintainers can be contacted by email at
  5574. B<cons-maintainers@gnu.org>
  5575. =head1 AUTHORS
  5576. Originally by Bob Sidebotham. Then significantly enriched by the members
  5577. of the Cons community B<cons-discuss@gnu.org>.
  5578. The Cons community would like to thank Ulrich Pfeifer for the original pod
  5579. documentation derived from the F<cons.html> file. Cons documentation is now
  5580. a part of the program itself.
  5581. =cut