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

index.js 164KB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
2 years ago
5 years ago
6 years ago
3 years ago
3 years ago
3 years ago
6 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
6 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354
  1. global.env = process.env
  2. global.env.NODE_ENV = global.env.NODE_ENV || 'development'
  3. var path = require('path');
  4. var utils = require('bbhverse');
  5. var any = utils.any;
  6. var Tasq = utils.Tasq
  7. var statuslog = utils.Traq
  8. var Traq = utils.Traq
  9. Tasq.addlistener(statuslog.statuslog)
  10. var cli = require('./cliverse')
  11. var nodeShellExec = cli.nodeShellExec;
  12. var chalk = require('chalk')
  13. const homedir = require('os').homedir();
  14. function sysAddPathVar(addpath){
  15. // Object.assign({
  16. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  17. // }, options)
  18. // powershell $env:Path -split ';'
  19. if (__isElevated) {
  20. return nodeShellExec('Powershell.exe', [
  21. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  22. $newpath = $path + ';${addpath}'
  23. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  24. ]).then(() => {
  25. fs.writeFileSync('run.done', 'success')
  26. }).catch(() => {
  27. fs.writeFileSync('run.done', 'error')
  28. })
  29. }
  30. else return op['runas']()
  31. // var newpath = addpath.split(';');
  32. // newpath.push(addpath)
  33. // newpath = Array.from(new Set(newpath)).join(';')
  34. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  35. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  36. // // %AppData%\npm
  37. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  38. }
  39. // singleton one time lazy
  40. var getCredentials = function(){
  41. // First call
  42. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  43. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  44. console.log(creds);
  45. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  46. // Subsequent calls
  47. getCredentials = ()=>{ return creds }
  48. return getCredentials();
  49. }
  50. function getCurrentFolder(){
  51. var tasks = [
  52. // () => {
  53. // // Use junctions to avoid npm package issues
  54. // var p = nodeShellExec('cd').then((result)=>{
  55. // console.dir(result)
  56. // }).catch((e) => { console.error(e) })
  57. // return p;
  58. // }
  59. ()=>{
  60. return Promise.resolve(process.cwd())
  61. }
  62. ];
  63. return any(tasks);
  64. }
  65. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  66. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  67. const runtimestamp = (new Date()).getTime();
  68. function getVersion() { return BUILD_VERSION; }
  69. console.log(getVersion());
  70. // 'use strict';
  71. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  72. // PB : TODO --
  73. // runas bypass non elevated tasks when we request privelege
  74. // runas message is always error needs to be fixed.
  75. // runas wait needs to be parallelized.
  76. // suppress elevation check error messages
  77. // support runas lauched directly from shell.
  78. // pass in environment in hta to shellexecute.
  79. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  80. (function () {
  81. "use strict";
  82. if (!Array.prototype.earlyreduce) {
  83. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  84. var iterable = this;
  85. var donecallback = donecallback || (a=>a)
  86. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  87. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  88. // function *earlyReduceGenerator(acc, v, i, a) {
  89. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  90. var element = iterable[i]
  91. result = eachcallback(result, element, i, iterable)
  92. if(result.done) return donecallback(result)
  93. }
  94. // }
  95. return donecallback(result)
  96. }
  97. }
  98. }());
  99. const { existsSync } = require('fs');
  100. const existslink = function(name, cb){
  101. fs.lstat(name, (error, stats) => {
  102. if (error) {
  103. console.log(error);
  104. cb(error)
  105. }
  106. else {
  107. console.log("Stats object for: example_directory.txt");
  108. console.log(stats);
  109. // Using methods of the Stats object
  110. console.log("Path is file:", stats.isFile());
  111. console.log("Path is directory:", stats.isDirectory());
  112. cb(null, true)
  113. }
  114. });
  115. }
  116. const existsFolderSync = existsSync;
  117. const fs = require('fs')
  118. const cliargs = utils.cliargs;
  119. const processedArgs = cliargs(process.argv.slice(2));
  120. if(!processedArgs.wd){
  121. if(process.env.wd){
  122. }
  123. else {
  124. process.env.wd = process.cwd();
  125. if(process.cwd() === __dirname) {
  126. // This script was launched in the same dir.
  127. // We do not know if it was copied to some random location. Check if we have elxr installed in current location. Or subidr.
  128. process.env.wd = path.dirname( process.env.wd ); // Default to the parent.
  129. }
  130. }
  131. }
  132. else process.env.wd = processedArgs.wd
  133. var ENV = Object.assign({}, process.env); // Shallow clone it.
  134. console.dir(processedArgs)
  135. // PB : TODO -- defaults for valuless arguments if passed.
  136. // Object.keys(processedArgs).forEach(a=>{
  137. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  138. // }
  139. // })
  140. //
  141. // Object.keys(clioverrides).forEach( prop => { })
  142. var globSync = require('glob').sync;
  143. const { readdir } = require("fs").promises
  144. // Directory shallow walk and do perform on each dir.
  145. const dirs = async (perform, path) => {
  146. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  147. if (dir.isDirectory()) perform(dir)
  148. }
  149. }
  150. var templateprocess = function(str, substitutes){
  151. const regex = /__(.*?)__/gm;
  152. // const str = `__link____instance__server-lib__name__`;
  153. let m;
  154. return str.replace(regex, function(match, key) {
  155. console.log(`Found match, group ${match}: ${key}`);
  156. return substitutes[key] || match;
  157. })
  158. // while ((m = regex.exec(str)) !== null) {
  159. // // This is necessary to avoid infinite loops with zero-width matches
  160. // if (m.index === regex.lastIndex) {
  161. // regex.lastIndex++;
  162. // }
  163. // var rstr = str;
  164. // // The result can be accessed through the `m`-variable.
  165. // m.forEach((match, groupIndex) => {
  166. // // rstr = rstr.replace( groupIndex
  167. // console.log(`Found match, group ${groupIndex}: ${match}`);
  168. // if(groupIndex === 0) return
  169. // });
  170. // }
  171. }
  172. function copyFileSync( source, target , options) {
  173. var targetFile = target;
  174. // If target is a directory, a new file with the same name will be created
  175. if ( fs.existsSync( target ) ) {
  176. if ( fs.lstatSync( target ).isDirectory() ) {
  177. targetFile = path.join( target, path.basename( source ) );
  178. }
  179. }
  180. fs.writeFileSync(targetFile, fs.readFileSync(source));
  181. }
  182. function copyFolderRecursiveSync( source, target, options ) {
  183. var files = [];
  184. // Check if folder needs to be created or integrated
  185. var targetFolder = path.join( target, path.basename( source ) );
  186. if ( !fs.existsSync( targetFolder ) ) {
  187. fs.mkdirSync( targetFolder );
  188. }
  189. // Copy
  190. if ( fs.lstatSync( source ).isDirectory() ) {
  191. files = fs.readdirSync( source );
  192. files.forEach( function ( file ) {
  193. var curSource = path.join( source, file );
  194. if ( fs.lstatSync( curSource ).isDirectory() ) {
  195. copyFolderRecursiveSync( curSource, targetFolder );
  196. } else {
  197. copyFileSync( curSource, targetFolder );
  198. }
  199. } );
  200. }
  201. }
  202. var getShellTask = (command, args, options) => {
  203. options = options || {}
  204. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  205. return () => {
  206. var p = callshell( [command, args, Object.assign({
  207. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  208. }, options)
  209. ])()
  210. if (options.ignorefailures) {
  211. return p.catch(e => {
  212. // Ignore. Not a major error.
  213. })
  214. }
  215. else return p;
  216. }
  217. }
  218. var callshelltask = (args) => {
  219. // console.dir(args)
  220. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  221. return args;
  222. }
  223. return getshelltask(args)()
  224. }
  225. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  226. var getshelltask = (args) => {
  227. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  228. var getgitbashtask = (args, onEachError) => { return () => {
  229. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  230. }
  231. var getTaskCheckExists = (command, options) => {
  232. options = options || {}
  233. return () => {
  234. var p = nodeShellExec.apply(null, ['where', [command]])
  235. if (options.ignorefailures) {
  236. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  237. return false;
  238. })
  239. }
  240. else return p.then(() => { return true });
  241. }
  242. }
  243. var getTaskWithElevation = function(tasdef){
  244. return ()=>{
  245. if (__isElevated) {
  246. return tasdef.elevatedpulltasks().then(()=>{
  247. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  248. fs.writeFileSync('run.done', 'success')
  249. }).catch(e=>{
  250. fs.writeFileSync('run.done', 'failure')
  251. });
  252. }
  253. else {
  254. // PB : TODO -- Rename op['runas'] to 'elevate'
  255. var __runasresult = null;
  256. return op['runas']().then((r) => { return __runasresult = r; })
  257. .catch((e) => {
  258. console.error(e)
  259. })
  260. .finally(() => {
  261. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  262. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  263. })
  264. }
  265. }
  266. }
  267. var getTaskWithoutElevation = function(tasdef){
  268. return ()=>{
  269. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  270. else Promise.resolve(true)
  271. }
  272. }
  273. var gitops = {
  274. getdiscoverbranchcmd : function(repo){
  275. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  276. var cmd = [gitbash
  277. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  278. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  279. return cmd
  280. }
  281. }
  282. var getPullCmd = (repo, branch) => {
  283. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  284. // console.log(useGitPull)
  285. var pullCmd = []
  286. if(!branch) {
  287. // console.warn('No branch was specified detecting from working client.')
  288. // First check if working client exists.
  289. // if (existsSync(instanceroot + '/' + repo)) {
  290. pullCmd= gitops.getdiscoverbranchcmd(repo)
  291. // }
  292. // else performpull
  293. }
  294. // var pullCmd = [gitInstallDir
  295. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  296. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  297. if(branch) {
  298. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  299. var pullCmd = [ gitbash
  300. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  301. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  302. }
  303. // var pullCmd = ['pullall', [], { cwd : repo }]
  304. if (useGitPull) pullCmd = ['git', ['pull'], {
  305. inherit: true, shell: true,
  306. cwd: instanceroot + '/' + repo
  307. // , env: process.env
  308. , runas: processedArgs.runas
  309. , title: `git pull ${repo}`
  310. }]
  311. return pullCmd
  312. }
  313. var performPull = (repo, branch, repoowner, errHandler) => {
  314. // PB : TODO -- Handle no branch passed in case.
  315. // if(!branch) { throw 'No branch specified' }
  316. try{
  317. var exists = existsSync(instanceroot + '/' + repo)
  318. }
  319. catch(e){
  320. exists = false
  321. console.log(e)
  322. }
  323. if (exists) {
  324. var branchprint = branch ? ' branch :' + branch : '';
  325. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  326. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  327. if (__isElevated) {
  328. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  329. }
  330. else statuslog.statuslog(null, repo)
  331. return true;
  332. })
  333. .catch((e) => {
  334. e.repo = repo;
  335. if(errHandler) throw errHandler(e)
  336. if (__isElevated) {
  337. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  338. }
  339. else statuslog.statuslog(e);
  340. // console.error(e)
  341. throw e;
  342. })
  343. }
  344. else {
  345. console.log('cloning ' + repo)
  346. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  347. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
  348. {
  349. inherit: true, shell: true,
  350. env: process.env
  351. , cwd : instanceroot
  352. , runas: processedArgs.runas
  353. }).then(() => {
  354. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  355. {
  356. inherit: true, shell: true,
  357. env: process.env
  358. , cwd: instanceroot + '/' + repo
  359. , runas: processedArgs.runas
  360. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  361. })
  362. .then(() => {
  363. if (__isElevated) {
  364. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  365. }
  366. else statuslog.statuslog(null, repo)
  367. })
  368. .catch((e) => {
  369. e.repo = repo;
  370. if (__isElevated) {
  371. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  372. }
  373. else statuslog.statuslog(e);
  374. })
  375. })
  376. .catch(e => {
  377. e.repo = repo;
  378. if(errHandler) throw errHandler(e)
  379. if (__isElevated) {
  380. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  381. }
  382. else statuslog.statuslog(e);
  383. throw e
  384. })
  385. }
  386. }
  387. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  388. // -- Currently workaround is to always run from a non-elevated shell.
  389. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  390. var acquireElevationState = () => {
  391. if (__isElevated === null) {
  392. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  393. inherit: true
  394. // , shell: true
  395. , stdio: 'ignore'
  396. , env: process.env
  397. , title: `check privileged execution mode using "fsutil dirty query C:"`
  398. }).then((exitcode) => {
  399. console.log('Elevated')
  400. __isElevated = true;
  401. return true;
  402. }).catch(() => {
  403. __isElevated = false;
  404. console.log('Not Elevated');
  405. return false;
  406. });
  407. }
  408. else return Promise.resolve(__isElevated);
  409. }
  410. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  411. var defaultRepoOwner = 'chess';
  412. var elevatedRunasRepos = null
  413. var gitRepos = null
  414. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  415. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  416. var dbForLabel = function (label) {
  417. var dbsForLabel = {
  418. devmysql: 'mysql'
  419. , development: 'mssql'
  420. , production: 'mssql'
  421. }
  422. return dbsForLabel[label] || 'mysql'
  423. }
  424. // SAM : TODO Use nodeshellexec where to detect git installation dir
  425. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  426. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  427. // Relevant git repos
  428. var exludeMergeRepos = [];
  429. var useGitPull = processedArgs.useGitPull || false;
  430. var configPromise = null
  431. var op = {
  432. 'h': () => { console.log(elxr.help()); return '-h' }
  433. , 'clean' : () => {
  434. // delete all node_module folders and links.
  435. var tasklist = [];
  436. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  437. return Promise.all(tasklist)
  438. }
  439. // , 'undefined': () => { return acquireChoices( {} ); }
  440. , 'reset': () => {
  441. // Reset NPM packages semver so major versions can be updated.
  442. const fs = require('fs')
  443. const wipeDependencies = (__package) => {
  444. const file = fs.readFileSync(__package + '/package.json')
  445. const content = JSON.parse(file)
  446. for (var devDep in content.devDependencies) {
  447. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  448. content.devDependencies[devDep] = '*';
  449. }
  450. }
  451. for (var dep in content.dependencies) {
  452. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  453. content.dependencies[dep] = '*';
  454. }
  455. }
  456. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  457. }
  458. var repos = ['client'];
  459. // repos = gitRepos;
  460. repos.forEach(wipeDependencies)
  461. // if (require.main === module) {
  462. // } else {
  463. // module.exports = wipeDependencies
  464. // }
  465. }
  466. , 'upgrade': () => {
  467. console.log('upgrade.......')
  468. var tasks = [
  469. () => {
  470. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  471. inherit: true, shell: true
  472. , env: process.env
  473. }).catch((e) => { console.error(e) })
  474. p.position = 1;
  475. console.log('One')
  476. return p;
  477. }
  478. , () => {
  479. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  480. inherit: true, shell: true
  481. , env: process.env
  482. }).catch((e) => { console.error(e) })
  483. p.position = 2;
  484. console.log('Two')
  485. return p;
  486. }
  487. , () => {
  488. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  489. inherit: true, shell: true
  490. , env: process.env
  491. }).catch((e) => { console.error(e) })
  492. p.position = 3;
  493. console.log('Three')
  494. return p;
  495. }
  496. , () => {
  497. var p = nodeShellExec('n', ['latest'], {
  498. inherit: true, shell: true
  499. , env: process.env
  500. }).catch((e) => { console.error(e) })
  501. p.position = 4;
  502. console.log('Four')
  503. return p;
  504. }
  505. ]
  506. any(tasks)
  507. console.log('.......done')
  508. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  509. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  510. console.info('Uninstalling existing ember globally');
  511. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  512. stdio: ['pipe', process.stdout, process.stderr],
  513. inherit: true,
  514. shell: true,
  515. cwd: path.dirname(__dirname),
  516. env: env
  517. })
  518. step1.on('close', () => {
  519. console.info('Installing ember globally');
  520. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  521. stdio: ['pipe', process.stdout, process.stderr],
  522. inherit: true,
  523. shell: true,
  524. cwd: path.dirname(__dirname),
  525. env: env
  526. })
  527. step2.on('close', () => {
  528. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  529. stdio: ['pipe', process.stdout, process.stderr],
  530. inherit: true,
  531. shell: true,
  532. cwd: path.dirname(__dirname),
  533. env: env
  534. })
  535. })
  536. })
  537. }
  538. , 'runas': () => {
  539. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  540. console.log('Testing Elevation')
  541. if (__isElevated) {
  542. try {
  543. op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs)
  544. }
  545. catch (e) {
  546. console.error('Error Invalid command : ' + e)
  547. fs.writeFileSync('run.done', 'error')
  548. }
  549. finally {
  550. }
  551. }
  552. else {
  553. console.log('Requesting Elevated Privileges');
  554. // Wait for the runas to complete before we read it.
  555. try {
  556. fs.unlinkSync('run.done')
  557. fs.unlinkSync('run.log')
  558. }
  559. catch (e) { } //Ignore
  560. // Find node path to send to hta.
  561. return nodeShellExec('where', ['node']).then(r => {
  562. var namedArgs = [];
  563. console.log('result : ' + JSON.stringify(r))
  564. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  565. // PB : TODO -- Convert all the cli args back to string.
  566. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._)
  567. namedArgs.length > 0 ? args = args.concat(namedArgs.join(' ')) : null;
  568. args.push('--runas=self');
  569. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  570. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  571. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  572. // console.dir(processedArgs._)
  573. // console.dir(namedArgs.join(' '))
  574. console.dir(args)
  575. // throw 'test'
  576. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  577. , {
  578. inherit: true
  579. , shell: true
  580. , env: ENV
  581. , runas: 'self'
  582. , title: `runas`
  583. }
  584. ).then(() => {
  585. // runas returned.
  586. try {
  587. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  588. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  589. runaslog.forEach((logEntry) => {
  590. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  591. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  592. })
  593. }
  594. catch (e) {
  595. // We must have a runas log
  596. statuslog.statuslog(e)
  597. console.error('Run log error probably was not created by runas : ' + e)
  598. }
  599. })
  600. .catch(err => console.error('Elevation failed : ' + err));
  601. })
  602. }
  603. }
  604. , 'push': () => {
  605. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  606. // init remote bare from local
  607. // pushandinitremotebare
  608. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  609. // connect to repo server -- net use 172.16.0.27
  610. // cd 172.16.0.27/repos/
  611. // mkdir repo.git
  612. // cd repo.git
  613. // git init --bare
  614. // cd localrepo
  615. // git remote rename origin githubclone
  616. // git remote add origin //172.16.0.27/repos/repo.git
  617. // git push origin master
  618. var repo = processedArgs._[1];
  619. var sequentialTaskShellCommands = [];
  620. if (!existsSync(`Z:/${repo}.git`)) {
  621. sequentialTaskShellCommands = [
  622. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  623. // inherit : true, shell: true
  624. // , env: process.env
  625. // }]
  626. ['pwd', { cwd: 'Z:', inherit: true }]
  627. , ['mkdir', [`${repo}.git`], {
  628. cwd: `Z:`
  629. , inherit: true, shell: true
  630. , env: process.env
  631. }]
  632. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  633. , ['git', ['init', '--bare'], {
  634. cwd: `Z:/${repo}.git`
  635. , inherit: true, shell: true
  636. , env: process.env
  637. }]
  638. // PB : TODO -- Do this conditionally only...
  639. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  640. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  641. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  642. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  643. // PB : TODO -- If threre is a gitbubclone origin
  644. // Set the master to pull from the local repo.
  645. ]
  646. if (!existsSync(`Z:`)) {
  647. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  648. inherit: true, shell: true
  649. , env: process.env
  650. }])
  651. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  652. // throw 'done'
  653. }
  654. }
  655. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  656. // console.dir(sequentialTaskShellCommands);
  657. var tasks = [];
  658. sequentialTaskShellCommands.forEach(shellcmd => {
  659. // console.log(shellcmd)
  660. tasks.push(() => {
  661. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  662. return p;
  663. })
  664. })
  665. any(tasks);
  666. }
  667. , 'is-git-repo': (dir) => {
  668. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  669. }
  670. // git remote equivalents...
  671. // git branch --set-upstream-to=elixir-unc/master master
  672. // git push --set-upstream elixir-unc branch..
  673. , 'remote': (args) => {
  674. // Subcommands!
  675. // PB : TODO -- we can now pass in hypehnated args...
  676. if(!processedArgs.v) return false; // Only -v is supported presently..
  677. var serial_perform = (repo) => {
  678. var options = { cwd: instanceroot + '/' + repo }
  679. return [
  680. ['git', ['remote', '-v'], options]
  681. ]
  682. }
  683. var x = (args) => {
  684. var tasq = () => {
  685. // console.log(args)
  686. return nodeShellExec.apply(null, args).catch(e => {
  687. // We continue on failure.
  688. console.error(tasq.toString())
  689. })
  690. }
  691. tasq.toString = function(){
  692. return JSON.stringify(args)
  693. }
  694. return tasq;
  695. }
  696. var perform = (dir) => {
  697. return any(serial_perform(dir.name).map(x))
  698. }
  699. dirs(perform)
  700. }
  701. , 'remote set-url': (args) => {
  702. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  703. var __args = {
  704. remotename : args.remotename || processedArgs._[2]
  705. , url : args.url || processedArgs._[3]
  706. }
  707. // pushable doesn't mean the remote doesn't support being pushed to.
  708. // 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.
  709. // PB : TODO -- change this to enablepushing.
  710. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  711. var pushable = processedArgs.pushable || false;
  712. remotename = __args.remotename
  713. url = __args.url
  714. var serial_perform_git_seturl = (repo) => {
  715. var options = { cwd: instanceroot + '/' + repo }
  716. // console.log(repo)
  717. if (pushable) {
  718. return [
  719. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  720. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  721. ]
  722. }
  723. else {
  724. return [
  725. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  726. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  727. ]
  728. }
  729. }
  730. var x = (args) => {
  731. var tasq = () => {
  732. // console.log(args)
  733. return nodeShellExec.apply(null, args).catch(e => {
  734. // We continue on failure.
  735. console.error(tasq.toString())
  736. })
  737. }
  738. tasq.toString = function(){
  739. return JSON.stringify(args)
  740. }
  741. return tasq;
  742. }
  743. var perform_git_seturl = (dir) => {
  744. op['is-git-repo'](dir).then((logEntry) => {
  745. return any(serial_perform_git_seturl(dir.name).map(x))
  746. }).catch((e) => {
  747. // console.log('Failed : ' + dir.name)
  748. })
  749. }
  750. dirs(perform_git_seturl)
  751. }
  752. // , 'reset' : ()=>{
  753. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  754. // // Reset the whole installation pertaining to this elxr folder.
  755. // }
  756. , 'remote exists': (args) => {
  757. var __args = {
  758. remotename : args.remotename|| processedArgs._[2]
  759. , url : args.url || processedArgs._[3]
  760. , branch : args.branch || processedArgs._[4]
  761. }
  762. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  763. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  764. var commands = [
  765. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  766. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  767. ['git', ['remote', '-v'], utils.assign( {
  768. evaluateResult : function(err, result){
  769. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  770. var remotes = []
  771. var found = false;
  772. console.dir(result.messages)
  773. console.log(result + '---------------')
  774. result.messages.forEach( (line)=> {
  775. console.log(line + '$$$$$$$$$$$$$$$$$$$$')
  776. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  777. if(matches) {
  778. var remote = {};
  779. remote[matches[1]] = matches[2];
  780. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  781. found = true;
  782. result.url = remote[remotename];
  783. }
  784. }
  785. })
  786. console.dir(remotes)
  787. return [
  788. found
  789. , result
  790. ]
  791. }
  792. } , options) ]
  793. , function(prevserialtaskresult) {
  794. console.log('================================')
  795. var url = __args || prevserialtaskresult.url;
  796. console.dir(prevserialtaskresult)
  797. return getshelltask(['git', ['ls-remote', url], utils.assign( {
  798. evaluateResult : function(err, result){
  799. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  800. // `fatal: repository '${__args.url}/' not found`
  801. var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  802. return [
  803. !hasfailed, result
  804. ]
  805. }
  806. } , options) ])()
  807. }
  808. ]
  809. var mapped = commands.map(callshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  810. return any(mapped).then( allresolved =>{
  811. console.dir(allresolved)
  812. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  813. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  814. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  815. : console.log('was not added as a remote but url is currently accessible.')
  816. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  817. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  818. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  819. : [0, 1] // => was not added and remote and url is accessible.
  820. })
  821. }
  822. , 'remote refresh': (args) => {
  823. var __args = {
  824. remotename : args.remotename|| processedArgs._[2]
  825. , url : args.url || processedArgs._[3]
  826. , branch : args.branch || processedArgs._[4]
  827. }
  828. // use the repo manifest to create missing remotes.
  829. function perform_remote_refresh(dir){
  830. var repo = dir.name
  831. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  832. try {
  833. var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null, selectedinstance).remotes || [];
  834. }
  835. catch(e){
  836. var remotes = []
  837. }
  838. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  839. // console.dir(remotes)
  840. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  841. console.log('Processing : ' + dir.name)
  842. var branch = __branch
  843. __args.repo = repo
  844. __args.branch = __branch
  845. var promises = []
  846. remotes.forEach(remote =>{
  847. Object.keys(remote).forEach(remotename => {
  848. __args.remotename = remotename
  849. __args.url = remote[remotename]
  850. promises.push( op['remote exists']( __args ).then( exists => {
  851. if(!exists[0]) {
  852. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ) }
  853. else return op['remote add']( { remotename,
  854. // PB : TODO -- use the most accessible remote instead of the first available.
  855. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  856. } )
  857. }
  858. })
  859. )
  860. })
  861. })
  862. return Promise.all(promises)
  863. })
  864. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  865. }
  866. return dirs(perform_remote_refresh)
  867. }
  868. , 'remote add': (args) => {
  869. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  870. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  871. // That explicitly has a remote name prefix.
  872. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  873. // git branch branch_name -u your_new_remote/branch_name -- older versions
  874. // git branch -vv -- Detect which branch are we tracking.
  875. // default upstream should be users own fork.
  876. // Also need alias branches to
  877. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  878. // probably git merge from all remotes... and relevant branches...
  879. // alias pushall='for i in `git remote`; do git push $i; done;'
  880. // alias pullall='for i in `git remote`; do git pull $i; done;'
  881. // args === processedArgs ? args = {} : null;
  882. var __args = {
  883. remotename : args.remotename|| processedArgs._[2]
  884. , url : args.url || processedArgs._[3]
  885. , branch : args.branch || processedArgs._[4]
  886. }
  887. var remotename = __args.remotename
  888. var url = __args.url
  889. var branch = __args.branch
  890. var pushable = processedArgs.pushable || false;
  891. var serial_perform_git_add = (repo) => {
  892. var options = { cwd: instanceroot + '/' + repo }
  893. // console.log(repo)
  894. if (pushable) {
  895. return [
  896. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  897. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  898. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  899. ]
  900. }
  901. else {
  902. return [
  903. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  904. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  905. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  906. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  907. ]
  908. }
  909. }
  910. var x = (args) => {
  911. return () => {
  912. // console.log(args)
  913. return nodeShellExec.apply(null, args)
  914. }
  915. // return Promise.resolve(true)
  916. }
  917. var perform_git_add = (dir) => {
  918. op['is-git-repo'](dir).then((logEntry) => {
  919. // console.log(code)
  920. if (logEntry.success) {
  921. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  922. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  923. })
  924. .catch((e) => {
  925. any(serial_perform_git_add(dir.name).map(x))
  926. })
  927. }
  928. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  929. }).catch((e) => {
  930. console.log('Failed : ' + dir.name)
  931. })
  932. }
  933. const { readdir } = require("fs").promises
  934. dirs(perform_git_add)
  935. }
  936. , 'remote remove': (args) => {
  937. var __args = {
  938. remotename : args.remotename|| processedArgs._[2]
  939. }
  940. var remotename = __args.remotename
  941. var serial_perform_git_remove = (repo) => {
  942. var options = { cwd: instanceroot + '/' + repo }
  943. // console.log(repo)
  944. return [
  945. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  946. ]
  947. }
  948. var x = (args) => {
  949. return () => {
  950. // console.log(args)
  951. return nodeShellExec.apply(null, args)
  952. }
  953. // return Promise.resolve(true)
  954. }
  955. var perform_git_remove = (dir) => {
  956. op['is-git-repo'](dir).then((logEntry) => {
  957. // console.log(code)
  958. if (logEntry.success) {
  959. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  960. any(serial_perform_git_remove(dir.name).map(x))
  961. })
  962. .catch((e) => {
  963. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  964. })
  965. }
  966. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  967. }).catch((e) => {
  968. // console.log('Failed : ' + dir.name)
  969. })
  970. }
  971. const { readdir } = require("fs").promises
  972. dirs(perform_git_remove)
  973. }
  974. , 'init-gitea': (user) => {
  975. user = user || processedArgs._[1]
  976. if (!user) throw 'User name required'
  977. var serial_perform_init_gitea = (repo) => {
  978. var options = { cwd: instanceroot + '/' + repo }
  979. // console.log(repo)
  980. return [
  981. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  982. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  983. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  984. ]
  985. }
  986. var x = (args) => {
  987. return () => {
  988. // console.log(args)
  989. return nodeShellExec.apply(null, args)
  990. }
  991. // return Promise.resolve(true)
  992. }
  993. var perform_init_gitea = (dir) => {
  994. op['is-git-repo'](dir).then((logEntry) => {
  995. // console.log(code)
  996. if (logEntry.success) {
  997. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  998. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  999. })
  1000. .catch((e) => {
  1001. any(serial_perform_init_gitea(dir.name).map(x))
  1002. })
  1003. }
  1004. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1005. }).catch((e) => {
  1006. // console.log('Failed : ' + dir.name)
  1007. })
  1008. }
  1009. const { readdir } = require("fs").promises
  1010. dirs(perform_init_gitea)
  1011. }
  1012. , 'syncmaster': (label) => {
  1013. // Usage :
  1014. // elxr pull -- Defaults to run config
  1015. var env = Object.assign({}, process.env); // Shallow clone it.
  1016. // console.dir(env)
  1017. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1018. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  1019. if (__isElevated) {
  1020. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  1021. fs.writeFileSync('run.done', 'success')
  1022. }).catch(() => {
  1023. fs.writeFileSync('run.done', 'error')
  1024. })
  1025. }
  1026. else return op['runas']()
  1027. }
  1028. , 'repo-relocate' : function(args){
  1029. // relocate a subfolder in source repo to same subfolder in target repo with history.
  1030. var args = args || {
  1031. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  1032. , folder : processedArgs._[3] || 'server'
  1033. , sourcerepo : processedArgs._[2] || 'client'
  1034. , targetrepo : processedArgs._[1] || 'elixir-server'
  1035. }
  1036. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  1037. // , stdio: ['pipe', process.stdout, process.stderr]
  1038. , inherit: true,
  1039. shell: true,
  1040. env: process.env
  1041. , runas: processedArgs.runas
  1042. }
  1043. return op['repo-split'](args).then(()=>{
  1044. return op['repo-merge'](args).then(()=>{
  1045. // cleanup folder from source.
  1046. var cmdseq = [
  1047. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  1048. // commits have to intentional...
  1049. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  1050. ]
  1051. return any(cmdseq.map(getshelltask))
  1052. })
  1053. }).catch(e=>{console.error(e)})
  1054. }
  1055. , 'repo-split' : function(args) {
  1056. // https://gist.github.com/smdabdoub/17065c348289158277b5
  1057. /**
  1058. * Eg : folder, remotebase, sourcerepo, targetrepo
  1059. * args.folder = 'server'
  1060. * args.remotebase = 'https://git.bbh/chess/'
  1061. * args.sourcerepo = 'client'
  1062. * args.targetrepo = 'elixir-server'
  1063. */
  1064. var args = args || {
  1065. folder : 'server'
  1066. , remotebase : 'http://git.bbh/chess/'
  1067. , sourcerepo : 'client'
  1068. , targetrepo : 'elixir-server'
  1069. }
  1070. var options = { cwd: `${instanceroot}/relocate`
  1071. // , stdio: ['pipe', process.stdout, process.stderr]
  1072. , inherit: true,
  1073. shell: true,
  1074. env: process.env
  1075. , runas: processedArgs.runas
  1076. }
  1077. var cmdseq = [
  1078. // create a temporary working dir in current folder where we started execution.
  1079. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  1080. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  1081. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  1082. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  1083. ]
  1084. return any(cmdseq.map(getshelltask)).then(() => {
  1085. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1086. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  1087. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1088. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  1089. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  1090. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  1091. // subtree split and filter-branch are options. We currently use repo-filter.
  1092. return op['filter-repo'](args)
  1093. }).catch(e=>{console.error(e); throw 'failed'})
  1094. }
  1095. , 'repo-merge' : function(args) {
  1096. // Merge source repo into target repo
  1097. var args = args || {
  1098. folder : 'server'
  1099. , remotebase : 'http://git.bbh/chess/'
  1100. , sourcerepo : 'client'
  1101. , targetrepo : 'elixir-server'
  1102. }
  1103. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1104. // , stdio: ['pipe', process.stdout, process.stderr]
  1105. , inherit: true,
  1106. shell: true,
  1107. env: process.env
  1108. , runas: processedArgs.runas
  1109. }
  1110. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  1111. // , stdio: ['pipe', process.stdout, process.stderr]
  1112. , inherit: true,
  1113. shell: true,
  1114. env: process.env
  1115. , runas: processedArgs.runas
  1116. }
  1117. var cmdseq = [
  1118. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  1119. , targetrepooptions ]
  1120. // , ['git', ['push', targetrepooptions ] // manual push for now..
  1121. ]
  1122. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  1123. }
  1124. , 'filter-repo' : function(args){
  1125. // Merge source repo into target repo
  1126. var args = args || {
  1127. folder : 'server'
  1128. , remotebase : 'http://git.bbh/chess/'
  1129. , targetrepo : 'elixir-server'
  1130. }
  1131. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1132. , inherit: true, shell: true
  1133. , env: process.env
  1134. , runas: processedArgs.runas
  1135. }
  1136. var cmdseq = [
  1137. // git checkout -b feature/merge-old-project
  1138. // git remote add src-project ../src-project
  1139. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  1140. ]
  1141. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  1142. }
  1143. , 'filter-branch' : function(preservefolder, repo){
  1144. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  1145. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  1146. // Preserve a specific folder.
  1147. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  1148. /*
  1149. git clone repo reposplit
  1150. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  1151. git remote rm origin
  1152. */
  1153. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  1154. }
  1155. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  1156. // // Merge repo2 into a subfolder in repo1
  1157. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  1158. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  1159. // /*
  1160. // cd repo1
  1161. // git remote add -f tempmergesource ../{{mergesource}}/.git
  1162. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  1163. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  1164. // git commit
  1165. // // Repair History
  1166. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  1167. // #!/usr/bin/env bash
  1168. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  1169. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  1170. // subdir=server
  1171. // git filter-branch --tree-filter '
  1172. // first='"$first"'
  1173. // last='"$last"'
  1174. // subdir='"$subdir"'
  1175. // log_file=/tmp/filter.log
  1176. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  1177. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  1178. // echo "=== $GIT_COMMIT: making changes"
  1179. // files=$(git ls-tree --name-only $GIT_COMMIT)
  1180. // mkdir -p $subdir
  1181. // for i in $files; do
  1182. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  1183. // done
  1184. // else
  1185. // echo "=== $GIT_COMMIT: ignoring"
  1186. // fi \
  1187. // >> $log_file
  1188. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  1189. // status=0 # tell tree-filter never to fail
  1190. // '
  1191. // git remote rm tempmergesource
  1192. // */
  1193. // // better alternative for history
  1194. // /**
  1195. // *
  1196. // git clone git@server.com:old-project.git
  1197. // git clone git@server.com:new-project.git
  1198. // cd old-project
  1199. // mkdir old-project
  1200. // git mv !(old-project) old-project
  1201. // ls -la and gt mv hidden files ....
  1202. // git commit -a -S -m “Moving old project into its own subdirectory”
  1203. // cd ../new-project
  1204. // git remote add old-project ../old-project
  1205. // git fetch old-project
  1206. // git checkout -b feature/merge-old-project
  1207. // git merge -S --allow-unrelated-histories old-project/master
  1208. // git push origin feature/merge-old-project
  1209. // git remote rm old-project
  1210. // */
  1211. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  1212. // }
  1213. , 'pull' : (label) => {
  1214. // Usage :
  1215. // elxr pull -- Defaults to run config
  1216. return elxr.getpulltask(selectedinstance)()
  1217. }
  1218. , 'isInstalled': () => {
  1219. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  1220. console.log(processedArgs._[1] + ' exists.')
  1221. return true;
  1222. });
  1223. }
  1224. , 'c' : ()=>{
  1225. }
  1226. , 'i' : () => {
  1227. var tasks = []
  1228. // tasks.push(op['pull']);
  1229. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1230. tasks.push(op['use'])
  1231. if (!__isElevated) {
  1232. tasks.push(op['npmi'])
  1233. }
  1234. // var tasksdefs = [
  1235. // ['elxr', ['pull']]
  1236. // , ['elxr', ['use', 'elixir']]
  1237. // , ['elxr', ['npmi']]
  1238. // ]
  1239. // tasksdefs.forEach(tasksdef=>{
  1240. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1241. // })
  1242. return any(tasks);
  1243. }
  1244. , 'npmi': () => {
  1245. var tasks = [];
  1246. // Build fails without babel...
  1247. tasks.push(getShellTask(
  1248. 'npm',[ 'i', '-g', 'babel-cli' ]
  1249. ) )
  1250. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1251. // npmbuildrepos = []
  1252. npmbuildrepos.forEach(repo => {
  1253. tasks.push(() => {
  1254. return nodeShellExec('npm', ['i --force'], {
  1255. inherit: true, shell: true
  1256. , cwd: instanceroot + '/' + repo
  1257. , env: process.env
  1258. , title: `npm i for ${repo}`
  1259. }).catch((e) => {
  1260. console.error('Ignoring Benign Error'); console.error(e);
  1261. }).then(() => {
  1262. console.log(`--npm run build for ${repo}--------------------`)
  1263. return nodeShellExec('npm', ['run build'], {
  1264. inherit: true, shell: true
  1265. , cwd: instanceroot + '/' + repo
  1266. , env: process.env
  1267. , title: `npm run build for ${repo}`
  1268. }).then(Tasq.then).catch(Tasq.catch)
  1269. })
  1270. })
  1271. })
  1272. return any(tasks).then(() => {
  1273. gitRepos.push({ repo : 'chess-server-lib/server'});
  1274. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1275. // console.dir(gitRepos)
  1276. // throw ""
  1277. // gitRepos = [
  1278. // // 'bbhverse', 'serververse', 'elixir-server',
  1279. // // 'clientverse',
  1280. // 'client'
  1281. // ];
  1282. var rmtasks = []
  1283. var repotasks = []
  1284. var env = Object.assign({}, process.env)
  1285. delete env.NODE_ENV
  1286. gitRepos.forEach(repodef => {
  1287. rmtasks.push(
  1288. // () => {
  1289. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1290. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1291. callshelltask(['rm', ['package-lock.json'], {
  1292. inherit: true, shell: true
  1293. , cwd: instanceroot + '/' + repodef.repo
  1294. , env: process.env
  1295. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1296. }])
  1297. .then(()=>{
  1298. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1299. }).catch((e) => { console.error(e) })
  1300. // }
  1301. )
  1302. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1303. repotasks.push(
  1304. () => {
  1305. console.log(`--npm i for ${repodef.repo}--------------------`)
  1306. var p = nodeShellExec('npm', ['i', '--force'], {
  1307. inherit: true, shell: true
  1308. , cwd: instanceroot + '/' + repodef.repo
  1309. , env
  1310. , title: `npm i for ${repodef.repo}`
  1311. }).then(Tasq.then).catch(Tasq.catch)
  1312. return p;
  1313. })
  1314. }
  1315. })
  1316. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  1317. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1318. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1319. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1320. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1321. // Second time try also doesnt work.
  1322. // repotasks.push(
  1323. // () => {
  1324. // var env = Object.assign({}, process.env)
  1325. // delete env.NODE_ENV
  1326. // console.log(`--------------------second time npm i for client--------------------`)
  1327. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1328. // // return nodeShellExec('npm', ['i --force'], {
  1329. // inherit: true, shell: true
  1330. // , cwd: instanceroot + '/' + 'client'
  1331. // , env
  1332. // , title: `npm i for client`
  1333. // }).then(Tasq.then).catch(Tasq.catch)
  1334. // })
  1335. var bowerRepos = [{ repo : 'client'}]
  1336. var bowertasks = []
  1337. bowerRepos.forEach(repodef => {
  1338. bowertasks.push(() => {
  1339. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1340. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1341. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1342. inherit: true, shell: true
  1343. , cwd: instanceroot + '/' + repodef.repo
  1344. , env: process.env
  1345. , title: `bower i for ${repodef.repo}`
  1346. }).then(Tasq.then).catch(Tasq.catch)
  1347. return p;
  1348. })
  1349. })
  1350. // console.log('rmtasks.length : ' + rmtasks.length)
  1351. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  1352. }).catch(e => {
  1353. console.error(e)
  1354. }).finally(statuslog.finally)
  1355. }
  1356. , 'start': (args) => {
  1357. var label = clioverrides.cmd
  1358. var env = Object.assign({}, process.env); // Shallow clone it.
  1359. env.NODE_ENV = clioverrides.node_env || 'development';
  1360. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  1361. function startFn( o ){
  1362. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  1363. console.log(`Starting ${o.name}.`);
  1364. var childPromise = nodeShellExec('cmd', ['/k', getCmdString(cmd) ], {
  1365. // inherit : true,
  1366. shell: true,
  1367. detached: true,
  1368. stdio: 'ignore',
  1369. cwd: instanceroot + o.path
  1370. , env: env
  1371. })
  1372. var child = childPromise.process;
  1373. var cpid = child.pid
  1374. if (typeof child.pid !== 'undefined') {
  1375. childPromise.then(()=>{
  1376. console.log(` *** started Elixir Loopback Server PID(${cpid}) : NODE_ENV=${clioverrides.node_env} ${cmd}`);
  1377. fs.writeFileSync('.elixir-server.elixir.server.pid', '' + cpid)
  1378. })
  1379. .catch(e => console.errror(e) )
  1380. }
  1381. }
  1382. if(clioverrides.node_env === 'development') {
  1383. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1384. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server' } )
  1385. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server' } )
  1386. // cmd = 'node'()
  1387. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1388. // inherit : true,
  1389. // shell: true, detached: true,
  1390. // cwd : 'qms/server',
  1391. // env: env,
  1392. // shell : true
  1393. // })
  1394. // nodeShellExec('ember', ['s'], {
  1395. // // inherit : true,
  1396. // shell: true, detached: true,
  1397. // cwd : 'client/',
  1398. // env: env
  1399. // })
  1400. console.log('Starting Elixir Client Host.');
  1401. var cmd = ['ember', ['s']]
  1402. var childPromise = nodeShellExec(...cmd, {
  1403. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1404. // PB : TODO -- ember debugging.
  1405. // inherit : true,
  1406. shell: true,
  1407. detached: true,
  1408. stdio: 'ignore',
  1409. cwd: instanceroot + '/' + 'client'
  1410. , env: env
  1411. })
  1412. // .catch(e=>console.error(e))
  1413. child = childPromise.process;
  1414. if (typeof child.pid !== 'undefined') {
  1415. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1416. fs.writeFileSync('.client.server.pid', child.pid, {
  1417. encoding: 'utf8'
  1418. })
  1419. }
  1420. }
  1421. }
  1422. , 'stop': (label) => {
  1423. const kill = require('tree-kill');
  1424. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1425. encoding: 'utf8'
  1426. })
  1427. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1428. console.log(serverPid)
  1429. kill(serverPid)
  1430. serverPid = fs.readFileSync('.express.server.pid', {
  1431. encoding: 'utf8'
  1432. })
  1433. fs.unlinkSync('.express.server.pid')
  1434. console.log(serverPid)
  1435. kill(serverPid)
  1436. }
  1437. , 'model' : () => {
  1438. if (__isElevated) {
  1439. var tasks = [
  1440. () => {
  1441. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1442. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1443. inherit: true, shell: true
  1444. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1445. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1446. , env: process.env
  1447. }).catch((e) => { console.error(e) })
  1448. return p;
  1449. }
  1450. ];
  1451. return any(tasks).then(() => {
  1452. fs.writeFileSync('run.done', 'success')
  1453. }).catch(() => {
  1454. fs.writeFileSync('run.done', 'error')
  1455. })
  1456. }
  1457. else return op['runas']()
  1458. }
  1459. , 'use' : () => {
  1460. // use a certain named instance.
  1461. // Eg :
  1462. // 1) elxr use elixir
  1463. // 2) elxr use cihsr
  1464. // If environment is not specified defaults to development.
  1465. // 1) NODE=test elxr use elixir
  1466. /*// Steps
  1467. 1) Delete Config and Data symlinks
  1468. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1469. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1470. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1471. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1472. */
  1473. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1474. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1475. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1476. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1477. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1478. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1479. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1480. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1481. if (existsSync('config') && existsSync('data')){
  1482. return
  1483. }
  1484. }
  1485. var tasks = [
  1486. () => {
  1487. var promise = new Promise((resolve, reject)=>{
  1488. existslink('config', function(err, data){
  1489. if(data) {
  1490. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env })
  1491. .then(()=>{resolve(true)})
  1492. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1493. }
  1494. else resolve(false)
  1495. })
  1496. })
  1497. return promise;
  1498. },
  1499. () => {
  1500. var promise = new Promise((resolve, reject)=>{
  1501. existslink('data', function(err, data){
  1502. if(data) {
  1503. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env })
  1504. .then(()=>{resolve(true)})
  1505. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1506. }
  1507. else resolve(false)
  1508. })
  1509. })
  1510. return promise;
  1511. },
  1512. ];
  1513. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1514. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1515. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1516. // console.log(process.env.cwd)
  1517. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1518. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1519. var checkoutMap = { 'development': 'master' }
  1520. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1521. var performPullOrCloneForBranch = (def)=>{
  1522. var promise = Promise.resolve(true)
  1523. if (!branch) {
  1524. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1525. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1526. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1527. }
  1528. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1529. }
  1530. var performCloneAndCheckout = null;
  1531. // cant use git checkout -b it fails when branch already exists.
  1532. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1533. return performPullOrCloneForBranch(def).then(()=>{
  1534. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1535. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1536. // inherit : true, shell: true,
  1537. cwd: instanceroot + '/' + def.repo
  1538. // , stdio : ignore // Use when we want to silence output completely.
  1539. , runas: processedArgs.runas
  1540. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1541. }).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 } })
  1542. })
  1543. }
  1544. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1545. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1546. var elevatedqueue = [];
  1547. var enqueueOnce = (queue, task, def) => {
  1548. var found = queue.find(element => {
  1549. var keys = Object.keys( element )
  1550. for(var k=0; k < keys.length; k++) {
  1551. if(element[keys[k]] !== def[k]) return false;
  1552. }
  1553. })
  1554. queue.push(function(){ return task(this)}.bind(def));
  1555. }
  1556. var enqueue = (queue, task, def) => {
  1557. queue.push(function(){ return task(def)}.bind(def));
  1558. }
  1559. var mergeSources = {
  1560. 'development': null,
  1561. 'test': 'master',
  1562. 'production': 'master'
  1563. }
  1564. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1565. // Checkout is reduced to pull provided the current branch is the targetbranch
  1566. if(branch === mergesource) performCheckout = (def) => {
  1567. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1568. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1569. if(branch === __branch) return performCloneAndCheckout(def)
  1570. return performPullOrCloneForBranch(def)
  1571. })
  1572. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1573. }
  1574. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1575. var performPullAll = (def) => {
  1576. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1577. return nodeShellExec('git', ['pull', '--all'], {
  1578. // inherit : true, shell: true,
  1579. cwd: instanceroot + '/' + def.repo
  1580. , runas: processedArgs.runas
  1581. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1582. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1583. }
  1584. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1585. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1586. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1587. var performMerge = (def) => {
  1588. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1589. return nodeShellExec('git', ['merge', mergesource], {
  1590. inherit: true, shell: true,
  1591. cwd: instanceroot + '/' + def.repo
  1592. , runas: processedArgs.runas
  1593. }).catch((e) => { console.error(e) })
  1594. }
  1595. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1596. // var performRepoOperation = function(def) {
  1597. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1598. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1599. // }
  1600. return any(tasks).then(() => {
  1601. var pr = Promise.resolve(true)
  1602. if (!__isElevated) {
  1603. pr = op['runas']()
  1604. return pr.then(()=>{
  1605. //target is the env is we specify in elxr use command. Default is dev
  1606. //Switch to target branch
  1607. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1608. // pull or clone target branch
  1609. .then(() => {
  1610. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1611. return any(gitRepos.map((repo) => performPullAll(repo)))
  1612. })
  1613. // switch to source branch
  1614. .then( () => {
  1615. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1616. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1617. })
  1618. //Pull on merge source branch
  1619. .then( () => {
  1620. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1621. return any(gitRepos.map((repo) => performPullAll(repo)))
  1622. })
  1623. //Switch to target branch
  1624. .then( () => {
  1625. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1626. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1627. })
  1628. .then( //Merge source branch to target branch
  1629. () => {
  1630. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1631. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1632. })
  1633. })
  1634. }
  1635. else {
  1636. tasks = [
  1637. () => {
  1638. // Use junctions to avoid npm package issues
  1639. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1640. inherit: true, shell: true
  1641. , cwd : instanceroot
  1642. , env: process.env
  1643. }).catch((e) => { console.error(e) })
  1644. return p;
  1645. }
  1646. ];
  1647. if (processedArgs._[1]) {
  1648. tasks = tasks.concat(
  1649. [
  1650. () => {
  1651. var dataToLink = runconfig.use + '-data' + '-' + process.env.NODE_ENV
  1652. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  1653. var p = nodeShellExec('mklink', ['/J', 'data', dataToLink], {
  1654. inherit: true, shell: true
  1655. , cwd : instanceroot
  1656. , env: process.env
  1657. }).catch((e) => { console.error(e) })
  1658. return p;
  1659. }
  1660. ]
  1661. )
  1662. }
  1663. return any(tasks).then(()=>{
  1664. // checkout target branch
  1665. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1666. // pull or clone target branch
  1667. .then(() => {
  1668. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1669. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1670. })
  1671. // switch to source branch
  1672. .then( () => {
  1673. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1674. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1675. })
  1676. //Pull on merge source branch
  1677. .then( () => {
  1678. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1679. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1680. })
  1681. //Switch to target branch
  1682. .then( () => {
  1683. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1684. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1685. })
  1686. .then( //Merge source branch to target branch
  1687. () => {
  1688. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1689. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1690. })
  1691. .then(() => {
  1692. fs.writeFileSync('run.done', 'success')
  1693. }).catch(() => {
  1694. fs.writeFileSync('run.done', 'error')
  1695. })
  1696. })
  1697. }
  1698. }).catch(() => {
  1699. fs.writeFileSync('run.done', 'error')
  1700. })
  1701. // Antibiotic stewardship program.
  1702. // 1st use is fine.
  1703. // Max vials dispense
  1704. // 2nd use Pharmacy needs justification Form.
  1705. // Approval after a certain period of time.
  1706. }
  1707. , 'g' : () => {
  1708. if (processedArgs.h) {
  1709. console.log('elxr g model [modelname] => generate a model named [modelname]');
  1710. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  1711. console.log('elxr g => regenerate all known models');
  1712. return
  1713. }
  1714. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1715. // console.log('Starting directory: ' + process.cwd());
  1716. // try {
  1717. // child = child.on('close', () => { process.chdir(label) } );
  1718. // console.log('New directory: ' + process.cwd());
  1719. // }
  1720. // catch (err) {
  1721. // console.log('chdir: ' + err);
  1722. // }
  1723. // child.on('close', function(){
  1724. // var options = {
  1725. // shell : true
  1726. // , inherit : true
  1727. // // , cwd : '' + process.cwd
  1728. // // , env : process.env
  1729. // };
  1730. // nodeShellExec('git', ['init'], { inherit : true});
  1731. if (0) {
  1732. // PB : TODO -- Special google chrome profile for tests etc.
  1733. nodeShellExec('pwd', { inherit: true });
  1734. // /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"
  1735. // "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
  1736. // "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
  1737. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1738. "--profile-directory=Profile 1"
  1739. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1740. }
  1741. // nodeShellExec('npm', ['init', '-y'], options);
  1742. // nodeShellExec('npm', ['init', '-y'], options);
  1743. // })
  1744. var g = {
  1745. 'client': () => {
  1746. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1747. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1748. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1749. stdio: ['pipe', process.stdout, process.stderr],
  1750. inherit: true,
  1751. shell: true,
  1752. cwd: path.dirname(__dirname),
  1753. env: env
  1754. })
  1755. },
  1756. 'modelr': () => {
  1757. var tasks = [
  1758. () => {
  1759. var p = nodeShellExec('"ember"', [
  1760. 'g'
  1761. , 'modelr'
  1762. , processedArgs._[2]], {
  1763. inherit: true, shell: true, env: process.env
  1764. }).then(() => {
  1765. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1766. return true;
  1767. }).catch((e) => { console.error(e) })
  1768. return p;
  1769. },
  1770. () => {
  1771. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1772. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1773. chromeprefs = JSON.parse(chromeprefs)
  1774. var previous = chromeprefs.download.default_directory;
  1775. var parentDir = path.dirname(__dirname);
  1776. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1777. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1778. // PB : TODO -- detect where chrome is installed.
  1779. // PB : TODO -- set the download dir to the place where files are needed.
  1780. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1781. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1782. , '--profile-directory="chess"'
  1783. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1784. inherit: true, shell: true
  1785. , env: process.env
  1786. }).then(() => {
  1787. chromeprefs.download.default_directory = previous;
  1788. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1789. return true;
  1790. }).catch((e) => { console.error(e) })
  1791. return p;
  1792. }
  1793. ,
  1794. () => {
  1795. console.log('Browser process should have closed here....')
  1796. return true;
  1797. }
  1798. ]
  1799. any(tasks)
  1800. }
  1801. , 'undefined' : ()=>{
  1802. console.warn('Are you sure you want to refresh all the models.');
  1803. throw 'NOT YET IMPLMENTED'
  1804. }
  1805. , 'vmodel' : ()=>{
  1806. var verse = [ '__universe__/vmodel' ]
  1807. // console.dir(templateprocess(`__link____instance__server-lib__name__`, { link( ){
  1808. // return processed }, instance : 'elixir-', name : 'newmodel' } )
  1809. // )
  1810. }
  1811. }
  1812. g[processedArgs._[1]]();
  1813. }
  1814. , 'create' : () => { return createInstance(selectedinstance) }
  1815. , 'httpget' : () => {
  1816. // RESTAPI.get({
  1817. // hostname: 'git.bbh',
  1818. // // port: 443,
  1819. // protocol : 'http:',
  1820. // path: '/',
  1821. // method: 'GET'
  1822. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  1823. return createInstance(selectedinstance)
  1824. }
  1825. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  1826. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  1827. }
  1828. // elxr cli operations
  1829. var noprerequisites = {
  1830. add : true, 'set-url' : true, 'repo-relocate' : true
  1831. , remote : true, 'c' : true, 'h' : true
  1832. , httpget : true, getuser : true
  1833. , 'switch user' : true
  1834. , 'switch' : true
  1835. // , 'undefined' : true
  1836. }
  1837. var reconfirmcmds = { create : true }
  1838. var subcommandlabels = {
  1839. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1840. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  1841. }
  1842. var independentcmd = function(){
  1843. return false;
  1844. }
  1845. var cmds = {
  1846. remote : {
  1847. // return a interpreted set of arguments for this comd run context.
  1848. interpret() {
  1849. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  1850. }
  1851. }
  1852. , resetgitconfig : {
  1853. // return a interpreted set of arguments for this comd run context.
  1854. cmdFn : resetgitconfig
  1855. , interpret() { return { cmd : 'resetgitconfig' } }
  1856. , getPossiblePrompts(){ return {} }
  1857. , noprerequisites : true
  1858. , independentcmd : true
  1859. }
  1860. , reinit : {
  1861. // return a interpreted set of arguments for this comd run context.
  1862. cmdFn : reinit
  1863. , interpret() { return { cmd : 'reinit' } }
  1864. , getPossiblePrompts(){ return {} }
  1865. , noprerequisites : true
  1866. , independentcmd : true
  1867. , requiresElevation : true
  1868. , requires : [ generateDependencies ]
  1869. }
  1870. , init : {
  1871. // return a interpreted set of arguments for this comd run context.
  1872. cmdFn : init
  1873. , interpret() { return { cmd : 'init' } }
  1874. , getPossiblePrompts(){ return {} }
  1875. , noprerequisites : true
  1876. , independentcmd : true
  1877. , requiresElevation : true
  1878. , requires : [ generateDependencies ]
  1879. }
  1880. , switch : {
  1881. interpret() {
  1882. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  1883. , reposerver : __default.reposerver
  1884. }
  1885. }
  1886. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  1887. }
  1888. , 'switch user' : {
  1889. interpret() {
  1890. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  1891. }
  1892. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  1893. }
  1894. // Flat linear structure. Every subcommand should have a top level 'label'
  1895. , 'users' : {
  1896. // default to the users list
  1897. subcommands : { list : {} }
  1898. , cmdFn : ()=>getCredentials() // default
  1899. , cmd : 'users'
  1900. , noprerequisites : true
  1901. }
  1902. , 'users list' : {
  1903. cmdFn : ()=>getCredentials()
  1904. , cmd : 'users list'
  1905. , noprerequisites : true
  1906. }
  1907. , 'g' : {
  1908. cmdFn : op['g'] // default
  1909. , cmd : 'g'
  1910. , noprerequisites : true
  1911. , getPossiblePrompts(){ return {} }
  1912. }
  1913. , 'link' : {
  1914. 'cmd' : 'link'
  1915. // , cmdFn : function( sourecpath, filename, dir ){
  1916. // var afterTargetPath = (dir)=>{
  1917. // console.dir(dir);
  1918. // // var tasks = [
  1919. // // () => {
  1920. // // // Use junctions to avoid npm package issues
  1921. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  1922. // // inherit: true, shell: true
  1923. // // , cwd : dir || instanceroot
  1924. // // , env: process.env
  1925. // // }).catch((e) => { console.error(e) })
  1926. // // return p;
  1927. // // }
  1928. // // ];
  1929. // }
  1930. // // console.dir(process.env)
  1931. // if(!dir) getCurrentFolder().then(afterTargetPath);
  1932. // else afterTargetPath(dir)
  1933. // }
  1934. , cmdFn : function( cmdopts ){
  1935. // sourecpathandfile should include name of file name
  1936. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  1937. // console.log(processedArgs)
  1938. if(!targetfilename) return Promise.reject('error no file provided for linking')
  1939. targetdir = cmdopts.targetdir || process.env.wd
  1940. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  1941. var tasks = [
  1942. () => {
  1943. // Use junctions to avoid npm package issues
  1944. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  1945. inherit: true, shell: true
  1946. , cwd : targetdir
  1947. , env: process.env
  1948. }).catch((e) => { console.error(e) })
  1949. return p;
  1950. }
  1951. ];
  1952. if (__isElevated) {
  1953. return any(tasks).then(() => {
  1954. fs.writeFileSync('run.done', 'success')
  1955. }).catch(() => {
  1956. fs.writeFileSync('run.done', 'error')
  1957. })
  1958. }
  1959. else return op['runas']()
  1960. }
  1961. , noprerequisites : true
  1962. , privileged : true
  1963. }
  1964. }
  1965. var elxrcmd = (function(){
  1966. var __cmdprototype = function(){}
  1967. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  1968. var __cmd = {
  1969. interpret() { return { cmd : this.cmd } }
  1970. , getPossiblePrompts(){ return {} } // Requires only one argument...
  1971. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  1972. , finalized : true
  1973. }
  1974. function __createO(o){
  1975. if(o.finalized) return o;
  1976. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  1977. // console.log(subs)
  1978. // console.log(o)
  1979. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  1980. var created = utils.assign_strict({}, __cmd, cmds[o.cmd], o)
  1981. cmds[o.cmd] = created;
  1982. op[o.cmd] = created.cmdFn;
  1983. noprerequisites[o.cmd] = created.noprerequisites
  1984. return created.cmdFn;
  1985. }
  1986. function create(o){ return __createO(o) }
  1987. __cmdprototype.create = create;
  1988. return __cmdprototype;
  1989. })()
  1990. elxrcmd.create(cmds['users'])
  1991. elxrcmd.create(cmds['g'])
  1992. elxrcmd.create(cmds['link'])
  1993. var interpretrun = function(){
  1994. var cmd = processedArgs._[0];
  1995. var clioverrides = { cmd }
  1996. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  1997. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  1998. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  1999. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  2000. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  2001. // return clioverrides
  2002. cmds[cmd] = {
  2003. interpret() {
  2004. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  2005. }
  2006. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  2007. instanceName : true, instanceType : true, reposerver : true } }
  2008. }
  2009. return cmds[cmd].interpret()
  2010. })()
  2011. }
  2012. var clioverrides = interpretrun()
  2013. console.dir(clioverrides)
  2014. var util = require('util');
  2015. var cliname = 'elxr';
  2016. var ver = '1.1';
  2017. var readme = `
  2018. Command syntax examples
  2019. elxr
  2020. Displays help. Same as elxr h
  2021. elxr i
  2022. Runs interactive propmts to help choose installation options.
  2023. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  2024. General command syntax.
  2025. Eg: NODE_ENV=development elxr pull elixir
  2026. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  2027. The specific cmd defines what the value is interpreted as.
  2028. There are several cmds that do not require an {{instancename}} parameter.
  2029. Eg: elxr remote remove origin
  2030. Git operations or passthrough external commands on all repository folders in you working directory.
  2031. Main objectives.
  2032. elxr cli is a wrapper around other shell commands and api based operations.
  2033. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  2034. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  2035. `;
  2036. var help = `
  2037. ${readme}
  2038. # list of commands... please refer dveloper documentation for ${cliname}
  2039. \r\n\t${
  2040. Object.keys(op).join('\r\n\t')
  2041. }
  2042. `;
  2043. var elxr = {
  2044. help() {
  2045. return chalk.cyanBright(`
  2046. -------------------------------------------------------------------------------
  2047. *** BBH Elixir ***
  2048. -------------------------------------------------------------------------------
  2049. elxr ${ver}
  2050. A cli tool for chess
  2051. ${help}
  2052. -------------------------------------------------------------------------------
  2053. `)
  2054. }
  2055. , info() {
  2056. return chalk.cyanBright(`
  2057. -------------------------------------------------------------------------------
  2058. *** BBH Elixir ***
  2059. -------------------------------------------------------------------------------
  2060. elxr ${ver}
  2061. A cli tool for chess
  2062. -------------------------------------------------------------------------------
  2063. `)
  2064. }
  2065. , getpulltask(args){
  2066. // def can be an instance config
  2067. // Or an object with many repos and elevated repos
  2068. // Or a single repo ( Either Elevated or normal. )
  2069. // USAGE
  2070. // elxr pull elixir origin master
  2071. // elxr pull
  2072. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  2073. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  2074. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  2075. // The branch pipline should feed back to master
  2076. // master -> test -> stage -> release[nnnn] -> production
  2077. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  2078. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  2079. var __args = {
  2080. remotename : args.remotename|| processedArgs._[2]
  2081. , url : args.url || processedArgs._[3]
  2082. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  2083. }
  2084. // var commands = [
  2085. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  2086. // ,
  2087. // ]
  2088. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2089. // var pullCmd = [ gitbash
  2090. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2091. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2092. var def = args || {
  2093. repos : selectedinstance.repos,
  2094. elevated : selectedinstance.elevated
  2095. }
  2096. var elevatedpulltasks = null;
  2097. if(def.repo) {
  2098. // Single repo case.
  2099. if(def.repo.requiresElevation) {
  2100. elevatedpulltasks = function() {
  2101. return performPull(def.repo).then(() => {
  2102. return true;
  2103. }).catch((e) => {
  2104. console.error(e)
  2105. })
  2106. }
  2107. return
  2108. }
  2109. else {
  2110. var regularpulltasks = function(){
  2111. var pendingpulls = [];
  2112. pendingpulls.push(performPull(def.repo))
  2113. return Promise.all(pendingpulls).finally(Traq.finally)
  2114. }
  2115. }
  2116. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2117. else return getTaskWithoutElevation({ regularpulltasks})
  2118. }
  2119. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  2120. console.dir(def)
  2121. var env = Object.assign({}, process.env); // Shallow clone it.
  2122. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2123. var useGitPull = processedArgs.useGitPull || false;
  2124. if(def.elevated || def.repos) {
  2125. if(def.elevated) def.requiresElevation = true;
  2126. else delete def.requiresElevation;
  2127. }
  2128. else {
  2129. if(def.requiresElevation) def.elevated = [def]
  2130. else def.repos = [def]
  2131. }
  2132. var regularpulltasks = function(){ return Promise.resolve(true) }
  2133. if(def.elevated){
  2134. elevatedpulltasks = function() {
  2135. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  2136. return true;
  2137. }).catch((e) => {
  2138. console.error(e)
  2139. })
  2140. }
  2141. }
  2142. if(def.repos) {
  2143. var regularpulltasks = function(){
  2144. var pendingpulls = [];
  2145. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  2146. return Promise.all(pendingpulls).finally(Traq.finally)
  2147. }
  2148. }
  2149. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2150. else return getTaskWithoutElevation({ regularpulltasks})
  2151. }
  2152. }
  2153. function preworkerconfig(){
  2154. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  2155. gitRepos = selectedinstance.repos
  2156. // gitRepos = ['chess-server-lib'];
  2157. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  2158. elevatedRunasRepos = selectedinstance.elevated
  2159. // Repos that should excluded from merge for releases...
  2160. exludeMergeRepos = selectedinstance.exludeMergeRepos
  2161. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  2162. // mysql -u root -p db_name < drop_all_tables.sql
  2163. var mysql = '../xampp/mysql/bin/mysql'
  2164. var mysqldump = '../xampp/mysql/bin/mysqldump'
  2165. }
  2166. // The main elxr cli process
  2167. function elxrworker() {
  2168. var __runcmd = function (label) {
  2169. var distinquishedlabel = subcommandlabels[label] || label
  2170. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  2171. }
  2172. // --runas
  2173. if (processedArgs.runas) {
  2174. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  2175. return __runcmd('runas')
  2176. }
  2177. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  2178. }
  2179. // function acquireChoices(selectedinstance) {
  2180. // var hasconfig = false;
  2181. // console.warn(chalk.cyan(`
  2182. // -------------------------------------------------------------------------------
  2183. // Could not locate your preferred configuration (you may not specified it)
  2184. // You should fork the default chess configuration to customize and make it
  2185. // your own instance with a named config as
  2186. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  2187. // And then run this tool as follows
  2188. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  2189. // OR
  2190. // Run this tool with the following command to use a quick start default.
  2191. // elxr --default
  2192. // OR
  2193. // Choose one of the options below to run interactively.
  2194. // We will run your choice at the next prompt.
  2195. // -------------------------------------------------------------------------------
  2196. // `))
  2197. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  2198. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2199. // return initinstances(selectedinstance)
  2200. // })
  2201. // // var prompt = cli.prompter;
  2202. // // return prompt.ask(`Choose an option :
  2203. // // d) Install the default chess instance.
  2204. // // => elxr i chess node_env=development --default
  2205. // // n) Create your custom new instance interactively
  2206. // // => elxr i {{instanceName}} node_env={{environment}}
  2207. // // i) Choose an instance and environment to install
  2208. // // => elxr i {{instanceName}} node_env={{environment}}
  2209. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2210. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2211. // // h) Help
  2212. // // q) Quit
  2213. // // Default <= d
  2214. // // : `).then((choice) => {
  2215. // // if (choice && choice === 'd' || !choice) {
  2216. // // processedArgs._[0] = 'i'
  2217. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2218. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2219. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2220. // // }
  2221. // // else if (choice === 'h') {
  2222. // // processedArgs._[0] = 'h'
  2223. // // fs.writeFileSync('run.done', 'noop help');
  2224. // // console.log(elxr.help()); process.exit()
  2225. // // }
  2226. // // else if (choice === 'n' || choice === 'i') {
  2227. // // var p1 = cli.prompter;
  2228. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2229. // // processedArgs._[0] = 'i'
  2230. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  2231. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2232. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2233. // // if (choice === 'n') {
  2234. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2235. // // console.warn(
  2236. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  2237. // // process.exit();
  2238. // // }
  2239. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2240. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2241. // // })
  2242. // // })
  2243. // // })
  2244. // // } else if (choice === 'c') {
  2245. // // var p1 = cli.prompter;
  2246. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2247. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  2248. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2249. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2250. // // return p1.ask(`Enter cmd :
  2251. // // p) pull
  2252. // // Default <= p
  2253. // // : `).then(function (cmd) {
  2254. // // if (!cmd || cmd === 'p') {
  2255. // // processedArgs._[0] = 'pull'
  2256. // // }
  2257. // // else processedArgs._[0] = cmd
  2258. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2259. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2260. // // })
  2261. // // })
  2262. // // })
  2263. // // })
  2264. // // } else {
  2265. // // 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.`));
  2266. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  2267. // // fs.writeFileSync('run.done', 'noop quit');
  2268. // // process.exit()
  2269. // // }
  2270. // // })
  2271. // }
  2272. var mergeObjByKey = function(arrOfObjs, keyName) {
  2273. var keyedDistinct = {}
  2274. var distinctArrOfObjs = []
  2275. arrOfObjs.forEach( o => {
  2276. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  2277. })
  2278. Object.keys(keyedDistinct).forEach(key => {
  2279. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  2280. })
  2281. return distinctArrOfObjs;
  2282. }
  2283. var cacheWriteInstanceConfig = function(chessinstances){
  2284. var instanceName = chessinstances['current_run'].instanceName;
  2285. var node_env = chessinstances['current_run'].node_env;
  2286. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  2287. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  2288. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  2289. }
  2290. var configs = (function(){
  2291. return {
  2292. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2293. return __acquireConfig(selected, selected.username, clusternodename
  2294. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  2295. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2296. return e; }
  2297. )
  2298. }
  2299. , ownerInstnace(selected) { return __acquireConfig(selected, selected.username, null, null
  2300. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2301. return e }
  2302. )
  2303. }
  2304. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2305. , commonInstance(selected) { return __acquireConfig(selected, defaultRepoOwner
  2306. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2307. ) }
  2308. , genericChessInstance(selected) { return __acquireConfig(selected) }
  2309. }
  2310. })()
  2311. var eNotImplemented = function(){
  2312. console.error('Not yet implemented')
  2313. process.exit()
  2314. }
  2315. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  2316. var acquireConfig = function(slections){
  2317. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2318. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  2319. return acquireData(slections)
  2320. })
  2321. }
  2322. var instanceData = (function(){
  2323. return {
  2324. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2325. return __acquireData(selected, selected.username, clusternodename
  2326. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  2327. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2328. return e; }
  2329. )
  2330. }
  2331. , ownerInstnace(selected) { return __acquireData(selected, selected.username, null
  2332. , selected.instanceName + '-data-' + selected.node_env
  2333. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2334. return e }
  2335. )
  2336. }
  2337. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2338. , commonInstance(selected) { return __acquireData(selected, defaultRepoOwner
  2339. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2340. ) }
  2341. , genericChessInstance(selected) { return __acquireData(selected) }
  2342. }
  2343. })()
  2344. var acquireData = function(slections){
  2345. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2346. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  2347. }
  2348. function reinit(){
  2349. sysAddPathVar('%AppData%\\npm')
  2350. resetgitconfig()
  2351. }
  2352. function init(){
  2353. sysAddPathVar('%AppData%\\npm')
  2354. resetgitconfig()
  2355. }
  2356. function resetgitconfig(){
  2357. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  2358. // Git Credential storage...
  2359. // git config --global credential.helper 'store --file ~/.gitcredentials'
  2360. // git credential-store --file ~/.gitcredentials store
  2361. // // notepad C:/Program Files/Git/etc/gitconfig
  2362. // git config --global --unset credential
  2363. // git config --edit --system
  2364. // git config --global credential.helper "store --file ~/gitcredentials"
  2365. // git credential fill
  2366. // git credential-store --file ~/git.store store
  2367. // Find system git config
  2368. // git config --global --edit
  2369. // git config --list --show-origin
  2370. // git config --list --show-origin --show-scope
  2371. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  2372. // Recipie
  2373. // git config --global --unset credentials.helper
  2374. // cd /path/to/my/repo
  2375. // git config --unset credential.helper
  2376. // git config credential.helper 'store --file ~/.git_repo_credentials'
  2377. // git config credential.*.username my_user_name
  2378. // git config credential.https://gitlab.com.username my_user_name
  2379. // git credential fill
  2380. // git config --global credential.modalprompt false // doesnst work.
  2381. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  2382. var options = {
  2383. inherit: true, shell: true //, env: process.env
  2384. , cwd: instanceroot
  2385. , runas: processedArgs.runas
  2386. }
  2387. var task = ['git', ['config'], options]
  2388. var tasklist = [
  2389. // ['--global', '--unset credentials.helper']
  2390. // ['--unset', 'credentials.helper']
  2391. // ,
  2392. // ['credential.helper', `'store --file git_repo_credentials'`]
  2393. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  2394. , ['--global', '--replace-all', 'user.name', 'pb']
  2395. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  2396. // , ['--list']
  2397. // , ['credential', 'fill']
  2398. ]
  2399. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  2400. var shellT = (args) => { return getgitbashtask(args, onEachError)
  2401. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  2402. }
  2403. execserial(tasklist, task, shellT, onEachError )
  2404. }
  2405. var createTasq = (args, shellT, onEachError) => {
  2406. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  2407. tasq.toString = function(){ return JSON.stringify(args)}
  2408. return tasq;
  2409. }
  2410. var execserial = function(tasklist, task, shellT){
  2411. var exec = (taskArgs)=>{
  2412. var thistask = task.concat();
  2413. thistask[1] = thistask[1].concat()
  2414. thistask[1].push.apply(thistask[1], taskArgs)
  2415. return createTasq(thistask, shellT)
  2416. }
  2417. return any(tasklist.map(exec))
  2418. }
  2419. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  2420. var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) {
  2421. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2422. var errorHandler = (e) => {
  2423. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2424. // console.error('Could not connect to repo server. Timed Out')
  2425. 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 => {
  2426. if(propValue === 'y') {
  2427. reconfirm = getReconfirmAll()
  2428. return startElxr()
  2429. }
  2430. else if(propValue === 'r'){
  2431. return acquireConfig(selected)
  2432. }
  2433. else process.exit()
  2434. })
  2435. }
  2436. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  2437. var choices = {
  2438. t : `install a new temporary local instance with this name ( will not persist ).
  2439. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2440. , e : 'exit' }
  2441. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2442. choices = utils.assign({
  2443. i : 'create a new instance with this name => will fork the default config under your username'
  2444. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2445. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2446. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2447. , p : 'create a custom config for yourself '
  2448. }, choices)
  2449. }
  2450. return cli.prompt( choices
  2451. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2452. if(propValue === 't') {
  2453. selectedinstance.local = true; return createInstance(selectedinstance)
  2454. }
  2455. if(propValue === 'i') return eNotImplemented()
  2456. if(propValue === 'f') return eNotImplemented()
  2457. if(propValue === 'o') return eNotImplemented()
  2458. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2459. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2460. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2461. else process.exit()
  2462. })
  2463. }
  2464. console.warn(e)
  2465. throw e; //('Config acquisition failed.')
  2466. }
  2467. var successHandler = () => {
  2468. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2469. utils.assign_strict(selectedinstance, require(manifestpath)( null, selectedinstance))
  2470. console.dir(selectedinstance.repos)
  2471. // Config from server always override merges into selection except for the current selection.
  2472. // PB : TODO -- utils.assign Array merges are non-distinct...
  2473. if(!selectedinstance.repos[0].repo) {
  2474. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2475. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2476. }
  2477. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2478. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2479. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2480. }
  2481. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  2482. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2483. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2484. cacheWriteInstanceConfig(chessinstances)
  2485. ENV.NODE_ENV = selectedinstance.node_env;
  2486. }
  2487. return performPull(configrepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2488. .catch( (e)=>{
  2489. // if(e){
  2490. if(Promise.resolve(e) === e) return e;
  2491. console.error(e)
  2492. throw e; // Not a hard error but we need this for bcontinueonfailure
  2493. // }
  2494. })
  2495. }
  2496. var __acquireData = function (selected, owner, clusternodename, datarepo, errHandler) {
  2497. datarepo = datarepo || selected.instanceName + '-data';
  2498. var errorHandler = (e) => {
  2499. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2500. // console.error('Could not connect to repo server. Timed Out')
  2501. 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 => {
  2502. if(propValue === 'y') {
  2503. reconfirm = getReconfirmAll()
  2504. return startElxr()
  2505. }
  2506. else if(propValue === 'r'){
  2507. return acquireConfig(selected)
  2508. }
  2509. else process.exit()
  2510. })
  2511. }
  2512. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
  2513. var choices = {
  2514. t : `install a temporary local data folder.
  2515. For more options. Request and use a personal username at chess@bbh.org.in )`
  2516. , e : 'exit' }
  2517. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2518. choices = utils.assign({
  2519. i : 'create a new instance with this name => will fork the default config under your username'
  2520. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2521. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2522. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2523. , p : 'create a custom config for yourself '
  2524. }, choices)
  2525. }
  2526. return cli.prompt( choices
  2527. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  2528. if(propValue === 't') {
  2529. selectedinstance.local = true; return createInstanceData(selectedinstance)
  2530. }
  2531. if(propValue === 'i') return eNotImplemented()
  2532. if(propValue === 'f') return eNotImplemented()
  2533. if(propValue === 'o') return eNotImplemented()
  2534. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2535. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2536. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2537. else process.exit()
  2538. })
  2539. }
  2540. console.warn(e)
  2541. throw e; //('Config acquisition failed.')
  2542. }
  2543. var successHandler = () => {
  2544. }
  2545. return performPull(datarepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2546. .catch( (e)=>{
  2547. // if(e){
  2548. if(Promise.resolve(e) === e) return e;
  2549. console.error(e)
  2550. throw e; // Not a hard error but we need this for bcontinueonfailure
  2551. // }
  2552. })
  2553. }
  2554. var launchpath = path.resolve(path.normalize(process.env.wd))
  2555. 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 we were run.
  2556. // The easisest would be to ask for a target directory and default to current dir....
  2557. // path.dirname(launchpath).split(path.sep).pop()
  2558. var parent = path.dirname(launchpath);
  2559. var pp = launchpath;
  2560. var instancediscoverytasks = [];
  2561. while(parent !== pp){
  2562. instancediscoverytasks.push(
  2563. ((pa)=>{
  2564. var p = pa;
  2565. return function(){
  2566. return hasElxr(p).then((value)=>{
  2567. if(value) return p
  2568. // PB : TODO -- Using throw like this is not friendly with any...
  2569. throw { value : false };
  2570. })
  2571. }
  2572. })(pp)
  2573. )
  2574. pp = parent;
  2575. parent = path.dirname(parent);
  2576. }
  2577. var instanceroot = null
  2578. var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  2579. if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  2580. else instanceroot = ir.pVal
  2581. return instanceroot
  2582. }).catch(()=>{
  2583. instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  2584. })
  2585. // PB : TODO -- Embed this in the build instead of inlining it.
  2586. // Also attepmt to load from ../chess-config/...
  2587. var __default = ((name, options)=>{
  2588. // Default set of users in main repos.
  2589. var users = [
  2590. { username : `${options.username}`, password : `${options.password}` }
  2591. , { username : `chess` }
  2592. // , { username : `baptistdev`, password : 'encrypted' }
  2593. // , { username : `guest`, password : 'encrypted' }
  2594. ]
  2595. // ${options.reposerver} should be used to lookup current config.
  2596. // User can always add more branches and remotes as needed. Mainifest only occupies
  2597. // well defined namespaces
  2598. var remotes = {
  2599. // these are both fetch and push remotes. Use push - remotes to override push.
  2600. 'chess' : {
  2601. server : `${options.reposerver}`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2602. , push : 'no-pushing' }
  2603. , 'baptistdev-public' : {
  2604. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2605. , push : 'no-pushing' }
  2606. // Multiple urls dont tell us the current origin which may be
  2607. // different based on currently available/accessible based on device and client.
  2608. // We just treat them as different remotes and merge as needed.
  2609. //
  2610. , 'origin' : {
  2611. server : `${options.reposerver}`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2612. }
  2613. , 'origin-public' : {
  2614. server : `https://git.bbh.org.in`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2615. , push : {
  2616. server : `${options.reposerver}`, user : `${options.username}`, path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`}
  2617. }
  2618. }
  2619. , 'origin-unc' : {
  2620. server : `//172.16.0.27/repos`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2621. }
  2622. // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
  2623. }
  2624. // , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
  2625. // We therefore need to use
  2626. // - a pullall
  2627. // - or branch alias for multiple remote branch tracking branch strategy.
  2628. // -- This is however limited to corresponding branch names
  2629. // tracking branches.
  2630. // We at least need one branch for each remote that we wish to track.
  2631. // , 'tracking-branches' : [
  2632. // { master : ['origin/master', 'chess/master'] }
  2633. // ]
  2634. var reposerverinstances = {
  2635. 'http://git.bbh' : { users, remotes }
  2636. , 'https://git.bbh.org.in' : { users, remotes, external : true }
  2637. , '//172.16.0.27/repos' : { users, remotes }
  2638. , 'https://github.com' : {
  2639. // We host a miniaml set of repositories in github.
  2640. get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
  2641. , remotes : {
  2642. 'baptistdev-public' : {
  2643. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2644. , push : 'no-pushing' }
  2645. // , Add other remotes here.
  2646. }
  2647. , external : true, public : true
  2648. }
  2649. }
  2650. return {
  2651. reposervers : Object.keys(reposerverinstances)
  2652. , reposerverinstances
  2653. // Common baseline repos for all chess instances.
  2654. , repos : [
  2655. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  2656. , { repo : 'bbhverse' }
  2657. , { repo : 'clientverse' }
  2658. , { repo : 'serververse' }
  2659. , { repo : 'elxr' }
  2660. , { repo : 'ember-searchable-select' }
  2661. , { repo : 'loopback-component-jsonapi' }
  2662. , { repo : 'loopback-jsonapi-model-serializer' }
  2663. , { repo : 'loopback-connector-mysql' }
  2664. , { repo : 'loopback-connector-ds' }
  2665. , { repo : 'ember-service-worker' }
  2666. , { repo : 'ember-service-worker-asset-cache' }
  2667. , { repo : 'ember-service-worker-cache-fallback' }
  2668. , { repo : 'ember-service-worker-index' }
  2669. , { repo : 'ember-sw-client-route' }
  2670. , { repo : 'global-this' }
  2671. ]
  2672. , elevated : [ { repo : 'chess-server-lib' } ]
  2673. , exludeMergeRepos : { }
  2674. }
  2675. })(
  2676. '__default' // name
  2677. , { username : 'guest', instanceName : 'chess', node_env : 'development', reposerver : 'https://git.bbh.org.in' } // options
  2678. )
  2679. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2680. // Then acquire and reload and replace this default.
  2681. var hasElxr = function(path, options, cb) {
  2682. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  2683. options = options || {};
  2684. var tasks = [
  2685. '/elxr' // Is there a subfolder named elxr
  2686. , '/elxr/.git' // which is self git repository
  2687. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  2688. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  2689. ]
  2690. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  2691. var value = existsFolderSync(path + tpath);
  2692. return { value, done : acc && !value };
  2693. }).value }
  2694. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  2695. var value = existsFolderSync(path + tpath);
  2696. return { value, done : acc && !value };
  2697. }).value );
  2698. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  2699. var value = existsFolderSync(path + tpath);
  2700. return { value, done : acc && !value };
  2701. }).value);
  2702. }
  2703. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  2704. var detectfromroot = function(root){
  2705. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  2706. }
  2707. var detectLocalInstances = function () {
  2708. console.log(`launchpath = ${launchpath}`)
  2709. console.log(`thisscriptdir = ${thisscriptdir}`)
  2710. // PB : TODO -- !Postpone this.
  2711. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  2712. // Note : Paths should already be normalized fefore this.
  2713. var root = instanceroot;
  2714. var detected = { root };
  2715. var instanceoptions = [clioverrides]
  2716. return hasElxr(launchpath).then( (elxrCliExists) => {
  2717. // We need a reference to the root director for elxr cli to be properly oriented.
  2718. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  2719. // We were run from the proper root with elxr cli in the subfolder.
  2720. instanceroot = root = launchpath;
  2721. instanceoptions.splice( 0, 0, detected = { root })
  2722. instanceoptions.splice( 0, 0, detectfromroot(root))
  2723. }
  2724. else {
  2725. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  2726. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  2727. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  2728. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  2729. instanceroot = root = launchpath;
  2730. instanceoptions.splice( 0, 0, detected = { root })
  2731. instanceoptions.splice( 0, 0, detectfromroot(root))
  2732. }
  2733. else if (launchpath === thisscriptdir) {
  2734. var parentHasElxr = hasElxrSync(launchpath + '/..')
  2735. // PB : TODO -- verify if we have .elxr folder in the parent...
  2736. if(!parentHasElxr) {
  2737. // ! thisscriptdir is not elxr.
  2738. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  2739. }
  2740. // Same directory doesn't mean we are being run from elxr sub directory.
  2741. // In standalone build script we may or not be in the same location.
  2742. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  2743. // Unbuilt therefore we are in the elxr sub directory.
  2744. instanceroot = root = path.normalize(launchpath + '/..');
  2745. instanceoptions.splice( 0, 0, detected = { root });
  2746. instanceoptions.splice( 0, 0, detectfromroot(root));
  2747. }
  2748. else {
  2749. // Built version.
  2750. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  2751. if(parentHasElxr) {
  2752. // Built version was run from the full elxr subfolder. Should work
  2753. // PB : TODO -- but we should switch to the full version...
  2754. instanceroot = root = path.normalize(launchpath + '/..');
  2755. instanceoptions.splice( 0, 0, detected = { root })
  2756. instanceoptions.splice( 0, 0, detectfromroot(root))
  2757. }
  2758. else {
  2759. instanceroot = root = launchpath;
  2760. instanceoptions.splice( 0, 0, detected = { root })
  2761. instanceoptions.splice( 0, 0, detectfromroot(root))
  2762. // Assume current launchpath is a new instance and create.
  2763. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  2764. // if(clioverrides.instanceName) {
  2765. // if(clioverrides.node_env) {
  2766. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  2767. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  2768. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  2769. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  2770. // // eg : floder name can be elixir01 but instance name is elixr
  2771. // }
  2772. // else {
  2773. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  2774. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  2775. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  2776. // }
  2777. // }
  2778. // else {
  2779. // instanceroot = root = launchpath;
  2780. // if(clioverrides.node_env) {
  2781. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  2782. // instanceoptions.splice( 0, 0, detectfromroot(root))
  2783. // }
  2784. // else {
  2785. // // Nothing was specified... We only have one option from root.
  2786. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  2787. // }
  2788. // }
  2789. }
  2790. }
  2791. }
  2792. else {
  2793. if(elxrCliExists) {
  2794. instanceroot = root = launchpath;
  2795. instanceoptions.splice( 0, 0, detected = { root })
  2796. instanceoptions.splice( 0, 0, detectfromroot(root))
  2797. }
  2798. }
  2799. }
  2800. instanceroot = detected.root
  2801. __default.root = root;
  2802. clioverrides.root = clioverrides.root || root;
  2803. // Resolves empty array when No known instances detected.
  2804. return Promise.resolve(instanceoptions)
  2805. })
  2806. }
  2807. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  2808. if(clioverrides.reconfirm) {
  2809. var reconfirm = getReconfirmAll()
  2810. }
  2811. else { var reconfirm = {}; }
  2812. var shouldPrompt = function(k, possiblePrompts, target){
  2813. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  2814. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  2815. || reconfirm[k])
  2816. }
  2817. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  2818. return function(prompts, k, i, a){
  2819. // No local instances config found. We use a default initialized instance available in selectedinstance
  2820. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2821. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2822. if( shouldPrompt(k, possiblePrompts, target) ) {
  2823. delete reconfirm[k];
  2824. // console.log(k)
  2825. // console.dir(possiblePrompts); //console.dir(target)
  2826. prompts.push(async ()=>{
  2827. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  2828. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2829. // var asyncthis = Object.assign(this);
  2830. // By default Latest altered state is provided which is an implicit reference directly.
  2831. promptables[k].choices = choices[k]
  2832. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2833. return await target[k]
  2834. })
  2835. }
  2836. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  2837. return prompts
  2838. }
  2839. }
  2840. var __interactive_prompts = function( target, choices, promptsfilter ){
  2841. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2842. var interactionpoints = {
  2843. runchoice : {
  2844. label :
  2845. `Choose an option :
  2846. d) Install the default chess instance.
  2847. => elxr i chess node_env=development --default
  2848. n) Create your custom new instance interactively
  2849. => elxr i {{instanceName}} node_env={{environment}}
  2850. i) Choose an instance and environment to install
  2851. => elxr i {{instanceName}} node_env={{environment}}
  2852. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2853. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2854. h) Help
  2855. q) Quit
  2856. : `
  2857. , choices : []
  2858. , defaultchoice : 'c'
  2859. , interpret : function(choice){
  2860. var interpret_map = {
  2861. d : function(){
  2862. processedArgs._[0] = 'i'
  2863. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2864. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2865. target.reposerver = 'https://git.bbh.org.in'
  2866. }
  2867. , n : function() { processedArgs._[0] = 'i' }
  2868. , i : function() { processedArgs._[0] = 'i' }
  2869. , c : async function() {
  2870. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2871. label : `Enter cmd :
  2872. p) pull
  2873. Default <= p
  2874. : `
  2875. , defaultchoice : 'pull'
  2876. }
  2877. ));
  2878. var cmd = await target['cmd'];
  2879. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2880. else target['cmd'] = processedArgs._[0] = cmd
  2881. return cmd;
  2882. }
  2883. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2884. , q : function() { process.exit() }
  2885. }
  2886. var __interpreter = interpret_map['c']
  2887. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2888. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2889. return __interpreter.call(target)
  2890. }
  2891. }
  2892. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  2893. , choices : choices['instanceName'], defaultchoice : 'chess'}
  2894. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  2895. , choices : choices['instanceType'], defaultchoice : 'development'}
  2896. , reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  2897. , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'}
  2898. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  2899. , choices : choices['username'], defaultchoice : 'chess'} }
  2900. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  2901. , choices : choices['password'], defaultchoice : '***'} }
  2902. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  2903. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in'} }
  2904. }
  2905. function getPromptKeys() {
  2906. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  2907. return promptkeys
  2908. }
  2909. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  2910. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  2911. }
  2912. var downloadsdir = '../Downloads';
  2913. var prerequisites = [
  2914. {
  2915. shellcmd: 'git',
  2916. name : 'git',
  2917. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2918. , installer: 'Git-2.31.0-64-bit.exe'
  2919. , installcmd: ['cmd', ['/c', 'start',
  2920. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2921. , '/VERYSILENT'
  2922. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2923. ]]
  2924. , preinstallsteps: function() {
  2925. var steps = [
  2926. () => {
  2927. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2928. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2929. }
  2930. else return Promise.resolve(true)
  2931. }
  2932. ]
  2933. var prompts = this.getuser(null, ()=>{
  2934. // console.log('preinstallsteps')
  2935. // var gitUser = 'guest';
  2936. // var gitEmail = 'guest@bbh.org.in';
  2937. // var prompts = [];
  2938. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  2939. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  2940. // console.log('prompting in preinstallsteps')
  2941. // return any(prompts).then(()=>{
  2942. // var steps = [
  2943. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2944. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2945. // ]
  2946. // return any(steps.map(getshelltask)).then(() => {
  2947. // })
  2948. // });
  2949. return Promise.resolve(true)
  2950. })
  2951. return any([any(steps), prompts])
  2952. }
  2953. , installsteps: function () {
  2954. return any([this.installcmd].map(getshelltask))
  2955. }
  2956. , postinstallsteps: function(err, users){
  2957. return this.getuser(null, (err, data)=>{
  2958. // ignore err and proceed with data as guest.
  2959. console.dir(data)
  2960. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  2961. return username = data[0];
  2962. }
  2963. data = data || ['guest']
  2964. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2965. console.log('prompting in postinstallsteps')
  2966. var username = 'guest';
  2967. var email = 'guest@bbh.org.in';
  2968. var password = '***';
  2969. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  2970. if(!data.find(e => e === selectedinstance.username)) {
  2971. var steps = [
  2972. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  2973. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  2974. ]
  2975. return any(steps.map(getshelltask)).then(() => {
  2976. })
  2977. }
  2978. else {
  2979. return Promise.resolve(true)
  2980. }
  2981. });
  2982. })
  2983. }
  2984. , install: function () {
  2985. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2986. }
  2987. , verifyAndInstall : function(){
  2988. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2989. if(exists) {
  2990. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2991. return this.postinstallsteps.bind(this)()
  2992. }
  2993. return this.install();
  2994. });
  2995. }
  2996. , getuser : function(repo, onResult){
  2997. var __onResult = onResult || function(e, data){
  2998. data = data || []
  2999. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  3000. // console.dir(choices)
  3001. return data[0]
  3002. }
  3003. var globalOrLocal = '--global';
  3004. if(repo) globalOrLocal = '--local'
  3005. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  3006. // not yet configured.
  3007. if(!result.success) return __onResult(result)
  3008. else {
  3009. var users = result.messages[0].trim().split('\n');
  3010. if(users.length === 0 ||
  3011. users.length === 1 && users[0] === 'guest') {
  3012. return __onResult(result)
  3013. }
  3014. else {
  3015. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  3016. }
  3017. })
  3018. .catch((e)=>{
  3019. console.log(e)
  3020. return __onResult(e)
  3021. })
  3022. }
  3023. }
  3024. ,
  3025. {
  3026. shellcmd: 'node',
  3027. name : 'ndoe',
  3028. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  3029. , installer: 'node-v14.16.0-x64.msi'
  3030. , installcmd: ['MSIEXEC.exe', ['/i'
  3031. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  3032. , 'ACCEPT=YES', '/passive']]
  3033. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  3034. }
  3035. ]
  3036. for(var i=0; i<prerequisites.length; i++) {
  3037. prerequisites[prerequisites[i].name] = prerequisites[i];
  3038. }
  3039. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  3040. function ensureDirectoryExistence(filePath) {
  3041. var dirname = path.dirname(filePath);
  3042. if (fs.existsSync(dirname)) {
  3043. return filePath;
  3044. }
  3045. ensureDirectoryExistence(dirname);
  3046. fs.mkdirSync(dirname);
  3047. return filePath;
  3048. }
  3049. var mainTasks = [];
  3050. function verifyAndInstallPrerequisites() {
  3051. var downloadtasks = [];
  3052. var installtasks = [];
  3053. prerequisites.forEach(preq => {
  3054. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  3055. if (exists) console.log(`${preq.shellcmd} exists`)
  3056. else {
  3057. console.log(`${preq.shellcmd} is not installed`)
  3058. return preq.preinstallsteps.call(preq).then(() => {
  3059. installtasks.push(preq.install.bind(preq))
  3060. })
  3061. }
  3062. }))
  3063. })
  3064. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  3065. }
  3066. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  3067. return {
  3068. get (){
  3069. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  3070. var asyncprop = Promise.resolve(propValue)
  3071. if(promptable.interpret){
  3072. asyncprop = promptable.interpret(propValue)
  3073. }
  3074. return asyncprop.then(
  3075. ()=>{
  3076. Object.defineProperty(this, propName, {
  3077. value: propValue,
  3078. writable: true,
  3079. configurable : true,
  3080. enumerable : true
  3081. });
  3082. return propValue
  3083. }
  3084. )
  3085. })
  3086. }
  3087. // , set (propValue){
  3088. // Object.defineProperty(this, propName, {
  3089. // value: propValue,
  3090. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  3091. // configurable : true,
  3092. // enumerable : true
  3093. // })
  3094. // return propValue;
  3095. // }
  3096. , configurable : true
  3097. , enumerable : true
  3098. }
  3099. }
  3100. function acquirelocalinstances(selected){
  3101. // utils.assign is used to cleanup duplicates...
  3102. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  3103. return chessinstances
  3104. }
  3105. function findlocalinstances(chessinstances, instanceoptions){
  3106. // We can expect a .elxr at each level.
  3107. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  3108. earlyreduce( ( value, p, i, a )=>{
  3109. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  3110. if(existsSync( localinstancesPath )) {
  3111. try {
  3112. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  3113. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  3114. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  3115. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  3116. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  3117. return {
  3118. value : chessinstances[instanceName][instanceType]
  3119. , done : true
  3120. };
  3121. }
  3122. })
  3123. })
  3124. }
  3125. catch(e){
  3126. return { }
  3127. }
  3128. }
  3129. else return { }
  3130. }
  3131. )
  3132. }
  3133. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3134. var selectedinstance = { root : process.env.wd };
  3135. var chessinstances = { current_run : {} };
  3136. var promptkeys = {
  3137. cmd : processedArgs._[0] || 'pull'
  3138. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  3139. // 'instanceName' : true
  3140. // , 'node_env' : true
  3141. // , username : ''
  3142. // , runchoice : 'c'
  3143. }
  3144. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  3145. function createLocalChessInstance( cfg ){
  3146. // return createInstance(cfg)
  3147. reconfirm = getReconfirmAll()
  3148. var inst = {};
  3149. var __new = Object.assign({}, __default, cfg)
  3150. inst[cfg.node_env] = __new; return inst;
  3151. }
  3152. var choices = {
  3153. 'instanceName' : []
  3154. , 'reposerver' : []
  3155. , 'instanceType' : []
  3156. , username : ['guest', 'chessdemo', 'demo']
  3157. }
  3158. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  3159. var instances = []
  3160. var reposervers = [];
  3161. var instanceNames = []
  3162. var instanceTypes = ['development', 'production'];
  3163. Object.keys( chessinstances).forEach(instanceName => {
  3164. if(instanceName === 'current_run') return;
  3165. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  3166. var instance = chessinstances[instanceName][node_env];
  3167. reposervers = reposervers.concat(instance.reposervers)
  3168. if(instance.reposerver) reposervers.push(instance.reposerver)
  3169. instances.push(instance)
  3170. instanceTypes.push(instance.node_env)
  3171. instanceNames.push(instance.instanceName)
  3172. })
  3173. })
  3174. instances = instances.concat(detectedinstanceoptions)
  3175. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  3176. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  3177. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  3178. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  3179. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  3180. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  3181. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  3182. }
  3183. var detection_state = {
  3184. localInstanceDetected : false
  3185. }
  3186. const https = require('https')
  3187. const http = require('http');
  3188. const { resolve } = require('path');
  3189. const RESTAPI = (function(){
  3190. // Singleton
  3191. function RESTAPI(){}
  3192. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  3193. // const options = {
  3194. // hostname: 'whatever.com',
  3195. // port: 443,
  3196. // path: '/todos',
  3197. // method: 'POST',
  3198. // headers: {
  3199. // 'Content-Type': 'application/json',
  3200. // 'Content-Length': data.length
  3201. // }
  3202. // }
  3203. RESTAPI.method = function(options, resolve, reject){
  3204. var __method = function() {
  3205. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3206. if(options.payload) {
  3207. const data = new TextEncoder().encode( JSON.stringify(options.payload) )
  3208. options.headers = options.headers || {
  3209. 'Content-Type': 'application/json',
  3210. 'Content-Length': data.length
  3211. }
  3212. }
  3213. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  3214. var acquirer = getHTTPorS(options)
  3215. const req = acquirer.request(options, res => {
  3216. if (res.statusCode < 200 || res.statusCode >= 300) {
  3217. return reject(new Error('statusCode=' + res.statusCode));
  3218. }
  3219. var body = [];
  3220. // res.setEncoding('utf8');
  3221. res.on('data', function(chunk) {
  3222. body.push(chunk);
  3223. });
  3224. res.on('end', function() {
  3225. try {
  3226. body = JSON.parse(Buffer.concat(body).toString());
  3227. } catch(e) {
  3228. reject(e);
  3229. }
  3230. resolve(body);
  3231. });
  3232. });
  3233. req.on('error', error => {
  3234. console.error(error)
  3235. reject(error)
  3236. })
  3237. if(options.payload) req.write(data)
  3238. req.end()
  3239. }
  3240. if(!options.authenticatepost && !usertokens[options.username]) {
  3241. RESTAPI.authenticate(options, function(tokenresp){
  3242. usertokens[options.username] = tokenresp.sha1
  3243. __method(options, resolve, reject)
  3244. },
  3245. function(err){ throw err}
  3246. )
  3247. }
  3248. else __method(options, resolve, reject)
  3249. }
  3250. RESTAPI.post = RESTAPI.method
  3251. var usertokens = {}
  3252. RESTAPI.authenticate = function(options, resolve, reject){
  3253. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3254. if(!usertokens[options.username]) {
  3255. // Authenticate and acquire token.
  3256. // https://git.bbh/api/v1/users/<username>/tokens
  3257. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  3258. var _options = Object.assign({}, options)
  3259. // _options.username = 'demo'
  3260. // _options.password = 'demo123'
  3261. _options.method = 'POST'
  3262. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  3263. _options.path = `/api/v1/users/${_options.username}/tokens`
  3264. _options.authenticatepost = true
  3265. var postoptions = { name : _options.username }
  3266. delete _options.username
  3267. delete _options.password
  3268. _options.payload = postoptions
  3269. RESTAPI.post( _options, function(tokenresp){
  3270. // tokenresp = JSON.parse(tokenresp)
  3271. usertokens[options.username] = tokenresp.sha1
  3272. resolve(tokenresp)
  3273. },
  3274. function(err){ reject(err) }
  3275. )
  3276. }
  3277. else resolve(tokenresp.sha1)
  3278. }
  3279. RESTAPI.get = RESTAPI.post = RESTAPI.method
  3280. return RESTAPI
  3281. })();
  3282. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  3283. const GITEA = (function(){
  3284. function GITEA(){}
  3285. GITEA.repository = {
  3286. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3287. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  3288. // giteaoptions = {
  3289. // organization string
  3290. // --- organization name, if forking into an organization
  3291. // }
  3292. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  3293. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  3294. httpoptions.method = 'POST'
  3295. httpoptions.payload = giteaoptions;
  3296. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3297. }
  3298. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3299. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  3300. httpoptions.method = 'PATCH'
  3301. httpoptions.payload = giteaoptions;
  3302. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3303. }
  3304. }
  3305. GITEA.user = {
  3306. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3307. // ​/users​/{username} // Get a user
  3308. httpoptions.path = `/api/v1/users/${httpoptions.username}`
  3309. httpoptions.method = 'GET'
  3310. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  3311. }
  3312. }
  3313. return GITEA
  3314. })();
  3315. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  3316. const GIT = (function(){
  3317. function GIT(){}
  3318. Object.assign(GIT, {
  3319. 'switch user'(username){
  3320. var server = new URL(selectedinstance.reposerver);
  3321. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  3322. , username : selectedinstance.username, password : selectedinstance.password
  3323. }).then(()=>{
  3324. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  3325. {
  3326. inherit: true, shell: true,
  3327. env: process.env
  3328. , cwd: instanceroot + '/' + repo
  3329. , runas: processedArgs.runas
  3330. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  3331. })
  3332. }
  3333. )
  3334. .catch(e => {
  3335. console.error(e + 'Could not switch. Probably no such user.')
  3336. })
  3337. }
  3338. })
  3339. return GIT
  3340. })();
  3341. function createInstanceData(target, source) {
  3342. var sourceinstance = source || target;
  3343. console.dir(sourceinstance)
  3344. var args = {
  3345. remotebase : sourceinstance.reposerver + '/chess/'
  3346. , sourcerepo : sourceinstance.repo || 'chess-data'
  3347. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3348. }
  3349. if(sourceinstance.local) {
  3350. var options = {
  3351. inherit: true, shell: true,
  3352. env: process.env
  3353. , cwd : instanceroot
  3354. , runas: processedArgs.runas
  3355. }
  3356. var cmdseq = [
  3357. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3358. ]
  3359. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3360. }
  3361. else {
  3362. // http://try.gitea.io/api/v1/org/{org}/repos
  3363. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3364. throw 'createInstanceData is possible only within the same repository server.'
  3365. }
  3366. var server = new URL(target.reposerver);
  3367. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3368. , username : target.username, password : target.password
  3369. }
  3370. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3371. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3372. return GITEA.repository.updateattributes( {
  3373. hostname : server.host, protocol : server.protocol
  3374. , username : target.username, password : target.password
  3375. }
  3376. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3377. , { name : `${args.targetrepo}`}
  3378. )
  3379. }
  3380. )
  3381. }
  3382. // GITEA.repository.updateattributes( {
  3383. // hostname : server.host, protocol : server.protocol
  3384. // , username : selectedinstance.username, password : selectedinstance.password
  3385. // }
  3386. // , { repo : `chess-config`, owner : selectedinstance.username }
  3387. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3388. // )
  3389. // return selectedinstance
  3390. }
  3391. function createInstance(target, source) {
  3392. var sourceinstance = source || target;
  3393. console.dir(sourceinstance)
  3394. var args = {
  3395. remotebase : sourceinstance.reposerver + '/chess/'
  3396. , sourcerepo : sourceinstance.repo || 'chess-config'
  3397. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3398. }
  3399. if(sourceinstance.local) {
  3400. var options = {
  3401. inherit: true, shell: true,
  3402. env: process.env
  3403. , cwd : instanceroot
  3404. , runas: processedArgs.runas
  3405. }
  3406. var cmdseq = [
  3407. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3408. ]
  3409. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3410. }
  3411. else {
  3412. // http://try.gitea.io/api/v1/org/{org}/repos
  3413. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3414. throw 'createInstance is possible only within the same repository server.'
  3415. }
  3416. var server = new URL(target.reposerver);
  3417. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3418. , username : target.username, password : target.password
  3419. }
  3420. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3421. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3422. return GITEA.repository.updateattributes( {
  3423. hostname : server.host, protocol : server.protocol
  3424. , username : target.username, password : target.password
  3425. }
  3426. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3427. , { name : `${args.targetrepo}`}
  3428. )
  3429. }
  3430. )
  3431. }
  3432. // GITEA.repository.updateattributes( {
  3433. // hostname : server.host, protocol : server.protocol
  3434. // , username : selectedinstance.username, password : selectedinstance.password
  3435. // }
  3436. // , { repo : `chess-config`, owner : selectedinstance.username }
  3437. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3438. // )
  3439. // return selectedinstance
  3440. }
  3441. var skipprerequisites = false;
  3442. function initinstances(selected_overrides) {
  3443. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  3444. var instanceName = selected_overrides.instanceName
  3445. || clioverrides.instanceName
  3446. // || processedArgs._[1]
  3447. || chessinstances.current_run.instanceName
  3448. var node_env = selected_overrides.node_env
  3449. || clioverrides.node_env
  3450. // || processedArgs.node_env
  3451. || chessinstances.current_run.node_env
  3452. var reposerver = selected_overrides.reposerver
  3453. || clioverrides.reposerver
  3454. // || processedArgs.node_env
  3455. || chessinstances.current_run.reposerver
  3456. if(!instanceName) {
  3457. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  3458. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3459. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3460. }
  3461. if(!node_env) {
  3462. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3463. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3464. }
  3465. if(!reposerver) {
  3466. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3467. }
  3468. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  3469. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  3470. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  3471. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  3472. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  3473. }
  3474. // Override sequence.
  3475. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  3476. selectedinstance = utils.assign(
  3477. chessinstances[instanceName][node_env]
  3478. , clioverrides
  3479. , selected_overrides
  3480. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  3481. );
  3482. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  3483. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  3484. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  3485. // // Brand New.
  3486. // selectedinstance = Object.assign( __default, selectedinstance )
  3487. // }
  3488. if(!selectedinstance.repos[0].repo) {
  3489. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3490. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3491. }
  3492. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  3493. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3494. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3495. }
  3496. // Config from server always override merges into selection except for the current selection.
  3497. // PB : TODO -- utils.assign Array merges are non-distinct...
  3498. chessinstances[instanceName][node_env] = selectedinstance;
  3499. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3500. cacheWriteInstanceConfig(chessinstances)
  3501. // PB : TODO -- We should probably write the new server config also...
  3502. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3503. return chessinstances
  3504. }
  3505. var skipprereqs = {}
  3506. var maintask = () => {
  3507. // Default cmd to run !
  3508. processedArgs._[0] === processedArgs._[0] || 'pull';
  3509. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  3510. if(!noprerequisites[processedArgs._[0]]
  3511. && !skipprereqs[processedArgs._[0]]
  3512. ) {
  3513. return prerequisites.git.verifyAndInstall().then(()=>{
  3514. var e = { message : 'verifyAndInstall', success : true}
  3515. var inittasks = []
  3516. if(!detection_state.localInstanceDetected) {
  3517. var specifictask = ()=>{ return createInstance(selectedinstance) }
  3518. var commantask = () => { preworkerconfig(); return elxrworker(true) }
  3519. if(!__isElevated) {
  3520. }
  3521. else {
  3522. specifictask = ()=>{ Promise.resolve(true) }
  3523. }
  3524. inittasks.push(specifictask().then( commantask ))
  3525. }
  3526. else {
  3527. var specifictask = ()=>{ return acquireConfig(selectedinstance) }
  3528. var commantask = () => { preworkerconfig(); return elxrworker(true) }
  3529. if(!__isElevated) {
  3530. }
  3531. else {
  3532. specifictask = ()=>{ return Promise.resolve(true) }
  3533. }
  3534. inittasks.push( specifictask().catch((err) => {
  3535. e = err;
  3536. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  3537. console.error(err)
  3538. }).then( commantask )
  3539. // .finally(()=>{
  3540. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  3541. // if(!e.success) fs.writeFileSync('run.done', 'error');
  3542. // // return process.exit()
  3543. // }))
  3544. )
  3545. }
  3546. return any(inittasks)
  3547. })
  3548. }
  3549. else {
  3550. console.log('cmd has no preqs or has been configured to skip preqs')
  3551. preworkerconfig()
  3552. return elxrworker()
  3553. }
  3554. }
  3555. function generateDependencies(){
  3556. // PB : TODO -- Keep only the last n runs...
  3557. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3558. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3559. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  3560. // PB : TODO include and build from files... using rollup..
  3561. var downloadbatch =
  3562. `::**************************************************************************
  3563. :Download_ <url> <File>
  3564. Powershell.exe ^
  3565. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  3566. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  3567. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  3568. exit /b
  3569. ::**************************************************************************`
  3570. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  3571. var windowselevate =
  3572. `
  3573. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  3574. <script language="vbscript">
  3575. document.title = "elxr control panel"
  3576. self.ResizeTo 200,600
  3577. Sub Window_Onload
  3578. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  3579. End Sub
  3580. Set objShell = CreateObject("WScript.Shell")
  3581. Set objENV = objShell.Environment("Process")
  3582. dim NODE_ENV
  3583. NODE_ENV = objENV("NODE_ENV")
  3584. </script>
  3585. <script language="javascript">
  3586. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  3587. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  3588. // alert(windowselevate.commandLine)
  3589. var args = windowselevate.commandLine.split('"').slice(3);
  3590. // alert(args)
  3591. var processedArgs = { _ : [] }
  3592. var namedArgs = [];
  3593. namedArgs.push('--wd=' + objENV('wd'))
  3594. // alert(namedArgs)
  3595. for(var item in args){
  3596. if(args[item].charAt(0) === '-'){
  3597. namedArgs.push(args[item])
  3598. var split = args[item].split('=');
  3599. processedArgs[split[0].slice(2)] = split[1] || true;
  3600. }
  3601. else processedArgs._.push(args[item]);
  3602. }
  3603. // args = args.forEach(function(item){ })
  3604. // alert('processedArgs._ : ' + processedArgs._);
  3605. // alert(processedArgs.runas);
  3606. // alert(objENV('wd'))
  3607. // PB : TODO -- Convert all the cli args back to string.
  3608. // __filename will sure we are launhed using the same entry point.
  3609. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  3610. // alert(cargs)
  3611. var shell = new ActiveXObject('shell.application');
  3612. // alert('launching node privilged. ' + processedArgs['nodepath'])
  3613. // shell.ShellExecute('where', 'node', '', '', 10);
  3614. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  3615. // shell.ShellExecute('cmd.exe ', '/k node "' + cargs + '"', '', 'runas', 1);
  3616. shell.ShellExecute('node', cargs, '', 'runas', 1);
  3617. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  3618. var fso = new ActiveXObject('Scripting.FileSystemObject');
  3619. window.onload = function() {
  3620. document.body.style.backgroundColor = 'black';
  3621. document.body.style.fontFamily = 'arial';
  3622. var log = document.createElement('div');
  3623. log.innerHTML='Please Wait';
  3624. function l(msg){ log.innerHTML+= msg; };
  3625. log.style.color = 'blue';
  3626. log.style.width = '95%';
  3627. log.id = 'log';
  3628. document.body.appendChild(log);
  3629. l('<Br/>Current config : ')
  3630. l('<Br/>NODE_ENV = ' + NODE_ENV)
  3631. l('<Br/>cmd = ' + processedArgs._[0])
  3632. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  3633. l('<Br/><Br/>')
  3634. var timer = function(){
  3635. l('.');
  3636. if(fso.FileExists("run.done")) close();
  3637. else window.setTimeout(timer, 1000);
  3638. };
  3639. window.setTimeout(timer, 3000);
  3640. };
  3641. </script>
  3642. </html>
  3643. `
  3644. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  3645. }
  3646. var startElxr = function() {
  3647. const retaincount = 2
  3648. var min = runtimestamp;
  3649. var collect = []
  3650. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  3651. reconfirm = getReconfirmAll()
  3652. }
  3653. return detectLocalInstances().then((detectedinstanceoptions)=>{
  3654. detectedinstanceoptions.splice(0,0, __default)
  3655. var cmdinstance = cmds[clioverrides.cmd]
  3656. var cmdprompts = cmdinstance.getPossiblePrompts()
  3657. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  3658. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2), promptkeys )
  3659. // promptkeys = utils.assign(promptkeys, clioverrides)
  3660. if(cmdprompts.instanceName) {
  3661. // not an instanceless cmd.
  3662. console.dir(selectedinstance)
  3663. try {
  3664. chessinstances = acquirelocalinstances(selectedinstance);
  3665. findlocalinstances(chessinstances, detectedinstanceoptions)
  3666. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  3667. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3668. var inst = initinstances(selectedinstance)
  3669. detection_state.localInstanceDetected = true;
  3670. return inst;
  3671. })
  3672. }
  3673. catch (e) {
  3674. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  3675. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3676. return initinstances(selectedinstance)
  3677. })
  3678. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  3679. // // Weve not been told what to do.
  3680. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  3681. // }
  3682. todo = todo.then(() => {
  3683. try {
  3684. chessinstances = acquirelocalinstances(selectedinstance)
  3685. findlocalinstances(chessinstances, detectedinstanceoptions)
  3686. detectedinstanceoptions.splice(0,0, __default)
  3687. initinstances(selectedinstance)
  3688. detection_state.localInstanceDetected = true;
  3689. }
  3690. catch (e) {
  3691. // console.error(e)
  3692. console.log('No local instances config found in current root = ' + selectedinstance.root);
  3693. console.log('A config will be createed with the instance and environment chosen...')
  3694. // return (async ()=>{return await __default.reposerver})().then(()=>{
  3695. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  3696. // return selectedinstance = Object.assign(__default, selectedinstance);
  3697. // })
  3698. detection_state.localInstanceDetected = false;
  3699. return selectedinstance
  3700. }
  3701. })
  3702. }
  3703. return todo
  3704. }
  3705. else return Promise.resolve(true)
  3706. })
  3707. .then(()=>{
  3708. generateDependencies();
  3709. if(noprerequisites[processedArgs._[0]]
  3710. || skipprereqs[processedArgs._[0]]
  3711. ) {
  3712. return elxrworker()
  3713. }
  3714. if(!__isElevated) {
  3715. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  3716. // collect garbage
  3717. return dirs( (dir)=>{
  3718. var matches = /run-(.*)/gm.exec(dir.name)
  3719. if(matches) {
  3720. if(+(matches[1]) < min) {
  3721. min = matches[1]
  3722. collect.splice( 0, 0, matches[1] )
  3723. }
  3724. else collect.push(matches[1])
  3725. }
  3726. }, `${selectedinstance.root}/.elxr` )
  3727. .then(()=>{
  3728. // delete garbage
  3729. if(collect.length > retaincount) {
  3730. var asyncs = [];
  3731. while((collect.length - asyncs.length) > retaincount) {
  3732. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  3733. }
  3734. return Promise.all(asyncs)
  3735. }
  3736. else return true
  3737. })
  3738. .then(()=>{
  3739. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  3740. mainTasks.push(maintask)
  3741. return any(mainTasks);
  3742. })
  3743. }
  3744. else {
  3745. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  3746. mainTasks.push(maintask)
  3747. return any(mainTasks);
  3748. }
  3749. })
  3750. }
  3751. detectInstanceRoot.then(()=>{
  3752. var cmdobj = cmds[clioverrides.cmd]
  3753. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  3754. if(cmdobj.independentcmd) {
  3755. if(cmdobj.requiresElevation) {
  3756. return acquireElevationState().then(() => {
  3757. cmdobj.cmdFn() })
  3758. }
  3759. else return cmdobj.cmdFn()
  3760. }
  3761. else return acquireElevationState().then(() => {
  3762. return startElxr()
  3763. })
  3764. })
  3765. .catch(e => {
  3766. console.log('error ')
  3767. })
  3768. })
  3769. // detect if alread installed -> Take no action.
  3770. // download if no installer avalable -> next()
  3771. // install
  3772. function chackandinstall(items) {
  3773. var tasks = []
  3774. items.forEach(item => {
  3775. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  3776. })
  3777. return Promise.all(tasks).then(existances => {
  3778. existances.forEach((exists, i) => {
  3779. if (!exists) {
  3780. return downloadandinstall([items[i]])
  3781. }
  3782. })
  3783. })
  3784. }
  3785. function downloadandinstall(items) {
  3786. var tasks = []
  3787. items.forEach(item => {
  3788. tasks.push(getTaskDownload(item))
  3789. })
  3790. return Promise.all(tasks)
  3791. }
  3792. // Sample instances config.
  3793. // var instances = {
  3794. // "elixir": {
  3795. // "production": {
  3796. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  3797. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  3798. // , "exludeMergeRepos": {
  3799. // "elixir-config-development": true, "elixir-config-test": true
  3800. // , "elixir-config-production": true, "elixir-data": true
  3801. // }
  3802. // , "instanceName": "elixir", "node_env": "production"
  3803. // }
  3804. // },
  3805. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  3806. // }
  3807. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...