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

index.js 242KB

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