You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 241KB

2 jaren geleden
2 jaren geleden
2 jaren geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
3 jaren geleden
4 jaren geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
2 jaren geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
3 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
6 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
3 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
2 jaren geleden
1 jaar geleden
1 jaar geleden
3 jaren geleden
2 jaren geleden
3 jaren geleden
2 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500
  1. 
  2. // {{!-- https://corporatefinanceinstitute.com/resources/knowledge/accounting/general-ledger-gl/ --}}
  3. "use strict";
  4. // console.log([ 'If this is colorized we have color output...' ])
  5. // console.dir(process.env)
  6. var __g = require('global-this');
  7. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  8. __g.env = ENV
  9. ENV.NODE_ENV = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  10. const fs = require('fs')
  11. var path = require('path');
  12. var utils = require('bbhverse');
  13. var any = utils.any;
  14. var Tasq = utils.Tasq
  15. var statuslog = utils.Traq
  16. var Traq = utils.Traq
  17. // console.error('EEEEEEEEEEEEEEEEEEEE')
  18. var util = require('util')
  19. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  20. const cliargs = utils.cliargs;
  21. const processedArgs = cliargs(process.argv.slice(2));
  22. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  23. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  24. const runtimestamp = processedArgs.runtimestamp ? (new Date(processedArgs.runtimestamp)).getTime() : (new Date()).getTime();
  25. function getVersion() { return BUILD_VERSION; }
  26. // 'use strict';
  27. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  28. // PB : TODO --
  29. // runas bypass non elevated tasks when we request privelege
  30. // runas message is always error needs to be fixed.
  31. // runas wait needs to be parallelized.
  32. // suppress elevation check error messages
  33. // support runas lauched directly from shell.
  34. // pass in environment in hta to shellexecute.
  35. const https = require('https')
  36. const http = require('http');
  37. const { Console } = require('console');
  38. const { env } = require('process');
  39. const PATTERNAPI = require('serververse').PATTERNAPI
  40. // const RESTAPI = require('serververse').RESTAPI
  41. const RESTAPI = (function(){
  42. // Singleton
  43. function RESTAPI(){}
  44. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  45. // const httpsoptions = {
  46. // hostname: 'whatever.com',
  47. // port: 443,
  48. // path: '/todos',
  49. // method: 'POST',
  50. // headers: {
  51. // 'Content-Type': 'application/json',
  52. // 'Content-Length': data.length
  53. // }
  54. // }
  55. RESTAPI.method = function(options, resolve, reject){
  56. options.headers = options.headers || { 'Content-Type': 'application/json' }
  57. const data = options.payload ? new TextEncoder().encode( JSON.stringify(options.payload) ) : null
  58. options.headers = options.payload ? (options.headers || {
  59. 'Content-Type': 'application/json',
  60. 'Content-Length': data.length
  61. }) : (options.headers || {})
  62. !options.headers.Authorization && usertokens[options.username] ? (()=>{
  63. options.headers.Authorization = `token ${usertokens[options.username]}`
  64. delete options.username
  65. onauthenticated()
  66. })() : (()=>{
  67. if(!usertokens[options.username] && !options.isAuthCall) {
  68. RESTAPI.authenticate( utils.assign( {isAuthCall : true}, options ) , onauthenticated, function(err){
  69. // PB : TODO -- Retry without auth...
  70. console.error('Auth failed or not accessible')
  71. reject(err)
  72. })
  73. }
  74. else onauthenticated()
  75. })()
  76. function onauthenticated(){
  77. var acquirer = getHTTPorS(options)
  78. const req = acquirer.request(options, res => {
  79. if (res.statusCode < 200 || res.statusCode >= 300) {
  80. // new Error('statusCode=' + res.statusCode)
  81. return reject('statusCode = ' + res.statusCode);
  82. }
  83. var body = [];
  84. // res.setEncoding('utf8');
  85. res.on('data', (chunk)=>{ body.push(chunk); });
  86. res.on('end', ()=>{
  87. try {
  88. if(res.headers['content-type'] && res.headers['content-type'].split(';').find( (i)=> i.trim() === 'application/json' )) body = JSON.parse(Buffer.concat(body).toString());
  89. else body = Buffer.concat(body).toString();
  90. } catch(e) { return reject(e); }
  91. resolve(body);
  92. });
  93. });
  94. req.on('error', error => { reject(error) })
  95. if(options.payload) req.write(data)
  96. req.end()
  97. }
  98. }
  99. var usertokens = {}
  100. RESTAPI.authenticate = function(options, resolve, reject){
  101. options.headers = options.headers || { 'Content-Type': 'application/json' }
  102. if(!usertokens[options.username]) {
  103. // Authenticate and acquire token.
  104. // https://git.bbh/api/v1/users/<username>/tokens
  105. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  106. var _options = Object.assign({}, options)
  107. // _options.username = 'demo'
  108. // _options.password = 'demo123'
  109. _options.method = 'POST'
  110. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  111. _options.path = `/api/v1/users/${_options.username}/tokens`
  112. var postoptions = { name : _options.username }
  113. delete _options.username
  114. delete _options.password
  115. _options.payload = postoptions
  116. RESTAPI.post( _options, function(tokenresp){
  117. // tokenresp = JSON.parse(tokenresp)
  118. usertokens[options.username] = tokenresp.sha1
  119. resolve(tokenresp)
  120. },
  121. function(err){ reject(err) }
  122. )
  123. }
  124. else resolve(tokenresp.sha1)
  125. }
  126. RESTAPI.put = RESTAPI.get = RESTAPI.post = RESTAPI.method
  127. return RESTAPI
  128. })();
  129. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  130. const GITEA = (function(){
  131. function GITEA(){}
  132. GITEA.APIROOT = '/api/v1'
  133. GITEA.repository = {
  134. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  135. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  136. // giteaoptions = {
  137. // organization string
  138. // --- organization name, if forking into an organization
  139. // }
  140. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  141. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  142. httpoptions.method = 'POST'
  143. httpoptions.payload = giteaoptions;
  144. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  145. }
  146. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  147. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  148. httpoptions.method = 'PATCH'
  149. httpoptions.payload = giteaoptions;
  150. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  151. }
  152. , exists( httpoptions, repo, owner ) {
  153. // ​/users​/{username} // Get a user
  154. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repo}`
  155. httpoptions.method = 'GET'
  156. return new Promise( (resolve, reject) => {
  157. RESTAPI.get(httpoptions, function(o){
  158. if(o.id) return resolve(true)
  159. return resolve(false) }, reject || function(){ return false } )
  160. })
  161. }
  162. , addcollaborator( httpoptions, repodef, owner, collaborator, permission ) {
  163. permission = permission || 'Read'
  164. httpoptions.payload = { permission }
  165. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repodef.repo}/collaborators/${collaborator}`
  166. httpoptions.method = 'PUT'
  167. return new Promise( (resolve, reject) => {
  168. RESTAPI.put(httpoptions, function(o){
  169. //
  170. if(o === "") return resolve(true)
  171. return resolve(false) }, reject || function(){ return false } )
  172. })
  173. }
  174. }
  175. GITEA.user = {
  176. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  177. // ​/users​/{username} // Get a user
  178. httpoptions.path = `${GITEA.APIROOT}/users/${httpoptions.username}`
  179. httpoptions.method = 'GET'
  180. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  181. }
  182. }
  183. return GITEA
  184. })();
  185. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  186. const GIT = (function(){
  187. function GIT(){}
  188. Object.assign(GIT, {
  189. 'switch user'(username){
  190. var httpoptions = new URL(selectedinstance.reposerver);
  191. httpoptions.username = selectedinstance.username
  192. httpoptions.password = selectedinstance.password
  193. return GITEA.user.getuser(httpoptions).then(()=>{
  194. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  195. {
  196. inherit: true, shell: true,
  197. env: ENV
  198. , cwd: instanceroot + '/' + repo
  199. , runas: processedArgs.runas
  200. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  201. })
  202. }
  203. )
  204. .catch(e => {
  205. console.error(e + 'Could not switch. Probably no such user.')
  206. })
  207. }
  208. })
  209. return GIT
  210. })();
  211. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  212. (function () {
  213. "use strict";
  214. if (!Array.prototype.earlyreduce) {
  215. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  216. var iterable = this;
  217. var donecallback = donecallback || (a=>a)
  218. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  219. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  220. // function *earlyReduceGenerator(acc, v, i, a) {
  221. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  222. var element = iterable[i]
  223. result = eachcallback(result, element, i, iterable)
  224. if(result.done) return donecallback(result)
  225. }
  226. // }
  227. return donecallback(result)
  228. }
  229. }
  230. }());
  231. function isWin(){ return /^win/.test(process.platform) }
  232. if(isWin()) {
  233. var win_verse = require('./win_verse')
  234. var shell_verse = win_verse;
  235. shell_verse.getVersion = getVersion
  236. }
  237. else {
  238. var lin_verse = require('./lin_verse')
  239. var shell_verse = lin_verse;
  240. }
  241. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  242. // -- Currently workaround in windows is to always run from a non-elevated shell.
  243. shell_verse.acquireElevationState().then((isElevated) => {
  244. // PB : TODO -- Implement queues using streams. Specially form bundling all elevated tasks as a single out of proc run with post elevated queue run postponed until the elevated stream and its dependencies are completed....
  245. const { existsSync } = require('fs');
  246. const existslink = function(name, cb){
  247. fs.lstat(name, (error, stats) => {
  248. if (error) {
  249. console.log(error);
  250. cb(error)
  251. }
  252. else {
  253. console.log("Stats object for: example_directory.txt");
  254. console.log(stats);
  255. // Using methods of the Stats object
  256. console.log("Path is file:", stats.isFile());
  257. console.log("Path is directory:", stats.isDirectory());
  258. cb(null, true)
  259. }
  260. });
  261. }
  262. const existsFolderSync = existsSync;
  263. var hasElxr = function(path, options, cb) {
  264. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  265. options = options || {};
  266. var tasks = [
  267. '/elxr' // Is there a subfolder named elxr
  268. , '/elxr/.git' // which is also a git repository
  269. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  270. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  271. ]
  272. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  273. var value = existsFolderSync(path + tpath);
  274. return { value, done : acc && !value };
  275. }).value }
  276. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  277. var value = existsFolderSync(path + tpath);
  278. return { value, done : acc && !value };
  279. }).value );
  280. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  281. var value = existsFolderSync(path + tpath);
  282. return { value, done : acc && !value };
  283. }).value);
  284. }
  285. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  286. var uselauncdirasdefaultroot = false;
  287. if( ENV.NODE_ENV === 'production') uselauncdirasdefaultroot = true;
  288. // PB : TODO -- enable for for production.
  289. 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
  290. var root = undefined // process.cwd() // Root need not be the launchdir...
  291. // we typicall assume the cwd to be the root. However this should default to
  292. // elxr parent if the root is not recongnizable as an instance root....
  293. // wd is our own environment variable probably corresponding to the root but need not be the same.
  294. // console.log(processedArgs.root)
  295. // console.log('PWD :' + ENV.PWD)
  296. // console.log('cwd : ' + process.cwd())
  297. // console.log('launchscriptdir : ' + path.normalize(__dirname))
  298. console.log('----------------------------------------------------------------')
  299. console.log('BEFORE DISCOVERY')
  300. console.log('version : ' + getVersion());
  301. console.log('process.env.wd : ' + process.env.wd)
  302. console.log('processedArgs.root : ' + processedArgs.root)
  303. console.log('----------------------------------------------------------------')
  304. console.log('wd :' + ENV.wd)
  305. console.log('PWD :' + ENV.PWD)
  306. console.log('cwd : ' + process.cwd())
  307. console.log(`thisscriptdir = ${thisscriptdir}`)
  308. console.log(`root = ${root}`)
  309. console.log(`instanceroot = ${instanceroot}`)
  310. console.log('----------------------------------------------------------------')
  311. if(!processedArgs.root){ // There is no runtime invoke time named args override.
  312. console.log('discovery')
  313. // Script may exists in the same location where we were launched(PWD) but that doesn't mean we r running from elxr.
  314. // script could have been copied tosome random location and run from there.
  315. // check elxr is preinstalled in same location. If so we need to chdir to parent. Else promt for confirmation of root.
  316. var launchdir = /*process.env.PWD ||*/ process.cwd() // mingw + node --inspect-brk behaves differently has a PWD that windows commands cannot recognize /d instead of D:\ and process.chdir fails..
  317. var parentdir = path.dirname( launchdir )
  318. var parentFolderHasElxr = hasElxrSync(parentdir)
  319. var launchFolderHasElxr = hasElxrSync(launchdir)
  320. if( path.normalize(launchdir + '/elxr') === thisscriptdir ) {
  321. // launchFolderHasElxr is false -- and yet thiscriptdir is still proper.
  322. if(!launchFolderHasElxr) {
  323. console.warn('Warning : detected thisscriptdir as subfolder but did not recognize launchdir as a proper root. elxr may not autoupdate...')
  324. // hasElxr checks for git repo status and elxr id stamping etc.
  325. // exlr tool may have been acquired unconventionally and we may not be able to manage it.
  326. // We will run anyway though
  327. }
  328. root = ENV.wd = launchdir;
  329. }
  330. else if( path.normalize(parentdir + '/elxr') === thisscriptdir ) {
  331. if(!parentFolderHasElxr) {
  332. console.warn('Warning : detected thisscriptdir as subfolder but did not recognize parentdir as a proper root. elxr may not autoupdate...')
  333. }
  334. // PB : TODO -- Cleanup this should no longer be needed... selectedinstance is properly initialized...
  335. root = ENV.wd = parentdir; // Default to the parent.
  336. }
  337. else {
  338. if (launchdir === thisscriptdir) {
  339. // Same directory doesn't mean we are being run from elxr sub directory. It could be a dislocated standalone elxr script.
  340. // PB : TODO -- In case elxr is not full elxr we need to locate it and relaunch to switch to the full version...
  341. // if(!parentFolderHasElxr) console.error('Invalid run location in subfolder that looks like elxr. We should probably abort.')
  342. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  343. // Confirmed we were run from an Unbuilt ( meaning non standalone ) elxr therefore we are in the elxr sub directory.
  344. root = ENV.wd = parentdir; // Default to the parent.
  345. // instanceroot = root = path.normalize(selectedinstance.root + '/..');
  346. // instanceoptions.splice( 0, 0, detected = { root });
  347. // instanceoptions.splice( 0, 0, detectfromroot(root));
  348. }
  349. else if(!parentFolderHasElxr) {
  350. // Either case we use the launchdir.
  351. // if(launchFolderHasElxr) {
  352. // // Probably a standalone run. Lets just go with it
  353. // root = ENV.wd = launchdir;
  354. // }
  355. // In standalone build script we may or not be in the same location.
  356. // We could have been run from the elxr subfolder. However we cant say for sure.
  357. // Most likely that the built version isn't the full elxr. We assume elxr doesnt exist and create an new elxr under..
  358. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  359. root = ENV.wd = launchdir;
  360. }
  361. else {
  362. // Built version was run from the full elxr subfolder
  363. root = ENV.wd = parentdir; // Default to the parent.
  364. // instanceoptions.splice( 0, 0, detected = { root })
  365. // instanceoptions.splice( 0, 0, detectfromroot(root))
  366. // Assume current selectedinstance.root is a new instance and create.
  367. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  368. // if(clioverrides.instanceName) {
  369. // if(clioverrides.node_env) {
  370. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  371. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  372. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  373. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  374. // // eg : floder name can be elixir01 but instance name is elixr
  375. // }
  376. // else {
  377. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + 'development')
  378. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  379. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  380. // }
  381. // }
  382. // else {
  383. // instanceroot = root = selectedinstance.root;
  384. // if(clioverrides.node_env) {
  385. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  386. // instanceoptions.splice( 0, 0, detectfromroot(root))
  387. // }
  388. // else {
  389. // // Nothing was specified... We only have one option from root.
  390. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  391. // }
  392. // }
  393. }
  394. }
  395. else if(launchFolderHasElxr) {
  396. root = ENV.wd = launchdir;
  397. // instanceoptions.splice( 0, 0, detected = { root })
  398. // instanceoptions.splice( 0, 0, detectfromroot(root))
  399. }
  400. else {
  401. // Ambiguous but assume script is standalone in the instanceroot
  402. // Lets defualt to the script parent assuming there is an instanceroot there. Hoever this should probably be a prompt where possible.
  403. // when we r in that mode.
  404. if(uselauncdirasdefaultroot) {
  405. // must be a new install in the selectedinstance.root with script invoked from some random location.
  406. if(!process.env.wd){
  407. // Working directory as a .env variable was not passed in.
  408. root = ENV.wd = launchdir;
  409. }
  410. else root = ENV.wd = process.env.wd
  411. }
  412. else {
  413. var scriptparent = path.dirname( thisscriptdir )
  414. root = ENV.wd = scriptparent;
  415. }
  416. }
  417. }
  418. }
  419. else {
  420. if(process.env.wd && process.env.wd !== processedArgs.root) throw 'wd and root must match.'
  421. root = ENV.wd = process.env.wd = processedArgs.root
  422. }
  423. var instanceroot = root
  424. ENV.PWD = ENV.wd
  425. ENV.NODE_ENV = processedArgs.node_env || (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  426. console.log('----------------------------------------------------------------')
  427. console.log('AFTER DISCOVERY')
  428. console.log('version : ' + getVersion());
  429. console.log('process.env.wd : ' + process.env.wd)
  430. console.log('processedArgs.root : ' + processedArgs.root)
  431. console.log('----------------------------------------------------------------')
  432. console.log('wd :' + ENV.wd)
  433. process.chdir(ENV.wd) // Ensure cwd is the actual working dir.
  434. console.log('PWD :' + ENV.PWD)
  435. console.log('cwd : ' + process.cwd())
  436. console.log(`thisscriptdir = ${thisscriptdir}`)
  437. console.log(`root = ${root}`)
  438. console.log(`instanceroot = ${instanceroot}`)
  439. console.log('----------------------------------------------------------------')
  440. var cli = require('./cliverse')
  441. // throw 'initbreak'
  442. // We no longer use this Folder name may be different from instanceName
  443. // var detectfromroot = function(root){
  444. // return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  445. // }
  446. // independent elxr cli operations
  447. var noprerequisites = {
  448. add : true, 'set-url' : true, 'repo-relocate' : true
  449. , remote : true, 'c' : true, 'h' : true
  450. , httpget : true, getuser : true
  451. , 'switch user' : true
  452. , 'switch' : true
  453. // , 'undefined' : true
  454. }
  455. var __default = {
  456. // Common baseline repos for all chess chessinstances.
  457. repos : [
  458. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  459. , { repo : 'bbhverse' }
  460. , { repo : 'clientverse' }
  461. , { repo : 'serververse' }
  462. , { repo : 'elxr' }
  463. , { repo : 'ember-searchable-select' }
  464. , { repo : 'loopback-component-jsonapi' }
  465. , { repo : 'loopback-jsonapi-model-serializer' }
  466. , { repo : 'loopback-connector-mysql' }
  467. , { repo : 'loopback-connector-ds' }
  468. , { repo : 'ember-service-worker' }
  469. , { repo : 'ember-service-worker-asset-cache' }
  470. , { repo : 'ember-service-worker-cache-fallback' }
  471. , { repo : 'ember-service-worker-index' }
  472. , { repo : 'ember-sw-client-route' }
  473. , { repo : 'global-this' }
  474. ]
  475. // Requires elevation only in windows
  476. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  477. , exludeMergeRepos : { }
  478. }; // PB : TODO -- Use initialized instance instead of __default everywhere.
  479. var regexreplaceall = function(content, ps){
  480. var repmatches
  481. var replaced = content;
  482. while (repmatches = ps.strOrregexp.exec(content)) {
  483. if(content.length > 0) {
  484. var replacement = repmatches[0]
  485. for(var m = 1; m < repmatches.length; m++) {
  486. replacement = replacement.replace(repmatches[m], ps.substitutes[m-1])
  487. }
  488. replaced = replaced.replace( repmatches[0], replacement )
  489. }
  490. }
  491. return replaced
  492. }
  493. var cmds = {
  494. sqlpreprocess : {
  495. noprerequisites : true
  496. , cmdFn : function(args){
  497. var sqlquery = fs.readFileSync(args._[1], { encoding: 'utf8'})
  498. sqlquery = PATTERNAPI.includesql(sqlquery, path.dirname(args._[1]))
  499. fs.writeFileSync(args._[1] + '.d.sql', sqlquery, { encoding: 'utf8'})
  500. return sqlquery
  501. // // PB : TODO -- move to dsql preprocesor
  502. // // var sqlquery = 'SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(args._[1])).replace(/\'/g,"''") + "'"
  503. // var sqlquery = fs.readFileSync(args._[1], { encoding: 'utf8'})
  504. // var regExp = /\-\-\s{{INCLUDE(.*?) ([\s\S]*?)}}\s\-\-/gm;
  505. // var options = {}
  506. // sqlquery = replacepatterns(sqlquery, regExp, (matches, sqlquery)=>{
  507. // if (matches[1] === 'ASDSQL') options.dsql = true
  508. // var replacement = {
  509. // distinctpatterntoreplace : new RegExp("\\-\\-\\s{{INCLUDE\\s" + matches[2] + "}}\\s\\-\\-","gm")
  510. // , detectedvaluepattern : matches[2]
  511. // // escaped dsql... //'SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(args._[1])).replace(/\'/g,"''") + "'"
  512. // }
  513. // if(options.dsql) replacement.substituedvalue = ('SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(path.dirname(args._[1]) + '/' + matches[2])).replace(/\'/g,"''") + "'")
  514. // else replacement.substituedvalue = fs.readFileSync(path.dirname(args._[1]) + '/' + matches[2])
  515. // sqlquery = sqlquery.replace(replacement.distinctpatterntoreplace, replacement.substituedvalue);
  516. // regExp.lastIndex = 0;
  517. // })
  518. // // console.log(replaced)
  519. // fs.writeFileSync(args._[1] + '.d.sql', sqlquery, { encoding: 'utf8'})
  520. }
  521. , toArgs : function( o ){ return o }
  522. , interpret() { return { cmd : processedArgs._.slice(0, 1) } }
  523. }
  524. , remote : {
  525. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  526. , { cmd : processedArgs._.slice(0, 2).join(' '), runchoice : 'c' }) }
  527. , noprerequisites : true
  528. , independentcmd : true
  529. }
  530. , start : {
  531. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  532. , { cmd : 'start', runchoice : 'c'
  533. , node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV
  534. })}
  535. , toArgs : function( o ){
  536. return o
  537. }
  538. }
  539. , 'remote refresh' : {
  540. // return a interpreted set of arguments for this cmd run context.
  541. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  542. , { cmd : 'remote refresh', runchoice : 'c' }) }
  543. , noprerequisites : true
  544. , independentcmd : true
  545. // , requires : [ generateDependencies ]
  546. , toArgs : function( o ){
  547. return o
  548. }
  549. }
  550. , 'remote set-url' : {
  551. // return a interpreted set of arguments for this cmd run context.
  552. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  553. , { cmd : 'remote set-url', runchoice : 'c' }) }
  554. , noprerequisites : true
  555. , independentcmd : true
  556. // , requires : [ generateDependencies ]
  557. }
  558. , 'remote add' : {
  559. // return a interpreted set of arguments for this cmd run context.
  560. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  561. , { cmd : 'remote add', runchoice : 'c' }) }
  562. , noprerequisites : true
  563. , independentcmd : true
  564. // , requires : [ generateDependencies ]
  565. }
  566. , 'remote remove' : {
  567. // return a interpreted set of arguments for this cmd run context.
  568. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  569. , { cmd : 'remote remove', runchoice : 'c' }) }
  570. , noprerequisites : true
  571. , independentcmd : true
  572. }
  573. , 'addcollaborator' : {
  574. // Usage :
  575. // elxr addcollaborator instancename developer
  576. cmdFn : function(args){
  577. var __each = function(args){
  578. var collaborator = args.collaborator;
  579. if(!collaborator) {console.error('Error : collaborator required'); throw 'Error : collaborator required' }
  580. var repo = args.repo
  581. var remotename = 'chess'
  582. var repodef = selectedinstance.reposindexed[repo];
  583. if(!repodef) return
  584. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  585. var remotes = selectedinstance.reposerverinstances[selectedinstance.reposerver].remotes
  586. // console.log('-----------------------------------------------------')
  587. // console.log(repo)
  588. // // console.dir(remotes)
  589. // console.log('-----------------------------------------------------')
  590. // PB : TODO -- pick up remote definitions per repository...
  591. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  592. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  593. , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  594. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  595. ))
  596. if( !reposmanfiest.error ) {
  597. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  598. var reporemotes = utils.assign(remotes, reposmanfiest.reposerverinstances[selectedinstance.reposerver].remotes)
  599. }
  600. else {
  601. var reporemotenames = remotenames
  602. var reporemotes = remotes
  603. }
  604. var remote = reporemotes[remotename]
  605. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  606. // selectedinstance.reposerverinstances[reposerver]
  607. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  608. var httpoptions = new URL(reposerver);
  609. httpoptions = {
  610. hostname: httpoptions.hostname
  611. , protocol : httpoptions.protocol
  612. }
  613. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  614. // PB : TODO -- handle credentials properly. cant mix and match passwords..
  615. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  616. // console.log(___args)
  617. // PB : TODO -- Check valid collaborator before adding...
  618. return GITEA.repository.addcollaborator(httpoptions, repodef, remote.owner, collaborator).then( v => {
  619. if(v === true) {
  620. console.log('-----------------------------------------------------')
  621. console.log('addcollaborator successful for ' + repo + ' ' + collaborator)
  622. console.log('-----------------------------------------------------')
  623. }
  624. } )
  625. }
  626. var promises = []
  627. var repos = Object.keys(selectedinstance.reposindexed)
  628. repos.forEach(repo => { promises.push(__each({ repo, collaborator : args._[2]})) }) // PB : TODO -- Move to toArgs.
  629. return Promise.all(promises).then(pr => { console.log('addcollaborator done') })
  630. }
  631. }
  632. , 'isurlaccessible' : {
  633. noprerequisites : true
  634. , independentcmd : true
  635. , toArgs : function( o ){
  636. return { url : o._[1] }
  637. }
  638. }
  639. , resetgitconfig : {
  640. // return a interpreted set of arguments for this comd run context.
  641. // cmdFn : resetgitconfig,
  642. interpret() { return { cmd : 'resetgitconfig' } }
  643. , noprerequisites : true
  644. , independentcmd : true
  645. }
  646. , reinit : {
  647. // return a interpreted set of arguments for this comd run context.
  648. // cmdFn : reinit
  649. // ,
  650. interpret() { return { cmd : 'reinit' } }
  651. , noprerequisites : true
  652. , independentcmd : true
  653. , requiresElevation : true
  654. // , requires : [ generateDependencies ]
  655. }
  656. , init : {
  657. // return a interpreted set of arguments for this comd run context.
  658. // cmdFn : init
  659. // ,
  660. interpret() { return { cmd : 'init' } }
  661. , noprerequisites : true
  662. , independentcmd : true
  663. , requiresElevation : true
  664. // , requires : [ generateDependencies ]
  665. }
  666. , switch : {
  667. interpret() {
  668. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  669. , reposerver : __default.reposerver // .?.?.?
  670. }
  671. }
  672. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  673. }
  674. , 'switch user' : {
  675. interpret() {
  676. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  677. }
  678. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  679. }
  680. // Flat linear structure. Every subcommand should have a top level 'label'
  681. , 'users' : {
  682. // default to the users list
  683. subcommands : { list : {} }
  684. , cmdFn : ()=>getCredentials() // default
  685. , cmd : 'users'
  686. , noprerequisites : true
  687. }
  688. , 'users list' : {
  689. cmdFn : ()=>getCredentials()
  690. , cmd : 'users list'
  691. , noprerequisites : true
  692. }
  693. , 'get-upstream' :{
  694. // cmdFn : op['get-upstream'] // default
  695. // ,
  696. cmd : 'get-upstream'
  697. , noprerequisites : true
  698. , independentcmd : true
  699. , interpret() { return { cmd : 'get-upstream' } }
  700. }
  701. , 'g' : {
  702. cmd : 'g'
  703. , noprerequisites : true
  704. }
  705. , 'link' : {
  706. 'cmd' : 'link'
  707. // , cmdFn : function( sourecpath, filename, dir ){
  708. // var afterTargetPath = (dir)=>{
  709. // console.dir(dir);
  710. // // var tasks = [
  711. // // () => {
  712. // // // Use junctions to avoid npm package issues
  713. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  714. // // inherit: true, shell: true
  715. // // , cwd : dir || instanceroot
  716. // // , env: ENV
  717. // // }).catch((e) => { console.error(e) })
  718. // // return p;
  719. // // }
  720. // // ];
  721. // }
  722. // // console.dir(ENV)
  723. // if(!dir) getCurrentFolder().then(afterTargetPath);
  724. // else afterTargetPath(dir)
  725. // }
  726. , cmdFn : function( cmdopts ){
  727. // sourecpathandfile should include name of file name
  728. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  729. // console.log(processedArgs)
  730. if(!targetfilename) return Promise.reject('error no file provided for linking')
  731. targetdir = cmdopts.targetdir || ENV.wd
  732. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  733. var tasks = [
  734. () => {
  735. // Use junctions to avoid npm package issues
  736. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  737. inherit: true, shell: true
  738. , cwd : targetdir
  739. , env: ENV
  740. }).catch((e) => { console.error(e) })
  741. return p;
  742. }
  743. ];
  744. var etask = ()=>{
  745. return any(tasks).then(() => {
  746. fs.writeFileSync('run.done', 'success')
  747. }).catch(() => {
  748. fs.writeFileSync('run.done', 'error')
  749. })
  750. }
  751. etask.statuslog = statuslog
  752. etask.selectedinstance = selectedinstance
  753. etask.processedArgs = processedArgs
  754. etask.runtimestamp = runtimestamp
  755. etask.ENV = ENV
  756. return shell_verse.runElevated(etask)
  757. }
  758. , noprerequisites : true
  759. , privileged : true
  760. }
  761. }
  762. function interpret() {
  763. var interpreted = this
  764. // Non custom command has universal positiona args.
  765. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  766. interpreted.runchoice = interpreted.cmd ? 'c' : null
  767. // interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  768. // return clioverrides
  769. // cmds[cmd] = {
  770. // interpret() {
  771. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  772. // }
  773. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  774. // instanceName : true, instanceType : true, reposerver : true } }
  775. // }
  776. // ... PB : TODO -- use cmd.toArgs
  777. // interpreted.cmd = this.cmd
  778. return interpreted
  779. }
  780. var interpretrun = function(){
  781. var cmd = processedArgs._[0];
  782. return cmds[cmd] && cmds[cmd].interpret ? cmds[cmd].interpret() : (function(){
  783. return cmds[cmd] = utils.assign(cmds[cmd] || {}, interpret.call({ cmd, toArgs : function( o ){
  784. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  785. return o } }))
  786. })()
  787. }
  788. var chessinstances = { current_run : {} };
  789. var clioverrides = interpretrun()
  790. clioverrides = utils.assign( { cmd : processedArgs._[0], node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV }
  791. , clioverrides, cmds[clioverrides.cmd].toArgs(processedArgs), { root : ENV.wd } )
  792. function acquirelocalinstances(selected){
  793. // utils.assign is used to cleanup duplicates... assuming it is probably not clean.
  794. // PB : TODO -- if require fails decipher instanceName from findlocalinstances using the root...
  795. try { var existinglocalinstances = require(path.normalize(selected.root + '/chessinstances.js'))}
  796. catch(e){
  797. console.warn( 'Local instances not found.' ) // This is not an error. A new fresh instance is probably being setup.
  798. var existinglocalinstances = { current_run : {}, error : true }
  799. }
  800. chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, existinglocalinstances);
  801. // console.dir(chessinstances)
  802. return chessinstances
  803. }
  804. function findlocalinstances(chessinstances, instanceoptions){
  805. // We can expect a .elxr at each level in folder and 2 levels up. higher up we will find a shared instance chessinstances.js
  806. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../../' /* instanceNames */].
  807. earlyreduce( ( reduced, p, i, a )=>{
  808. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  809. if(existsSync( localinstancesPath )) {
  810. try {
  811. acquirelocalinstances( { root : `${instanceroot}/${p}` } )
  812. if(chessinstances.error) {
  813. delete chessinstances.error; delete chessinstances.e
  814. return {}
  815. }
  816. return Object.keys(chessinstances).earlyreduce( ( reduced, instanceName) => {
  817. return Object.keys(chessinstances[instanceName]).earlyreduce( (reduced, instanceType) => {
  818. // Scan to find a matching instanceroot
  819. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  820. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  821. return {
  822. value : chessinstances[instanceName][instanceType]
  823. , done : true
  824. };
  825. }
  826. })
  827. })
  828. }
  829. catch(e){
  830. return { }
  831. }
  832. }
  833. else return { }
  834. }
  835. )
  836. }
  837. // PB : TODO -- Move this to utils assign... as an array merge option.
  838. var mergeObjByKey = function(arrOfObjs, keyName) {
  839. var keyedDistinct = {}
  840. var distinctArrOfObjs = []
  841. arrOfObjs.forEach( o => {
  842. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  843. })
  844. Object.keys(keyedDistinct).forEach(key => {
  845. distinctArrOfObjs.push( utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  846. , ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  847. })
  848. return distinctArrOfObjs;
  849. }
  850. var cacheWriteInstanceConfig = function(chessinstances, instanceroot, selectedinstance){
  851. if(selectedinstance) {
  852. var instanceName = selectedinstance.instanceName ;
  853. var node_env = selectedinstance.node_env;
  854. // PB : TODO -- handle current_run switch...
  855. // console.dir(chessinstances)
  856. // PB : TODO -- We should be able to do simply merge at a higher level using assign
  857. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
  858. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
  859. }
  860. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  861. }
  862. var loadmanifest = function( mpath, moverrides ){
  863. try {
  864. // PB : TODO -- pick up remote definitions per repository...
  865. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  866. , {}, require(path.normalize( mpath + '/repo-manifest'))( {utils}, null, moverrides ))
  867. }
  868. catch(e){
  869. // console.warn(e);
  870. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }, { error : true, e }, moverrides)
  871. }
  872. }
  873. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  874. if(clioverrides.reconfirm) {
  875. var reconfirm = getReconfirmAll()
  876. }
  877. else { var reconfirm = {}; }
  878. var shouldPrompt = function(k, possiblePrompts, target){
  879. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  880. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  881. || reconfirm[k])
  882. }
  883. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  884. return {
  885. get (){
  886. return any( promptable.dependencies || [] ).then(()=>{
  887. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  888. var asyncprop = Promise.resolve(propValue)
  889. if(promptable.interpret){
  890. asyncprop = promptable.interpret(propValue)
  891. }
  892. return asyncprop.then(
  893. ()=>{
  894. Object.defineProperty(this, propName, {
  895. value: propValue,
  896. writable: true,
  897. configurable : true,
  898. enumerable : true
  899. });
  900. return propValue
  901. }
  902. )
  903. })
  904. } )
  905. }
  906. // , set (propValue){
  907. // Object.defineProperty(this, propName, {
  908. // value: propValue,
  909. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  910. // configurable : true,
  911. // enumerable : true
  912. // })
  913. // return propValue;
  914. // }
  915. , configurable : true
  916. , enumerable : true
  917. }
  918. }
  919. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  920. return function(prompts, k, i, a){
  921. // Reducer for all prompts on targets.
  922. // No local instances config found. We use a default initialized instance available in selectedinstance
  923. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  924. // PB : TODO -- selectedinstance === __default check to prompt everything...
  925. if( shouldPrompt(k, possiblePrompts, target) ) {
  926. delete reconfirm[k];
  927. // console.log(k)
  928. // console.dir(possiblePrompts); //console.dir(target)
  929. prompts.push(async ()=>{
  930. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  931. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  932. // var asyncthis = Object.assign(this);
  933. // By default Latest altered state is provided which is an implicit reference directly.
  934. console.log('----------------------------------------------------')
  935. console.log(k)
  936. console.dir(choices[k])
  937. if(!promptables[k]) promptables[k] = {}
  938. promptables[k].choices = choices[k]
  939. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  940. return await target[k]
  941. })
  942. }
  943. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  944. return prompts
  945. }
  946. }
  947. // unbound. Bind before using.
  948. var unbound_interactionpoints = function(selectedinstance){
  949. var self = this;
  950. var _interactionpoints = {
  951. get runchoice() {
  952. return {
  953. label :
  954. `Choose an option :
  955. d) Install the default chess instance.
  956. => elxr i chess node_env=development --default
  957. n) Create your custom new instance interactively
  958. => elxr i {{instanceName}} node_env={{environment}}
  959. i) Choose an instance and environment to install
  960. => elxr i {{instanceName}} node_env={{environment}}
  961. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  962. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  963. h) Help
  964. q) Quit
  965. : `
  966. , choices : []
  967. , defaultchoice : 'c'
  968. , selectedchoice : self.target.runchoice
  969. , interpret : function(choice){
  970. var interpret_map = {
  971. d : function(){
  972. processedArgs._[0] = 'i'
  973. self.target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  974. self.target.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  975. self.target.reposerver = 'https://git.bbh.org.in' // PB : TODO -- Read from global defaults...
  976. }
  977. , n : function() { processedArgs._[0] = 'i' }
  978. , i : function() {
  979. processedArgs._[0] = 'i'
  980. // processedArgs._[1] = self.target.instanceName || processedArgs._[1] || 'chess';
  981. }
  982. , c : async function() {
  983. // self here will always be the self.target.
  984. Object.defineProperty(self, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  985. label : `Enter cmd :
  986. p) pull
  987. Default <= p
  988. : `
  989. , defaultchoice : 'pull'
  990. }
  991. ));
  992. var cmd = await self.target['cmd'];
  993. if (!cmd || cmd === 'p') { self.target['cmd'] = processedArgs._[0] = 'pull' }
  994. else self.target['cmd'] = processedArgs._[0] = cmd
  995. return cmd;
  996. }
  997. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  998. , q : function() { process.exit() }
  999. }
  1000. if(Promise.resolve(choice) === choice){
  1001. return choice.then( resolvedchoice => {
  1002. return (interpret_map[choice] || interpret_map['c']).call(self.target)
  1003. })
  1004. }
  1005. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(self.target) )
  1006. // var __interpreter = interpret_map[choice] || interpret_map['c']
  1007. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  1008. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  1009. // return __interpreter.call(self.target)
  1010. }
  1011. }
  1012. }
  1013. , get instanceName() {
  1014. return { label : `Enter Instance Name ( <= ${self.target.instanceName || 'chess'} ) : `
  1015. , choices : self.choices['instanceName'], defaultchoice : 'chess'
  1016. , selectedchoice : self.target.instanceName
  1017. }
  1018. }
  1019. , get instanceType() {
  1020. return { label : `Enter Instance Type ( <= ${self.target.instanceType || 'development'} ) : `
  1021. , choices : self.choices['instanceType'], defaultchoice : 'development'
  1022. , selectedchoice : self.target.instanceType || 'development'
  1023. }
  1024. }
  1025. , get reposerver() {
  1026. return { label : `Enter Repo Server Base Url ( <= ${self.target.reposerver || 'https://git.bbh.org.in'} ) : `
  1027. , get choices() {
  1028. // self.choices['reposerver'].forEach( rs => {
  1029. // var __rs = new URL(rs);
  1030. // __rs.hostname = __rs.host;
  1031. // __rs.path = '/'
  1032. // __rs.method = 'GET'
  1033. // RESTAPI.get(__rs, function(data){ rs.accessibility = 'accessible' }
  1034. // , function(error){ rs.accessibility = 'unaccessible' } )
  1035. // })
  1036. return self.choices['reposerver']
  1037. }
  1038. , set choices(cs) {
  1039. return self.choices['reposerver'].concat([selectedinstance.reposerver]).concat(cs)
  1040. }
  1041. , defaultchoice : selectedinstance.reposerver || 'https://git.bbh.org.in'
  1042. , selectedchoice : self.target.reposerver
  1043. }
  1044. }
  1045. // , 'upstream-remote' : { label : `Enter Remote Name ( <= ${self.target['upstream-remote'] || 'chess'} ) : `
  1046. // , get choices() {
  1047. // var reposerver = self.target['reposerver']
  1048. // var remotes = []
  1049. // var trs = self.target.reposervers || []
  1050. // trs.forEach(rs => {
  1051. // if(rs.server === reposerver){
  1052. // remotes.push(remote)
  1053. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1054. // }
  1055. // })
  1056. // return remotes
  1057. // }
  1058. // , set choices(addlchoices){
  1059. // var reposerver = self.target['reposerver']
  1060. // var remotes = []
  1061. // var trs = self.target.reposervers || []
  1062. // trs.forEach(rs => {
  1063. // if(rs.server === reposerver){
  1064. // remotes.push(remote)
  1065. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1066. // }
  1067. // })
  1068. // return remotes.concat(addlchoices)
  1069. // }
  1070. // , defaultchoice : 'userfork'
  1071. // , selectedchoice : self.target['upstream-remote'] || 'userfork'
  1072. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1073. // }
  1074. // , 'remote-type' : { label : `Enter Remote Type ( <= ${self.target['remote-type'] || 'public'} ) : `
  1075. // , get choices() {
  1076. // return ['external', 'public', 'private', 'github', 'unc']
  1077. // }
  1078. // , set choices(addlchoices){
  1079. // var reposerver = self.target['reposerver']
  1080. // var remotes = []
  1081. // var trs = self.target.reposervers || []
  1082. // trs.forEach(rs => {
  1083. // if(rs.server === reposerver){
  1084. // remotes.push(remote)
  1085. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1086. // }
  1087. // })
  1088. // return ['external', 'public', 'private', 'github', 'unc'].concat(addlchoices)
  1089. // }
  1090. // , defaultchoice : 'public'
  1091. // , selectedchoice : self.target['remote-type'] || 'public'
  1092. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1093. // }
  1094. // , 'selectedremotes' : { label : `Chose Remote Names ( <= ${self.target['selectedremotes'] || 'chess'} ) : `
  1095. // , get choices() {
  1096. // var reposerver = self.target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  1097. // var remotenames = []
  1098. // Object.entries(self.target.remotes || []).forEach( ([rname, r]) => {
  1099. // if(r.server === reposerver && r.accessibility.find( self.target[ 'remote-type' ] )){
  1100. // remotes.push(rname)
  1101. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1102. // }
  1103. // })
  1104. // // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  1105. // // Currenty handles all combinations without any priority order.
  1106. // var _remotechoices = [] // Array of arrays of choices.
  1107. // remotenames.forEach( r => {
  1108. // var __rcs = []
  1109. // _remotechoices.forEach(rc => {
  1110. // __rcs.push( rc.concat(r) )
  1111. // })
  1112. // Array.prototype.push.apply( _remotechoices, __rcs)
  1113. // _remotechoices.push(r)
  1114. // })
  1115. // return _remotechoices
  1116. // }
  1117. // , defaultchoice : ['userfork', 'chess'] // userfork and chess should imlicitly point to userfork-external and chess-external when external connectivity is dtetected.
  1118. // , selectedchoice : self.target['selectedremotes'] || ['userfork-external', 'chess-external']
  1119. // // , defaultchoice : { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1120. // // , selectedchoice : self.target['selectedremotes'] || { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1121. // // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1122. // }
  1123. , get username() { return { label : `Enter User Id for ${self.target.reposerver} ( <= ${self.target.username || 'chess'} ) : `
  1124. , choices : self.choices['username'], defaultchoice : self.target.username || 'chess', selectedchoice : self.target.username } }
  1125. , get password() { return { label : `Enter Password for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.password || ''} ) : `
  1126. , choices : self.choices['password'], defaultchoice : '***', selectedchoice : self.target.password } }
  1127. , get email() { return { label : `Enter Email for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.email || ''} ) : `
  1128. , choices : self.choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : self.target.email } }
  1129. }
  1130. return _interactionpoints
  1131. }
  1132. var get_interactionpoints_template = function(){
  1133. return {
  1134. instanceName : { label : `Enter Instance Name ( <= ${this.target.instanceName || 'chess'} ) : `
  1135. , choices : this.choices['instanceName'], defaultchoice : 'chess'
  1136. , selectedchoice : this.target.instanceName
  1137. }
  1138. }
  1139. }
  1140. var pending = (function() {
  1141. // PB : TODO -- Override cli prefs and call with undefined selectedinstance only if there is no cli overide or selection.
  1142. acquirelocalinstances( { root : ENV.wd } )
  1143. function createLocalChessInstance( cfg ){
  1144. // return createInstance(cfg)
  1145. reconfirm = getReconfirmAll()
  1146. var inst = {};
  1147. var __new = Object.assign({}, __default, cfg)
  1148. inst[cfg.node_env] = __new; return inst;
  1149. }
  1150. if(chessinstances.error) {
  1151. delete chessinstances.error
  1152. // use installchoices only when we don't find chessinstances.
  1153. try { var installchoices = require(path.normalize(ENV.wd + '/installchoices.js'))
  1154. var instanceName = installchoices.instanceName;
  1155. var reposerver = installchoices.reposerver
  1156. var node_env = clioverrides.node_env || installchoices.node_env
  1157. var __instance = (chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  1158. instanceName, node_env, root, reposerver /* promptkeys['reposerver'] */ } ))[node_env];
  1159. chessinstances['current_run'] = { instanceName, node_env, reposerver, root }
  1160. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  1161. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  1162. // }
  1163. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  1164. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  1165. __instance.username = installchoices.username = installchoices.gitUser
  1166. __instance.email = installchoices.email = installchoices.gitEmail
  1167. }
  1168. catch(e){
  1169. console.warn(e)
  1170. console.warn( 'Install choices not found. WIll prompt for choices' ) // This is not an error. A new fresh instance is probably being setup.
  1171. throw 'PROMPT FOR INSTLL CHOICES TO BE IMPLEMENTED'
  1172. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  1173. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  1174. }
  1175. }
  1176. // PB : chessinstances.js update if we are switching repo servers, username etc... Myabe always refresh on each run.
  1177. // root location for instance swithc ?? should not be allowd...
  1178. var instanceName = clioverrides.instanceName || chessinstances.current_run.instanceName
  1179. var instance = {}
  1180. function oninstanceName(instanceName) {
  1181. var instance_ = chessinstances[instanceName]
  1182. if(instance_) {
  1183. instance = instance_[clioverrides.node_env || chessinstances.current_run.node_env] || utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  1184. }
  1185. else instance = utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  1186. // PB : TODO We should promt like instanceName create a new one instad of undefined ??
  1187. return instance
  1188. }
  1189. if(!instanceName) {
  1190. var interactionpoints = (function() { return { instanceName : get_interactionpoints_template.bind({target : {}, choices : {}})()['instanceName'] } })()
  1191. var eachPrompt = getBoundEachPrompt(instance, utils.assign({}, interactionpoints), interactionpoints, {})
  1192. var pendingtasks = any( Object.keys(interactionpoints).reduce(eachPrompt, []) ).then(()=>{
  1193. return oninstanceName(instance.instanceName)
  1194. })
  1195. }
  1196. else {
  1197. var pendingtasks = Promise.resolve(oninstanceName(instanceName))
  1198. }
  1199. return pendingtasks.then((instance)=>{
  1200. // PB : TODO -- Embed defaults in the build instead of inlining here...
  1201. // PB : TODO -- All these values instanceName, node_env, username, reposervers should come from instace overridden by a finalized cliovrrides...
  1202. // Also attepmt to load preconfig specially for new chessinstances from ../chess-config/...
  1203. var __repo_manifest_elxr = loadmanifest( instance.root + '/elxr'
  1204. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  1205. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  1206. )
  1207. if(__repo_manifest_elxr.error) console.log(__repo_manifest_elxr.e.message)
  1208. var instance_specific_config_manifest = loadmanifest( instance.root + `/${instance.instanceName}-config-${clioverrides.node_env}`
  1209. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  1210. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  1211. )
  1212. if(instance_specific_config_manifest.error) console.log(instance_specific_config_manifest.e.message)
  1213. delete __repo_manifest_elxr.error
  1214. delete __repo_manifest_elxr.e
  1215. // delete __repo_manifest_elxr.utils
  1216. delete instance_specific_config_manifest.error
  1217. delete instance_specific_config_manifest.e
  1218. // delete instance_specific_config_manifest.utils
  1219. // selectedinstance is not complete until we load in the following order of priority...
  1220. // 1) inline defaults
  1221. // 2) elxr defaults & manifest
  1222. // 3) ../chess-config/... defaults TODO
  1223. // 4) local cached lastrun or cli selected instance from chessinstances
  1224. // 5) instance specific manifest from {{instanceName}}-config-{{node_env}} ( can work with stale or on demand currently pulled updated version )
  1225. // 5.5) runconfig ??? lastrun vs fixed runconfig for repetitive stuff. TODO -- runconfig overrides lastrun...
  1226. // 6) cli overrides from command promnt
  1227. // 7) promted selections and reconfirms.
  1228. var __pvt = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1229. , __default, __repo_manifest_elxr, instance
  1230. , { root : ENV.wd, node_env : ENV.NODE_ENV
  1231. , get instanceName() {
  1232. // FInalize to prevent subsequent overrides...
  1233. return instance.instanceName
  1234. }
  1235. }
  1236. , instance_specific_config_manifest
  1237. , clioverrides
  1238. )
  1239. // console.dir(__pvt)
  1240. // Unmergable server overrides
  1241. Object.keys(instance_specific_config_manifest).forEach( key => {
  1242. __pvt[key] = instance_specific_config_manifest[key]
  1243. })
  1244. var __pub = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, __pvt
  1245. // Finalized immutables.
  1246. // We don't need pub to prevent immutability.
  1247. , { get root(){ return __pvt.root }
  1248. , get node_env(){ return __pvt.node_env }
  1249. , get instanceName() { return __pvt.instanceName }
  1250. , get reposindexed(){
  1251. // PB : TODO -- Implement -- One time gettor and then cached...
  1252. var indexed = {}
  1253. this.repos.forEach(r => { indexed[r.repo] = r })
  1254. this.elevated.forEach(r => { indexed[r.repo] = r })
  1255. Object.defineProperty(this, 'reposindexed', { value: indexed, writable: false });
  1256. return indexed;
  1257. }
  1258. , set root(val){
  1259. throw 'root changes not yet supported'
  1260. // if the root changes while we r invoked from somewhere else... we need to reload everything from that location...
  1261. if(__pvt.root === val){
  1262. return __pvt.root = val
  1263. }
  1264. else __pvt.root
  1265. }
  1266. }
  1267. )
  1268. chessinstances[__pub.instanceName] = chessinstances[__pub.instanceName] || {}
  1269. chessinstances[__pub.instanceName][__pub.instanceType] = __pub
  1270. // PB : TODO initinstances is now obselete relocated here
  1271. // Upgrade old formats..
  1272. if(__pub?.repos && !__pub?.repos[0]?.repo) {
  1273. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1274. __pub.repos = __pub.repos.map(function(repo){ return { repo } })
  1275. }
  1276. if(__pub?.elevated && !__pub?.elevated[0]?.repo) {
  1277. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1278. __pub.elevated = __pub.elevated.map(function(repo){ return { repo } })
  1279. }
  1280. // Config from server always override merges into selection except for the current selection.
  1281. // PB : TODO -- utils.assign Array merges are non-distinct...
  1282. // chessinstances[instanceName][node_env] = selectedinstance;
  1283. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  1284. // PB : TODO -- We should probably write the new server config also...
  1285. // PB : TODO -- Attempt first one that is available and online...
  1286. // PB : TODO -- system select may need a reconfirm...
  1287. if(!__pub.reposerver) reconfirm['reposerver'] = true
  1288. __pub.reposerver = __pub.reposerver || __pub.reposervers[0]
  1289. cacheWriteInstanceConfig(chessinstances, __pub.root, __pub )
  1290. Object.defineProperty(__g, 'selectedinstance', {
  1291. get(){ return __pub}
  1292. , set( inst ){
  1293. utils.assign(__pub, inst); return __pub
  1294. }
  1295. })
  1296. return __pub;
  1297. })
  1298. })()
  1299. return pending.then(( selectedinstance)=>{
  1300. // PB : TODO -- Maybe create a new instance so we can switch around for different values...
  1301. shell_verse.init({ statuslog, selectedinstance, processedArgs, runtimestamp, ENV })
  1302. var op = {
  1303. 'h': () => { console.log(elxr.help()); return '-h' }
  1304. , 'clean' : () => {
  1305. // delete all node_module folders and links.
  1306. var tasklist = [];
  1307. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  1308. return Promise.all(tasklist)
  1309. }
  1310. // , 'undefined': () => { return acquireChoices( {} ); }
  1311. , 'isurlaccessible' : function(args){
  1312. // args.url... .. PB : TODO -- Extract from url
  1313. args = args || {}
  1314. var u = new URL(args.url || selectedinstance.reposerver)
  1315. console.log(u)
  1316. var httpoptions = { hostname : u.host || 'git.bbh.org.in', protocol : u.protocol || 'https'
  1317. , method : 'GET'
  1318. , username : args.username || selectedinstance.username || 'chess'
  1319. , password : selectedinstance.password || 'chess'
  1320. }
  1321. httpoptions.path = args.path || `/`
  1322. return new Promise(function( resolve, reject ){
  1323. RESTAPI.get(httpoptions, function(){
  1324. console.log('URL is accessible')
  1325. resolve(true)
  1326. }, function(){
  1327. console.error('URL is not accessible')
  1328. resolve(false)
  1329. })
  1330. })
  1331. }
  1332. , 'reset': () => {
  1333. // Reset NPM packages semver so major versions can be updated.
  1334. const fs = require('fs')
  1335. const wipeDependencies = (__package) => {
  1336. const file = fs.readFileSync(__package + '/package.json')
  1337. const content = JSON.parse(file)
  1338. for (var devDep in content.devDependencies) {
  1339. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1340. content.devDependencies[devDep] = '*';
  1341. }
  1342. }
  1343. for (var dep in content.dependencies) {
  1344. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1345. content.dependencies[dep] = '*';
  1346. }
  1347. }
  1348. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  1349. }
  1350. var repos = ['client'];
  1351. // repos = gitRepos;
  1352. repos.forEach(wipeDependencies)
  1353. // if (require.main === module) {
  1354. // } else {
  1355. // module.exports = wipeDependencies
  1356. // }
  1357. }
  1358. , 'upgrade': () => {
  1359. console.log('upgrade.......')
  1360. var tasks = [
  1361. () => {
  1362. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  1363. inherit: true, shell: true
  1364. , env: ENV
  1365. }).catch((e) => { console.error(e) })
  1366. p.position = 1;
  1367. console.log('One')
  1368. return p;
  1369. }
  1370. , () => {
  1371. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  1372. inherit: true, shell: true
  1373. , env: ENV
  1374. }).catch((e) => { console.error(e) })
  1375. p.position = 2;
  1376. console.log('Two')
  1377. return p;
  1378. }
  1379. , () => {
  1380. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  1381. inherit: true, shell: true
  1382. , env: ENV
  1383. }).catch((e) => { console.error(e) })
  1384. p.position = 3;
  1385. console.log('Three')
  1386. return p;
  1387. }
  1388. , () => {
  1389. var p = nodeShellExec('n', ['latest'], {
  1390. inherit: true, shell: true
  1391. , env: ENV
  1392. }).catch((e) => { console.error(e) })
  1393. p.position = 4;
  1394. console.log('Four')
  1395. return p;
  1396. }
  1397. ]
  1398. any(tasks)
  1399. console.log('.......done')
  1400. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  1401. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  1402. console.info('Uninstalling existing ember globally');
  1403. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  1404. stdio: ['pipe', process.stdout, process.stderr],
  1405. inherit: true,
  1406. shell: true,
  1407. cwd: path.dirname(__dirname),
  1408. env: ENV
  1409. })
  1410. step1.on('close', () => {
  1411. console.info('Installing ember globally');
  1412. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  1413. stdio: ['pipe', process.stdout, process.stderr],
  1414. inherit: true,
  1415. shell: true,
  1416. cwd: path.dirname(__dirname),
  1417. env: ENV
  1418. })
  1419. step2.on('close', () => {
  1420. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  1421. stdio: ['pipe', process.stdout, process.stderr],
  1422. inherit: true,
  1423. shell: true,
  1424. cwd: path.dirname(__dirname),
  1425. env: ENV
  1426. })
  1427. })
  1428. })
  1429. }
  1430. , 'push': () => {
  1431. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  1432. // init remote bare from local
  1433. // pushandinitremotebare
  1434. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  1435. // connect to repo server -- net use 172.16.0.27
  1436. // cd 172.16.0.27/repos/
  1437. // mkdir repo.git
  1438. // cd repo.git
  1439. // git init --bare
  1440. // cd localrepo
  1441. // git remote rename origin githubclone
  1442. // git remote add origin //172.16.0.27/repos/repo.git
  1443. // git push origin master
  1444. var repo = processedArgs._[1];
  1445. var remote = 'origin'
  1446. var sequentialTaskShellCommands = [];
  1447. if (!existsSync(`Z:/${repo}.git`)) {
  1448. sequentialTaskShellCommands = [
  1449. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  1450. // inherit : true, shell: true
  1451. // , env: ENV
  1452. // }]
  1453. ['pwd', { cwd: 'Z:', inherit: true }]
  1454. , ['mkdir', [`${repo}.git`], {
  1455. cwd: `Z:`
  1456. , inherit: true, shell: true
  1457. , env: ENV
  1458. }]
  1459. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  1460. , ['git', ['init', '--bare'], {
  1461. cwd: `Z:/${repo}.git`
  1462. , inherit: true, shell: true
  1463. , env: ENV
  1464. }]
  1465. // PB : TODO -- Do this conditionally only...
  1466. , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  1467. console.log(`Ignoring ${remote} rename error : ` + err); return true; //return true to continue.
  1468. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  1469. , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  1470. // PB : TODO -- If threre is a gitbubclone origin
  1471. // Set the master to pull from the local repo.
  1472. ]
  1473. if (!existsSync(`Z:`)) {
  1474. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  1475. inherit: true, shell: true
  1476. , env: ENV
  1477. }])
  1478. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  1479. // throw 'done'
  1480. }
  1481. }
  1482. sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  1483. // console.dir(sequentialTaskShellCommands);
  1484. var tasks = [];
  1485. sequentialTaskShellCommands.forEach(shellcmd => {
  1486. // console.log(shellcmd)
  1487. tasks.push(() => {
  1488. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  1489. return p;
  1490. })
  1491. })
  1492. any(tasks);
  1493. }
  1494. , 'is-git-repo': (dir) => {
  1495. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  1496. }
  1497. // git remote equivalents...
  1498. // git branch --set-upstream-to=elixir-unc/master master
  1499. // git push --set-upstream elixir-unc branch..
  1500. , 'remote': (args) => {
  1501. // Subcommands!
  1502. // PB : TODO -- we can now pass in hypehnated args...
  1503. if(!processedArgs.v) return false; // Only -v is supported presently..
  1504. var serial_perform = (repo) => {
  1505. var options = { cwd: instanceroot + '/' + repo }
  1506. return [
  1507. ['git', ['remote', '-v'], options]
  1508. ]
  1509. }
  1510. var x = (args) => {
  1511. var tasq = () => {
  1512. // console.log(args)
  1513. return nodeShellExec.apply(null, args).catch(e => {
  1514. // We continue on failure.
  1515. console.error(tasq.toString())
  1516. })
  1517. }
  1518. tasq.toString = function(){
  1519. return JSON.stringify(args)
  1520. }
  1521. return tasq;
  1522. }
  1523. var perform = (dir) => {
  1524. return any(serial_perform(dir.name).map(x))
  1525. }
  1526. dirs(perform)
  1527. }
  1528. , 'remote set-url': (args) => {
  1529. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  1530. var __args = {
  1531. remotename : args.remotename || processedArgs._[2]
  1532. , url : args.url || processedArgs._[3]
  1533. , branch : args.branch || processedArgs._[4] || 'master'
  1534. }
  1535. __args.upstream = args['upstream'] || processedArgs._[5] || `${__args.remotename}/${__args.branch}`
  1536. // pushable doesn't mean the remote doesn't support being pushed to.
  1537. // 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.
  1538. // PB : TODO -- change this to enablepushing.
  1539. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  1540. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1541. var remotename = __args.remotename
  1542. var url = __args.url
  1543. var branch = __args.branch
  1544. var upstream = __args.upstream
  1545. console.log('remotename : ' + args.remotename)
  1546. var serial_perform_git_seturl = (reponame) => {
  1547. var options = { cwd: instanceroot + '/' + reponame }
  1548. // console.log(reponame)
  1549. var serialcmds = [
  1550. ['git', ['remote', 'set-url', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1551. ]
  1552. if (!pushable) {
  1553. serialcmds.push(['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }])
  1554. }
  1555. var requiresElevation = selectedinstance.elevated.find( r => r.repo === reponame)
  1556. serialcmds.push(['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame, requiresElevation }]) // requires elevation based on repo
  1557. serialcmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1558. return serialcmds
  1559. }
  1560. var x = (xargs) => {
  1561. var tasq = () => {
  1562. // console.log(args)
  1563. var task = (onsuccess, onerror)=>{
  1564. return ()=>{
  1565. return nodeShellExec.apply(null, xargs).then( onsuccess ).catch(e => {
  1566. // We continue on failure.
  1567. // No such remote
  1568. if(e.messages[0].search('No such remote') > -1 ){
  1569. console.log(remotename + ' Remote doesnt exist will add.')
  1570. return op['remote add']( args )
  1571. }
  1572. console.error(util.inspect(e) + ' ' + tasq.toString())
  1573. })
  1574. }
  1575. }
  1576. if(xargs[2].requiresElevation){
  1577. if(!isElevated) {
  1578. var etask = task( ()=>{ return remotename } )
  1579. etask.statuslog = statuslog
  1580. etask.selectedinstance = selectedinstance
  1581. etask.processedArgs = processedArgs
  1582. etask.runtimestamp = runtimestamp
  1583. etask.ENV = ENV
  1584. return shell_verse.runElevated(etask)
  1585. }
  1586. }
  1587. return task(
  1588. () => { fs.writeFileSync('run.done', 'success')}
  1589. , () => { fs.writeFileSync('run.done', 'error') }
  1590. )()
  1591. }
  1592. tasq.toString = function(){ return JSON.stringify(args) }
  1593. return tasq;
  1594. }
  1595. var perform_git_seturl = (dir) => {
  1596. return op['is-git-repo'](dir).then((logEntry) => {
  1597. return any(serial_perform_git_seturl(dir.name).map(x))
  1598. }).catch((e) => {
  1599. console.log(e + ' Failed not recognized as a git repo : ' + dir.name)
  1600. })
  1601. }
  1602. if(args.dir) return perform_git_seturl(args.dir) // do this for a specific repo
  1603. else return dirs(perform_git_seturl) // Do for all
  1604. }
  1605. // , 'reset' : ()=>{
  1606. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  1607. // // Reset the whole installation pertaining to this elxr folder.
  1608. // }
  1609. , 'remote exists': (args) => {
  1610. var __args = {
  1611. remotename : args.remotename|| processedArgs._[2]
  1612. , url : args.url || processedArgs._[3]
  1613. , branch : args.branch || processedArgs._[4]
  1614. }
  1615. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  1616. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  1617. var commands = [
  1618. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  1619. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  1620. [
  1621. // 'git', ['remote', '-v']
  1622. 'git', ['config', `remote.${__args.remotename}.url`]
  1623. , utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1624. , {
  1625. benign : args.benign, ignorefailures : args.ignorefailures,
  1626. evaluateResult : function(err, result){
  1627. return [
  1628. +result.code === 0
  1629. , result
  1630. ]
  1631. }
  1632. } , options) ]
  1633. ]
  1634. var mapped = commands.map(getshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  1635. mapped.push( function(prevserialtaskresult) {
  1636. var pt = [false , null]
  1637. if(prevserialtaskresult.error) {
  1638. // Previous task has failed.
  1639. pt[1] = prevserialtaskresult.error[1]
  1640. }
  1641. else pt = prevserialtaskresult;
  1642. console.dir(prevserialtaskresult)
  1643. return getshelltask(['git', ['ls-remote', `${__args.url}`], utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1644. , {
  1645. benign : args.benign, ignorefailures : args.ignorefailures,
  1646. evaluateResult : function(err, result){
  1647. if(+result.code !== 0) return [pt, [ false, result]]
  1648. // var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  1649. return [pt, [true, result] ]
  1650. }
  1651. } , options) ])().catch( e => {
  1652. console.error(e)
  1653. return [pt, [ false, null]]
  1654. })
  1655. })
  1656. return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
  1657. console.dir(allresolved)
  1658. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  1659. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  1660. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  1661. : console.log('was not added as a remote but url is currently accessible.')
  1662. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  1663. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  1664. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  1665. : [0, 1] // => was not added and remote and url is accessible.
  1666. }).catch(e => {
  1667. console.log(e)
  1668. return [0, 0]
  1669. })
  1670. }
  1671. , 'remote refresh' : (args) => {
  1672. var url = args._[2] || selectedinstance.reposerver
  1673. return op['isurlaccessible']({ url }).then(( baccess )=>{
  1674. if(!baccess) {
  1675. var reposerver = selectedinstance.reposerverinstances[url]
  1676. if(!reposerver.external) {
  1677. // Internal server not accessible ask to switch to external.
  1678. console.log('Internal server not accsssible. Will switch to external')
  1679. // console.dir(selectedinstance.reposerverinstances)
  1680. url = reposerver.externalreposervers[0]
  1681. }
  1682. else {
  1683. console.log('External server not accsssible. Will switch to interal')
  1684. // PB : TODO -- Prompt and then switch.
  1685. url = reposerver.internalreposervers[0]
  1686. }
  1687. return op['isurlaccessible']({ url }).then(( baccess )=>{
  1688. if(!baccess) {
  1689. console.log('Neither internal nor external servers are accessible.... Presenting choices...')
  1690. console.log('PB : TODO -- Present appropriate choices...')
  1691. // Redo whole command...
  1692. }
  1693. return dorefresh()
  1694. })
  1695. }
  1696. dorefresh()
  1697. console.log(baccess)
  1698. }).catch((err)=>{ console.error(err) })
  1699. function dorefresh(){
  1700. // if(args.url === selectedinstance.reposerver) {
  1701. // // No change. Just refresh with same url anyway. We do not know which of the repos is not up to date and is an outlier.
  1702. // }
  1703. // else {
  1704. // // Also refreshs anyway
  1705. // }
  1706. args = args || {}
  1707. var __args = {
  1708. url : args.url || processedArgs._[2] || selectedinstance.reposerver
  1709. // , branch : args.branch || processedArgs._[4]
  1710. }
  1711. var serial_perform = (repo) => {
  1712. // if(repo === 'setup' || repo === 'chess-server-lib'){
  1713. var options = { cwd: instanceroot + '/' + repo }
  1714. console.log('serial_perform : ' + repo)
  1715. return [
  1716. ['git', ['remote', '-v'], options]
  1717. ]
  1718. // }
  1719. // else return []
  1720. }
  1721. var x = (args) => {
  1722. // console.log('MapX was called')
  1723. var tasq = () => {
  1724. console.log('--------------------------')
  1725. console.log(args)
  1726. return nodeShellExec.apply(null, args).catch(e => {
  1727. console.log('caught error ------------------------' + JSON.stringify(e))
  1728. // We continue on failure.
  1729. console.error(tasq.toString() + args[2].cwd)
  1730. })
  1731. }
  1732. tasq.toString = function(){
  1733. // console.log('sadfasdf------------------------')
  1734. return JSON.stringify(args) // PB : TODO -- Is this needed ?
  1735. }
  1736. return tasq;
  1737. }
  1738. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  1739. var remotes = selectedinstance.reposerverinstances[__args.url].remotes
  1740. // use the repo manifest to create missing remotes.
  1741. function perform_remote_refresh(dir){
  1742. var repo = dir.name
  1743. var ___args = {url : __args.url, repo}
  1744. if(repo === '.elxr') return Promise.resolve(true)
  1745. if(repo === '.git') return Promise.resolve(true)
  1746. if(repo === 'Downloads') return Promise.resolve(true)
  1747. // PB : TODO -- pick up remote definitions per repository...
  1748. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  1749. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  1750. , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  1751. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  1752. ))
  1753. if( !reposmanfiest.error ) {
  1754. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  1755. var reporemotes = utils.assign([], remotes, reposmanfiest.reposerverinstances[___args.url].remotes)
  1756. }
  1757. else {
  1758. var reporemotenames = remotenames
  1759. var reporemotes = remotes
  1760. }
  1761. return (()=>{
  1762. var promises = []
  1763. return any(serial_perform(repo).map(x)).then(()=>{
  1764. var branch = args.branch || 'master' // PB : TODO -- Dont default branch here.. Let each repos current state define this... ???
  1765. reporemotenames.forEach(rm =>{
  1766. console.log('Processing : ' + rm + ' ' + dir.name)
  1767. // if(repo != 'elxr') return //test
  1768. // if(repo != 'elixir-config-development') return //test
  1769. // if(repo != 'elixir-server') return //test
  1770. promises.push( ((rm) => {
  1771. var remotename = rm
  1772. var repodef = selectedinstance.reposindexed[repo];
  1773. if(!repodef) return
  1774. // if( repo !== 'cihsr-data') return
  1775. // username and owner are two different things. The repository (possibly forked) under the username is when the {{owner}} portion of the repo path is the same as the user.
  1776. // When one user or organiztion shares repos with others through a team without a fork a different user has access to a different {{owner}} path repo.
  1777. var remote = reporemotes[remotename]
  1778. // console.log(repodef)
  1779. // console.log(remote)
  1780. var owner = repodef.owner || remote.owner || defaultRepoOwner // should be based on the server, remote and repo combination.
  1781. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  1782. // selectedinstance.reposerverinstances[reposerver]
  1783. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  1784. var httpoptions = new URL(reposerver);
  1785. httpoptions = {
  1786. hostname: httpoptions.hostname
  1787. , method: 'GET'
  1788. , protocol : httpoptions.protocol
  1789. }
  1790. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  1791. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  1792. // console.log(___args)
  1793. var repourl = reporemotes[remotename].url + '/' + repo
  1794. // PB : TOOD -- USE GITTEA API
  1795. // op['isurlaccessible']({ url : repourl }).then((baccess)=>{
  1796. return GITEA.repository.exists( httpoptions, repo, owner ).then((bexists)=>{
  1797. console.log(remotename + ' ' + repourl)
  1798. if(bexists) {
  1799. console.log(remotename + ' ' + repourl + ' is accessible')
  1800. return ((remotename)=>{
  1801. return op['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1802. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1803. })(remotename)
  1804. // get upstream remote choice from user !!!
  1805. // PB : TODO -- Set upstream , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  1806. }
  1807. }).catch(e => {
  1808. console.warn(remotename + ' ' + repourl + ' ' + e) // Skip nonexistant not necessarily quietly
  1809. })
  1810. })(rm)
  1811. )
  1812. })
  1813. return Promise.all(promises).then( accessibleremotes => {
  1814. while(!accessibleremotes[accessibleremotes.length -1] && accessibleremotes.length) accessibleremotes.splice(accessibleremotes.length -1, 1)
  1815. if(accessibleremotes.length) {
  1816. ((remotename)=>{
  1817. var upstream = `${remotename}/${branch}`
  1818. var remote = reporemotes[remotename]
  1819. return op['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1820. , upstream
  1821. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1822. })( accessibleremotes[accessibleremotes.length -1] )
  1823. }
  1824. }).catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  1825. })
  1826. })()
  1827. }
  1828. if(isElevated) {
  1829. var elevatedpromises = []
  1830. selectedinstance.elevated.forEach( r => { elevatedpromises.push(perform_remote_refresh({ name : r.repo })) } )
  1831. return Promise.all(elevatedpromises)
  1832. }
  1833. else return dirs(perform_remote_refresh)
  1834. }
  1835. }
  1836. , 'remote add': (args) => {
  1837. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  1838. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  1839. // That explicitly has a remote name prefix.
  1840. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  1841. // git branch branch_name -u your_new_remote/branch_name -- older versions
  1842. // git branch -vv -- Detect which branch are we tracking.
  1843. // default upstream should be users own fork.
  1844. // Also need alias branches to
  1845. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  1846. // probably git merge from all remotes... and relevant branches...
  1847. // alias pushall='for i in `git remote`; do git push $i; done;'
  1848. // alias pullall='for i in `git remote`; do git pull $i; done;'
  1849. // args === processedArgs ? args = {} : null;
  1850. var __args = {
  1851. remotename : args.remotename|| processedArgs._[2]
  1852. , reponame : args.reponame || (args.repodef ? args.repodef.repo : undefined)
  1853. , url : args.url || processedArgs._[3]
  1854. , branch : args.branch || processedArgs._[4] || 'master'
  1855. }
  1856. __args.upstream = args['upstream'] || processedArgs._[5] || `${remotename}/${branch}`
  1857. var remotename = __args.remotename
  1858. var url = __args.url
  1859. var branch = __args.branch
  1860. var upstream = __args.upstream
  1861. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1862. var serial_perform_git_add = (reponame) => {
  1863. var options = { cwd: instanceroot + '/' + reponame }
  1864. // console.log(reponame)
  1865. if (pushable) {
  1866. var gacmds = [
  1867. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1868. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1869. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1870. ]
  1871. }
  1872. else {
  1873. var gacmds = [
  1874. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1875. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }]
  1876. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1877. // When we add a remote it should not automatically become the upstream. The upstream should be a chosen remote else we do not change
  1878. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1879. ]
  1880. }
  1881. if(__args['upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1882. return gacmds
  1883. }
  1884. // PB : TODO -- Accumulate using yield... and finally return a set of tasks or promises...
  1885. var perform_git_add = (dir) => {
  1886. return op['is-git-repo'](dir).then((logEntry) => {
  1887. // console.log(code)
  1888. if (logEntry.success) {
  1889. return nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1890. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  1891. return remotename;
  1892. })
  1893. .catch((e) => {
  1894. return perform( serial_perform_git_add, dir.name ).then(()=>{
  1895. return remotename
  1896. })
  1897. })
  1898. }
  1899. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1900. }).catch((e) => {
  1901. console.log('Failed : ' + dir.name)
  1902. })
  1903. }
  1904. if(__args.reponame) { return perform_git_add( { name : __args.reponame} ) }
  1905. else return dirs(perform_git_add)
  1906. }
  1907. , 'remote remove': (args) => {
  1908. var __args = {
  1909. remotename : args.remotename|| processedArgs._[2]
  1910. }
  1911. var remotename = __args.remotename
  1912. var serial_perform_git_remove = (repo) => {
  1913. var options = { cwd: instanceroot + '/' + repo }
  1914. // console.log(repo)
  1915. return [
  1916. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  1917. ]
  1918. }
  1919. var perform_git_remove = (dir) => {
  1920. op['is-git-repo'](dir).then((logEntry) => {
  1921. // console.log(code)
  1922. if (logEntry.success) {
  1923. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1924. any(serial_perform_git_remove(dir.name).map(getnodeshellexectask))
  1925. })
  1926. .catch((e) => {
  1927. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  1928. })
  1929. }
  1930. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1931. }).catch((e) => {
  1932. // console.log('Failed : ' + dir.name)
  1933. })
  1934. }
  1935. dirs(perform_git_remove)
  1936. }
  1937. , 'get-remotes' : (args) => {
  1938. // var __args = {
  1939. // repo : args?.repo || processedArgs._[1]
  1940. // }
  1941. var repo = args.repo
  1942. var serial_perform = (repo) => {
  1943. return [
  1944. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1945. evaluateResult : function( issuccess, result){
  1946. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1947. var lines = result.messages.join('').split('\n')
  1948. var remotes = {}
  1949. lines.forEach(line => {
  1950. // pattern = origin https://git.bbh.org.in/chess/elxr (fetch)
  1951. var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line)
  1952. if(match) {
  1953. var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] })
  1954. if(match[3] === 'push') { r.push = match[2] }
  1955. else r.url = match[2]
  1956. }
  1957. })
  1958. return remotes
  1959. }}]
  1960. ]
  1961. }
  1962. return perform( serial_perform, repo )
  1963. }
  1964. , 'get-remote' : (upstream) => {
  1965. // var __args = {
  1966. // repo : args?.repo || processedArgs._[1]
  1967. // }
  1968. var repo = upstream.repo
  1969. var serial_perform = (repo) => {
  1970. return [
  1971. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1972. evaluateResult : function( issuccess, result){
  1973. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1974. // origin https://git.bbh.org.in/chess/elxr (fetch)
  1975. var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '))
  1976. if(match) { upstream.url = match[1] }
  1977. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1978. return upstream
  1979. }}]
  1980. ]
  1981. }
  1982. return perform( serial_perform, repo )
  1983. }
  1984. , 'get-upstream' : (args) => {
  1985. var __args = {
  1986. repo : args?.repo || processedArgs._[1]
  1987. }
  1988. var repo = __args.repo
  1989. var serial_perform = (repo) => {
  1990. return [
  1991. ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1992. evaluateResult : function( issuccess, result){
  1993. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1994. var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '))
  1995. if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] } }
  1996. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1997. if(args?.remotes) {
  1998. var r = args.remotes[upstream.remotename];
  1999. if(!r) return op['get-remote'](upstream)
  2000. r.branch = upstream.branch
  2001. r.remotebranch = upstream.remotebranch
  2002. return r
  2003. }
  2004. return op['get-remote'](upstream)
  2005. }}]
  2006. ]
  2007. }
  2008. return perform( serial_perform, repo )
  2009. }
  2010. , 'init-gitea': (username) => {
  2011. // Change user to an object that has user.username and use here..
  2012. username = username || processedArgs._[1]
  2013. if (!username) throw 'User name required'
  2014. var serial_perform_init_gitea = (repo) => {
  2015. var options = { cwd: instanceroot + '/' + repo }
  2016. // console.log(repo)
  2017. return [
  2018. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  2019. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  2020. , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  2021. ]
  2022. }
  2023. var perform_init_gitea = (dir) => {
  2024. op['is-git-repo'](dir).then((logEntry) => {
  2025. // console.log(code)
  2026. if (logEntry.success) {
  2027. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  2028. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  2029. })
  2030. .catch((e) => {
  2031. perform( serial_perform_init_gitea, dir.name )
  2032. })
  2033. }
  2034. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  2035. }).catch((e) => {
  2036. // console.log('Failed : ' + dir.name)
  2037. })
  2038. }
  2039. dirs(perform_init_gitea)
  2040. }
  2041. , 'syncmaster': (label) => {
  2042. // Usage :
  2043. // elxr pull -- Defaults to run config
  2044. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2045. if (!processedArgs.runas) gitRepos.map((def) => {
  2046. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2047. else performPull(def, def.branch || 'master')
  2048. })
  2049. var etask = ()=>{
  2050. return any(elevatedRunasRepos.map((def) =>
  2051. {
  2052. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2053. else performPull(def, def.branch || 'master')
  2054. })).then(() => {
  2055. fs.writeFileSync('run.done', 'success')
  2056. }).catch(() => {
  2057. fs.writeFileSync('run.done', 'error')
  2058. })
  2059. }
  2060. etask.statuslog = statuslog
  2061. etask.selectedinstance = selectedinstance
  2062. etask.processedArgs = processedArgs
  2063. etask.runtimestamp = runtimestamp
  2064. etask.ENV = ENV
  2065. return shell_verse.runElevated(etask)
  2066. }
  2067. , 'repo-relocate' : function(args){
  2068. // relocate a subfolder in source repo to same subfolder in target repo with history.
  2069. var args = args || {
  2070. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  2071. , folder : processedArgs._[3] || 'server'
  2072. , sourcerepo : processedArgs._[2] || 'client'
  2073. , targetrepo : processedArgs._[1] || 'elixir-server'
  2074. }
  2075. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  2076. // , stdio: ['pipe', process.stdout, process.stderr]
  2077. , inherit: true,
  2078. shell: true,
  2079. env: ENV
  2080. , runas: processedArgs.runas
  2081. }
  2082. return op['repo-split'](args).then(()=>{
  2083. return op['repo-merge'](args).then(()=>{
  2084. // cleanup folder from source.
  2085. var cmdseq = [
  2086. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  2087. // commits have to intentional...
  2088. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  2089. ]
  2090. return any(cmdseq.map(getshelltask))
  2091. })
  2092. }).catch(e=>{console.error(e)})
  2093. }
  2094. , 'repo-split' : function(args) {
  2095. // https://gist.github.com/smdabdoub/17065c348289158277b5
  2096. /**
  2097. * Eg : folder, remotebase, sourcerepo, targetrepo
  2098. * args.folder = 'server'
  2099. * args.remotebase = 'https://git.bbh/chess/'
  2100. * args.sourcerepo = 'client'
  2101. * args.targetrepo = 'elixir-server'
  2102. */
  2103. var args = args || {
  2104. folder : 'server'
  2105. , remotebase : 'http://git.bbh/chess/'
  2106. , sourcerepo : 'client'
  2107. , targetrepo : 'elixir-server'
  2108. }
  2109. var options = { cwd: `${instanceroot}/relocate`
  2110. // , stdio: ['pipe', process.stdout, process.stderr]
  2111. , inherit: true,
  2112. shell: true,
  2113. env: ENV
  2114. , runas: processedArgs.runas
  2115. }
  2116. var cmdseq = [
  2117. // create a temporary working dir in current folder where we started execution.
  2118. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  2119. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  2120. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  2121. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  2122. ]
  2123. return any(cmdseq.map(getshelltask)).then(() => {
  2124. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2125. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  2126. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2127. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  2128. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  2129. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  2130. // subtree split and filter-branch are options. We currently use repo-filter.
  2131. return op['filter-repo'](args)
  2132. }).catch(e=>{console.error(e); throw 'failed'})
  2133. }
  2134. , 'repo-merge' : function(args) {
  2135. // Merge source repo into target repo
  2136. var args = args || {
  2137. folder : 'server'
  2138. , remotebase : 'http://git.bbh/chess/'
  2139. , sourcerepo : 'client'
  2140. , targetrepo : 'elixir-server'
  2141. }
  2142. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  2143. // , stdio: ['pipe', process.stdout, process.stderr]
  2144. , inherit: true,
  2145. shell: true,
  2146. env: ENV
  2147. , runas: processedArgs.runas
  2148. }
  2149. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  2150. // , stdio: ['pipe', process.stdout, process.stderr]
  2151. , inherit: true,
  2152. shell: true,
  2153. env: ENV
  2154. , runas: processedArgs.runas
  2155. }
  2156. var cmdseq = [
  2157. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  2158. , targetrepooptions ]
  2159. // , ['git', ['push', targetrepooptions ] // manual push for now..
  2160. ]
  2161. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  2162. }
  2163. , 'filter-repo' : function(args){
  2164. // Merge source repo into target repo
  2165. var args = args || {
  2166. folder : 'server'
  2167. , remotebase : 'http://git.bbh/chess/'
  2168. , targetrepo : 'elixir-server'
  2169. }
  2170. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  2171. , inherit: true, shell: true
  2172. , env: ENV
  2173. , runas: processedArgs.runas
  2174. }
  2175. var cmdseq = [
  2176. // git checkout -b feature/merge-old-project
  2177. // git remote add src-project ../src-project
  2178. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  2179. ]
  2180. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  2181. }
  2182. , 'filter-branch' : function(preservefolder, repo){
  2183. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  2184. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  2185. // Preserve a specific folder.
  2186. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  2187. /*
  2188. git clone repo reposplit
  2189. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  2190. git remote rm origin
  2191. */
  2192. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  2193. }
  2194. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  2195. // // Merge repo2 into a subfolder in repo1
  2196. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  2197. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  2198. // /*
  2199. // cd repo1
  2200. // git remote add -f tempmergesource ../{{mergesource}}/.git
  2201. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  2202. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  2203. // git commit
  2204. // // Repair History
  2205. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  2206. // #!/usr/bin/env bash
  2207. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  2208. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  2209. // subdir=server
  2210. // git filter-branch --tree-filter '
  2211. // first='"$first"'
  2212. // last='"$last"'
  2213. // subdir='"$subdir"'
  2214. // log_file=/tmp/filter.log
  2215. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  2216. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  2217. // echo "=== $GIT_COMMIT: making changes"
  2218. // files=$(git ls-tree --name-only $GIT_COMMIT)
  2219. // mkdir -p $subdir
  2220. // for i in $files; do
  2221. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  2222. // done
  2223. // else
  2224. // echo "=== $GIT_COMMIT: ignoring"
  2225. // fi \
  2226. // >> $log_file
  2227. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  2228. // status=0 # tell tree-filter never to fail
  2229. // '
  2230. // git remote rm tempmergesource
  2231. // */
  2232. // // better alternative for history
  2233. // /**
  2234. // *
  2235. // git clone git@server.com:old-project.git
  2236. // git clone git@server.com:new-project.git
  2237. // cd old-project
  2238. // mkdir old-project
  2239. // git mv !(old-project) old-project
  2240. // ls -la and gt mv hidden files ....
  2241. // git commit -a -S -m “Moving old project into its own subdirectory”
  2242. // cd ../new-project
  2243. // git remote add old-project ../old-project
  2244. // git fetch old-project
  2245. // git checkout -b feature/merge-old-project
  2246. // git merge -S --allow-unrelated-histories old-project/master
  2247. // git push origin feature/merge-old-project
  2248. // git remote rm old-project
  2249. // */
  2250. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  2251. // }
  2252. , 'pull' : (label) => {
  2253. // Usage :
  2254. // elxr pull -- Defaults to run config
  2255. return elxr.getpulltask(selectedinstance)
  2256. }
  2257. , 'isInstalled': () => {
  2258. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  2259. console.log(processedArgs._[1] + ' exists.')
  2260. return true;
  2261. });
  2262. }
  2263. , 'c' : ()=>{
  2264. }
  2265. , 'i' : () => {
  2266. var tasks = []
  2267. // tasks.push(op['pull']);
  2268. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  2269. tasks.push(op['use']) // Will pull repos...
  2270. op['npmi'].statuslog = statuslog
  2271. tasks.push(shell_verse.getNonElevatedTask(op['npmi'])) // We do not run npm i with elevated privilege for security reasons.
  2272. // var tasksdefs = [
  2273. // ['elxr', ['pull']]
  2274. // , ['elxr', ['use', 'elixir']]
  2275. // , ['elxr', ['npmi']]
  2276. // ]
  2277. // tasksdefs.forEach(tasksdef=>{
  2278. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  2279. // })
  2280. return any(tasks);
  2281. }
  2282. , 'npmi': () => {
  2283. var tasks = [];
  2284. // Build fails without babel...
  2285. tasks.push(getShellTask(
  2286. 'npm',[ 'i', '-g', 'babel-cli' ]
  2287. ) )
  2288. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  2289. // npmbuildrepos = []
  2290. npmbuildrepos.forEach(repo => {
  2291. tasks.push(() => {
  2292. return nodeShellExec('npm', ['i --force'], {
  2293. inherit: true, shell: true
  2294. , cwd: instanceroot + '/' + repo
  2295. , env: ENV
  2296. , title: `npm i for ${repo}`
  2297. }).catch((e) => {
  2298. console.error('Ignoring Benign Error'); console.error(e);
  2299. }).then(() => {
  2300. console.log(`--npm run build for ${repo}--------------------`)
  2301. return nodeShellExec('npm', ['run build'], {
  2302. inherit: true, shell: true
  2303. , cwd: instanceroot + '/' + repo
  2304. , env: ENV
  2305. , title: `npm run build for ${repo}`
  2306. }).then(Tasq.then).catch(Tasq.catch)
  2307. })
  2308. })
  2309. })
  2310. return any(tasks).then(() => {
  2311. gitRepos.push({ repo : 'chess-server-lib/server'});
  2312. gitRepos = gitRepos.concat(elevatedRunasRepos);
  2313. // console.dir(gitRepos)
  2314. // throw ""
  2315. // gitRepos = [
  2316. // // 'bbhverse', 'serververse', 'elixir-server',
  2317. // // 'clientverse',
  2318. // 'client'
  2319. // ];
  2320. var rmtasks = []
  2321. var repotasks = []
  2322. var env = Object.assign({}, ENV)
  2323. delete env.NODE_ENV // PB : TODO -- Why delete ??? npm i fails with NODE_ENV...
  2324. gitRepos.forEach(repodef => {
  2325. rmtasks.push(
  2326. // () => {
  2327. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2328. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  2329. callshelltask(['rm', ['package-lock.json'], {
  2330. inherit: true, shell: true
  2331. , cwd: instanceroot + '/' + repodef.repo
  2332. , env: ENV
  2333. , title: `rm 'package-lock.json' for ${repodef.repo}`
  2334. }])
  2335. .then(()=>{
  2336. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2337. }).catch((e) => { console.error(e) })
  2338. // }
  2339. )
  2340. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  2341. repotasks.push(
  2342. () => {
  2343. console.log(`--npm i for ${repodef.repo}--------------------`)
  2344. var p = nodeShellExec('npm', ['i', '--force'], {
  2345. inherit: true, shell: true
  2346. , cwd: instanceroot + '/' + repodef.repo
  2347. , env
  2348. , title: `npm i for ${repodef.repo}`
  2349. }).then(Tasq.then).catch(Tasq.catch)
  2350. return p;
  2351. })
  2352. }
  2353. })
  2354. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  2355. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  2356. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  2357. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  2358. // PB : TODO -- Investigate why NODE_ENV has an impact on npm i !??
  2359. // Second time try also doesnt work.
  2360. // repotasks.push(
  2361. // () => {
  2362. // var env = Object.assign({}, process.env)
  2363. // delete env.NODE_ENV
  2364. // console.log(`--------------------second time npm i for client--------------------`)
  2365. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  2366. // // return nodeShellExec('npm', ['i --force'], {
  2367. // inherit: true, shell: true
  2368. // , cwd: instanceroot + '/' + 'client'
  2369. // , env
  2370. // , title: `npm i for client`
  2371. // }).then(Tasq.then).catch(Tasq.catch)
  2372. // })
  2373. var bowerRepos = [{ repo : 'client'}]
  2374. var bowertasks = []
  2375. bowerRepos.forEach(repodef => {
  2376. bowertasks.push(() => {
  2377. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  2378. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  2379. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  2380. inherit: true, shell: true
  2381. , cwd: instanceroot + '/' + repodef.repo
  2382. , env: ENV
  2383. , title: `bower i for ${repodef.repo}`
  2384. }).then(Tasq.then).catch(Tasq.catch)
  2385. return p;
  2386. })
  2387. })
  2388. // console.log('rmtasks.length : ' + rmtasks.length)
  2389. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  2390. }).catch(e => {
  2391. console.error(e)
  2392. }).finally(statuslog.finally)
  2393. }
  2394. , 'start': (args) => {
  2395. // Usage : elxr start {{instanceName=elixir}} {{all||server||client||{{microserviceName=elixir||express}}}}
  2396. var label = clioverrides.cmd
  2397. var env = Object.assign({}, ENV); // Shallow clone it.
  2398. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  2399. function startFn( o ){
  2400. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  2401. console.log(`Starting ${o.name}.`);
  2402. if(shell_verse.iswin()){
  2403. var __cmd = 'cmd'
  2404. var a1 = '/k'
  2405. }
  2406. else if(shell_verse.islin()) {
  2407. var __cmd = 'sh'
  2408. var a1 = '-c'
  2409. }
  2410. if(o.cmd) {
  2411. cmd = o.cmd
  2412. var childPromise = nodeShellExec(...o.cmd, {
  2413. // inherit : true,
  2414. shell: true,
  2415. detached: true,
  2416. stdio: 'ignore',
  2417. cwd: instanceroot + o.path
  2418. , env
  2419. })
  2420. }
  2421. else {
  2422. var childPromise = nodeShellExec(__cmd, [a1, getCmdString(cmd) ], {
  2423. // inherit : true,
  2424. shell: true,
  2425. detached: true,
  2426. stdio: 'ignore',
  2427. cwd: instanceroot + o.path
  2428. , env
  2429. })
  2430. }
  2431. var child = childPromise.process;
  2432. var cpid = child.pid
  2433. childPromise.then(()=>{
  2434. console.log(` *** started ${o.name} PID(${cpid}) ${cmd}`);
  2435. fs.writeFileSync(o.pidstore, '' + cpid)
  2436. })
  2437. .catch(e => console.error(e) )
  2438. }
  2439. if(clioverrides.node_env === 'development') {
  2440. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  2441. if(!processedArgs._[2]) processedArgs._[2] = 'all'
  2442. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2443. || processedArgs._[2] === 'elixir' // specific microservice name.
  2444. ) {
  2445. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server'
  2446. , pidstore : '.elixir-server.elixir.server.pid'
  2447. } )
  2448. }
  2449. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2450. || processedArgs._[2] === 'express' // specific microservice name.
  2451. ) {
  2452. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server'
  2453. , pidstore : '.express.server.pid'
  2454. } )
  2455. }
  2456. if(processedArgs._[2] === 'client' || processedArgs._[2] === 'all') {
  2457. startFn( {
  2458. name : 'Elixir Ember Client', path : '/' + 'client'
  2459. , cmd : ['node_modules/ember-cli/bin/ember', ['s']]
  2460. , pidstore : '.client.server.pid'
  2461. } )
  2462. }
  2463. }
  2464. }
  2465. , 'stop': (label) => {
  2466. const kill = require('tree-kill');
  2467. try{
  2468. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8'})
  2469. fs.unlinkSync('.elixir-server.elixir.server.pid')
  2470. console.log(serverPid)
  2471. kill(serverPid)
  2472. }
  2473. catch(e){ console.error(e) }
  2474. try{
  2475. serverPid = fs.readFileSync('.express.server.pid', { encoding: 'utf8' })
  2476. fs.unlinkSync('.express.server.pid')
  2477. console.log(serverPid)
  2478. kill(serverPid)
  2479. }
  2480. catch(e){ console.error(e) }
  2481. try{
  2482. serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' })
  2483. fs.unlinkSync('.client.server.pid')
  2484. console.log(serverPid)
  2485. kill(serverPid)
  2486. }
  2487. catch(e){ console.error(e) }
  2488. }
  2489. , 'model' : () => {
  2490. var etask = ()=>{
  2491. var tasks = [
  2492. () => {
  2493. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  2494. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  2495. inherit: true, shell: true
  2496. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  2497. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  2498. , env: ENV
  2499. }).catch((e) => { console.error(e) })
  2500. return p;
  2501. }
  2502. ];
  2503. return any(tasks).then(() => {
  2504. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  2505. }).catch(() => {
  2506. fs.writeFileSync('run.done', 'error')
  2507. })
  2508. }
  2509. etask.statuslog = statuslog
  2510. etask.selectedinstance = selectedinstance
  2511. etask.processedArgs = processedArgs
  2512. etask.runtimestamp = runtimestamp
  2513. etask.ENV = ENV
  2514. return shell_verse.runElevated(etask)
  2515. }
  2516. , 'use' : () => {
  2517. // use a certain named instance.
  2518. // Eg :
  2519. // 1) elxr use elixir
  2520. // 2) elxr use cihsr
  2521. // If environment is not specified defaults to development.
  2522. // 1) NODE=test elxr use elixir
  2523. /*// Steps
  2524. 1) Delete Config and Data symlinks
  2525. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  2526. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  2527. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2528. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  2529. */
  2530. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  2531. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  2532. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  2533. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  2534. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  2535. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') } // PB : TODO -- IPC through files is needed only for windows.
  2536. if (existsSync('config') && existsSync('data')){
  2537. return
  2538. }
  2539. }
  2540. var tasks = [
  2541. () => {
  2542. var promise = new Promise((resolve, reject)=>{
  2543. existslink('config', function(err, data){
  2544. if(data) {
  2545. var p = shell_verse.removeJuncionOrLink('config')
  2546. .then(()=>{resolve(true)})
  2547. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2548. }
  2549. else resolve(false)
  2550. })
  2551. })
  2552. return promise;
  2553. },
  2554. () => {
  2555. var promise = new Promise((resolve, reject)=>{
  2556. existslink('data', function(err, data){
  2557. if(data) {
  2558. var p = shell_verse.removeJuncionOrLink('data')
  2559. .then(()=>{resolve(true)})
  2560. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2561. }
  2562. else resolve(false)
  2563. })
  2564. })
  2565. return promise;
  2566. },
  2567. ];
  2568. runconfig.NODE_ENV = ENV.NODE_ENV = ENV.NODE_ENV || runconfig.NODE_ENV || 'development';
  2569. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  2570. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  2571. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  2572. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  2573. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  2574. var performPullOrCloneForBranch = (def)=>{
  2575. var promise = Promise.resolve(true)
  2576. if (!branch) {
  2577. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  2578. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  2579. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2580. }
  2581. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  2582. }
  2583. var performCloneAndCheckout = null;
  2584. // cant use git checkout -b it fails when branch already exists.
  2585. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2586. return performPullOrCloneForBranch(def).then(()=>{
  2587. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2588. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2589. // inherit : true, shell: true,
  2590. cwd: instanceroot + '/' + def.repo
  2591. // , stdio : ignore // Use when we want to silence output completely.
  2592. , runas: processedArgs.runas
  2593. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  2594. }).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 } })
  2595. })
  2596. }
  2597. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  2598. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  2599. var elevatedqueue = [];
  2600. var enqueueOnce = (queue, task, def) => {
  2601. var found = queue.find(element => {
  2602. var keys = Object.keys( element )
  2603. for(var k=0; k < keys.length; k++) {
  2604. if(element[keys[k]] !== def[k]) return false;
  2605. }
  2606. })
  2607. queue.push(function(){ return task(this)}.bind(def));
  2608. }
  2609. var enqueue = (queue, task, def) => {
  2610. queue.push(function(){ return task(def)}.bind(def));
  2611. }
  2612. var mergeSources = {
  2613. 'development': null,
  2614. 'test': 'master',
  2615. 'production': 'master'
  2616. }
  2617. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2618. // Checkout is reduced to pull provided the current branch is the targetbranch
  2619. if(branch === mergesource) performCheckout = (def) => {
  2620. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  2621. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  2622. if(branch === __branch) return performCloneAndCheckout(def)
  2623. return performPullOrCloneForBranch(def)
  2624. })
  2625. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2626. }
  2627. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  2628. var performPullAll = (def) => {
  2629. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2630. return nodeShellExec('git', ['pull', '--all'], {
  2631. // inherit : true, shell: true,
  2632. cwd: instanceroot + '/' + def.repo
  2633. , runas: processedArgs.runas
  2634. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  2635. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  2636. }
  2637. var excludeCheckouts = Object.assign(exludeMergeRepos)
  2638. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  2639. // delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  2640. var performMerge = (def) => {
  2641. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2642. return nodeShellExec('git', ['merge', mergesource], {
  2643. inherit: true, shell: true,
  2644. cwd: instanceroot + '/' + def.repo
  2645. , runas: processedArgs.runas
  2646. }).catch((e) => { console.error(e) })
  2647. }
  2648. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  2649. // var performRepoOperation = function(def) {
  2650. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  2651. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  2652. // }
  2653. return any(tasks).then(() => {
  2654. var task = ()=>{
  2655. // Default target is developent. if some other target is specified in NODE_ENV in for shell call for the 'use' command we will switch to that target..
  2656. //Switch to target branch
  2657. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  2658. // pull or clone target branch
  2659. .then(() => {
  2660. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2661. return any(gitRepos.map((repo) => performPullAll(repo)))
  2662. })
  2663. // switch to source branch
  2664. .then( () => {
  2665. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  2666. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  2667. })
  2668. //Pull on merge source branch
  2669. .then( () => {
  2670. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2671. return any(gitRepos.map((repo) => performPullAll(repo)))
  2672. })
  2673. //Switch to target branch
  2674. .then( () => {
  2675. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2676. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  2677. })
  2678. .then( //Merge source branch to target branch
  2679. () => {
  2680. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2681. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  2682. })
  2683. }
  2684. task.statuslog = statuslog
  2685. var netask = shell_verse.getNonElevatedTask(task)
  2686. var eltask = ()=> {
  2687. var opts = {
  2688. inherit: true, shell: true
  2689. , cwd : instanceroot
  2690. , env: ENV
  2691. }
  2692. var tasks = [
  2693. () => {
  2694. // Use junctions to avoid npm package issues
  2695. var target = runconfig.use + '-' + 'config' + '-' + ENV.NODE_ENV
  2696. var p = shell_verse.createJuntionOrLink('config', target, opts)
  2697. return p;
  2698. }
  2699. ];
  2700. // if (processedArgs._[1]) {
  2701. tasks = tasks.concat( [
  2702. () => {
  2703. var dataToLink = runconfig.use + '-data' + '-' + ENV.NODE_ENV
  2704. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  2705. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  2706. return p;
  2707. }
  2708. ]
  2709. )
  2710. // }
  2711. return any(tasks).then(()=>{
  2712. // checkout target branch
  2713. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2714. // pull or clone target branch
  2715. .then(() => {
  2716. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2717. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  2718. })
  2719. // switch to source branch
  2720. .then( () => {
  2721. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2722. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  2723. })
  2724. //Pull on merge source branch
  2725. .then( () => {
  2726. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2727. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  2728. })
  2729. //Switch to target branch
  2730. .then( () => {
  2731. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2732. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2733. })
  2734. .then( //Merge source branch to target branch
  2735. () => {
  2736. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2737. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  2738. })
  2739. .then(() => {
  2740. fs.writeFileSync('run.done', 'success')
  2741. }).catch(() => {
  2742. fs.writeFileSync('run.done', 'error')
  2743. })
  2744. })
  2745. }
  2746. eltask.statuslog = statuslog
  2747. eltask.selectedinstance = selectedinstance
  2748. eltask.processedArgs = processedArgs
  2749. eltask.runtimestamp = runtimestamp
  2750. var eltask = shell_verse.getElevatedTask(eltask)
  2751. return eltask().then( ()=>{ return netask() })
  2752. }).catch((e) => {
  2753. fs.writeFileSync('run.done', 'error : ' + e)
  2754. })
  2755. // Antibiotic stewardship program.
  2756. // 1st use is fine.
  2757. // Max vials dispense
  2758. // 2nd use Pharmacy needs justification Form.
  2759. // Approval after a certain period of time.
  2760. }
  2761. , 'g' : () => {
  2762. if (processedArgs.h) {
  2763. console.log('elxr g model [modelname] => generate a model named [modelname]');
  2764. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  2765. console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
  2766. console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
  2767. console.log('elxr g => regenerate all known models');
  2768. return
  2769. }
  2770. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  2771. // try {
  2772. // child = child.on('close', () => { process.chdir(label) } );
  2773. // }
  2774. // catch (err) {
  2775. // console.log('chdir: ' + err);
  2776. // }
  2777. // child.on('close', function(){
  2778. // var options = {
  2779. // shell : true
  2780. // , inherit : true
  2781. // // , cwd : '' + process.cwd
  2782. // // , env : ENV
  2783. // };
  2784. // nodeShellExec('git', ['init'], { inherit : true});
  2785. if (0) {
  2786. // PB : TODO -- Special google chrome profile for tests etc.
  2787. nodeShellExec('pwd', { inherit: true });
  2788. // /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"
  2789. // "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
  2790. // "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
  2791. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  2792. "--profile-directory=Profile 1"
  2793. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  2794. }
  2795. // nodeShellExec('npm', ['init', '-y'], options);
  2796. // nodeShellExec('npm', ['init', '-y'], options);
  2797. // })
  2798. var g = {
  2799. 'client': () => {
  2800. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  2801. console.info('Creating new ember client named : ' + processedArgs._[2]);
  2802. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  2803. stdio: ['pipe', process.stdout, process.stderr],
  2804. inherit: true,
  2805. shell: true,
  2806. cwd: path.dirname(__dirname),
  2807. env : ENV
  2808. })
  2809. },
  2810. 'modelr': () => {
  2811. var tasks = [
  2812. () => {
  2813. var p = nodeShellExec('"ember"', [
  2814. 'g'
  2815. , 'modelr'
  2816. , processedArgs._[2]], {
  2817. inherit: true, shell: true, env: ENV
  2818. }).then(() => {
  2819. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  2820. return true;
  2821. }).catch((e) => { console.error(e) })
  2822. return p;
  2823. },
  2824. () => {
  2825. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  2826. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  2827. chromeprefs = JSON.parse(chromeprefs)
  2828. var previous = chromeprefs.download.default_directory;
  2829. var parentDir = path.dirname(__dirname);
  2830. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  2831. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2832. // PB : TODO -- detect where chrome is installed.
  2833. // PB : TODO -- set the download dir to the place where files are needed.
  2834. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  2835. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  2836. , '--profile-directory="chess"'
  2837. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  2838. inherit: true, shell: true
  2839. , env: ENV
  2840. }).then(() => {
  2841. chromeprefs.download.default_directory = previous;
  2842. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2843. return true;
  2844. }).catch((e) => { console.error(e) })
  2845. return p;
  2846. }
  2847. ,
  2848. () => {
  2849. console.log('Browser process should have closed here....')
  2850. return true;
  2851. }
  2852. ]
  2853. any(tasks)
  2854. }
  2855. , 'undefined' : ()=>{
  2856. console.warn('Are you sure you want to refresh all the models.');
  2857. throw 'NOT YET IMPLMENTED'
  2858. }
  2859. , 'vmodel' : (options)=>{
  2860. // node --inspect-brk elxr/index.js g vmodel qlabresults --server=true
  2861. options = options || {
  2862. generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
  2863. }
  2864. if(!options.generate) return 'Nothing specified for generation'
  2865. var name = processedArgs._[2];
  2866. if(!name) return 'No name specified for generation'
  2867. var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`
  2868. // var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel/__base__-server-lib/common/lib`
  2869. var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`
  2870. var destination = `${selectedinstance.root}`
  2871. // Create a tmp working copy for staging the changes.
  2872. return copyrecursive(templateverse, workingtarget).then( r => {
  2873. var base = 'chess' // -- The server base from where this instance was dervied from.
  2874. var patternsubstitutions = [
  2875. { strOrregexp : /(__name__)/g, substitutes : [name]}
  2876. , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
  2877. , { strOrregexp : /(__base__)/g, substitutes : [base]}
  2878. , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
  2879. , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']} // PB : TODO -- elixir-client etc... use a config to find the microclient..
  2880. ]
  2881. var options = { source : templateverse, target : workingtarget
  2882. , base , destinationroot : destination, workingtarget
  2883. , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions }
  2884. var actions = [
  2885. fswalk( workingtarget, options
  2886. , [ function(t, o){
  2887. // A series of tasks to be executed on each pattern in patternsubstitutions.
  2888. return any([
  2889. // PB : TODO -- Contentreplace is better addressed in memory instead of file IO so do all regexps in sequence in one shot and then rename.
  2890. ()=>{ return fscontentreplace( t, o ) }
  2891. , ()=>{ return fsrename( t, o ) }
  2892. ])
  2893. }] )
  2894. // Post process links in place.
  2895. , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
  2896. , workingtarget, null, options)
  2897. // Move to the final destination. Whole tree should move only top level folders are required.
  2898. // , () => fswalk( workingtarget, options, [ fsrename ])
  2899. // , () => dirs( ( child, src, target, options )=>{ return fs.renameSync(path.join(src, child.name), path.join(target, child.name) ) }
  2900. // , workingtarget, destination )
  2901. ]
  2902. return any(actions);
  2903. })
  2904. }
  2905. }
  2906. g[processedArgs._[1]]();
  2907. }
  2908. , 'launchui' : () => {
  2909. console.log('-----------------------------')
  2910. console.log('Launching Elxir Admin Console')
  2911. console.log('-----------------------------')
  2912. // shell_verse.getchrome()
  2913. processedArgs.awaitrun = true;
  2914. return shell_verse.launchui()
  2915. // shell_verse.getchrome().then( chrome => {
  2916. // nodeShellExec( `"${chrome}"`, [
  2917. // '--profile-directory="chess"'
  2918. // , `${selectedinstance.root}/elixir-client/elxr-admin-console/html/index.html`], {
  2919. // inherit: true, shell: true
  2920. // , env: ENV
  2921. // })
  2922. // .catch(e => console.dir(e))
  2923. // })
  2924. }
  2925. , 'create' : () => { return createInstance(selectedinstance) }
  2926. , 'httpget' : () => {
  2927. // RESTAPI.get({
  2928. // hostname: 'git.bbh',
  2929. // // port: 443,
  2930. // protocol : 'http:',
  2931. // path: '/',
  2932. // method: 'GET'
  2933. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  2934. return createInstance(selectedinstance)
  2935. }
  2936. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  2937. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  2938. }
  2939. Object.keys(op).forEach( oper => {
  2940. if(cmds[oper]) return
  2941. cmds[oper] = {}
  2942. // cmds[oper] = {
  2943. // // return a interpreted set of arguments for this cmd run context.
  2944. // interpret() { return { cmd : oper, runchoice : 'c' } }
  2945. // }
  2946. })
  2947. var elxrcmd = (function(){
  2948. var __cmdprototype = function(){}
  2949. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  2950. var __cmd = {
  2951. interpret() {
  2952. var interpreted = {}
  2953. // Non custom command has universal positiona args.
  2954. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  2955. interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  2956. // return clioverrides
  2957. // cmds[cmd] = {
  2958. // interpret() {
  2959. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  2960. // }
  2961. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  2962. // instanceName : true, instanceType : true, reposerver : true } }
  2963. // }
  2964. // ... PB : TODO -- use cmd.toArgs
  2965. interpreted.cmd = this.cmd
  2966. return interpreted
  2967. }
  2968. , getPossiblePrompts(){ return { username : true, password : true, instanceName : true, instanceType : true, reposerver : true } }
  2969. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  2970. , finalized : true
  2971. , toArgs : function( o ){
  2972. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  2973. return o }
  2974. }
  2975. function __createO(o){
  2976. if(o.finalized) return o;
  2977. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  2978. // console.log(subs)
  2979. // console.log(o)
  2980. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  2981. var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2982. , {}, __cmd, cmds[o.cmd], o)
  2983. cmds[o.cmd] = created;
  2984. created.cmdFn = op[o.cmd] || o.cmdFn || created.cmdFn
  2985. op[o.cmd] = created.cmdFn;
  2986. noprerequisites[o.cmd] = created.noprerequisites
  2987. return created.cmdFn;
  2988. }
  2989. function create(o){ return __createO(o) }
  2990. __cmdprototype.create = create;
  2991. return __cmdprototype;
  2992. })()
  2993. var cmdFns = {
  2994. resetgitconfig, reinit, init, g : op['g'], 'get-upstream' : op['get-upstream']
  2995. }
  2996. Object.entries(cmds).forEach( ca => {
  2997. ca[1].cmd = ca[0]
  2998. ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
  2999. elxrcmd.create( ca[1] )
  3000. })
  3001. shell_verse.cmds = cmds;
  3002. var __default = selectedinstance; // PB : TODO -- Eliminate __default references.
  3003. Tasq.addlistener(statuslog.statuslog)
  3004. // Instead of waiting for the root to be establised we start working at the current locatoin and then relocate when root changes.
  3005. var runlogjson = `${selectedinstance.root}/.elxr/run-${runtimestamp}/run.log`
  3006. ensureDirectoryExistence(runlogjson)
  3007. fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true})) // Initialize a new log file with "logrotate" for every run
  3008. Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  3009. var nodeShellExec = cli.nodeShellExec;
  3010. var chalk = require('chalk')
  3011. const homedir = require('os').homedir();
  3012. function sysAddPathVar(addpath){
  3013. // Object.assign({
  3014. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  3015. // }, options)
  3016. // powershell $env:Path -split ';'
  3017. var etask = ()=>{
  3018. return nodeShellExec('Powershell.exe', [
  3019. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  3020. $newpath = $path + ';${addpath}'
  3021. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  3022. ]).then(() => {
  3023. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  3024. }).catch(() => {
  3025. fs.writeFileSync('run.done', 'error')
  3026. })
  3027. }
  3028. etask.statuslog = statuslog
  3029. etask.selectedinstance = selectedinstance
  3030. etask.processedArgs = processedArgs
  3031. etask.runtimestamp = runtimestamp
  3032. etask.ENV = ENV
  3033. return shell_verse.runElevated(etask)
  3034. // var newpath = addpath.split(';');
  3035. // newpath.push(addpath)
  3036. // newpath = Array.from(new Set(newpath)).join(';')
  3037. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  3038. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  3039. // // %AppData%\npm
  3040. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  3041. }
  3042. // singleton one time lazy
  3043. var getCredentials = function(){
  3044. // try {
  3045. // First call
  3046. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  3047. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  3048. console.log(creds);
  3049. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  3050. // }
  3051. // catch(e){
  3052. // console.warn('Credentials not cached. You will be prompted for username and password.')
  3053. // }
  3054. // Subsequent calls
  3055. getCredentials = ()=>{ return creds }
  3056. return getCredentials();
  3057. }
  3058. // console.dir(processedArgs)
  3059. // PB : TODO -- defaults for valuless arguments if passed.
  3060. // Object.keys(processedArgs).forEach(a=>{
  3061. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  3062. // }
  3063. // })
  3064. const { readdir } = require("fs").promises
  3065. // Directory shallow walk and do perform on each dir.
  3066. const dirs = async (perform, src, target, options) => {
  3067. var rs = []
  3068. for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
  3069. if (dir.isDirectory()) rs.push( perform(dir, src, target, options) )
  3070. }
  3071. return any(rs)
  3072. }
  3073. var fsMove = async function(from, to, options) {
  3074. if(!options?.innernode) {
  3075. var exists = fs.existsSync(from);
  3076. var stats = exists && fs.statSync(from);
  3077. var isDirectory = exists && stats.isDirectory();
  3078. }
  3079. else {
  3080. var isDirectory = options.innernode.isDirectory()
  3081. }
  3082. if(!isDirectory) return fs.renameSync(from, to)
  3083. fs.mkdirSync(to, { recursive : true })
  3084. var rs = [];
  3085. for (const innernode of await readdir(from, { withFileTypes: true })) {
  3086. rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) )
  3087. }
  3088. return any(rs)
  3089. };
  3090. // PB : TODO -- Should return a bunch of promises to wait for...
  3091. var copyrecursive = async function(src, target, options) {
  3092. if(!options?.innernode) {
  3093. var exists = fs.existsSync(src);
  3094. var stats = exists && fs.statSync(src);
  3095. var isDirectory = exists && stats.isDirectory();
  3096. }
  3097. else {
  3098. var isDirectory = options.innernode.isDirectory()
  3099. }
  3100. if(!isDirectory) return fs.copyFileSync(src, target)
  3101. fs.mkdirSync(target, { recursive : true })
  3102. var rs = [];
  3103. for (const innernode of await readdir(src, { withFileTypes: true })) {
  3104. rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
  3105. // .then(()=>{
  3106. // return any(actions.map( a => ()=>a(dir, { isDirectory : true}) ))
  3107. // })
  3108. )
  3109. }
  3110. return any(rs)
  3111. // return fswalk( src, {}, [
  3112. // (src, options)=> {
  3113. // if(options.innernode.isDirectory()) fs.mkdirSync(options.target, { recursive : true })
  3114. // else fs.copyFileSync(src, options.target)
  3115. // }
  3116. // ])
  3117. // var exists = fs.existsSync(src);
  3118. // var stats = exists && fs.statSync(src);
  3119. // var isDirectory = exists && stats.isDirectory();
  3120. // if (isDirectory) {
  3121. // fs.mkdirSync(dest, { recursive : true });
  3122. // return dirs( function(childItemName) {
  3123. // return copyrecursive(path.join(src, childItemName.name),
  3124. // path.join(dest, childItemName.name));
  3125. // }, src )
  3126. // } else {
  3127. // fs.copyFileSync(src, dest);
  3128. // }
  3129. };
  3130. // var renamerecursive = function(from, to){
  3131. // var exists = fs.existsSync(from);
  3132. // var stats = exists && fs.statSync(from);
  3133. // var isDirectory = exists && stats.isDirectory();
  3134. // if (isDirectory) {
  3135. // fs.mkdirSync(to);
  3136. // dirs( function(childItemName) {
  3137. // renamerecursive(path.join(from, childItemName),
  3138. // path.join(to, childItemName));
  3139. // }, from )
  3140. // // fs.readdirSync(from).forEach(function(childItemName) {
  3141. // // copyrecursive(path.join(from, childItemName),
  3142. // // path.join(to, childItemName));
  3143. // // });
  3144. // } else {
  3145. // fsrename(from, to);
  3146. // }
  3147. // }
  3148. // filesystem walk
  3149. const fswalk = async (pathToWalk, options, actions) => {
  3150. // options = options || { depthfirst : true }
  3151. if(!options.innernode) {
  3152. var exists = fs.existsSync(pathToWalk);
  3153. var stats = exists && fs.statSync(pathToWalk);
  3154. var isDirectory = exists && stats.isDirectory();
  3155. }
  3156. else {
  3157. var isDirectory = options.innernode.isDirectory()
  3158. }
  3159. if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  3160. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
  3161. var rs = [];
  3162. for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
  3163. rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
  3164. // .then(()=>{
  3165. // return any(actions.map( a => ()=>a(innernode, { isDirectory : true}) ))
  3166. // })
  3167. )
  3168. }
  3169. // Wait for the walk to complete before renaming directories.
  3170. Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  3171. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ))
  3172. return any(rs)
  3173. }
  3174. var fsrecurse = function(target, options, actions, root) {
  3175. var exists = fs.existsSync(target);
  3176. var stats = exists && fs.statSync(target);
  3177. var isDirectory = exists && stats.isDirectory();
  3178. if (isDirectory) {
  3179. var tasks = []
  3180. tasks.push( dirs( function(childItemName) {
  3181. return fsrecurse(path.join(target, childItemName.name)
  3182. , options, actions, root);
  3183. }, target ))
  3184. return any(tasks)
  3185. } else {
  3186. var prevActionResult = null;
  3187. return any( actions.map( (action) => prevActionResult = action.apply(null, target, options) ))
  3188. }
  3189. };
  3190. // var fslink = function(to, options){ try { fs.linkSync( to, options.from ) } catch(e) { throw e } }
  3191. var fslink = function(to, options){ fs.symlinkSync( to, options.from /*, type = "junction"*/ ) }
  3192. var fsrename = function(target, options){
  3193. // PB : TODO -- streaming and async.. target could be a stream a string or a filesystem item or a tree node...
  3194. var targetname = options.innernode?.name || path.parse(target).base;
  3195. var replaced = targetname;
  3196. options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ) })
  3197. if(replaced && replaced !== targetname) {
  3198. var tr = target.replace( targetname, replaced )
  3199. fs.renameSync(target, tr)
  3200. return tr;
  3201. }
  3202. else return replaced
  3203. }
  3204. var fscontentreplace = function( target, options ){
  3205. // do many replacements in one shot in the file.
  3206. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
  3207. var content = fs.readFileSync(target, { encoding: 'utf8' }) // PB : TODO -- streaming and async..
  3208. options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ) })
  3209. fs.writeFileSync(target, content)
  3210. }
  3211. }
  3212. var templatelink = function(target, options){
  3213. var targetSubPath = target.replace(options.workingtarget + '/', '' );
  3214. var targetSubPathsplit = targetSubPath.split("/")
  3215. var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`
  3216. var linkToSubPathReplacement = `${options.base}-server-lib/common`
  3217. // var rgxp = new RegExp(`(__link__)${options.base}-server-lib`, "g")
  3218. var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g")
  3219. var linkToSubPath = targetSubPath
  3220. var b = target.match(rgxp)
  3221. var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } )
  3222. linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot)
  3223. if( b ) {
  3224. // Only if the pattern matches which is link instruction.
  3225. linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } )
  3226. }
  3227. options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ) })
  3228. var linkToName = `${options.destinationroot}/${linkToSubPath}`
  3229. if(b){
  3230. linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement)
  3231. // PB : DONT DELETE EVERYTHING ??? Only the linkable ones... Or use an add strategy without deleting...
  3232. fs.unlinkSync( target );
  3233. fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } )
  3234. }
  3235. else {
  3236. fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName )
  3237. // fsMove( `${options.workingtarget}/${linkToSubPath}`, linkFromName )
  3238. }
  3239. }
  3240. // Source and Target are files or folders. We need another version or a unifed version for strings..
  3241. var processpatterns = function(target, options){
  3242. // Accept a set of patterns and substitutions and operate on a target and apply all patterns substitutions.
  3243. // options = options || { targettype : 'inplace', sourcetype : 'filesystem' }
  3244. // options.source, options.target sourcetype = 'string' | 'filesystem' options.targettype = 'inplace' | 'copy'
  3245. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' ) {
  3246. options.patternsubstitutions.forEach( ps => {
  3247. // var replacement = regexreplaceall( from, ps.strOrregexp, ps.substitutes )
  3248. // if(targetname) { // Porcess all files. Even if file names dont have patterns the content needs to be replaced.
  3249. return options.tasks.map( t => { return t( target, ps ) } )
  3250. // }
  3251. // return str.replace(regex, function(match, key) {
  3252. // console.log(`Found match, group ${match}: ${key}`);
  3253. // return substitutes[key] || match;
  3254. // })
  3255. })
  3256. }
  3257. // while ((m = regex.exec(str)) !== null) {
  3258. // // This is necessary to avoid infinite loops with zero-width matches
  3259. // if (m.index === regex.lastIndex) {
  3260. // regex.lastIndex++;
  3261. // }
  3262. // var rstr = str;
  3263. // // The result can be accessed through the `m`-variable.
  3264. // m.forEach((match, groupIndex) => {
  3265. // // rstr = rstr.replace( groupIndex
  3266. // console.log(`Found match, group ${groupIndex}: ${match}`);
  3267. // if(groupIndex === 0) return
  3268. // });
  3269. // }
  3270. }
  3271. function copyFileSync( source, target , options) {
  3272. var targetFile = target;
  3273. // If target is a directory, a new file with the same name will be created
  3274. if ( fs.existsSync( target ) ) {
  3275. if ( fs.lstatSync( target ).isDirectory() ) {
  3276. targetFile = path.join( target, path.basename( source ) );
  3277. }
  3278. }
  3279. fs.writeFileSync(targetFile, fs.readFileSync(source));
  3280. }
  3281. function copyFolderRecursiveSync( source, target, options ) {
  3282. var files = [];
  3283. // Check if folder needs to be created or integrated
  3284. var targetFolder = path.join( target, path.basename( source ) );
  3285. if ( !fs.existsSync( targetFolder ) ) {
  3286. fs.mkdirSync( targetFolder );
  3287. }
  3288. // Copy
  3289. if ( fs.lstatSync( source ).isDirectory() ) {
  3290. files = fs.readdirSync( source );
  3291. files.forEach( function ( file ) {
  3292. var curSource = path.join( source, file );
  3293. if ( fs.lstatSync( curSource ).isDirectory() ) {
  3294. copyFolderRecursiveSync( curSource, targetFolder );
  3295. } else {
  3296. copyFileSync( curSource, targetFolder );
  3297. }
  3298. } );
  3299. }
  3300. }
  3301. var getShellTask = (command, args, options) => {
  3302. options = options || {}
  3303. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  3304. return () => {
  3305. var p = callshell( [command, args, Object.assign({
  3306. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  3307. }, options)
  3308. ])()
  3309. if (options.ignorefailures) {
  3310. return p.catch(e => {
  3311. // Ignore. Not a major error.
  3312. })
  3313. }
  3314. else return p;
  3315. }
  3316. }
  3317. var callshelltask = (args) => {
  3318. // console.dir(args)
  3319. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  3320. return args;
  3321. }
  3322. return getshelltask(args)()
  3323. }
  3324. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  3325. var getshelltask = (args) => {
  3326. return args[0] === 'rm' ? getgitbashtask(args) : () => {
  3327. return nodeShellExec.apply(null, args).catch(function(e){
  3328. e.benign = args[2].benign;
  3329. if(!e.benign) { console.error(e); }
  3330. throw e
  3331. })
  3332. }
  3333. }
  3334. var getgitbashtask = (args, onEachError) => { return () => {
  3335. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  3336. }
  3337. var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }}
  3338. var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) }
  3339. var getTaskCheckExists = shell_verse.getTaskCheckExists
  3340. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  3341. // var getTaskWithoutElevation = function(tasdef){
  3342. // return ()=>{
  3343. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  3344. // else Promise.resolve(true)
  3345. // }
  3346. // }
  3347. var gitops = {
  3348. getdiscoverbranchcmd : function(repo){
  3349. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3350. var cmd = [gitbash
  3351. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3352. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  3353. return cmd
  3354. }
  3355. }
  3356. var getPullCmd = (repodef, branch) => {
  3357. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  3358. // console.log(useGitPull)
  3359. var repo = repodef.repo
  3360. var pullCmd = []
  3361. if(!branch) {
  3362. // console.warn('No branch was specified detecting from working client.')
  3363. // First check if working client exists.
  3364. // if (existsSync(instanceroot + '/' + repo)) {
  3365. pullCmd= gitops.getdiscoverbranchcmd(repo)
  3366. // }
  3367. // else performpull
  3368. }
  3369. // var pullCmd = [gitInstallDir
  3370. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3371. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  3372. if(branch) {
  3373. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3374. var pullCmd = [ gitbash
  3375. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3376. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3377. }
  3378. // var pullCmd = ['pullall', [], { cwd : repo }]
  3379. if (useGitPull) pullCmd = ['git', ['pull'], {
  3380. inherit: true, shell: true,
  3381. cwd: instanceroot + '/' + repo
  3382. // , env: ENV
  3383. , runas: processedArgs.runas
  3384. , title: `git pull ${repo}`
  3385. }]
  3386. return pullCmd
  3387. }
  3388. // PB : TODO -- Use queueing with async tasks..
  3389. var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  3390. var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
  3391. var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch)
  3392. // var waitForBatchAdditions = function(){
  3393. // return pT;
  3394. // }
  3395. // Execute is implied.
  3396. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  3397. // else
  3398. return pT() // Execute it.
  3399. }
  3400. var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  3401. // PB : TODO -- Handle no branch passed in case.
  3402. // if(!branch) { throw 'No branch specified' }
  3403. var repo = repodef.repo;
  3404. elevatedBatch = elevatedBatch || [];
  3405. regularBatch = regularBatch || [];
  3406. try{
  3407. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  3408. // This remote repo and branch may have been or may need to be added as a local tracking branch
  3409. // to any other local repo folder (with a different name)
  3410. var exists = existsSync(instanceroot + '/' + repo)
  3411. }
  3412. catch(e){
  3413. exists = false
  3414. console.log(e)
  3415. }
  3416. function initTask(etask){
  3417. etask.info = { repo }
  3418. etask.errHandler = errHandler
  3419. etask.statuslog = statuslog
  3420. etask.processedArgs = processedArgs
  3421. etask.selectedinstance = selectedinstance
  3422. etask.runtimestamp = runtimestamp
  3423. etask.ENV = ENV
  3424. }
  3425. function initElevatedBatch(){
  3426. elevatedBatch.info = { repo }
  3427. elevatedBatch.errHandler = errHandler
  3428. elevatedBatch.statuslog = statuslog
  3429. elevatedBatch.processedArgs = processedArgs
  3430. elevatedBatch.selectedinstance = selectedinstance
  3431. elevatedBatch.runtimestamp = runtimestamp
  3432. elevatedBatch.ENV = ENV
  3433. }
  3434. if (exists) {
  3435. var tasks = [];
  3436. return (()=>{
  3437. // PB : TODO -- We need a non cacheable set of properties that need to default to something but then need to escplicitly specified in each run.
  3438. if(selectedinstance.addremotes) {
  3439. return op['get-remotes']({repo}).then(( remotes )=>{
  3440. return op['get-upstream']({repo, remotes}).then(( upstream ) => {
  3441. return __addremotesandpull({ upstream, remotes})
  3442. })
  3443. })
  3444. }
  3445. else return __pull();
  3446. })()
  3447. function __pull(){
  3448. var branchprint = branch ? ' branch :' + branch : '';
  3449. var task = ()=>{
  3450. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  3451. return any(tasks).then( ()=>{
  3452. return nodeShellExec.apply(null, getPullCmd(repodef, branch)).then(() => {
  3453. return true;
  3454. })
  3455. })
  3456. }
  3457. initTask(task)
  3458. if(repodef.requiresElevation) {
  3459. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3460. if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]) } // PB : TDOO -- Make sure first task also has run context. May need to be moved to win_verse
  3461. else initTask(elevatedBatch[elevatedBatch.length-1])
  3462. return elevatedBatch[elevatedBatch.length-1]
  3463. }
  3464. else {
  3465. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3466. return regularBatch[regularBatch.length-1]
  3467. }
  3468. }
  3469. function __addremotesandpull(options){
  3470. // Add the remotes
  3471. var tasks = []
  3472. // selectedinstance.selectedremotes are optional and need not be enforced to be chosen. The selection for hte selected remotes
  3473. // could also be derived from a crossfilter of remote-type selected for this run and the current chosen and operating reposervers.
  3474. var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
  3475. if(selectedremotes.length > 0) var selectedremoteFilter = function(rs) { return selectedremotes.find( rs.server ) }
  3476. else var selectedremoteFilter = function(){ return true }
  3477. var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
  3478. // We need a most permissive filtered list to use as an efficient starting point to further reduce to whats actually needed.
  3479. // However if such a cached list is not available we need to build it by scaning and apply all the filters anyway on the whole world.
  3480. Object.keys(repoRemotes).forEach((remotename)=>{
  3481. // PB : TODO -- ai prefix for all apis that require an answer amongst many choices.
  3482. var ai_RemoteAddNeeded = (r)=>{
  3483. if(r.server === reposerver && selectedremoteFilter() && r.accessibility.find( selectedinstance[ 'remote-type' ] )){ // currently chosen remotetype...
  3484. var exists = false;
  3485. if(exists = (options.remotes[r.remotename] || Object.keys(options.remotes).find( lrn => {
  3486. var exists = options.remotes[lrn].server === r.server && !options.remotes[r.remotename]
  3487. if(exists) console.warn('Found duplicate remote with a different name for the same server...')
  3488. return exists
  3489. } )) ) {
  3490. return false // Already a remote not required.
  3491. }
  3492. return true // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3493. }
  3494. return false
  3495. };
  3496. tasks.push(
  3497. ()=>{
  3498. return op['remote exists']({
  3499. remotename, repo, benign : true, ignorefailures : true
  3500. , url : repoRemotes[remotename].url + repo
  3501. , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3502. }).then( (r) => {
  3503. if(!r[1]) return false; // PB : TODO -- Not accessible skip for now probably should remove.
  3504. else if(r[0]) return true; // Already added nothing to do
  3505. else if(ai_RemoteAddNeeded( repoRemotes[remotename] )) return op['remote add']( { remotename,
  3506. 'set-upstream' : (selectedinstance['upstream'] || `${remotename}/${branch}`) // ??? when url accessible... in order of highest priority
  3507. , reponame : repo
  3508. , url : repoRemotes[remotename].url , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3509. })
  3510. // else skipped as remote is not relevant for this repo...
  3511. })
  3512. }
  3513. )
  3514. })
  3515. __pull()
  3516. }
  3517. }
  3518. else {
  3519. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  3520. console.log('cloning ' + repo)
  3521. // PB : TODO -- add additional remotes after cloning and pull again...
  3522. var task = ()=>{
  3523. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repodef.owner || repoowner || defaultRepoOwner}/` + repo + '.git'],
  3524. {
  3525. inherit: true, shell: true,
  3526. env: ENV
  3527. , cwd : instanceroot
  3528. , runas: processedArgs.runas
  3529. }).then(() => {
  3530. var task = ()=>{
  3531. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  3532. {
  3533. inherit: true, shell: true,
  3534. env: ENV
  3535. , cwd: instanceroot + '/' + repo
  3536. , runas: processedArgs.runas
  3537. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  3538. })
  3539. }
  3540. initTask(task)
  3541. if(repodef.requiresElevation) {
  3542. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3543. return elevatedBatch[elevatedBatch.length-1]
  3544. }
  3545. else {
  3546. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3547. return regularBatch[regularBatch.length-1]
  3548. }
  3549. })
  3550. }
  3551. initTask(task)
  3552. if(repodef.requiresElevation) {
  3553. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3554. return elevatedBatch[elevatedBatch.length-1]
  3555. }
  3556. else {
  3557. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3558. return regularBatch[regularBatch.length-1]
  3559. }
  3560. }
  3561. }
  3562. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  3563. var defaultRepoOwner = 'chess';
  3564. var elevatedRunasRepos = null
  3565. var gitRepos = null
  3566. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  3567. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  3568. var dbForLabel = function (label) {
  3569. var dbsForLabel = {
  3570. devmysql: 'mysql'
  3571. , development: 'mssql'
  3572. , production: 'mssql'
  3573. }
  3574. return dbsForLabel[label] || 'mysql'
  3575. }
  3576. // Maps an environment to a branch. Not required if the branch is appropriately named.
  3577. var checkoutMap = { 'development': 'master' }
  3578. // SAM : TODO Use nodeshellexec where to detect git installation dir
  3579. var gitbash = shell_verse.getbash()
  3580. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  3581. // Relevant git repos
  3582. var exludeMergeRepos = [];
  3583. var useGitPull = processedArgs.useGitPull || false;
  3584. var configPromise = null
  3585. var reconfirmcmds = { create : true }
  3586. var subcommandlabels = {
  3587. switch : (`switch ${processedArgs._[1] || ''}`).trim()
  3588. }
  3589. var independentcmd = function(){
  3590. return false;
  3591. }
  3592. var util = require('util');
  3593. var cliname = 'elxr';
  3594. var ver = '1.1';
  3595. var readme = `
  3596. Command syntax examples
  3597. elxr
  3598. Displays help. Same as elxr h
  3599. elxr i
  3600. Runs interactive propmts to help choose installation options.
  3601. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  3602. General command syntax.
  3603. Eg: NODE_ENV=development elxr pull elixir
  3604. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  3605. The specific cmd defines what the value is interpreted as.
  3606. There are several cmds that do not require an {{instancename}} parameter.
  3607. Eg: elxr remote remove origin
  3608. Git operations or passthrough external commands on all repository folders in you working directory.
  3609. Main objectives.
  3610. elxr cli is a wrapper around other shell commands and api based operations.
  3611. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  3612. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  3613. `;
  3614. var help = `
  3615. ${readme}
  3616. # list of commands... please refer dveloper documentation for ${cliname}
  3617. \r\n\t${
  3618. Object.keys(op).join('\r\n\t')
  3619. }
  3620. `;
  3621. var elxr = {
  3622. help() {
  3623. return chalk.cyanBright(`
  3624. -------------------------------------------------------------------------------
  3625. *** BBH Elixir ***
  3626. -------------------------------------------------------------------------------
  3627. elxr ${ver}
  3628. A cli tool for chess
  3629. ${help}
  3630. -------------------------------------------------------------------------------
  3631. `)
  3632. }
  3633. , info() {
  3634. return chalk.cyanBright(`
  3635. -------------------------------------------------------------------------------
  3636. *** BBH Elixir ***
  3637. -------------------------------------------------------------------------------
  3638. elxr ${ver}
  3639. A cli tool for chess
  3640. -------------------------------------------------------------------------------
  3641. `)
  3642. }
  3643. , getpulltask(args){
  3644. // def can be an instance config
  3645. // Or an object with many repos and elevated repos
  3646. // Or a single repo ( Either Elevated or normal. )
  3647. // USAGE
  3648. // elxr pull elixir origin master
  3649. // elxr pull
  3650. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  3651. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  3652. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  3653. // The branch pipline should feed back to master
  3654. // master -> test -> stage -> release[nnnn] -> production
  3655. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  3656. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  3657. var __args = {
  3658. remotename : args.remotename|| processedArgs._[2]
  3659. , url : args.url || processedArgs._[3]
  3660. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  3661. }
  3662. // var commands = [
  3663. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  3664. // ,
  3665. // ]
  3666. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3667. // var pullCmd = [ gitbash
  3668. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3669. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3670. var def = args || {
  3671. repos : selectedinstance.repos,
  3672. elevated : selectedinstance.elevated
  3673. }
  3674. var elevatedpulltasks = null;
  3675. if(def.repo) {
  3676. // Single repo case.
  3677. if(def.repo.requiresElevation) {
  3678. var t1 = function() {
  3679. return performPull(def).then(() => {
  3680. return true;
  3681. }).catch((e) => {
  3682. console.error(e)
  3683. }).finally(Traq.finally)
  3684. }
  3685. t1.statuslog = statuslog
  3686. t1.selectedinstance = selectedinstance
  3687. t1.processedArgs = processedArgs
  3688. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  3689. }
  3690. else {
  3691. var t2 = function(){
  3692. return performPull(def).then(() => {
  3693. console.log('pulled ' + JSON.stringify(def.repo))
  3694. return true;
  3695. }).catch((e) => {
  3696. console.error(e)
  3697. })
  3698. // .finally(Traq.finally)
  3699. }
  3700. t2.statuslog = statuslog
  3701. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  3702. }
  3703. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3704. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  3705. }
  3706. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  3707. console.dir(def)
  3708. console.log('Running exlr pull : ' + path.dirname(__dirname))
  3709. var useGitPull = processedArgs.useGitPull || false;
  3710. if(def.elevated || def.repos) {
  3711. if(def.elevated) def.requiresElevation = true;
  3712. else delete def.requiresElevation;
  3713. }
  3714. else {
  3715. if(def.requiresElevation) def.elevated = [def]
  3716. else def.repos = [def]
  3717. }
  3718. var regularpulltasks = function(){ return Promise.resolve(true) }
  3719. if(def.elevated){
  3720. elevatedpulltasks = function() {
  3721. var eBatch = []
  3722. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch))
  3723. if(eBatch.length<1) return Promise.resolve(true);
  3724. eBatch[0].processedArgs = processedArgs
  3725. return shell_verse.runElevatedBatch(eBatch).then(() => {
  3726. return true;
  3727. }).catch((e) => {
  3728. console.error(e)
  3729. })
  3730. }
  3731. elevatedpulltasks.statuslog = statuslog
  3732. }
  3733. if(def.repos) {
  3734. var regularpulltasks = function(){
  3735. var pendingpulls = [];
  3736. def.repos.forEach((def) => {
  3737. pendingpulls.push(
  3738. // PB : TODO serializing to prevent out of memory.
  3739. // Need to optimize as batches and streams...
  3740. function(){
  3741. // if(def.repo === 'setup') return;
  3742. // if(def.repo !== 'chess-client-lib') return;
  3743. return performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  3744. .catch(e => {
  3745. console.error(util.inspect(e)); throw e })
  3746. }
  3747. )
  3748. })
  3749. return any(pendingpulls).finally(Traq.finally)
  3750. }
  3751. regularpulltasks.statuslog = statuslog
  3752. }
  3753. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3754. // else return getTaskWithoutElevation({ regularpulltasks})
  3755. return elevatedpulltasks().then(()=>{
  3756. if(isWin() && isElevated) return Promise.resolve(true);
  3757. return regularpulltasks()
  3758. })
  3759. }
  3760. }
  3761. function preworkerconfig(){
  3762. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  3763. gitRepos = selectedinstance.repos
  3764. // gitRepos = ['chess-server-lib'];
  3765. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  3766. elevatedRunasRepos = selectedinstance.elevated
  3767. // Repos that should excluded from merge for releases...
  3768. exludeMergeRepos = selectedinstance.exludeMergeRepos
  3769. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  3770. // mysql -u root -p db_name < drop_all_tables.sql
  3771. var mysql = '../xampp/mysql/bin/mysql'
  3772. var mysqldump = '../xampp/mysql/bin/mysqldump'
  3773. }
  3774. // The main elxr cli process
  3775. function elxrworker() {
  3776. var __runcmd = function (label) {
  3777. var distinquishedlabel = subcommandlabels[label] || label
  3778. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  3779. }
  3780. return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  3781. }
  3782. // function acquireChoices(selectedinstance) {
  3783. // var hasconfig = false;
  3784. // console.warn(chalk.cyan(`
  3785. // -------------------------------------------------------------------------------
  3786. // Could not locate your preferred configuration (you may not specified it)
  3787. // You should fork the default chess configuration to customize and make it
  3788. // your own instance with a named config as
  3789. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  3790. // And then run this tool as follows
  3791. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  3792. // OR
  3793. // Run this tool with the following command to use a quick start default.
  3794. // elxr --default
  3795. // OR
  3796. // Choose one of the options below to run interactively.
  3797. // We will run your choice at the next prompt.
  3798. // -------------------------------------------------------------------------------
  3799. // `))
  3800. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  3801. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  3802. // return initinstances(selectedinstance)
  3803. // })
  3804. // // var prompt = cli.prompter;
  3805. // // return prompt.ask(`Choose an option :
  3806. // // d) Install the default chess instance.
  3807. // // => elxr i chess node_env=development --default
  3808. // // n) Create your custom new instance interactively
  3809. // // => elxr i {{instanceName}} node_env={{environment}}
  3810. // // i) Choose an instance and environment to install
  3811. // // => elxr i {{instanceName}} node_env={{environment}}
  3812. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3813. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3814. // // h) Help
  3815. // // q) Quit
  3816. // // Default <= d
  3817. // // : `).then((choice) => {
  3818. // // if (choice && choice === 'd' || !choice) {
  3819. // // processedArgs._[0] = 'i'
  3820. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3821. // // selectedinstance.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3822. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3823. // // }
  3824. // // else if (choice === 'h') {
  3825. // // processedArgs._[0] = 'h'
  3826. // // fs.writeFileSync('run.done', 'noop help');
  3827. // // console.log(elxr.help()); process.exit()
  3828. // // }
  3829. // // else if (choice === 'n' || choice === 'i') {
  3830. // // var p1 = cli.prompter;
  3831. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3832. // // processedArgs._[0] = 'i'
  3833. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  3834. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3835. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3836. // // if (choice === 'n') {
  3837. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3838. // // console.warn(
  3839. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  3840. // // process.exit();
  3841. // // }
  3842. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3843. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3844. // // })
  3845. // // })
  3846. // // })
  3847. // // } else if (choice === 'c') {
  3848. // // var p1 = cli.prompter;
  3849. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3850. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  3851. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3852. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3853. // // return p1.ask(`Enter cmd :
  3854. // // p) pull
  3855. // // Default <= p
  3856. // // : `).then(function (cmd) {
  3857. // // if (!cmd || cmd === 'p') {
  3858. // // processedArgs._[0] = 'pull'
  3859. // // }
  3860. // // else processedArgs._[0] = cmd
  3861. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3862. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3863. // // })
  3864. // // })
  3865. // // })
  3866. // // })
  3867. // // } else {
  3868. // // 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.`));
  3869. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  3870. // // fs.writeFileSync('run.done', 'noop quit');
  3871. // // process.exit()
  3872. // // }
  3873. // // })
  3874. // }
  3875. var os = require("os");
  3876. var hostname = os.hostname();
  3877. var clustername = null; // PB : TODO -- Prompt to acquire.
  3878. var configs = (function(){
  3879. // We need to discover and use the most specialized config available.
  3880. // Two passes are required as the config currently cloned may be switched by the discovery.
  3881. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  3882. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  3883. return {
  3884. ownerClusterNodeConfig(selected) {
  3885. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  3886. // Also many cluster node instance can be running as a set of services on the same host on the same port with ( specific domain names )
  3887. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3888. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3889. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  3890. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  3891. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  3892. e.benign = true
  3893. return e; }
  3894. )
  3895. }
  3896. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  3897. , selected.instanceName + '-config-' + selected.node_env
  3898. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  3899. e.benign = true
  3900. return e }
  3901. )
  3902. }
  3903. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3904. , commonInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }
  3905. , undefined
  3906. , function(e){
  3907. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  3908. statuslog.statuslog(e, e)
  3909. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  3910. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  3911. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  3912. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  3913. console.dir(selectedinstance.repos)
  3914. // Config from server always override merges into selection except for the current selection.
  3915. // PB : TODO -- utils.assign Array merges are non-distinct...
  3916. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  3917. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3918. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3919. }
  3920. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  3921. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3922. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3923. }
  3924. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3925. , selected, selectedinstance)
  3926. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  3927. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3928. cacheWriteInstanceConfig(chessinstances, selectedinstance.root, selectedinstance)
  3929. // ENV.NODE_ENV = selectedinstance.node_env;
  3930. throw e
  3931. }
  3932. ) }
  3933. // , genericChessInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }) }
  3934. }
  3935. })()
  3936. var eNotImplemented = function(){
  3937. console.error('Not yet implemented')
  3938. process.exit()
  3939. }
  3940. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  3941. var acquireConfig = function(slections){
  3942. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3943. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  3944. return acquireData(slections)
  3945. })
  3946. }
  3947. var instanceData = (function(){
  3948. return {
  3949. ownerClusterNodeData(selected) {
  3950. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3951. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3952. return __acquireData(selected, { remote : 'userfork' }
  3953. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  3954. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  3955. e.benign = true
  3956. return e; }
  3957. )
  3958. }
  3959. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  3960. , selected.instanceName + '-data-' + selected.node_env
  3961. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  3962. e.benign = true
  3963. return e }
  3964. )
  3965. }
  3966. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3967. , commonInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }
  3968. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  3969. ) }
  3970. , genericChessInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }) }
  3971. }
  3972. })()
  3973. var acquireData = function(slections){
  3974. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3975. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  3976. }
  3977. function reinit(){
  3978. sysAddPathVar('%AppData%\\npm')
  3979. resetgitconfig()
  3980. }
  3981. function init(){
  3982. sysAddPathVar('%AppData%\\npm')
  3983. resetgitconfig()
  3984. }
  3985. function resetgitconfig(){
  3986. // https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  3987. // use git config --edit --system to remove the helper = manager line so that it is no longer registered as a credential helper.
  3988. // For bonus points, use git config --edit --global and insert:
  3989. // [core]
  3990. // askpass =
  3991. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  3992. // Git Credential storage...
  3993. // git config --global credential.helper 'store --file ~/.elxrcredentials'
  3994. // git credential fill
  3995. // protocol=https
  3996. // host=git.bbh.org.in
  3997. // username=bob
  3998. // password=pppp
  3999. // git credential-store --file ~/.gitcredentials store
  4000. // // notepad C:/Program Files/Git/etc/gitconfig
  4001. // git config --edit --system
  4002. // git credential-store --file ~/git.store store
  4003. // Find system git config
  4004. // git config --global --edit
  4005. // git config --list --show-origin
  4006. // git config --list --show-origin --show-scope
  4007. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  4008. // Recipie
  4009. // git config --global --unset credentials.helper
  4010. // cd /path/to/my/repo
  4011. // git config --unset credential.helper
  4012. // git config credential.helper 'store --file ~/.git_repo_credentials'
  4013. // git config credential.*.username my_user_name
  4014. // git config credential.https://gitlab.com.username my_user_name
  4015. // git credential fill
  4016. // git config --global credential.modalprompt false // doesnst work.
  4017. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  4018. var options = {
  4019. inherit: true, shell: true, env: ENV
  4020. , cwd: instanceroot
  4021. , runas: processedArgs.runas
  4022. }
  4023. var task = ['git', ['config'], options]
  4024. var tasklist = [
  4025. // ['--global', '--unset credentials.helper']
  4026. // ['--unset', 'credentials.helper']
  4027. // ,
  4028. // ['credential.helper', `'store --file git_repo_credentials'`]
  4029. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  4030. , ['--global', '--replace-all', 'user.name', 'pb']
  4031. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  4032. // , ['--list']
  4033. // , ['credential', 'fill']
  4034. ]
  4035. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  4036. var shellT = (args) => { return getgitbashtask(args, onEachError)
  4037. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  4038. }
  4039. execserial(tasklist, task, shellT, onEachError )
  4040. }
  4041. var createTasq = (args, shellT, onEachError) => {
  4042. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  4043. tasq.toString = function(){ return JSON.stringify(args)}
  4044. return tasq;
  4045. }
  4046. var execserial = function(tasklist, task, shellT){
  4047. var exec = (taskArgs)=>{
  4048. var thistask = task.concat();
  4049. thistask[1] = thistask[1].concat()
  4050. thistask[1].push.apply(thistask[1], taskArgs)
  4051. return createTasq(thistask, shellT)
  4052. }
  4053. return any(tasklist.map(exec))
  4054. }
  4055. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  4056. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  4057. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  4058. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  4059. var errorHandler = (e) => {
  4060. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  4061. // console.error('Could not connect to repo server. Timed Out')
  4062. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  4063. if(propValue === 'y') {
  4064. reconfirm = getReconfirmAll()
  4065. return startElxr()
  4066. }
  4067. else if(propValue === 'r'){
  4068. return acquireConfig(selected)
  4069. }
  4070. else process.exit()
  4071. })
  4072. }
  4073. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/' not found`))){
  4074. var choices = {
  4075. t : `install a new temporary local instance with this name ( will not persist ).
  4076. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  4077. , e : 'exit' }
  4078. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  4079. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4080. , {
  4081. i : 'create a new instance with this name => will fork the default config under your username'
  4082. , f : 'fork a new instance with this name for yourself for this node from another instance'
  4083. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  4084. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  4085. , p : 'create a custom config for yourself '
  4086. }, choices)
  4087. }
  4088. return cli.prompt( choices
  4089. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  4090. if(propValue === 't') {
  4091. selectedinstance.local = true; return createInstance(selectedinstance)
  4092. }
  4093. if(propValue === 'i') return eNotImplemented()
  4094. if(propValue === 'f') return eNotImplemented()
  4095. if(propValue === 'o') return eNotImplemented()
  4096. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4097. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4098. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4099. else process.exit()
  4100. })
  4101. }
  4102. console.warn(e)
  4103. throw e; //('Config acquisition failed.')
  4104. }
  4105. var successHandler = () => {
  4106. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  4107. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  4108. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4109. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }))
  4110. console.dir(selectedinstance.repos)
  4111. // Config from server always override merges into selection except for the current selection.
  4112. // PB : TODO -- utils.assign Array merges are non-distinct...
  4113. if(!selectedinstance.repos[0].repo) {
  4114. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4115. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4116. }
  4117. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  4118. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4119. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4120. }
  4121. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4122. , selected, selectedinstance)
  4123. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  4124. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4125. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4126. ENV.NODE_ENV = selectedinstance.node_env;
  4127. }
  4128. return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
  4129. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4130. .catch( (e)=>{
  4131. // if(e){
  4132. if(Promise.resolve(e) === e) return e;
  4133. // console.error(e)
  4134. e.benign = true;
  4135. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  4136. // }
  4137. })
  4138. }
  4139. var __acquireData = function (selected, options, datarepo, errHandler) {
  4140. datarepo = datarepo || selected.instanceName + '-data';
  4141. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  4142. var errorHandler = (e) => {
  4143. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  4144. // console.error('Could not connect to repo server. Timed Out')
  4145. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  4146. if(propValue === 'y') {
  4147. reconfirm = getReconfirmAll()
  4148. return startElxr()
  4149. }
  4150. else if(propValue === 'r'){
  4151. return acquireConfig(selected)
  4152. }
  4153. else process.exit()
  4154. })
  4155. }
  4156. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/' not found`))){
  4157. var choices = {
  4158. t : `install a temporary local data folder.
  4159. For more options. Request and use a personal username at chess@bbh.org.in )`
  4160. , e : 'exit' }
  4161. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  4162. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4163. , {
  4164. i : 'create a new instance with this name => will fork the default config under your username'
  4165. , f : 'fork a new instance with this name for yourself for this node from another instance'
  4166. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  4167. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  4168. , p : 'create a custom config for yourself '
  4169. }, choices)
  4170. }
  4171. return cli.prompt( choices
  4172. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  4173. if(propValue === 't') {
  4174. selectedinstance.local = true; return createInstanceData(selectedinstance)
  4175. }
  4176. if(propValue === 'i') return eNotImplemented()
  4177. if(propValue === 'f') return eNotImplemented()
  4178. if(propValue === 'o') return eNotImplemented()
  4179. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4180. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4181. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4182. else process.exit()
  4183. })
  4184. }
  4185. console.warn(e)
  4186. throw e; //('Config acquisition failed.')
  4187. }
  4188. var successHandler = () => {
  4189. }
  4190. return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
  4191. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4192. .catch( (e)=>{
  4193. // if(e){
  4194. if(Promise.resolve(e) === e) return e;
  4195. // console.error(e)
  4196. e.benign = true;
  4197. throw e; // Not a hard error but we need this for bcontinueonfailure
  4198. // }
  4199. })
  4200. }
  4201. // ----------------------------------------------------------------
  4202. // PB : TODO -- Review and obsolete...
  4203. // ----------------------------------------------------------------
  4204. // var launchpath = path.resolve(path.normalize(ENV.wd))
  4205. var launchpath = selectedinstance.root
  4206. // // we were run.
  4207. // // The easisest would be to ask for a target directory and default to current dir....
  4208. // // path.dirname(launchpath).split(path.sep).pop()
  4209. // var parent = path.dirname(launchpath);
  4210. // var pp = launchpath;
  4211. // var instancediscoverytasks = [];
  4212. // while(parent !== pp){
  4213. // instancediscoverytasks.push(
  4214. // ((pa)=>{
  4215. // var p = pa;
  4216. // return function(){
  4217. // return hasElxr(p).then((value)=>{
  4218. // if(value) return p
  4219. // // PB : TODO -- Using throw like this is not friendly with any...
  4220. // throw Object.assign( new Error('Benign Failure in Batch')
  4221. // , { value : false, benign : true });
  4222. // })
  4223. // }
  4224. // })(pp)
  4225. // )
  4226. // pp = parent;
  4227. // parent = path.dirname(parent);
  4228. // }
  4229. // var instanceroot = null
  4230. // var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  4231. // if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  4232. // else instanceroot = ir.pVal
  4233. // return instanceroot
  4234. // }).catch(()=>{
  4235. // instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  4236. // })
  4237. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  4238. // Then acquire and reload and replace this default.
  4239. var __interactive_prompts = function( target, choices, promptsfilter ){
  4240. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  4241. var interactionpoints = unbound_interactionpoints.bind({target, choices})(selectedinstance)
  4242. function getPromptKeys() {
  4243. // PB : TODO -- get interactionpoints
  4244. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  4245. return promptkeys // PB : TODO __ Convert pormptkeys to filtered interactionpoints.
  4246. }
  4247. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  4248. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  4249. }
  4250. var downloadsdir = shell_verse.downloadsdir;
  4251. var prerequisites = [
  4252. {
  4253. shellcmd: 'git',
  4254. name : 'git',
  4255. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  4256. , installer: 'Git-2.31.0-64-bit.exe'
  4257. , installcmd: ['cmd', ['/c', 'start',
  4258. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  4259. , '/VERYSILENT'
  4260. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  4261. ]]
  4262. , preinstallsteps: function() {
  4263. var steps = [
  4264. () => {
  4265. if (!existsSync(downloadsdir + '/' + this.installer)) {
  4266. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  4267. }
  4268. else return Promise.resolve(true)
  4269. }
  4270. ]
  4271. var prompts = this.getuser(null, ()=>{
  4272. // console.log('preinstallsteps')
  4273. // var gitUser = 'guest';
  4274. // var gitEmail = 'guest@bbh.org.in';
  4275. // var prompts = [];
  4276. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  4277. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  4278. // console.log('prompting in preinstallsteps')
  4279. // return any(prompts).then(()=>{
  4280. // var steps = [
  4281. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  4282. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  4283. // ]
  4284. // return any(steps.map(getshelltask)).then(() => {
  4285. // })
  4286. // });
  4287. return Promise.resolve(true)
  4288. })
  4289. return any([any(steps), prompts])
  4290. }
  4291. , installsteps: function () {
  4292. return any([this.installcmd].map(getshelltask))
  4293. }
  4294. , postinstallsteps: function(err, users){
  4295. return this.getuser(null, (err, data)=>{
  4296. // ignore err and proceed with data as guest.
  4297. console.dir(data)
  4298. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  4299. return username = data[0];
  4300. }
  4301. data = data || ['guest']
  4302. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4303. console.log('prompting in postinstallsteps')
  4304. var username = 'guest';
  4305. var email = 'guest@bbh.org.in';
  4306. var password = '***';
  4307. return any( getInteractionPoints([selectedinstance], promptkeys, { username, password, email}) ).then(()=>{
  4308. if(!data.find(e => e === selectedinstance.username)) {
  4309. var steps = [
  4310. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  4311. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  4312. ]
  4313. return any(steps.map(getshelltask)).then(() => {
  4314. })
  4315. }
  4316. else {
  4317. return Promise.resolve(true)
  4318. }
  4319. });
  4320. })
  4321. }
  4322. , install: function () {
  4323. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  4324. }
  4325. , verifyAndInstall : function(){
  4326. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  4327. if(exists) {
  4328. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  4329. return this.postinstallsteps.bind(this)()
  4330. }
  4331. return this.install();
  4332. });
  4333. }
  4334. , getuser : function(repo, onResult){
  4335. var __onResult = onResult || function(e, data){
  4336. data = data || []
  4337. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4338. // console.dir(choices)
  4339. return data[0]
  4340. }
  4341. var globalOrLocal = '--global';
  4342. if(repo) globalOrLocal = '--local'
  4343. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  4344. // not yet configured.
  4345. if(!result.success) return __onResult(result)
  4346. else {
  4347. var users = result.messages[0].trim().split('\n');
  4348. if(users.length === 0 ||
  4349. users.length === 1 && users[0] === 'guest') {
  4350. return __onResult(result)
  4351. }
  4352. else {
  4353. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  4354. }
  4355. })
  4356. .catch((e)=>{
  4357. console.error(e)
  4358. return __onResult(e)
  4359. })
  4360. }
  4361. }
  4362. ,
  4363. {
  4364. shellcmd: 'node',
  4365. name : 'node',
  4366. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  4367. , installer: 'node-v14.16.0-x64.msi'
  4368. , installcmd: ['MSIEXEC.exe', ['/i'
  4369. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  4370. , 'ACCEPT=YES', '/passive']]
  4371. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  4372. }
  4373. ]
  4374. for(var i=0; i<prerequisites.length; i++) {
  4375. prerequisites[prerequisites[i].name] = prerequisites[i];
  4376. }
  4377. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  4378. function ensureDirectoryExistence(filePath) { return shell_verse.ensureDirectoryExistence(filePath) }
  4379. var mainTasks = [];
  4380. function verifyAndInstallPrerequisites() {
  4381. var downloadtasks = [];
  4382. var installtasks = [];
  4383. prerequisites.forEach(preq => {
  4384. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  4385. if (exists) console.log(`${preq.shellcmd} exists`)
  4386. else {
  4387. console.log(`${preq.shellcmd} is not installed`)
  4388. return preq.preinstallsteps.call(preq).then(() => {
  4389. installtasks.push(preq.install.bind(preq))
  4390. })
  4391. }
  4392. }))
  4393. })
  4394. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  4395. }
  4396. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  4397. var runconfig = null;
  4398. var promptkeys = {
  4399. cmd : processedArgs._[0] || 'pull'
  4400. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  4401. // 'instanceName' : true
  4402. // , 'node_env' : true
  4403. // , username : ''
  4404. // , runchoice : 'c'
  4405. }
  4406. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  4407. var choices = {
  4408. 'instanceName' : []
  4409. , 'reposerver' : []
  4410. , 'upstream-remote' : []
  4411. , 'instanceType' : []
  4412. , username : ['guest', 'chessdemo', 'demo']
  4413. }
  4414. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  4415. var instances = []
  4416. var reposervers = [];
  4417. var remotes = [];
  4418. var instanceNames = []
  4419. var instanceTypes = ['development', 'production'];
  4420. // Accumulate all known choices from every possible instance...
  4421. Object.keys( chessinstances).forEach(instanceName => {
  4422. if(instanceName === 'current_run') return ;
  4423. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  4424. var instance = chessinstances[instanceName][node_env];
  4425. reposervers = reposervers.concat(instance.reposervers)
  4426. if(instance.reposerver) reposervers.push(instance.reposerver)
  4427. instances.push(instance)
  4428. instanceTypes.push(instance.node_env)
  4429. instanceNames.push(instance.instanceName)
  4430. var otherremotes = instance?.reposerverinstances
  4431. if(otherremotes) otherremotes = otherremotes[instance?.reposerver]?.remotes
  4432. otherremotes = otherremotes || {}
  4433. Array.prototype.push.apply(remotes, Object.keys(otherremotes))
  4434. })
  4435. })
  4436. instances = instances.concat(detectedinstanceoptions)
  4437. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  4438. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  4439. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  4440. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  4441. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  4442. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  4443. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  4444. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  4445. }
  4446. var detection_state = {
  4447. localInstanceDetected : false
  4448. }
  4449. function createInstanceData(target, source) {
  4450. var sourceinstance = source || target;
  4451. console.dir(sourceinstance)
  4452. var args = {
  4453. remotebase : sourceinstance.reposerver + '/chess/'
  4454. , sourcerepo : sourceinstance.repo || 'chess-data'
  4455. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4456. }
  4457. if(sourceinstance.local) {
  4458. var options = {
  4459. inherit: true, shell: true,
  4460. env: ENV
  4461. , cwd : instanceroot
  4462. , runas: processedArgs.runas
  4463. }
  4464. var cmdseq = [
  4465. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4466. ]
  4467. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4468. }
  4469. else {
  4470. // http://try.gitea.io/api/v1/org/{org}/repos
  4471. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4472. throw 'createInstanceData is possible only within the same repository server.'
  4473. }
  4474. var server = new URL(target.reposerver);
  4475. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4476. , username : target.username, password : target.password
  4477. }
  4478. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4479. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4480. return GITEA.repository.updateattributes( {
  4481. hostname : server.host, protocol : server.protocol
  4482. , username : target.username, password : target.password
  4483. }
  4484. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4485. , { name : `${args.targetrepo}`}
  4486. )
  4487. }
  4488. )
  4489. }
  4490. // GITEA.repository.updateattributes( {
  4491. // hostname : server.host, protocol : server.protocol
  4492. // , username : selectedinstance.username, password : selectedinstance.password
  4493. // }
  4494. // , { repo : `chess-config`, owner : selectedinstance.username }
  4495. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4496. // )
  4497. // return selectedinstance
  4498. }
  4499. function createInstance(target, source) {
  4500. var sourceinstance = source || target;
  4501. console.dir(sourceinstance)
  4502. var args = {
  4503. remotebase : sourceinstance.reposerver + '/chess/'
  4504. , sourcerepo : sourceinstance.repo || 'chess-config'
  4505. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4506. }
  4507. if(sourceinstance.local) {
  4508. var options = {
  4509. inherit: true, shell: true,
  4510. env: ENV
  4511. , cwd : instanceroot
  4512. , runas: processedArgs.runas
  4513. }
  4514. var cmdseq = [
  4515. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4516. ]
  4517. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4518. }
  4519. else {
  4520. // http://try.gitea.io/api/v1/org/{org}/repos
  4521. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4522. throw 'createInstance is possible only within the same repository server.'
  4523. }
  4524. var server = new URL(target.reposerver);
  4525. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4526. , username : target.username, password : target.password
  4527. }
  4528. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4529. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4530. return GITEA.repository.updateattributes( {
  4531. hostname : server.host, protocol : server.protocol
  4532. , username : target.username, password : target.password
  4533. }
  4534. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4535. , { name : `${args.targetrepo}`}
  4536. )
  4537. }
  4538. )
  4539. }
  4540. // GITEA.repository.updateattributes( {
  4541. // hostname : server.host, protocol : server.protocol
  4542. // , username : selectedinstance.username, password : selectedinstance.password
  4543. // }
  4544. // , { repo : `chess-config`, owner : selectedinstance.username }
  4545. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4546. // )
  4547. // return selectedinstance
  4548. }
  4549. var skipprerequisites = false;
  4550. function initinstances() {
  4551. // var root = selectedinstance.root
  4552. var instanceName = selectedinstance.instanceName
  4553. var node_env = selectedinstance.node_env
  4554. var reposerver = selectedinstance.reposerver
  4555. // var instanceName = selectedinstance.instanceName
  4556. // || clioverrides.instanceName
  4557. // // || processedArgs._[1]
  4558. // || chessinstances.current_run.instanceName
  4559. // var node_env = selectedinstance.node_env
  4560. // || clioverrides.node_env
  4561. // // || processedArgs.node_env
  4562. // || chessinstances.current_run.node_env
  4563. // var reposerver = selectedinstance.reposerver
  4564. // || clioverrides.reposerver
  4565. // // || processedArgs.node_env
  4566. // || chessinstances.current_run.reposerver
  4567. // if(!instanceName) {
  4568. // promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  4569. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4570. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4571. // }
  4572. // if(!node_env) {
  4573. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4574. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4575. // }
  4576. // if(!reposerver) {
  4577. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4578. // }
  4579. // chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  4580. // instanceName, node_env, root : selectedinstance.root, reposerver : selectedinstance.reposerver /* promptkeys['reposerver'] */ } );
  4581. // chessinstances['current_run'] = { instanceName: selectedinstance.instanceName, node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver, root }
  4582. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  4583. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  4584. // }
  4585. // Override sequence.
  4586. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  4587. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  4588. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  4589. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  4590. if(selectedinstance.node_env === undefined) delete selectedinstance.node_env
  4591. // selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4592. // , __default
  4593. // , chessinstances[instanceName][node_env]
  4594. // , clioverrides
  4595. // , selectedinstance
  4596. // // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  4597. // );
  4598. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  4599. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  4600. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  4601. // // Brand New.
  4602. // selectedinstance = Object.assign( __default, selectedinstance )
  4603. // }
  4604. // Upgrade old formats..
  4605. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  4606. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4607. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4608. }
  4609. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  4610. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4611. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4612. }
  4613. // Config from server always override merges into selection except for the current selection.
  4614. // PB : TODO -- utils.assign Array merges are non-distinct...
  4615. // chessinstances[instanceName][node_env] = selectedinstance;
  4616. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  4617. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4618. // PB : TODO -- We should probably write the new server config also...
  4619. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4620. return chessinstances
  4621. }
  4622. var skipprereqs = {}
  4623. var maintask = () => {
  4624. // Default cmd to run !
  4625. processedArgs._[0] === processedArgs._[0] || 'pull';
  4626. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  4627. if(!noprerequisites[processedArgs._[0]]
  4628. && !skipprereqs[processedArgs._[0]]
  4629. ) {
  4630. return prerequisites.git.verifyAndInstall().then(()=>{
  4631. var e = { message : 'verifyAndInstall', success : true}
  4632. var inittasks = []
  4633. var commontask = () => { preworkerconfig(); return elxrworker(true) }
  4634. if(!detection_state.localInstanceDetected) {
  4635. var t1 = ()=>{ return createInstance(selectedinstance) };
  4636. t1.statuslog = statuslog
  4637. var specifictask = shell_verse.getNonElevatedTask(t1)
  4638. }
  4639. else {
  4640. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  4641. t2.statuslog = statuslog
  4642. var specifictask = shell_verse.getNonElevatedTask(t2)
  4643. }
  4644. inittasks.push( specifictask().catch((err) => {
  4645. e = err;
  4646. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  4647. console.error(err)
  4648. }).then( commontask )
  4649. // .finally(()=>{
  4650. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  4651. // if(!e.success) fs.writeFileSync('run.done', 'error');
  4652. // // return process.exit()
  4653. // }))
  4654. )
  4655. return any(inittasks)
  4656. })
  4657. }
  4658. else {
  4659. console.log('cmd has no preqs or has been configured to skip preqs')
  4660. preworkerconfig()
  4661. return elxrworker()
  4662. }
  4663. }
  4664. function generateDependencies(){ return shell_verse.generateDependencies() }
  4665. var startElxr = function() {
  4666. const retaincount = 2
  4667. var min = runtimestamp;
  4668. var collect = []
  4669. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  4670. reconfirm = getReconfirmAll()
  4671. }
  4672. // detectedinstanceoptions.splice(0,0, __default) // PB : TODO -- Merge multiple...
  4673. var detectedinstanceoptions = [selectedinstance]
  4674. var cmdinstance = cmds[clioverrides.cmd]
  4675. var cmdprompts = cmdinstance.getPossiblePrompts()
  4676. // selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  4677. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  4678. utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, selectedinstance, promptkeys )
  4679. // promptkeys = utils.assign(promptkeys, clioverrides)
  4680. // startElxr requires instance // Independent cmds should have already been bypassed.
  4681. // if(cmdprompts.instanceName) {
  4682. // not an instanceless cmd.
  4683. // console.dir(selectedinstance)
  4684. try {
  4685. // chessinstances = acquirelocalinstances(selectedinstance);
  4686. // findlocalinstances(chessinstances, detectedinstanceoptions)
  4687. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  4688. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4689. var inst = initinstances(selectedinstance)
  4690. detection_state.localInstanceDetected = true;
  4691. return inst;
  4692. })
  4693. }
  4694. catch (e) {
  4695. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  4696. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4697. return initinstances(selectedinstance)
  4698. })
  4699. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  4700. // // Weve not been told what to do.
  4701. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  4702. // }
  4703. todo = todo.then(() => {
  4704. try {
  4705. // chessinstances = acquirelocalinstances(selectedinstance)
  4706. // findlocalinstances(chessinstances, detectedinstanceoptions)
  4707. // detectedinstanceoptions.splice(0,0, __default)
  4708. initinstances(selectedinstance)
  4709. detection_state.localInstanceDetected = true;
  4710. }
  4711. catch (e) {
  4712. // console.error(e)
  4713. console.log('No local instances config found in current root = ' + selectedinstance.root);
  4714. console.log('A config will be createed with the instance and environment chosen...')
  4715. // return (async ()=>{return await __default.reposerver})().then(()=>{
  4716. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  4717. // return selectedinstance = Object.assign(__default, selectedinstance);
  4718. // })
  4719. detection_state.localInstanceDetected = false;
  4720. return selectedinstance
  4721. }
  4722. })
  4723. }
  4724. return todo.then( ()=>{
  4725. // PB : TODO -- Embed this in the build instead of inlining it.
  4726. // PB : TODO -- Also attepmt to load from ../chess-config/... as base for new instances...
  4727. initinstances(selectedinstance) // PB : TODO Review Initinstancess... and cleanup
  4728. // ---------------------------
  4729. runconfig = { NODE_ENV: selectedinstance.node_env }
  4730. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  4731. generateDependencies();
  4732. if(noprerequisites[processedArgs._[0]]
  4733. || skipprereqs[processedArgs._[0]]
  4734. ) {
  4735. return elxrworker()
  4736. }
  4737. var neTask = ()=>{
  4738. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  4739. // collect garbage
  4740. return dirs( (dir)=>{
  4741. var matches = /run-(.*)/gm.exec(dir.name)
  4742. if(matches) {
  4743. if(+(matches[1]) < min) {
  4744. min = matches[1]
  4745. collect.splice( 0, 0, matches[1] )
  4746. }
  4747. else collect.push(matches[1])
  4748. }
  4749. return Promise.resolve(collect);
  4750. }, `${selectedinstance.root}/.elxr` )
  4751. .then(()=>{
  4752. // delete garbage
  4753. if(collect.length > retaincount) {
  4754. var asyncs = [];
  4755. while((collect.length - asyncs.length) > retaincount) {
  4756. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  4757. }
  4758. return Promise.all(asyncs)
  4759. }
  4760. else return true
  4761. })
  4762. .catch(e => {
  4763. console.error
  4764. })
  4765. }
  4766. neTask.statuslog = statuslog
  4767. shell_verse.getNonElevatedTask( neTask )()
  4768. var commonTask = ()=>{
  4769. verifyAndInstallPrerequisites.statuslog = statuslog
  4770. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  4771. mainTasks.push(maintask)
  4772. return any(mainTasks);
  4773. }
  4774. return commonTask()
  4775. })
  4776. // }
  4777. // else return Promise.resolve(true)
  4778. }
  4779. // return detectInstanceRoot.then(()=>{
  4780. var cmdobj = cmds[selectedinstance.cmd]
  4781. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  4782. if(cmdobj.independentcmd) {
  4783. if(cmdobj.requiresElevation) {
  4784. return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4785. }
  4786. else return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4787. }
  4788. else return startElxr()
  4789. })
  4790. .catch(e => {
  4791. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  4792. else console.log('error : ' + e)
  4793. })
  4794. // })
  4795. })
  4796. })
  4797. // .then( () => {
  4798. // console.log(process._getActiveHandles());
  4799. // console.log(process._getActiveRequests());
  4800. // })
  4801. // detect if alread installed -> Take no action.
  4802. // download if no installer avalable -> next()
  4803. // install
  4804. function checkandinstall(items) {
  4805. var tasks = []
  4806. items.forEach(item => {
  4807. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  4808. })
  4809. return Promise.all(tasks).then(existances => {
  4810. existances.forEach((exists, i) => {
  4811. if (!exists) {
  4812. return downloadandinstall([items[i]])
  4813. }
  4814. })
  4815. })
  4816. }
  4817. function downloadandinstall(items) {
  4818. var tasks = []
  4819. items.forEach(item => {
  4820. tasks.push(getTaskDownload(item))
  4821. })
  4822. return Promise.all(tasks)
  4823. }
  4824. // Sample instances config.
  4825. // var instances = {
  4826. // "elixir": {
  4827. // "production": {
  4828. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  4829. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  4830. // , "exludeMergeRepos": {
  4831. // "elixir-config-development": true, "elixir-config-test": true
  4832. // , "elixir-config-production": true, "elixir-data": true
  4833. // }
  4834. // , "instanceName": "elixir", "node_env": "production"
  4835. // }
  4836. // },
  4837. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  4838. // }
  4839. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...