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

index.js 242KB

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