Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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