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

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