555
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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