Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
4 anos atrás
3 anos atrás
4 anos atrás
3 anos atrás
3 anos atrás
5 anos atrás
3 anos atrás
6 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
6 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
4 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
5 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
5 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
6 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091
  1. var path = require('path');
  2. var utils = require('bbhverse');
  3. var any = utils.any;
  4. var Tasq = utils.Tasq
  5. var statuslog = utils.Traq
  6. var Traq = utils.Traq
  7. Tasq.addlistener(statuslog.statuslog)
  8. var cli = require('./cliverse')
  9. var nodeShellExec = cli.nodeShellExec;
  10. var chalk = require('chalk')
  11. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  12. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  13. const runtimestamp = (new Date()).getTime();
  14. function getVersion() { return BUILD_VERSION; }
  15. console.log(getVersion());
  16. // 'use strict';
  17. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  18. // PB : TODO --
  19. // runas bypass non elevated tasks when we request privelege
  20. // runas message is always error needs to be fixed.
  21. // runas wait needs to be parallelized.
  22. // suppress elevation check error messages
  23. // support runas lauched directly from shell.
  24. // pass in environment in hta to shellexecute.
  25. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  26. (function () {
  27. "use strict";
  28. if (!Array.prototype.earlyreduce) {
  29. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  30. var iterable = this;
  31. var donecallback = donecallback || (a=>a)
  32. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  33. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  34. // function *earlyReduceGenerator(acc, v, i, a) {
  35. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  36. var element = iterable[i]
  37. result = eachcallback(result, element, i, iterable)
  38. if(result.done) return donecallback(result)
  39. }
  40. // }
  41. return donecallback(result)
  42. }
  43. }
  44. }());
  45. const { existsSync } = require('fs');
  46. const existsFolderSync = existsSync;
  47. const fs = require('fs')
  48. const cliargs = utils.cliargs;
  49. const processedArgs = cliargs(process.argv.slice(2));
  50. console.dir(processedArgs)
  51. // PB : TODO -- defaults for valuless arguments if passed.
  52. // Object.keys(processedArgs).forEach(a=>{
  53. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  54. // }
  55. // })
  56. var subcommandlabels = {
  57. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  58. }
  59. var interpretrun = function(){
  60. var cmds = {
  61. 'remote' : function() {
  62. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  63. }
  64. }
  65. var cmd = processedArgs._[0];
  66. var clioverrides = { cmd }
  67. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  68. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  69. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  70. return cmds[cmd] ? cmds[cmd]() : (function(){
  71. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  72. return clioverrides
  73. })()
  74. }
  75. var clioverrides = interpretrun()
  76. console.dir(clioverrides)
  77. // Object.keys(clioverrides).forEach( prop => { })
  78. var globSync = require('glob').sync;
  79. var ENV = Object.assign({}, process.env); // Shallow clone it.
  80. const { readdir } = require("fs").promises
  81. // Directory shallow walk and do perform on each dir.
  82. const dirs = async (perform, path) => {
  83. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  84. if (dir.isDirectory()) perform(dir)
  85. }
  86. }
  87. var getShellTask = (command, args, options) => {
  88. options = options || {}
  89. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  90. return () => {
  91. var p = callshell( [command, args, Object.assign({
  92. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  93. }, options)
  94. ])
  95. if (options.ignorefailures) {
  96. return p.catch(e => {
  97. // Ignore. Not a major error.
  98. })
  99. }
  100. else return p;
  101. }
  102. }
  103. var callshelltask = (args) => {
  104. // console.dir(args)
  105. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  106. return args;
  107. }
  108. return getshelltask(args)()
  109. }
  110. var getshelltask = (args) => {
  111. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  112. var getgitbashtask = (args) => { return () => {
  113. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  114. }
  115. var getTaskCheckExists = (command, options) => {
  116. options = options || {}
  117. return () => {
  118. var p = nodeShellExec.apply(null, ['where', [command]])
  119. if (options.ignorefailures) {
  120. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  121. return false;
  122. })
  123. }
  124. else return p.then(() => { return true });
  125. }
  126. }
  127. var getTaskWithElevation = function(tasdef){
  128. return ()=>{
  129. if (__isElevated) {
  130. return tasdef.elevatedpulltasks().then(()=>{
  131. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  132. fs.writeFileSync('run.done', 'success')
  133. }).catch(e=>{
  134. fs.writeFileSync('run.done', 'failure')
  135. });
  136. }
  137. else {
  138. // PB : TODO -- Rename op['runas'] to 'elevate'
  139. var __runasresult = null;
  140. return op['runas']().then((r) => { return __runasresult = r; })
  141. .catch((e) => {
  142. console.error(e)
  143. })
  144. .finally(() => {
  145. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  146. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  147. })
  148. }
  149. }
  150. }
  151. var getTaskWithoutElevation = function(tasdef){
  152. return ()=>{
  153. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  154. else Promise.resolve(true)
  155. }
  156. }
  157. var gitops = {
  158. getdiscoverbranchcmd : function(repo){
  159. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  160. var cmd = [gitbash
  161. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  162. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  163. return cmd
  164. }
  165. }
  166. var getPullCmd = (repo, branch) => {
  167. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  168. // console.log(useGitPull)
  169. var pullCmd = []
  170. if(!branch) {
  171. // console.warn('No branch was specified detecting from working client.')
  172. // First check if working client exists.
  173. // if (existsSync(instanceroot + '/' + repo)) {
  174. pullCmd= gitops.getdiscoverbranchcmd(repo)
  175. // }
  176. // else performpull
  177. }
  178. // var pullCmd = [gitInstallDir
  179. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  180. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  181. if(branch) {
  182. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  183. var pullCmd = [ gitbash
  184. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  185. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  186. }
  187. // var pullCmd = ['pullall', [], { cwd : repo }]
  188. if (useGitPull) pullCmd = ['git', ['pull'], {
  189. inherit: true, shell: true,
  190. cwd: instanceroot + '/' + repo
  191. // , env: process.env
  192. , runas: processedArgs.runas
  193. , title: `git pull ${repo}`
  194. }]
  195. return pullCmd
  196. }
  197. var performPull = (repo, branch) => {
  198. // PB : TODO -- Handle no branch passed in case.
  199. // if(!branch) { throw 'No branch specified' }
  200. if (existsSync(instanceroot + '/' + repo)) {
  201. var branchprint = branch ? ' branch :' + branch : '';
  202. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  203. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  204. if (__isElevated) {
  205. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  206. }
  207. else statuslog.statuslog(null, repo)
  208. return true;
  209. })
  210. .catch((e) => {
  211. e.repo = repo;
  212. if (__isElevated) {
  213. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  214. }
  215. else statuslog.statuslog(e); console.error(e)
  216. })
  217. }
  218. else {
  219. console.log('cloning ' + repo)
  220. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  221. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  222. {
  223. inherit: true, shell: true,
  224. env: process.env
  225. , cwd : instanceroot
  226. , runas: processedArgs.runas
  227. }).catch((e) => {
  228. throw e;
  229. }).then(() => {
  230. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  231. {
  232. inherit: true, shell: true,
  233. env: process.env
  234. , cwd: instanceroot + '/' + repo
  235. , runas: processedArgs.runas
  236. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  237. })
  238. .then(() => {
  239. if (__isElevated) {
  240. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  241. }
  242. else statuslog.statuslog(null, repo)
  243. })
  244. .catch((e) => {
  245. e.repo = repo;
  246. if (__isElevated) {
  247. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  248. }
  249. else statuslog.statuslog(e);
  250. })
  251. })
  252. .catch(e => {
  253. e.repo = repo;
  254. if (__isElevated) {
  255. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  256. }
  257. else statuslog.statuslog(e);
  258. })
  259. }
  260. }
  261. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  262. // -- Currently workaround is to always run from a non-elevated shell.
  263. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  264. var acquireElevationState = () => {
  265. if (__isElevated === null) {
  266. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  267. inherit: true
  268. // , shell: true
  269. , stdio: 'ignore'
  270. , env: process.env
  271. , title: `check privileged execution mode using "fsutil dirty query C:"`
  272. }).then((exitcode) => {
  273. console.log('Elevated')
  274. __isElevated = true;
  275. return true;
  276. }).catch(() => {
  277. __isElevated = false;
  278. console.log('Not Elevated');
  279. return false;
  280. });
  281. }
  282. else return Promise.resolve(__isElevated);
  283. }
  284. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  285. var defaultRepoOwner = 'chess';
  286. var elevatedRunasRepos = null
  287. var gitRepos = null
  288. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  289. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  290. var dbForLabel = function (label) {
  291. var dbsForLabel = {
  292. devmysql: 'mysql'
  293. , development: 'mssql'
  294. , production: 'mssql'
  295. }
  296. return dbsForLabel[label] || 'mysql'
  297. }
  298. // SAM : TODO Use nodeshellexec where to detect git installation dir
  299. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  300. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  301. // Relevant git repos
  302. var exludeMergeRepos = [];
  303. var useGitPull = processedArgs.useGitPull || false;
  304. var configPromise = null
  305. // elxr cli operations
  306. var op = {
  307. 'h': () => { console.log(elxr.help()); return '-h' }
  308. , 'clean' : () => {
  309. // delete all node_module folders and links.
  310. var tasklist = [];
  311. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  312. return Promise.all(tasklist)
  313. }
  314. , 'undefined': () => { return op.h(); }
  315. , 'reset': () => {
  316. // Reset NPM packages semver so major versions can be updated.
  317. const fs = require('fs')
  318. const wipeDependencies = (__package) => {
  319. const file = fs.readFileSync(__package + '/package.json')
  320. const content = JSON.parse(file)
  321. for (var devDep in content.devDependencies) {
  322. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  323. content.devDependencies[devDep] = '*';
  324. }
  325. }
  326. for (var dep in content.dependencies) {
  327. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  328. content.dependencies[dep] = '*';
  329. }
  330. }
  331. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  332. }
  333. var repos = ['client'];
  334. // repos = gitRepos;
  335. repos.forEach(wipeDependencies)
  336. // if (require.main === module) {
  337. // } else {
  338. // module.exports = wipeDependencies
  339. // }
  340. }
  341. , 'upgrade': () => {
  342. console.log('upgrade.......')
  343. var tasks = [
  344. () => {
  345. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  346. inherit: true, shell: true
  347. , env: process.env
  348. }).catch((e) => { console.error(e) })
  349. p.position = 1;
  350. console.log('One')
  351. return p;
  352. }
  353. , () => {
  354. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  355. inherit: true, shell: true
  356. , env: process.env
  357. }).catch((e) => { console.error(e) })
  358. p.position = 2;
  359. console.log('Two')
  360. return p;
  361. }
  362. , () => {
  363. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  364. inherit: true, shell: true
  365. , env: process.env
  366. }).catch((e) => { console.error(e) })
  367. p.position = 3;
  368. console.log('Three')
  369. return p;
  370. }
  371. , () => {
  372. var p = nodeShellExec('n', ['latest'], {
  373. inherit: true, shell: true
  374. , env: process.env
  375. }).catch((e) => { console.error(e) })
  376. p.position = 4;
  377. console.log('Four')
  378. return p;
  379. }
  380. ]
  381. any(tasks)
  382. console.log('.......done')
  383. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  384. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  385. console.info('Uninstalling existing ember globally');
  386. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  387. stdio: ['pipe', process.stdout, process.stderr],
  388. inherit: true,
  389. shell: true,
  390. cwd: path.dirname(__dirname),
  391. env: env
  392. })
  393. step1.on('close', () => {
  394. console.info('Installing ember globally');
  395. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  396. stdio: ['pipe', process.stdout, process.stderr],
  397. inherit: true,
  398. shell: true,
  399. cwd: path.dirname(__dirname),
  400. env: env
  401. })
  402. step2.on('close', () => {
  403. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  404. stdio: ['pipe', process.stdout, process.stderr],
  405. inherit: true,
  406. shell: true,
  407. cwd: path.dirname(__dirname),
  408. env: env
  409. })
  410. })
  411. })
  412. }
  413. , 'runas': () => {
  414. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  415. console.log('Testing Elevation')
  416. if (__isElevated) {
  417. try {
  418. op[processedArgs.label || processedArgs._[0] || 'h']()
  419. }
  420. catch (e) {
  421. console.error('Error Invalid command : ' + e)
  422. fs.writeFileSync('run.done', 'error')
  423. }
  424. finally {
  425. }
  426. }
  427. else {
  428. console.log('Requesting Elevated Privileges');
  429. // Wait for the runas to complete before we read it.
  430. try {
  431. fs.unlinkSync('run.done')
  432. fs.unlinkSync('run.log')
  433. }
  434. catch (e) { } //Ignore
  435. // Find node path to send to hta.
  436. return nodeShellExec('where', ['node']).then(r => {
  437. var namedArgs = [];
  438. console.log('result : ' + JSON.stringify(r))
  439. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  440. // PB : TODO -- Convert all the cli args back to string.
  441. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  442. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  443. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  444. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  445. console.dir(processedArgs)
  446. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  447. , {
  448. inherit: true
  449. , shell: true
  450. , env: ENV
  451. , runas: 'self'
  452. , title: `runas`
  453. }
  454. ).then(() => {
  455. // runas returned.
  456. try {
  457. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  458. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  459. runaslog.forEach((logEntry) => {
  460. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  461. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  462. })
  463. }
  464. catch (e) {
  465. // We must have a runas log
  466. statuslog.statuslog(e)
  467. console.error('Run log error probably was not created by runas : ' + e)
  468. }
  469. })
  470. .catch(err => console.error('Elevation failed : ' + err));
  471. })
  472. }
  473. }
  474. , 'push': () => {
  475. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  476. // init remote bare from local
  477. // pushandinitremotebare
  478. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  479. // connect to repo server -- net use 172.16.0.27
  480. // cd 172.16.0.27/repos/
  481. // mkdir repo.git
  482. // cd repo.git
  483. // git init --bare
  484. // cd localrepo
  485. // git remote rename origin githubclone
  486. // git remote add origin //172.16.0.27/repos/repo.git
  487. // git push origin master
  488. var repo = processedArgs._[1];
  489. var sequentialTaskShellCommands = [];
  490. if (!existsSync(`Z:/${repo}.git`)) {
  491. sequentialTaskShellCommands = [
  492. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  493. // inherit : true, shell: true
  494. // , env: process.env
  495. // }]
  496. ['pwd', { cwd: 'Z:', inherit: true }]
  497. , ['mkdir', [`${repo}.git`], {
  498. cwd: `Z:`
  499. , inherit: true, shell: true
  500. , env: process.env
  501. }]
  502. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  503. , ['git', ['init', '--bare'], {
  504. cwd: `Z:/${repo}.git`
  505. , inherit: true, shell: true
  506. , env: process.env
  507. }]
  508. // PB : TODO -- Do this conditionally only...
  509. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  510. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  511. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  512. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  513. // PB : TODO -- If threre is a gitbubclone origin
  514. // Set the master to pull from the local repo.
  515. ]
  516. if (!existsSync(`Z:`)) {
  517. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  518. inherit: true, shell: true
  519. , env: process.env
  520. }])
  521. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  522. // throw 'done'
  523. }
  524. }
  525. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  526. // console.dir(sequentialTaskShellCommands);
  527. var tasks = [];
  528. sequentialTaskShellCommands.forEach(shellcmd => {
  529. // console.log(shellcmd)
  530. tasks.push(() => {
  531. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  532. return p;
  533. })
  534. })
  535. any(tasks);
  536. }
  537. , 'is-git-repo': (dir) => {
  538. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  539. }
  540. // git remote equivalents...
  541. // git branch --set-upstream-to=elixir-unc/master master
  542. // git push --set-upstream elixir-unc branch..
  543. , 'remote': (args) => {
  544. // Subcommands!
  545. // PB : TODO -- we can now pass in hypehnated args...
  546. if(!processedArgs.v) return false; // Only -v is supported presently..
  547. var serial_perform = (repo) => {
  548. var options = { cwd: instanceroot + '/' + repo }
  549. return [
  550. ['git', ['remote', '-v'], options]
  551. ]
  552. }
  553. var x = (args) => {
  554. var tasq = () => {
  555. // console.log(args)
  556. return nodeShellExec.apply(null, args).catch(e => {
  557. // We continue on failure.
  558. console.error(tasq.toString())
  559. })
  560. }
  561. tasq.toString = function(){
  562. return JSON.stringify(args)
  563. }
  564. return tasq;
  565. }
  566. var perform = (dir) => {
  567. return any(serial_perform(dir.name).map(x))
  568. }
  569. dirs(perform)
  570. }
  571. , 'remote set-url': (args) => {
  572. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  573. var __args = {
  574. remotename : args.remotename || processedArgs._[2]
  575. , url : args.url || processedArgs._[3]
  576. }
  577. // pushable doesn't mean the remote doesn't support being pushed to.
  578. // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
  579. // PB : TODO -- change this to enablepushing.
  580. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  581. var pushable = processedArgs.pushable || false;
  582. remotename = __args.remotename
  583. url = __args.url
  584. var serial_perform_git_seturl = (repo) => {
  585. var options = { cwd: instanceroot + '/' + repo }
  586. // console.log(repo)
  587. if (pushable) {
  588. return [
  589. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  590. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  591. ]
  592. }
  593. else {
  594. return [
  595. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  596. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  597. ]
  598. }
  599. }
  600. var x = (args) => {
  601. var tasq = () => {
  602. // console.log(args)
  603. return nodeShellExec.apply(null, args).catch(e => {
  604. // We continue on failure.
  605. console.error(tasq.toString())
  606. })
  607. }
  608. tasq.toString = function(){
  609. return JSON.stringify(args)
  610. }
  611. return tasq;
  612. }
  613. var perform_git_seturl = (dir) => {
  614. op['is-git-repo'](dir).then((logEntry) => {
  615. return any(serial_perform_git_seturl(dir.name).map(x))
  616. }).catch((e) => {
  617. // console.log('Failed : ' + dir.name)
  618. })
  619. }
  620. dirs(perform_git_seturl)
  621. }
  622. // , 'reset' : ()=>{
  623. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  624. // // Reset the whole installation pertaining to this elxr folder.
  625. // }
  626. , 'remote exists': (args) => {
  627. var __args = {
  628. remotename : args.remotename|| processedArgs._[2]
  629. , url : args.url || processedArgs._[3]
  630. , branch : args.branch || processedArgs._[4]
  631. }
  632. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  633. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  634. var commands = [
  635. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  636. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  637. ['git', ['remote', '-v'], utils.assign( {
  638. evaluateResult : function(err, result){
  639. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  640. var remotes = []
  641. var found = false;
  642. console.dir(result.messages)
  643. console.log(result + '---------------')
  644. result.messages.forEach( (line)=> {
  645. console.log(line + '$$$$$$$$$$$$$$$$$$$$')
  646. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  647. if(matches) {
  648. var remote = {};
  649. remote[matches[1]] = matches[2];
  650. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  651. found = true;
  652. result.url = remote[remotename];
  653. }
  654. }
  655. })
  656. console.dir(remotes)
  657. return [
  658. found
  659. , result
  660. ]
  661. }
  662. } , options) ]
  663. , function(prevserialtaskresult) {
  664. console.log('================================')
  665. var url = __args || prevserialtaskresult.url;
  666. console.dir(prevserialtaskresult)
  667. return getshelltask(['git', ['ls-remote', url], utils.assign( {
  668. evaluateResult : function(err, result){
  669. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  670. // `fatal: repository '${__args.url}/' not found`
  671. var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  672. return [
  673. !hasfailed, result
  674. ]
  675. }
  676. } , options) ])()
  677. }
  678. ]
  679. var mapped = commands.map(callshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  680. return any(mapped).then( allresolved =>{
  681. console.dir(allresolved)
  682. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  683. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  684. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  685. : console.log('was not added as a remote but url is currently accessible.')
  686. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  687. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  688. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  689. : [0, 1] // => was not added and remote and url is accessible.
  690. })
  691. }
  692. , 'remote refresh': (args) => {
  693. var __args = {
  694. remotename : args.remotename|| processedArgs._[2]
  695. , url : args.url || processedArgs._[3]
  696. , branch : args.branch || processedArgs._[4]
  697. }
  698. // use the repo manifest to create missing remotes.
  699. function perform_remote_refresh(dir){
  700. var repo = dir.name
  701. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  702. try {
  703. var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null, selectedinstance).remotes || [];
  704. }
  705. catch(e){
  706. var remotes = []
  707. }
  708. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  709. // console.dir(remotes)
  710. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  711. console.log('Processing : ' + dir.name)
  712. var branch = __branch
  713. __args.repo = repo
  714. __args.branch = __branch
  715. var promises = []
  716. remotes.forEach(remote =>{
  717. Object.keys(remote).forEach(remotename => {
  718. __args.remotename = remotename
  719. __args.url = remote[remotename]
  720. promises.push( op['remote exists']( __args ).then( exists => {
  721. if(!exists[0]) {
  722. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ) }
  723. else return op['remote add']( { remotename,
  724. // PB : TODO -- use the most accessible remote instead of the first available.
  725. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  726. } )
  727. }
  728. })
  729. )
  730. })
  731. })
  732. return Promise.all(promises)
  733. })
  734. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  735. }
  736. return dirs(perform_remote_refresh)
  737. }
  738. , 'remote add': (args) => {
  739. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  740. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  741. // That explicitly has a remote name prefix.
  742. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  743. // git branch branch_name -u your_new_remote/branch_name -- older versions
  744. // git branch -vv -- Detect which branch are we tracking.
  745. // default upstream should be users own fork.
  746. // Also need alias branches to
  747. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  748. // probably git merge from all remotes... and relevant branches...
  749. // alias pushall='for i in `git remote`; do git push $i; done;'
  750. // alias pullall='for i in `git remote`; do git pull $i; done;'
  751. // args === processedArgs ? args = {} : null;
  752. var __args = {
  753. remotename : args.remotename|| processedArgs._[2]
  754. , url : args.url || processedArgs._[3]
  755. , branch : args.branch || processedArgs._[4]
  756. }
  757. var remotename = __args.remotename
  758. var url = __args.url
  759. var branch = __args.branch
  760. var pushable = processedArgs.pushable || false;
  761. var serial_perform_git_add = (repo) => {
  762. var options = { cwd: instanceroot + '/' + repo }
  763. // console.log(repo)
  764. if (pushable) {
  765. return [
  766. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  767. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  768. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  769. ]
  770. }
  771. else {
  772. return [
  773. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  774. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  775. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  776. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  777. ]
  778. }
  779. }
  780. var x = (args) => {
  781. return () => {
  782. // console.log(args)
  783. return nodeShellExec.apply(null, args)
  784. }
  785. // return Promise.resolve(true)
  786. }
  787. var perform_git_add = (dir) => {
  788. op['is-git-repo'](dir).then((logEntry) => {
  789. // console.log(code)
  790. if (logEntry.success) {
  791. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  792. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  793. })
  794. .catch((e) => {
  795. any(serial_perform_git_add(dir.name).map(x))
  796. })
  797. }
  798. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  799. }).catch((e) => {
  800. console.log('Failed : ' + dir.name)
  801. })
  802. }
  803. const { readdir } = require("fs").promises
  804. dirs(perform_git_add)
  805. }
  806. , 'remote remove': (args) => {
  807. var __args = {
  808. remotename : args.remotename|| processedArgs._[2]
  809. }
  810. var remotename = __args.remotename
  811. var serial_perform_git_remove = (repo) => {
  812. var options = { cwd: instanceroot + '/' + repo }
  813. // console.log(repo)
  814. return [
  815. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  816. ]
  817. }
  818. var x = (args) => {
  819. return () => {
  820. // console.log(args)
  821. return nodeShellExec.apply(null, args)
  822. }
  823. // return Promise.resolve(true)
  824. }
  825. var perform_git_remove = (dir) => {
  826. op['is-git-repo'](dir).then((logEntry) => {
  827. // console.log(code)
  828. if (logEntry.success) {
  829. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  830. any(serial_perform_git_remove(dir.name).map(x))
  831. })
  832. .catch((e) => {
  833. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  834. })
  835. }
  836. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  837. }).catch((e) => {
  838. // console.log('Failed : ' + dir.name)
  839. })
  840. }
  841. const { readdir } = require("fs").promises
  842. dirs(perform_git_remove)
  843. }
  844. , 'init-gitea': (user) => {
  845. user = user || processedArgs._[1]
  846. if (!user) throw 'User name required'
  847. var serial_perform_init_gitea = (repo) => {
  848. var options = { cwd: instanceroot + '/' + repo }
  849. // console.log(repo)
  850. return [
  851. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  852. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  853. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  854. ]
  855. }
  856. var x = (args) => {
  857. return () => {
  858. // console.log(args)
  859. return nodeShellExec.apply(null, args)
  860. }
  861. // return Promise.resolve(true)
  862. }
  863. var perform_init_gitea = (dir) => {
  864. op['is-git-repo'](dir).then((logEntry) => {
  865. // console.log(code)
  866. if (logEntry.success) {
  867. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  868. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  869. })
  870. .catch((e) => {
  871. any(serial_perform_init_gitea(dir.name).map(x))
  872. })
  873. }
  874. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  875. }).catch((e) => {
  876. // console.log('Failed : ' + dir.name)
  877. })
  878. }
  879. const { readdir } = require("fs").promises
  880. dirs(perform_init_gitea)
  881. }
  882. , 'syncmaster': (label) => {
  883. // Usage :
  884. // elxr pull -- Defaults to run config
  885. var env = Object.assign({}, process.env); // Shallow clone it.
  886. // console.dir(env)
  887. console.log('Running exlr pull : ' + path.dirname(__dirname))
  888. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  889. if (__isElevated) {
  890. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  891. fs.writeFileSync('run.done', 'success')
  892. }).catch(() => {
  893. fs.writeFileSync('run.done', 'error')
  894. })
  895. }
  896. else return op['runas']()
  897. }
  898. , 'repo-relocate' : function(args){
  899. // relocate a subfolder in source repo to same subfolder in target repo with history.
  900. var args = args || {
  901. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  902. , folder : processedArgs._[3] || 'server'
  903. , sourcerepo : processedArgs._[2] || 'client'
  904. , targetrepo : processedArgs._[1] || 'elixir-server'
  905. }
  906. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  907. // , stdio: ['pipe', process.stdout, process.stderr]
  908. , inherit: true,
  909. shell: true,
  910. env: process.env
  911. , runas: processedArgs.runas
  912. }
  913. return op['repo-split'](args).then(()=>{
  914. return op['repo-merge'](args).then(()=>{
  915. // cleanup folder from source.
  916. var cmdseq = [
  917. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  918. // commits have to intentional...
  919. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  920. ]
  921. return any(cmdseq.map(getshelltask))
  922. })
  923. }).catch(e=>{console.error(e)})
  924. }
  925. , 'repo-split' : function(args) {
  926. // https://gist.github.com/smdabdoub/17065c348289158277b5
  927. /**
  928. * Eg : folder, remotebase, sourcerepo, targetrepo
  929. * args.folder = 'server'
  930. * args.remotebase = 'https://git.bbh/chess/'
  931. * args.sourcerepo = 'client'
  932. * args.targetrepo = 'elixir-server'
  933. */
  934. var args = args || {
  935. folder : 'server'
  936. , remotebase : 'http://git.bbh/chess/'
  937. , sourcerepo : 'client'
  938. , targetrepo : 'elixir-server'
  939. }
  940. var options = { cwd: `${instanceroot}/relocate`
  941. // , stdio: ['pipe', process.stdout, process.stderr]
  942. , inherit: true,
  943. shell: true,
  944. env: process.env
  945. , runas: processedArgs.runas
  946. }
  947. var cmdseq = [
  948. // create a temporary working dir in current folder where we started execution.
  949. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  950. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  951. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  952. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  953. ]
  954. return any(cmdseq.map(getshelltask)).then(() => {
  955. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  956. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  957. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  958. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  959. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  960. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  961. // subtree split and filter-branch are options. We currently use repo-filter.
  962. return op['filter-repo'](args)
  963. }).catch(e=>{console.error(e); throw 'failed'})
  964. }
  965. , 'repo-merge' : function(args) {
  966. // Merge source repo into target repo
  967. var args = args || {
  968. folder : 'server'
  969. , remotebase : 'http://git.bbh/chess/'
  970. , sourcerepo : 'client'
  971. , targetrepo : 'elixir-server'
  972. }
  973. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  974. // , stdio: ['pipe', process.stdout, process.stderr]
  975. , inherit: true,
  976. shell: true,
  977. env: process.env
  978. , runas: processedArgs.runas
  979. }
  980. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  981. // , stdio: ['pipe', process.stdout, process.stderr]
  982. , inherit: true,
  983. shell: true,
  984. env: process.env
  985. , runas: processedArgs.runas
  986. }
  987. var cmdseq = [
  988. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  989. , targetrepooptions ]
  990. // , ['git', ['push', targetrepooptions ] // manual push for now..
  991. ]
  992. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  993. }
  994. , 'filter-repo' : function(args){
  995. // Merge source repo into target repo
  996. var args = args || {
  997. folder : 'server'
  998. , remotebase : 'http://git.bbh/chess/'
  999. , targetrepo : 'elixir-server'
  1000. }
  1001. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1002. , inherit: true, shell: true
  1003. , env: process.env
  1004. , runas: processedArgs.runas
  1005. }
  1006. var cmdseq = [
  1007. // git checkout -b feature/merge-old-project
  1008. // git remote add src-project ../src-project
  1009. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  1010. ]
  1011. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  1012. }
  1013. , 'filter-branch' : function(preservefolder, repo){
  1014. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  1015. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  1016. // Preserve a specific folder.
  1017. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  1018. /*
  1019. git clone repo reposplit
  1020. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  1021. git remote rm origin
  1022. */
  1023. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  1024. }
  1025. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  1026. // // Merge repo2 into a subfolder in repo1
  1027. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  1028. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  1029. // /*
  1030. // cd repo1
  1031. // git remote add -f tempmergesource ../{{mergesource}}/.git
  1032. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  1033. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  1034. // git commit
  1035. // // Repair History
  1036. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  1037. // #!/usr/bin/env bash
  1038. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  1039. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  1040. // subdir=server
  1041. // git filter-branch --tree-filter '
  1042. // first='"$first"'
  1043. // last='"$last"'
  1044. // subdir='"$subdir"'
  1045. // log_file=/tmp/filter.log
  1046. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  1047. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  1048. // echo "=== $GIT_COMMIT: making changes"
  1049. // files=$(git ls-tree --name-only $GIT_COMMIT)
  1050. // mkdir -p $subdir
  1051. // for i in $files; do
  1052. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  1053. // done
  1054. // else
  1055. // echo "=== $GIT_COMMIT: ignoring"
  1056. // fi \
  1057. // >> $log_file
  1058. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  1059. // status=0 # tell tree-filter never to fail
  1060. // '
  1061. // git remote rm tempmergesource
  1062. // */
  1063. // // better alternative for history
  1064. // /**
  1065. // *
  1066. // git clone git@server.com:old-project.git
  1067. // git clone git@server.com:new-project.git
  1068. // cd old-project
  1069. // mkdir old-project
  1070. // git mv !(old-project) old-project
  1071. // ls -la and gt mv hidden files ....
  1072. // git commit -a -S -m “Moving old project into its own subdirectory”
  1073. // cd ../new-project
  1074. // git remote add old-project ../old-project
  1075. // git fetch old-project
  1076. // git checkout -b feature/merge-old-project
  1077. // git merge -S --allow-unrelated-histories old-project/master
  1078. // git push origin feature/merge-old-project
  1079. // git remote rm old-project
  1080. // */
  1081. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  1082. // }
  1083. , 'pull' : (label) => {
  1084. // Usage :
  1085. // elxr pull -- Defaults to run config
  1086. return elxr.getpulltask(selectedinstance)()
  1087. }
  1088. , 'isInstalled': () => {
  1089. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  1090. console.log(processedArgs._[1] + ' exists.')
  1091. return true;
  1092. });
  1093. }
  1094. , 'i' : () => {
  1095. var tasks = []
  1096. // tasks.push(op['pull']);
  1097. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1098. tasks.push(op['use'])
  1099. if (!__isElevated) {
  1100. tasks.push(op['npmi'])
  1101. }
  1102. // var tasksdefs = [
  1103. // ['elxr', ['pull']]
  1104. // , ['elxr', ['use', 'elixir']]
  1105. // , ['elxr', ['npmi']]
  1106. // ]
  1107. // tasksdefs.forEach(tasksdef=>{
  1108. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1109. // })
  1110. return any(tasks);
  1111. }
  1112. , 'npmi': () => {
  1113. var tasks = [];
  1114. // Build fails without babel...
  1115. tasks.push(getShellTask(
  1116. 'npm',[ 'i', '-g', 'babel-cli' ]
  1117. ) )
  1118. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1119. npmbuildrepos = []
  1120. npmbuildrepos.forEach(repo => {
  1121. tasks.push(() => {
  1122. return nodeShellExec('npm', ['i --force'], {
  1123. inherit: true, shell: true
  1124. , cwd: instanceroot + '/' + repo
  1125. , env: process.env
  1126. , title: `npm i for ${repo}`
  1127. }).catch((e) => {
  1128. console.error('Ignoring Benign Error'); console.error(e);
  1129. }).then(() => {
  1130. console.log(`--npm run build for ${repo}--------------------`)
  1131. return nodeShellExec('npm', ['run build'], {
  1132. inherit: true, shell: true
  1133. , cwd: instanceroot + '/' + repo
  1134. , env: process.env
  1135. , title: `npm run build for ${repo}`
  1136. }).then(Tasq.then).catch(Tasq.catch)
  1137. })
  1138. })
  1139. })
  1140. any(tasks).then(() => {
  1141. gitRepos.push('client/server');
  1142. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1143. // gitRepos = [
  1144. // // 'bbhverse', 'serververse', 'elixir-server',
  1145. // // 'clientverse',
  1146. // 'client'
  1147. // ];
  1148. var rmtasks = []
  1149. var repotasks = []
  1150. var env = Object.assign({}, process.env)
  1151. delete env.NODE_ENV
  1152. gitRepos.forEach(repodef => {
  1153. rmtasks.push(
  1154. // () => {
  1155. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1156. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1157. (callShellTask(['rm', ['package-lock.json'], {
  1158. inherit: true, shell: true
  1159. , cwd: instanceroot + '/' + repodef.repo
  1160. , env: process.env
  1161. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1162. }]))()
  1163. .then(()=>{
  1164. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1165. }).catch((e) => { console.error(e) })
  1166. // }
  1167. )
  1168. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1169. repotasks.push(
  1170. () => {
  1171. console.log(`--npm i for ${repodef.repo}--------------------`)
  1172. var p = nodeShellExec('npm', ['i', '--force'], {
  1173. inherit: true, shell: true
  1174. , cwd: instanceroot + '/' + repodef.repo
  1175. , env
  1176. , title: `npm i for ${repodef.repo}`
  1177. }).then(Tasq.then).catch(Tasq.catch)
  1178. return p;
  1179. })
  1180. }
  1181. })
  1182. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1183. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1184. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1185. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1186. // Second time try also doesnt work.
  1187. // repotasks.push(
  1188. // () => {
  1189. // var env = Object.assign({}, process.env)
  1190. // delete env.NODE_ENV
  1191. // console.log(`--------------------second time npm i for client--------------------`)
  1192. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1193. // // return nodeShellExec('npm', ['i --force'], {
  1194. // inherit: true, shell: true
  1195. // , cwd: instanceroot + '/' + 'client'
  1196. // , env
  1197. // , title: `npm i for client`
  1198. // }).then(Tasq.then).catch(Tasq.catch)
  1199. // })
  1200. var bowerRepos = [{ repo : 'client'}]
  1201. bowerRepos.forEach(repodef => {
  1202. repotasks.push(() => {
  1203. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1204. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1205. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1206. inherit: true, shell: true
  1207. , cwd: instanceroot + '/' + repodef.repo
  1208. , env: process.env
  1209. , title: `bower i for ${repodef.repo}`
  1210. }).then(Tasq.then).catch(Tasq.catch)
  1211. return p;
  1212. })
  1213. })
  1214. // console.log('rmtasks.length : ' + rmtasks.length)
  1215. return Promise.all(rmtasks).then(() => any(repotasks));
  1216. }).catch(e => {
  1217. }).finally(statuslog.finally)
  1218. }
  1219. , 'start': (label) => {
  1220. console.log('Starting Elixir Server.');
  1221. var env = Object.assign({}, process.env); // Shallow clone it.
  1222. // console.dir(env)
  1223. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1224. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1225. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1226. // cmd = 'node'
  1227. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1228. var childPromise = nodeShellExec(...cmd, {
  1229. // inherit : true,
  1230. shell: true,
  1231. detached: true,
  1232. stdio: 'ignore',
  1233. cwd: instanceroot + '/' + 'elixir-server'
  1234. , env: env
  1235. })
  1236. var child = childPromise.process;
  1237. if (typeof child.pid !== 'undefined') {
  1238. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1239. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1240. encoding: 'utf8'
  1241. })
  1242. }
  1243. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1244. // inherit : true,
  1245. // shell: true, detached: true,
  1246. // cwd : 'qms/server',
  1247. // env: env,
  1248. // shell : true
  1249. // })
  1250. // nodeShellExec('ember', ['s'], {
  1251. // // inherit : true,
  1252. // shell: true, detached: true,
  1253. // cwd : 'client/',
  1254. // env: env
  1255. // })
  1256. console.log('Starting Elixir Client Host.');
  1257. var cmd = ['ember', ['s']]
  1258. var childPromise = nodeShellExec(...cmd, {
  1259. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1260. // PB : TODO -- ember debugging.
  1261. // inherit : true,
  1262. shell: true,
  1263. detached: true,
  1264. stdio: 'ignore',
  1265. cwd: instanceroot + '/' + 'client'
  1266. , env: env
  1267. })
  1268. // .catch(e=>console.error(e))
  1269. child = childPromise.process;
  1270. if (typeof child.pid !== 'undefined') {
  1271. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1272. fs.writeFileSync('.client.server.pid', child.pid, {
  1273. encoding: 'utf8'
  1274. })
  1275. }
  1276. }
  1277. , 'stop': (label) => {
  1278. const kill = require('tree-kill');
  1279. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1280. encoding: 'utf8'
  1281. })
  1282. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1283. console.log(serverPid)
  1284. kill(serverPid)
  1285. serverPid = fs.readFileSync('.client.server.pid', {
  1286. encoding: 'utf8'
  1287. })
  1288. fs.unlinkSync('.client.server.pid')
  1289. console.log(serverPid)
  1290. kill(serverPid)
  1291. }
  1292. , 'model' : () => {
  1293. if (__isElevated) {
  1294. var tasks = [
  1295. () => {
  1296. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1297. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1298. inherit: true, shell: true
  1299. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1300. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1301. , env: process.env
  1302. }).catch((e) => { console.error(e) })
  1303. return p;
  1304. }
  1305. ];
  1306. return any(tasks).then(() => {
  1307. fs.writeFileSync('run.done', 'success')
  1308. }).catch(() => {
  1309. fs.writeFileSync('run.done', 'error')
  1310. })
  1311. }
  1312. else return op['runas']()
  1313. }
  1314. , 'use' : () => {
  1315. // use a certain named instance.
  1316. // Eg :
  1317. // 1) elxr use elixir
  1318. // 2) elxr use cihsr
  1319. // If environment is not specified defaults to development.
  1320. // 1) NODE=test elxr use elixir
  1321. /*// Steps
  1322. 1) Delete Config and Data symlinks
  1323. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1324. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1325. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1326. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1327. */
  1328. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1329. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1330. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1331. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1332. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1333. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1334. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1335. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1336. return
  1337. }
  1338. var tasks = [
  1339. () => {
  1340. if (existsSync('config')) {
  1341. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1342. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1343. return p;
  1344. }
  1345. else return Promise.resolve(true);
  1346. },
  1347. () => {
  1348. if (existsSync('data')) {
  1349. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1350. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1351. return p;
  1352. }
  1353. else return Promise.resolve(true);
  1354. },
  1355. ];
  1356. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1357. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1358. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1359. // console.log(process.env.cwd)
  1360. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1361. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1362. var checkoutMap = { 'development': 'master' }
  1363. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1364. var performPullOrCloneForBranch = (def)=>{
  1365. var promise = Promise.resolve(true)
  1366. if (!branch) {
  1367. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1368. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1369. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1370. }
  1371. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1372. }
  1373. var performCloneAndCheckout = null;
  1374. // cant use git checkout -b it fails when branch already exists.
  1375. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1376. return performPullOrCloneForBranch(def).then(()=>{
  1377. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1378. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1379. // inherit : true, shell: true,
  1380. cwd: instanceroot + '/' + def.repo
  1381. // , stdio : ignore // Use when we want to silence output completely.
  1382. , runas: processedArgs.runas
  1383. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1384. }).then(()=>{ console.log( `SUCCESS : git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}` ) }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1385. })
  1386. }
  1387. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1388. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1389. var elevatedqueue = [];
  1390. var enqueueOnce = (queue, task, def) => {
  1391. var found = queue.find(element => {
  1392. var keys = Object.keys( element )
  1393. for(var k=0; k < keys.length; k++) {
  1394. if(element[keys[k]] !== def[k]) return false;
  1395. }
  1396. })
  1397. queue.push(function(){ return task(this)}.bind(def));
  1398. }
  1399. var enqueue = (queue, task, def) => {
  1400. queue.push(function(){ return task(def)}.bind(def));
  1401. }
  1402. var mergeSources = {
  1403. 'development': null,
  1404. 'test': 'master',
  1405. 'production': 'master'
  1406. }
  1407. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1408. // Checkout is reduced to pull provided the current branch is the targetbranch
  1409. if(branch === mergesource) performCheckout = (def) => {
  1410. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1411. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1412. if(branch === __branch) return performCloneAndCheckout(def)
  1413. return performPullOrCloneForBranch(def)
  1414. })
  1415. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1416. }
  1417. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1418. var performPullAll = (def) => {
  1419. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1420. return nodeShellExec('git', ['pull', '--all'], {
  1421. // inherit : true, shell: true,
  1422. cwd: instanceroot + '/' + def.repo
  1423. , runas: processedArgs.runas
  1424. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1425. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1426. }
  1427. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1428. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1429. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1430. var performMerge = (def) => {
  1431. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1432. return nodeShellExec('git', ['merge', mergesource], {
  1433. inherit: true, shell: true,
  1434. cwd: instanceroot + '/' + def.repo
  1435. , runas: processedArgs.runas
  1436. }).catch((e) => { console.error(e) })
  1437. }
  1438. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1439. // var performRepoOperation = function(def) {
  1440. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1441. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1442. // }
  1443. return any(tasks).then(() => {
  1444. var pr = Promise.resolve(true)
  1445. if (!__isElevated) {
  1446. pr = op['runas']()
  1447. return pr.then(()=>{
  1448. //target is the env is we specify in elxr use command. Default is dev
  1449. //Switch to target branch
  1450. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1451. // pull or clone target branch
  1452. .then(() => {
  1453. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1454. return any(gitRepos.map((repo) => performPullAll(repo)))
  1455. })
  1456. // switch to source branch
  1457. .then( () => {
  1458. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1459. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1460. })
  1461. //Pull on merge source branch
  1462. .then( () => {
  1463. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1464. return any(gitRepos.map((repo) => performPullAll(repo)))
  1465. })
  1466. //Switch to target branch
  1467. .then( () => {
  1468. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1469. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1470. })
  1471. .then( //Merge source branch to target branch
  1472. () => {
  1473. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1474. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1475. })
  1476. })
  1477. }
  1478. else {
  1479. tasks = [
  1480. () => {
  1481. // Use junctions to avoid npm package issues
  1482. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1483. inherit: true, shell: true
  1484. , cwd : instanceroot
  1485. , env: process.env
  1486. }).catch((e) => { console.error(e) })
  1487. return p;
  1488. }
  1489. ];
  1490. if (processedArgs._[1]) {
  1491. tasks = tasks.concat(
  1492. [
  1493. () => {
  1494. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1495. inherit: true, shell: true
  1496. , cwd : instanceroot
  1497. , env: process.env
  1498. }).catch((e) => { console.error(e) })
  1499. return p;
  1500. }
  1501. ]
  1502. )
  1503. }
  1504. return any(tasks).then(()=>{
  1505. // checkout target branch
  1506. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1507. // pull or clone target branch
  1508. .then(() => {
  1509. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1510. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1511. })
  1512. // switch to source branch
  1513. .then( () => {
  1514. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1515. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1516. })
  1517. //Pull on merge source branch
  1518. .then( () => {
  1519. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1520. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1521. })
  1522. //Switch to target branch
  1523. .then( () => {
  1524. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1525. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1526. })
  1527. .then( //Merge source branch to target branch
  1528. () => {
  1529. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1530. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1531. })
  1532. .then(() => {
  1533. fs.writeFileSync('run.done', 'success')
  1534. }).catch(() => {
  1535. fs.writeFileSync('run.done', 'error')
  1536. })
  1537. })
  1538. }
  1539. }).catch(() => {
  1540. fs.writeFileSync('run.done', 'error')
  1541. })
  1542. // Antibiotic stewardship program.
  1543. // 1st use is fine.
  1544. // Max vials dispense
  1545. // 2nd use Pharmacy needs justification Form.
  1546. // Approval after a certain period of time.
  1547. }
  1548. , 'g': () => {
  1549. if (processedArgs.h) {
  1550. console.log('elxr g [modelname] => generate a model named [modelname]');
  1551. console.log('elxr g => regenerate all known models');
  1552. return
  1553. }
  1554. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1555. // console.log('Starting directory: ' + process.cwd());
  1556. // try {
  1557. // child = child.on('close', () => { process.chdir(label) } );
  1558. // console.log('New directory: ' + process.cwd());
  1559. // }
  1560. // catch (err) {
  1561. // console.log('chdir: ' + err);
  1562. // }
  1563. // child.on('close', function(){
  1564. // var options = {
  1565. // shell : true
  1566. // , inherit : true
  1567. // // , cwd : '' + process.cwd
  1568. // // , env : process.env
  1569. // };
  1570. // nodeShellExec('git', ['init'], { inherit : true});
  1571. if (0) {
  1572. // PB : TODO -- Special google chrome profile for tests etc.
  1573. nodeShellExec('pwd', { inherit: true });
  1574. // /c/Program\ Files\ \(x86\)/Google/Chrome/Application/chrome.exe --user-data-dir=/c/chess/instances/elixir_01/data/Google/Chrome/User\ Data --profile-directory="chess"
  1575. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/admin/crud/create/item
  1576. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/tests/index.html?grep=loopback
  1577. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1578. "--profile-directory=Profile 1"
  1579. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1580. }
  1581. // nodeShellExec('npm', ['init', '-y'], options);
  1582. // nodeShellExec('npm', ['init', '-y'], options);
  1583. // })
  1584. var g = {
  1585. 'client': () => {
  1586. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1587. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1588. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1589. stdio: ['pipe', process.stdout, process.stderr],
  1590. inherit: true,
  1591. shell: true,
  1592. cwd: path.dirname(__dirname),
  1593. env: env
  1594. })
  1595. },
  1596. 'modelr': () => {
  1597. var tasks = [
  1598. () => {
  1599. var p = nodeShellExec('"ember"', [
  1600. 'g'
  1601. , 'modelr'
  1602. , processedArgs._[2]], {
  1603. inherit: true, shell: true, env: process.env
  1604. }).then(() => {
  1605. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1606. return true;
  1607. }).catch((e) => { console.error(e) })
  1608. return p;
  1609. },
  1610. () => {
  1611. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1612. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1613. chromeprefs = JSON.parse(chromeprefs)
  1614. var previous = chromeprefs.download.default_directory;
  1615. var parentDir = path.dirname(__dirname);
  1616. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1617. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1618. // PB : TODO -- detect where chrome is installed.
  1619. // PB : TODO -- set the download dir to the place where files are needed.
  1620. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1621. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1622. , '--profile-directory="chess"'
  1623. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1624. inherit: true, shell: true
  1625. , env: process.env
  1626. }).then(() => {
  1627. chromeprefs.download.default_directory = previous;
  1628. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1629. return true;
  1630. }).catch((e) => { console.error(e) })
  1631. return p;
  1632. }
  1633. ,
  1634. () => {
  1635. console.log('Browser process should have closed here....')
  1636. return true;
  1637. }
  1638. ]
  1639. any(tasks)
  1640. }
  1641. }
  1642. g[processedArgs._[1]]();
  1643. }
  1644. }
  1645. var util = require('util');
  1646. var cliname = 'elxr';
  1647. var ver = '1.1';
  1648. var readme = `
  1649. Command syntax examples
  1650. elxr
  1651. Displays help. Same as elxr h
  1652. elxr i
  1653. Runs interactive propmts to help choose installation options.
  1654. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1655. General command syntax.
  1656. Eg: NODE_ENV=development elxr pull elixir
  1657. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1658. The specific cmd defines what the value is interpreted as.
  1659. There are several cmds that do not require an {{instancename}} parameter.
  1660. Eg: elxr remote remove origin
  1661. Git operations or passthrough external commands on all repository folders in you working directory.
  1662. Main objectives.
  1663. elxr cli is a wrapper around other shell commands and api based operations.
  1664. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1665. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1666. `;
  1667. var help = `
  1668. ${readme}
  1669. # list of commands... please refer dveloper documentation for ${cliname}
  1670. ${
  1671. // util.inspect(
  1672. [Object.keys(op)]
  1673. // )
  1674. }
  1675. `;
  1676. var elxr = {
  1677. help() {
  1678. return chalk.cyanBright(`
  1679. -------------------------------------------------------------------------------
  1680. *** BBH Elixir ***
  1681. -------------------------------------------------------------------------------
  1682. elxr ${ver}
  1683. A cli tool for chess
  1684. ${help}
  1685. -------------------------------------------------------------------------------
  1686. `)
  1687. }
  1688. , info() {
  1689. return chalk.cyanBright(`
  1690. -------------------------------------------------------------------------------
  1691. *** BBH Elixir ***
  1692. -------------------------------------------------------------------------------
  1693. elxr ${ver}
  1694. A cli tool for chess
  1695. -------------------------------------------------------------------------------
  1696. `)
  1697. }
  1698. , getpulltask(args){
  1699. // def can be an instance config
  1700. // Or an object with many repos and elevated repos
  1701. // Or a single repo ( Either Elevated or normal. )
  1702. // USAGE
  1703. // elxr pull elixir origin master
  1704. // elxr pull
  1705. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  1706. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  1707. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  1708. // The branch pipline should feed back to master
  1709. // master -> test -> stage -> release[nnnn] -> production
  1710. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  1711. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  1712. var __args = {
  1713. remotename : args.remotename|| processedArgs._[2]
  1714. , url : args.url || processedArgs._[3]
  1715. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  1716. }
  1717. // var commands = [
  1718. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  1719. // ,
  1720. // ]
  1721. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1722. // var pullCmd = [ gitbash
  1723. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1724. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  1725. var def = args || {
  1726. repos : selectedinstance.repos,
  1727. elevated : selectedinstance.elevated
  1728. }
  1729. var elevatedpulltasks = null;
  1730. if(def.repo) {
  1731. // Single repo case.
  1732. if(def.repo.requiresElevation) {
  1733. elevatedpulltasks = function() {
  1734. return performPull(def.repo).then(() => {
  1735. return true;
  1736. }).catch((e) => {
  1737. console.error(e)
  1738. })
  1739. }
  1740. return
  1741. }
  1742. else {
  1743. var regularpulltasks = function(){
  1744. var pendingpulls = [];
  1745. pendingpulls.push(performPull(def.repo))
  1746. return Promise.all(pendingpulls).finally(Traq.finally)
  1747. }
  1748. }
  1749. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1750. else return getTaskWithoutElevation({ regularpulltasks})
  1751. }
  1752. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1753. console.dir(def)
  1754. var env = Object.assign({}, process.env); // Shallow clone it.
  1755. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1756. var useGitPull = processedArgs.useGitPull || false;
  1757. if(def.elevated || def.repos) {
  1758. if(def.elevated) def.requiresElevation = true;
  1759. else delete def.requiresElevation;
  1760. }
  1761. else {
  1762. if(def.requiresElevation) def.elevated = [def]
  1763. else def.repos = [def]
  1764. }
  1765. var regularpulltasks = function(){ return Promise.resolve(true) }
  1766. if(def.elevated){
  1767. elevatedpulltasks = function() {
  1768. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1769. return true;
  1770. }).catch((e) => {
  1771. console.error(e)
  1772. })
  1773. }
  1774. }
  1775. if(def.repos) {
  1776. var regularpulltasks = function(){
  1777. var pendingpulls = [];
  1778. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1779. return Promise.all(pendingpulls).finally(Traq.finally)
  1780. }
  1781. }
  1782. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1783. else return getTaskWithoutElevation({ regularpulltasks})
  1784. }
  1785. }
  1786. function preworkerconfig(){
  1787. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1788. gitRepos = selectedinstance.repos
  1789. // gitRepos = ['chess-server-lib'];
  1790. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1791. elevatedRunasRepos = selectedinstance.elevated
  1792. // Repos that should excluded from merge for releases...
  1793. exludeMergeRepos = selectedinstance.exludeMergeRepos
  1794. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1795. // mysql -u root -p db_name < drop_all_tables.sql
  1796. var mysql = '../xampp/mysql/bin/mysql'
  1797. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1798. }
  1799. // The main elxr cli process
  1800. function elxrworker() {
  1801. var __runcmd = function (label) {
  1802. var distinquishedlabel = subcommandlabels[label] || label
  1803. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1804. }
  1805. // --runas
  1806. if (processedArgs.runas) {
  1807. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1808. return __runcmd('runas')
  1809. }
  1810. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1811. }
  1812. function acquireChoices(selectedinstance) {
  1813. var hasconfig = false;
  1814. console.warn(chalk.cyan(`
  1815. -------------------------------------------------------------------------------
  1816. Warning : Cannot locate your preferred configuration since it was not specified
  1817. You should fork the default chess configuration to customize and make it
  1818. your own instance with a named config as
  1819. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1820. And then run this tool as follows
  1821. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1822. OR
  1823. Run this tool with the following command to use a quick start default.
  1824. elxr --default
  1825. OR
  1826. Choose one of the options below to run interactively.
  1827. We will run your choice at the next prompt.
  1828. -------------------------------------------------------------------------------
  1829. `))
  1830. var prompt = cli.prompter;
  1831. return prompt.ask(`Choose an option :
  1832. d) Install the default chess instance.
  1833. => elxr i chess node_env=development --default
  1834. n) Create your custom new instance interactively
  1835. => elxr i {{instanceName}} node_env={{environment}}
  1836. i) Choose an instance and environment to install
  1837. => elxr i {{instanceName}} node_env={{environment}}
  1838. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1839. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1840. h) Help
  1841. q) Quit
  1842. Default <= d
  1843. : `).then((choice) => {
  1844. if (choice && choice === 'd' || !choice) {
  1845. processedArgs._[0] = 'i'
  1846. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1847. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1848. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1849. }
  1850. else if (choice === 'h') {
  1851. processedArgs._[0] = 'h'
  1852. fs.writeFileSync('run.done', 'noop help');
  1853. console.log(elxr.help()); process.exit()
  1854. }
  1855. else if (choice === 'n' || choice === 'i') {
  1856. var p1 = cli.prompter;
  1857. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1858. processedArgs._[0] = 'i'
  1859. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1860. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1861. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1862. if (choice === 'n') {
  1863. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1864. console.warn(
  1865. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1866. process.exit();
  1867. }
  1868. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1869. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1870. })
  1871. })
  1872. })
  1873. } else if (choice === 'c') {
  1874. var p1 = cli.prompter;
  1875. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1876. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1877. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1878. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1879. return p1.ask(`Enter cmd :
  1880. p) pull
  1881. Default <= p
  1882. : `).then(function (cmd) {
  1883. if (!cmd || cmd === 'p') {
  1884. processedArgs._[0] = 'pull'
  1885. }
  1886. else processedArgs._[0] = cmd
  1887. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1888. selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1889. })
  1890. })
  1891. })
  1892. })
  1893. } else {
  1894. console.log(chalk.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  1895. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1896. fs.writeFileSync('run.done', 'noop quit');
  1897. process.exit()
  1898. }
  1899. })
  1900. }
  1901. var mergeObjByKey = function(arrOfObjs, keyName) {
  1902. var keyedDistinct = {}
  1903. var distinctArrOfObjs = []
  1904. arrOfObjs.forEach( o => {
  1905. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1906. })
  1907. Object.keys(keyedDistinct).forEach(key => {
  1908. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1909. })
  1910. return distinctArrOfObjs;
  1911. }
  1912. var cacheWriteInstanceConfig = function(chessinstances){
  1913. var instanceName = chessinstances['current_run'].instanceName;
  1914. var node_env = chessinstances['current_run'].node_env;
  1915. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1916. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1917. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1918. }
  1919. var acquireConfig = function (selected) {
  1920. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1921. return performPull(configrepo).then(() => {
  1922. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1923. selectedinstance = require(manifestpath)()
  1924. // Config from server always override merges into selection ecept for the current selection.
  1925. // PB : TODO -- utils.assign Array merges are non-distinct...
  1926. if(!selectedinstance.repos[0].repo) {
  1927. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1928. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  1929. }
  1930. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  1931. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1932. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  1933. }
  1934. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  1935. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  1936. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1937. cacheWriteInstanceConfig(chessinstances)
  1938. ENV.NODE_ENV = selectedinstance.node_env;
  1939. })
  1940. .catch((e) => {
  1941. console.error(e)
  1942. console.error('Config acquisition failed.')
  1943. })
  1944. }
  1945. var launchpath = path.normalize(process.cwd())
  1946. var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  1947. // The easisest would be to ask for a target directory and default to current dir....
  1948. var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  1949. var __default = {
  1950. // Default is public server only.
  1951. // All public repos are by default available.
  1952. reposervers: ['https://git.bbh.org.in']
  1953. , repos: [
  1954. { repo : 'setup' }
  1955. , { repo : 'elxr' }
  1956. , { repo : 'loopback-connector-mysql' }
  1957. , { repo : 'loopback-jsonapi-model-serializer' }
  1958. , { repo : 'loopback-component-jsonapi' }
  1959. , { repo : 'ember-service-worker' }
  1960. , { repo : 'ember-service-worker-asset-cache' }
  1961. , { repo : 'ember-service-worker-cache-fallback' }
  1962. , { repo : 'ember-service-worker-index' }
  1963. , { repo : 'ember-sw-client-route' }
  1964. ]
  1965. , elevated: []
  1966. , exludeMergeRepos: {}
  1967. , instanceName: 'chess'
  1968. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1969. , node_env: 'development'
  1970. }
  1971. var hasElxr = function(path, options, cb) {
  1972. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  1973. options = options || {};
  1974. var tasks = [
  1975. '/elxr' // Is there a subfolder named elxr
  1976. , '/elxr/.git' // which is self git repository
  1977. , '/elxr/.elxr' // and has .elxr subfolder
  1978. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  1979. ]
  1980. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  1981. var value = existsFolderSync(path + tpath);
  1982. return { value, done : acc && !value };
  1983. }).value }
  1984. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  1985. var value = existsFolderSync(path + tpath);
  1986. return { value, done : acc && !value };
  1987. }).value );
  1988. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  1989. var value = existsFolderSync(path + tpath);
  1990. return { value, done : acc && !value };
  1991. }).value);
  1992. }
  1993. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  1994. var detectfromroot = function(root){
  1995. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  1996. }
  1997. var detectinstances = function () {
  1998. console.log(`launchpath = ${launchpath}`)
  1999. console.log(`thisscriptdir = ${thisscriptdir}`)
  2000. // PB : TODO -- !Postpone this.
  2001. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  2002. // Note : Paths should already be normalized fefore this.
  2003. var root = instanceroot;
  2004. var detected = { root };
  2005. var instanceoptions = [clioverrides]
  2006. return hasElxr(launchpath).then( (elxrCliExists) => {
  2007. // We need a reference to the root director for elxr cli to be properly oriented.
  2008. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  2009. // We were run from the proper root with elxr cli in the subfolder.
  2010. instanceroot = root = launchpath;
  2011. instanceoptions.splice( 0, 0, detected = { root })
  2012. instanceoptions.splice( 0, 0, detectfromroot(root))
  2013. }
  2014. else {
  2015. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  2016. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  2017. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  2018. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  2019. instanceroot = root = launchpath;
  2020. instanceoptions.splice( 0, 0, detected = { root })
  2021. instanceoptions.splice( 0, 0, detectfromroot(root))
  2022. }
  2023. else if (launchpath === thisscriptdir) {
  2024. var parentHasElxr = hasElxrSync(launchpath + '/..')
  2025. // PB : TODO -- verify if we have .elxr folder in the parent...
  2026. if(!parentHasElxr) {
  2027. // ! thisscriptdir is not elxr.
  2028. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  2029. }
  2030. // Same directory doesn't mean we are being run from elxr sub directory.
  2031. // In standalone build script we may or not be in the same location.
  2032. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  2033. // Unbuilt therefore we are in the elxr sub directory.
  2034. instanceroot = root = path.normalize(launchpath + '/..');
  2035. instanceoptions.splice( 0, 0, detected = { root });
  2036. instanceoptions.splice( 0, 0, detectfromroot(root));
  2037. }
  2038. else {
  2039. // Built version.
  2040. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  2041. if(parentHasElxr) {
  2042. // Built version was run from the full elxr subfolder. Should work
  2043. // PB : TODO -- but we should switch to the full version...
  2044. instanceroot = root = path.normalize(launchpath + '/..');
  2045. instanceoptions.splice( 0, 0, detected = { root })
  2046. instanceoptions.splice( 0, 0, detectfromroot(root))
  2047. }
  2048. else {
  2049. instanceroot = root = launchpath;
  2050. instanceoptions.splice( 0, 0, detected = { root })
  2051. instanceoptions.splice( 0, 0, detectfromroot(root))
  2052. // Assume current launchpath is a new instance and create.
  2053. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  2054. // if(clioverrides.instanceName) {
  2055. // if(clioverrides.node_env) {
  2056. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  2057. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  2058. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  2059. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  2060. // // eg : floder name can be elixir01 but instance name is elixr
  2061. // }
  2062. // else {
  2063. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  2064. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  2065. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  2066. // }
  2067. // }
  2068. // else {
  2069. // instanceroot = root = launchpath;
  2070. // if(clioverrides.node_env) {
  2071. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  2072. // instanceoptions.splice( 0, 0, detectfromroot(root))
  2073. // }
  2074. // else {
  2075. // // Nothing was specified... We only have one option from root.
  2076. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  2077. // }
  2078. // }
  2079. }
  2080. }
  2081. }
  2082. else {
  2083. if(elxrCliExists) {
  2084. instanceroot = root = launchpath;
  2085. instanceoptions.splice( 0, 0, detected = { root })
  2086. instanceoptions.splice( 0, 0, detectfromroot(root))
  2087. }
  2088. }
  2089. }
  2090. instanceroot = detected.root
  2091. __default.root = root;
  2092. clioverrides.root = clioverrides.root || root;
  2093. // Resolves empty array when No known instances detected.
  2094. return Promise.resolve(instanceoptions)
  2095. })
  2096. }
  2097. if(clioverrides.reconfirm) {
  2098. var reconfirm = { 'instanceName' : clioverrides['instanceName'] === 'chess' }
  2099. }
  2100. else { var reconfirm = {}; }
  2101. var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
  2102. return function(prompts, k, i, a){
  2103. // No local instances config found. We use a default initialized instance available in selectedinstance
  2104. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2105. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2106. if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
  2107. || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
  2108. || reconfirm[k]) {
  2109. prompts.push(async ()=>{
  2110. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2111. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2112. // If latest altered state is required we can reerence this directly.
  2113. // var asyncthis = Object.assign(this);
  2114. promptables[k].choices = choices[k]
  2115. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2116. return await target[k]
  2117. })
  2118. }
  2119. delete mustPrompt[k]
  2120. return prompts
  2121. }
  2122. }
  2123. var __interactive_prompts = function( target, choices ){
  2124. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2125. var interactionpoints = {
  2126. runchoice : {
  2127. label :
  2128. `Choose an option :
  2129. d) Install the default chess instance.
  2130. => elxr i chess node_env=development --default
  2131. n) Create your custom new instance interactively
  2132. => elxr i {{instanceName}} node_env={{environment}}
  2133. i) Choose an instance and environment to install
  2134. => elxr i {{instanceName}} node_env={{environment}}
  2135. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2136. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2137. h) Help
  2138. q) Quit
  2139. : `
  2140. , choices : []
  2141. , defaultchoice : 'c'
  2142. , interpret : function(choice){
  2143. var interpret_map = {
  2144. d : function(){
  2145. processedArgs._[0] = 'i'
  2146. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2147. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2148. target.reposerver = 'https://git.bbh.org.in'
  2149. }
  2150. , n : function() { processedArgs._[0] = 'i' }
  2151. , i : function() { processedArgs._[0] = 'i' }
  2152. , c : async function() {
  2153. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2154. label : `Enter cmd :
  2155. p) pull
  2156. Default <= p
  2157. : `
  2158. , defaultchoice : 'pull'
  2159. }
  2160. ));
  2161. var cmd = await target['cmd'];
  2162. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2163. else target['cmd'] = processedArgs._[0] = cmd
  2164. return cmd;
  2165. }
  2166. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2167. , q : function() { process.exit() }
  2168. }
  2169. var __interpreter = interpret_map['c']
  2170. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2171. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2172. return __interpreter.call(target)
  2173. }
  2174. }
  2175. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  2176. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
  2177. , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
  2178. , repouser : { label : `Enter User Id for ${target.reposerver} ( <= ${target.repouser || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  2179. }
  2180. var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices)
  2181. return Object.keys(interactionpoints).reduce(eachPrompt, [])
  2182. }
  2183. var downloadsdir = '../Downloads';
  2184. var prerequisites = [
  2185. {
  2186. shellcmd: 'git',
  2187. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2188. , installer: 'Git-2.31.0-64-bit.exe'
  2189. , installcmd: ['cmd', ['/c', 'start',
  2190. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2191. , '/VERYSILENT'
  2192. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2193. ]]
  2194. , preinstallsteps: function() {
  2195. var prompt = cli.prompter;
  2196. var steps = [
  2197. () => {
  2198. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2199. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2200. }
  2201. else return Promise.resolve(true)
  2202. }
  2203. ]
  2204. var prompts = [
  2205. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  2206. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  2207. ]
  2208. return any([any(steps), any(prompts)])
  2209. }
  2210. , installsteps: function () {
  2211. return any([this.installcmd].map(getshelltask))
  2212. }
  2213. , postinstallsteps: function(){
  2214. var prompt = cli.prompter;
  2215. var gitUser = 'guest';
  2216. var gitEmail = 'guest@bbh.org.in';
  2217. var prompts = [];
  2218. prompts.push(
  2219. ()=>{
  2220. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  2221. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  2222. }
  2223. )
  2224. prompts.push(
  2225. ()=>{
  2226. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  2227. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  2228. }
  2229. )
  2230. return any(prompts).then(()=>{
  2231. var steps = [
  2232. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2233. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2234. ]
  2235. return any(steps.map(getshelltask)).then(() => {
  2236. })
  2237. });
  2238. }
  2239. , install: function () {
  2240. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2241. }
  2242. , verifyAndInstall : function(){
  2243. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2244. if(exists) {
  2245. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2246. return this.getUser(null, this.postinstallsteps.bind(this))
  2247. }
  2248. return this.install();
  2249. });
  2250. }
  2251. , getUser : function(repo, onNoResult){
  2252. onNoResult = onNoResult || function(){return false}
  2253. var globalOrLocal = '--global';
  2254. if(!repo) globalOrLocal = '--global';
  2255. else globalOrLocal = '--local'
  2256. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  2257. // not yet configured.
  2258. if(!result.success) return onNoResult()
  2259. else {
  2260. var users = result.messages[0].trim().split('\n');
  2261. if(users.length === 0 ||
  2262. users.length === 1 && users[0] === 'guest') {
  2263. return onNoResult()
  2264. }
  2265. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  2266. }
  2267. })
  2268. .catch((e)=>{
  2269. console.log(e)
  2270. return onNoResult()
  2271. })
  2272. }
  2273. }
  2274. ,
  2275. {
  2276. shellcmd: 'node',
  2277. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  2278. , installer: 'node-v14.16.0-x64.msi'
  2279. , installcmd: ['MSIEXEC.exe', ['/i'
  2280. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  2281. , 'ACCEPT=YES', '/passive']]
  2282. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  2283. }
  2284. ]
  2285. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  2286. function ensureDirectoryExistence(filePath) {
  2287. var dirname = path.dirname(filePath);
  2288. if (fs.existsSync(dirname)) {
  2289. return filePath;
  2290. }
  2291. ensureDirectoryExistence(dirname);
  2292. fs.mkdirSync(dirname);
  2293. return filePath;
  2294. }
  2295. var mainTasks = [];
  2296. function verifyAndInstallPrerequisites() {
  2297. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  2298. // PB : TODO include and build from files... using rollup..
  2299. var downloadbatch =
  2300. `::**************************************************************************
  2301. :Download_ <url> <File>
  2302. Powershell.exe ^
  2303. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2304. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2305. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2306. exit /b
  2307. ::**************************************************************************`
  2308. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  2309. var windowselevate =
  2310. `
  2311. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2312. <script language="vbscript">
  2313. document.title = "elxr control panel"
  2314. self.ResizeTo 200,600
  2315. Sub Window_Onload
  2316. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2317. End Sub
  2318. Set objShell = CreateObject("WScript.Shell")
  2319. Set objENV = objShell.Environment("Process")
  2320. dim NODE_ENV
  2321. NODE_ENV = objENV("NODE_ENV")
  2322. </script>
  2323. <script language="javascript">
  2324. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2325. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2326. // alert(windowselevate.commandLine)
  2327. var args = windowselevate.commandLine.split('"').slice(3);
  2328. // alert(args)
  2329. var processedArgs = { _ : [] }
  2330. var namedArgs = [];
  2331. for(var item in args){
  2332. if(args[item].charAt(0) === '-'){
  2333. namedArgs.push(args[item])
  2334. var split = args[item].split('=');
  2335. processedArgs[split[0].slice(2)] = split[1] || true;
  2336. }
  2337. else processedArgs._.push(args[item]);
  2338. }
  2339. // args = args.forEach(function(item){ })
  2340. // alert('processedArgs._ : ' + processedArgs._);
  2341. // alert(processedArgs.runas);
  2342. // PB : TODO -- Convert all the cli args back to string.
  2343. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2344. // alert(cargs)
  2345. var shell = new ActiveXObject('shell.application');
  2346. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2347. // shell.ShellExecute('where', 'node', '', '', 10);
  2348. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2349. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2350. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2351. window.onload = function() {
  2352. document.body.style.backgroundColor = 'black';
  2353. document.body.style.fontFamily = 'arial';
  2354. var log = document.createElement('div');
  2355. log.innerHTML='Please Wait';
  2356. function l(msg){ log.innerHTML+= msg; };
  2357. log.style.color = 'blue';
  2358. log.style.width = '95%';
  2359. log.id = 'log';
  2360. document.body.appendChild(log);
  2361. l('<Br/>Current config : ')
  2362. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2363. l('<Br/>cmd = ' + processedArgs._[0])
  2364. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2365. l('<Br/><Br/>')
  2366. var timer = function(){
  2367. l('.');
  2368. if(fso.FileExists("run.done")) close();
  2369. else window.setTimeout(timer, 1000);
  2370. };
  2371. window.setTimeout(timer, 3000);
  2372. };
  2373. </script>
  2374. </html>
  2375. `
  2376. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2377. var downloadtasks = [];
  2378. var installtasks = [];
  2379. prerequisites.forEach(preq => {
  2380. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2381. if (exists) console.log(`${preq.shellcmd} exists`)
  2382. else {
  2383. console.log(`${preq.shellcmd} is not installed`)
  2384. return preq.preinstallsteps.call(preq).then(() => {
  2385. installtasks.push(preq.install.bind(preq))
  2386. })
  2387. }
  2388. }))
  2389. })
  2390. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2391. }
  2392. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  2393. return {
  2394. get (){
  2395. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  2396. var asyncprop = Promise.resolve(propValue)
  2397. if(promptable.interpret){
  2398. asyncprop = promptable.interpret(propValue)
  2399. }
  2400. return asyncprop.then(
  2401. ()=>{
  2402. Object.defineProperty(this, propName, {
  2403. value: propValue,
  2404. writable: true,
  2405. configurable : true,
  2406. enumerable : true
  2407. });
  2408. return propValue
  2409. }
  2410. )
  2411. })
  2412. }
  2413. // , set (propValue){
  2414. // Object.defineProperty(this, propName, {
  2415. // value: propValue,
  2416. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  2417. // configurable : true,
  2418. // enumerable : true
  2419. // })
  2420. // return propValue;
  2421. // }
  2422. , configurable : true
  2423. , enumerable : true
  2424. }
  2425. }
  2426. function acquirelocalinstances(selected){
  2427. // utils.assign is used to cleanup duplicates...
  2428. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2429. return chessinstances
  2430. }
  2431. function findlocalinstances(chessinstances, instanceoptions){
  2432. // We can expect a .elxr at each level.
  2433. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  2434. earlyreduce( ( value, p, i, a )=>{
  2435. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  2436. if(existsSync( localinstancesPath )) {
  2437. try {
  2438. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  2439. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  2440. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  2441. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  2442. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  2443. return {
  2444. value : chessinstances[instanceName][instanceType]
  2445. , done : true
  2446. };
  2447. }
  2448. })
  2449. })
  2450. }
  2451. catch(e){
  2452. return { }
  2453. }
  2454. }
  2455. else return { }
  2456. }
  2457. )
  2458. }
  2459. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2460. var selectedinstance = null;
  2461. var chessinstances = { current_run : {} };
  2462. var promptkeys = {
  2463. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  2464. // 'instanceName' : true
  2465. // , 'node_env' : true
  2466. }
  2467. function createChessInsance( cfg ){
  2468. var inst = {};
  2469. var __new = Object.assign({}, __default, cfg)
  2470. inst[cfg.node_env] = __new; return inst;
  2471. }
  2472. acquireElevationState().then(() => {
  2473. var skipprerequisites = false;
  2474. function initinstances(selected_overrides) {
  2475. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectinstances.
  2476. var instanceName = selected_overrides.instanceName
  2477. || clioverrides.instanceName
  2478. // || processedArgs._[1]
  2479. || chessinstances.current_run.instanceName
  2480. var node_env = selected_overrides.node_env
  2481. || clioverrides.node_env
  2482. // || processedArgs.node_env
  2483. || chessinstances.current_run.node_env
  2484. var reposerver = selected_overrides.reposerver
  2485. || clioverrides.reposerver
  2486. // || processedArgs.node_env
  2487. || chessinstances.current_run.reposerver
  2488. if(!instanceName) {
  2489. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  2490. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2491. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2492. }
  2493. if(!node_env) {
  2494. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2495. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2496. }
  2497. if(!reposerver) {
  2498. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2499. }
  2500. chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
  2501. instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
  2502. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  2503. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  2504. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  2505. }
  2506. // Override sequence.
  2507. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2508. selectedinstance = utils.assign(
  2509. chessinstances[instanceName][node_env]
  2510. , clioverrides
  2511. , selected_overrides
  2512. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  2513. );
  2514. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  2515. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  2516. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  2517. // // Brand New.
  2518. // selectedinstance = Object.assign( __default, selectedinstance )
  2519. // }
  2520. if(!selectedinstance.repos[0].repo) {
  2521. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2522. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2523. }
  2524. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2525. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2526. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2527. }
  2528. // Config from server always override merges into selection except for the current selection.
  2529. // PB : TODO -- utils.assign Array merges are non-distinct...
  2530. chessinstances[instanceName][node_env] = selectedinstance;
  2531. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2532. cacheWriteInstanceConfig(chessinstances)
  2533. // PB : TODO -- We should probably write the new server config also...
  2534. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2535. return chessinstances
  2536. }
  2537. var noprerequisites = {
  2538. add : true, 'set-url' : true, 'repo-relocate' : true
  2539. , remote : true
  2540. }
  2541. var skipprereqs = {}
  2542. var maintask = () => {
  2543. // Default cmd to run !
  2544. processedArgs._[0] === processedArgs._[0] || 'pull';
  2545. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  2546. if(!noprerequisites[processedArgs._[0]]
  2547. && !skipprereqs[processedArgs._[0]]
  2548. ) {
  2549. return prerequisites.git.verifyAndInstall().then(()=>{
  2550. var e = { message : 'verifyAndInstall', success : true}
  2551. return acquireConfig(selectedinstance).catch((err) => {
  2552. e = err;
  2553. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  2554. console.error(err)
  2555. }).then(() => { preworkerconfig(); return elxrworker(true) })
  2556. // .finally(()=>{
  2557. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2558. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2559. // // return process.exit()
  2560. // })
  2561. })
  2562. }
  2563. else {
  2564. console.log('cmd has no preqs or has been configured to skip preqs')
  2565. preworkerconfig()
  2566. return elxrworker()
  2567. }
  2568. }
  2569. const retaincount = 2
  2570. var min = runtimestamp;
  2571. var collect = []
  2572. // if(noprerequisites[processedArgs._[0]]
  2573. // || skipprereqs[processedArgs._[0]]
  2574. // ) {
  2575. // return elxrworker()
  2576. // }
  2577. var getchoices = function(detectedinstanceoptions, promptkeys){
  2578. var instances = []
  2579. var reposervers = [];
  2580. var instnaceNames = []
  2581. var instanceTypes = ['development', 'production'];
  2582. Object.keys( chessinstances).forEach(instanceName => {
  2583. if(instanceName === 'current_run') return;
  2584. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  2585. var instance = chessinstances[instanceName][node_env];
  2586. reposervers = reposervers.concat(instance.reposervers)
  2587. if(instance.reposerver) reposervers.push(instance.reposerver)
  2588. instances.push(instance)
  2589. instanceTypes.push(instance.node_env)
  2590. instnaceNames.push(instance.instanceName)
  2591. })
  2592. })
  2593. instances = instances.concat(detectedinstanceoptions)
  2594. if(selectedinstance['instanceName']) instnaceNames.push(selectedinstance['instanceName'])
  2595. if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName'])
  2596. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  2597. var choices = {
  2598. 'instanceName' : Array.from( new Set(instnaceNames) )
  2599. , 'reposerver' : Array.from( new Set(reposervers) )
  2600. , 'instanceType' : Array.from( new Set(instanceTypes) )
  2601. }
  2602. return choices;
  2603. }
  2604. return detectinstances().then((detectedinstanceoptions)=>{
  2605. detectedinstanceoptions.splice(0,0, __default)
  2606. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  2607. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2) )
  2608. // promptkeys = utils.assign(promptkeys, clioverrides)
  2609. console.dir(selectedinstance)
  2610. try {
  2611. chessinstances = acquirelocalinstances(selectedinstance);
  2612. findlocalinstances(chessinstances, detectedinstanceoptions)
  2613. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  2614. var choices = getchoices(detectedinstanceoptions, promptkeys)
  2615. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2616. return initinstances(selectedinstance)
  2617. })
  2618. }
  2619. catch (e) {
  2620. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  2621. var choices = getchoices(detectedinstanceoptions, promptkeys)
  2622. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2623. return initinstances(selectedinstance)
  2624. })
  2625. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2626. // // Weve not been told what to do.
  2627. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  2628. // }
  2629. todo = todo.then(() => {
  2630. try {
  2631. chessinstances = acquirelocalinstances(selectedinstance)
  2632. findlocalinstances(chessinstances, detectedinstanceoptions)
  2633. detectedinstanceoptions.splice(0,0, __default)
  2634. initinstances(selectedinstance)
  2635. }
  2636. catch (e) {
  2637. console.error(e)
  2638. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2639. console.log('A config will be createed with the instance and environment chosen...')
  2640. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2641. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2642. // return selectedinstance = Object.assign(__default, selectedinstance);
  2643. // })
  2644. return selectedinstance
  2645. }
  2646. })
  2647. }
  2648. return todo
  2649. })
  2650. .then(()=>{
  2651. if(!__isElevated) {
  2652. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  2653. // collect garbage
  2654. return dirs( (dir)=>{
  2655. var matches = /run-(.*)/gm.exec(dir.name)
  2656. if(matches) {
  2657. if(+(matches[1]) < min) {
  2658. min = matches[1]
  2659. collect.splice( 0, 0, matches[1] )
  2660. }
  2661. else collect.push(matches[1])
  2662. }
  2663. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  2664. // delete garbage
  2665. if(collect.length > retaincount) {
  2666. var asyncs = [];
  2667. while((collect.length - asyncs.length) > retaincount) {
  2668. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  2669. }
  2670. return Promise.all(asyncs)
  2671. }
  2672. else return true
  2673. })
  2674. }
  2675. else return true;
  2676. })
  2677. .then(()=>{
  2678. // PB : TODO -- Keep only the last n runs...
  2679. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  2680. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  2681. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  2682. mainTasks.push(maintask)
  2683. return any(mainTasks);
  2684. })
  2685. })
  2686. // detect if alread installed -> Take no action.
  2687. // download if no installer avalable -> next()
  2688. // install
  2689. function chackandinstall(items) {
  2690. var tasks = []
  2691. items.forEach(item => {
  2692. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  2693. })
  2694. return Promise.all(tasks).then(existances => {
  2695. existances.forEach((exists, i) => {
  2696. if (!exists) {
  2697. return downloadandinstall([items[i]])
  2698. }
  2699. })
  2700. })
  2701. }
  2702. function downloadandinstall(items) {
  2703. var tasks = []
  2704. items.forEach(item => {
  2705. tasks.push(getTaskDownload(item))
  2706. })
  2707. return Promise.all(tasks)
  2708. }
  2709. // Sample instances config.
  2710. // var instances = {
  2711. // "elixir": {
  2712. // "production": {
  2713. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  2714. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  2715. // , "exludeMergeRepos": {
  2716. // "elixir-config-development": true, "elixir-config-test": true
  2717. // , "elixir-config-production": true, "elixir-data": true
  2718. // }
  2719. // , "instanceName": "elixir", "node_env": "production"
  2720. // }
  2721. // },
  2722. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  2723. // }
  2724. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...