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

index.js 162KB

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