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 242KB

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