Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 222KB

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