Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

pirms 3 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814
  1. 'use strict';
  2. var path = require('path');
  3. var utils = require('bbhverse');
  4. var any = utils.any;
  5. var Tasq = utils.Tasq;
  6. var statuslog = utils.Traq;
  7. var Traq = utils.Traq;
  8. Tasq.addlistener(statuslog.statuslog);
  9. var cli = require('./cliverse');
  10. var nodeShellExec = cli.nodeShellExec;
  11. var chalk = require('chalk');
  12. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b';
  13. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  14. const runtimestamp = (new Date()).getTime();
  15. function getVersion() { return BUILD_VERSION; }
  16. console.log(getVersion());
  17. // 'use strict';
  18. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  19. // PB : TODO --
  20. // runas bypass non elevated tasks when we request privelege
  21. // runas message is always error needs to be fixed.
  22. // runas wait needs to be parallelized.
  23. // suppress elevation check error messages
  24. // support runas lauched directly from shell.
  25. // pass in environment in hta to shellexecute.
  26. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  27. (function () {
  28. if (!Array.prototype.earlyreduce) {
  29. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  30. var iterable = this;
  31. var donecallback = donecallback || (a=>a);
  32. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  33. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  34. // function *earlyReduceGenerator(acc, v, i, a) {
  35. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  36. var element = iterable[i];
  37. result = eachcallback(result, element, i, iterable);
  38. if(result.done) return donecallback(result)
  39. }
  40. // }
  41. return donecallback(result)
  42. };
  43. }
  44. }());
  45. const { existsSync } = require('fs');
  46. const existsFolderSync = existsSync;
  47. const fs = require('fs');
  48. const cliargs = utils.cliargs;
  49. const processedArgs = cliargs(process.argv.slice(2));
  50. console.dir(processedArgs);
  51. // PB : TODO -- defaults for valuless arguments if passed.
  52. // Object.keys(processedArgs).forEach(a=>{
  53. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  54. // }
  55. // })
  56. var clioverrides = { };
  57. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  58. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  59. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  60. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  61. Object.keys(clioverrides).forEach( prop => { });
  62. require('glob').sync;
  63. var ENV = Object.assign({}, process.env); // Shallow clone it.
  64. const { readdir } = require("fs").promises;
  65. // Directory shallow walk and do perform on each dir.
  66. const dirs = async (perform, path) => {
  67. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  68. if (dir.isDirectory()) perform(dir);
  69. }
  70. };
  71. var getShellTask = (command, args, options) => {
  72. options = options || {};
  73. var callshell = command === 'rm' ? callgitbashtask : callsheltask;
  74. return () => {
  75. var p = callshell( [command, args, Object.assign({
  76. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  77. }, options)
  78. ]);
  79. if (options.ignorefailures) {
  80. return p.catch(e => {
  81. // Ignore. Not a major error.
  82. })
  83. }
  84. else return p;
  85. }
  86. };
  87. var callsheltask = (args) => {
  88. return args[0] === 'rm' ? callgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } };
  89. var callgitbashtask = (args) => { return () => {
  90. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  91. };
  92. var getTaskCheckExists = (command, options) => {
  93. options = options || {};
  94. return () => {
  95. var p = nodeShellExec.apply(null, ['where', [command]]);
  96. if (options.ignorefailures) {
  97. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  98. return false;
  99. })
  100. }
  101. else return p.then(() => { return true });
  102. }
  103. };
  104. var getTaskWithElevation = function(tasdef){
  105. return ()=>{
  106. if (__isElevated) {
  107. return tasdef.elevatedpulltasks().then(()=>{
  108. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  109. fs.writeFileSync('run.done', 'success');
  110. }).catch(e=>{
  111. fs.writeFileSync('run.done', 'failure');
  112. });
  113. }
  114. else {
  115. // PB : TODO -- Rename op['runas'] to 'elevate'
  116. var __runasresult = null;
  117. return op['runas']().then((r) => { return __runasresult = r; })
  118. .catch((e) => {
  119. console.error(e);
  120. })
  121. .finally(() => {
  122. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done');
  123. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  124. })
  125. }
  126. }
  127. };
  128. var getTaskWithoutElevation = function(tasdef){
  129. return ()=>{
  130. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  131. else Promise.resolve(true);
  132. }
  133. };
  134. var gitops = {
  135. getdiscoverbranchcmd : function(repo){
  136. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  137. var cmd = [gitbash
  138. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  139. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }];
  140. return cmd
  141. }
  142. };
  143. var getPullCmd = (repo, branch) => {
  144. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  145. // console.log(useGitPull)
  146. // var pullCmd = [gitInstallDir
  147. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  148. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  149. if(branch) {
  150. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  151. var pullCmd = [ gitbash
  152. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  153. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  154. }
  155. else {
  156. // console.warn('No branch was specified detecting from working client.')
  157. // First check if working client exits.
  158. // if (existsSync(instanceroot + '/' + repo)) {
  159. var pullCmd = gitops.getdiscoverbranchcmd(repo);
  160. // }
  161. // else performpull
  162. }
  163. // var pullCmd = ['pullall', [], { cwd : repo }]
  164. if (useGitPull) pullCmd = ['git', ['pull'], {
  165. inherit: true, shell: true,
  166. cwd: instanceroot + '/' + repo
  167. // , env: process.env
  168. , runas: processedArgs.runas
  169. , title: `git pull ${repo}`
  170. }];
  171. return pullCmd
  172. };
  173. var performPull = (repo, branch) => {
  174. // PB : TODO -- Handle no branch passed in case.
  175. // if(!branch) { throw 'No branch specified' }
  176. if (existsSync(instanceroot + '/' + repo)) {
  177. var branchprint = branch ? ' branch :' + branch : '';
  178. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  179. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  180. if (__isElevated) {
  181. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  182. }
  183. else statuslog.statuslog(null, repo);
  184. return true;
  185. })
  186. .catch((e) => {
  187. e.repo = repo;
  188. if (__isElevated) {
  189. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  190. }
  191. else statuslog.statuslog(e); console.error(e);
  192. })
  193. }
  194. else {
  195. console.log('cloning ' + repo);
  196. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  197. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  198. {
  199. inherit: true, shell: true,
  200. env: process.env
  201. , cwd : instanceroot
  202. , runas: processedArgs.runas
  203. }).catch((e) => {
  204. throw e;
  205. }).then(() => {
  206. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  207. {
  208. inherit: true, shell: true,
  209. env: process.env
  210. , cwd: instanceroot + '/' + repo
  211. , runas: processedArgs.runas
  212. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  213. })
  214. .then(() => {
  215. if (__isElevated) {
  216. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  217. }
  218. else statuslog.statuslog(null, repo);
  219. })
  220. .catch((e) => {
  221. e.repo = repo;
  222. if (__isElevated) {
  223. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  224. }
  225. else statuslog.statuslog(e);
  226. })
  227. })
  228. .catch(e => {
  229. e.repo = repo;
  230. if (__isElevated) {
  231. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  232. }
  233. else statuslog.statuslog(e);
  234. })
  235. }
  236. };
  237. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  238. // -- Currently workaround is to always run from a non-elevated shell.
  239. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  240. var acquireElevationState = () => {
  241. if (__isElevated === null) {
  242. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  243. inherit: true
  244. // , shell: true
  245. , stdio: 'ignore'
  246. , env: process.env
  247. , title: `check privileged execution mode using "fsutil dirty query C:"`
  248. }).then((exitcode) => {
  249. console.log('Elevated');
  250. __isElevated = true;
  251. return true;
  252. }).catch(() => {
  253. __isElevated = false;
  254. console.log('Not Elevated');
  255. return false;
  256. });
  257. }
  258. else return Promise.resolve(__isElevated);
  259. };
  260. var defaultRepoOwner = 'chess';
  261. var elevatedRunasRepos = null;
  262. var gitRepos = null;
  263. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  264. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  265. var dbForLabel = function (label) {
  266. var dbsForLabel = {
  267. devmysql: 'mysql'
  268. , development: 'mssql'
  269. , production: 'mssql'
  270. };
  271. return dbsForLabel[label] || 'mysql'
  272. };
  273. // SAM : TODO Use nodeshellexec where to detect git installation dir
  274. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
  275. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  276. // Relevant git repos
  277. var exludeMergeRepos = [];
  278. var useGitPull = processedArgs.useGitPull || false;
  279. // elxr cli operations
  280. var op = {
  281. 'h': () => { console.log(elxr.help()); return '-h' }
  282. , 'clean' : () => {
  283. // delete all node_module folders and links.
  284. var tasklist = [];
  285. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  286. return Promise.all(tasklist)
  287. }
  288. , 'undefined': () => { return op.h(); }
  289. , 'reset': () => {
  290. // Reset NPM packages semver so major versions can be updated.
  291. const fs = require('fs');
  292. const wipeDependencies = (__package) => {
  293. const file = fs.readFileSync(__package + '/package.json');
  294. const content = JSON.parse(file);
  295. for (var devDep in content.devDependencies) {
  296. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  297. content.devDependencies[devDep] = '*';
  298. }
  299. }
  300. for (var dep in content.dependencies) {
  301. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  302. content.dependencies[dep] = '*';
  303. }
  304. }
  305. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  306. };
  307. var repos = ['client'];
  308. // repos = gitRepos;
  309. repos.forEach(wipeDependencies);
  310. // if (require.main === module) {
  311. // } else {
  312. // module.exports = wipeDependencies
  313. // }
  314. }
  315. , 'upgrade': () => {
  316. console.log('upgrade.......');
  317. var tasks = [
  318. () => {
  319. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  320. inherit: true, shell: true
  321. , env: process.env
  322. }).catch((e) => { console.error(e); });
  323. p.position = 1;
  324. console.log('One');
  325. return p;
  326. }
  327. , () => {
  328. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  329. inherit: true, shell: true
  330. , env: process.env
  331. }).catch((e) => { console.error(e); });
  332. p.position = 2;
  333. console.log('Two');
  334. return p;
  335. }
  336. , () => {
  337. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  338. inherit: true, shell: true
  339. , env: process.env
  340. }).catch((e) => { console.error(e); });
  341. p.position = 3;
  342. console.log('Three');
  343. return p;
  344. }
  345. , () => {
  346. var p = nodeShellExec('n', ['latest'], {
  347. inherit: true, shell: true
  348. , env: process.env
  349. }).catch((e) => { console.error(e); });
  350. p.position = 4;
  351. console.log('Four');
  352. return p;
  353. }
  354. ];
  355. any(tasks);
  356. console.log('.......done');
  357. console.log('Running exlr upgrade in : ' + path.dirname(__dirname));
  358. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  359. console.info('Uninstalling existing ember globally');
  360. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  361. stdio: ['pipe', process.stdout, process.stderr],
  362. inherit: true,
  363. shell: true,
  364. cwd: path.dirname(__dirname),
  365. env: env
  366. });
  367. step1.on('close', () => {
  368. console.info('Installing ember globally');
  369. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  370. stdio: ['pipe', process.stdout, process.stderr],
  371. inherit: true,
  372. shell: true,
  373. cwd: path.dirname(__dirname),
  374. env: env
  375. });
  376. step2.on('close', () => {
  377. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  378. stdio: ['pipe', process.stdout, process.stderr],
  379. inherit: true,
  380. shell: true,
  381. cwd: path.dirname(__dirname),
  382. env: env
  383. });
  384. });
  385. });
  386. }
  387. , 'runas': () => {
  388. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  389. console.log('Testing Elevation');
  390. if (__isElevated) {
  391. try {
  392. op[processedArgs.label || processedArgs._[0] || 'h']();
  393. }
  394. catch (e) {
  395. console.error('Error Invalid command : ' + e);
  396. fs.writeFileSync('run.done', 'error');
  397. }
  398. finally {
  399. }
  400. }
  401. else {
  402. console.log('Requesting Elevated Privileges');
  403. // Wait for the runas to complete before we read it.
  404. try {
  405. fs.unlinkSync('run.done');
  406. fs.unlinkSync('run.log');
  407. }
  408. catch (e) { } //Ignore
  409. // Find node path to send to hta.
  410. return nodeShellExec('where', ['node']).then(r => {
  411. var namedArgs = [];
  412. console.log('result : ' + JSON.stringify(r));
  413. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  414. // PB : TODO -- Convert all the cli args back to string.
  415. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  416. args.push('--nodepath=' + r[r.length - 1]);
  417. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV);
  418. if (processedArgs.debug) args.push('--debug=true'); // Enable to debug elevated..
  419. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  420. , {
  421. inherit: true
  422. , shell: true
  423. , env: ENV
  424. , runas: 'self'
  425. , title: `runas`
  426. }
  427. ).then(() => {
  428. // runas returned.
  429. try {
  430. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  431. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  432. runaslog.forEach((logEntry) => {
  433. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  434. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  435. });
  436. }
  437. catch (e) {
  438. // We must have a runas log
  439. statuslog.statuslog(e);
  440. console.error('Run log error probably was not created by runas : ' + e);
  441. }
  442. })
  443. .catch(err => console.error('Elevation failed : ' + err));
  444. })
  445. }
  446. }
  447. , 'push': () => {
  448. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  449. // init remote bare from local
  450. // pushandinitremotebare
  451. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  452. // connect to repo server -- net use 172.16.0.27
  453. // cd 172.16.0.27/repos/
  454. // mkdir repo.git
  455. // cd repo.git
  456. // git init --bare
  457. // cd localrepo
  458. // git remote rename origin githubclone
  459. // git remote add origin //172.16.0.27/repos/repo.git
  460. // git push origin master
  461. var repo = processedArgs._[1];
  462. var sequentialTaskShellCommands = [];
  463. if (!existsSync(`Z:/${repo}.git`)) {
  464. sequentialTaskShellCommands = [
  465. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  466. // inherit : true, shell: true
  467. // , env: process.env
  468. // }]
  469. ['pwd', { cwd: 'Z:', inherit: true }]
  470. , ['mkdir', [`${repo}.git`], {
  471. cwd: `Z:`
  472. , inherit: true, shell: true
  473. , env: process.env
  474. }]
  475. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  476. , ['git', ['init', '--bare'], {
  477. cwd: `Z:/${repo}.git`
  478. , inherit: true, shell: true
  479. , env: process.env
  480. }]
  481. // PB : TODO -- Do this conditionally only...
  482. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  483. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  484. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  485. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  486. // PB : TODO -- If threre is a gitbubclone origin
  487. // Set the master to pull from the local repo.
  488. ];
  489. if (!existsSync(`Z:`)) {
  490. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  491. inherit: true, shell: true
  492. , env: process.env
  493. }]);
  494. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  495. // throw 'done'
  496. }
  497. }
  498. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  499. // console.dir(sequentialTaskShellCommands);
  500. var tasks = [];
  501. sequentialTaskShellCommands.forEach(shellcmd => {
  502. // console.log(shellcmd)
  503. tasks.push(() => {
  504. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  505. return p;
  506. });
  507. });
  508. any(tasks);
  509. }
  510. , 'is-git-repo': (dir) => {
  511. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  512. }
  513. // git remote equivalents...
  514. // git branch --set-upstream-to=elixir-unc/master master
  515. // git push --set-upstream elixir-unc branch..
  516. , 'remote': (args) => {
  517. // Subcommands!
  518. if(!processedArgs.v) return false; // Only -v is supported presently..
  519. var serial_perform = (repo) => {
  520. var options = { cwd: instanceroot + '/' + repo };
  521. return [
  522. ['git', ['remote', '-v'], options]
  523. ]
  524. };
  525. var x = (args) => {
  526. var tasq = () => {
  527. // console.log(args)
  528. return nodeShellExec.apply(null, args).catch(e => {
  529. // We continue on failure.
  530. console.error(tasq.toString());
  531. })
  532. };
  533. tasq.toString = function(){
  534. return JSON.stringify(args)
  535. };
  536. return tasq;
  537. };
  538. var perform = (dir) => {
  539. return any(serial_perform(dir.name).map(x))
  540. };
  541. dirs(perform);
  542. }
  543. , 'remote set-url': (args) => {
  544. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  545. var __args = {
  546. remotename : args.remotename || processedArgs._[2]
  547. , url : args.url || processedArgs._[3]
  548. };
  549. // pushable doesn't mean the remote doesn't support being pushed to.
  550. // 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.
  551. // PB : TODO -- change this to enablepushing.
  552. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  553. var pushable = processedArgs.pushable || false;
  554. remotename = __args.remotename;
  555. url = __args.url;
  556. var serial_perform_git_seturl = (repo) => {
  557. // console.log(repo)
  558. if (pushable) {
  559. return [
  560. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  561. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  562. ]
  563. }
  564. else {
  565. return [
  566. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  567. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  568. ]
  569. }
  570. };
  571. var x = (args) => {
  572. var tasq = () => {
  573. // console.log(args)
  574. return nodeShellExec.apply(null, args).catch(e => {
  575. // We continue on failure.
  576. console.error(tasq.toString());
  577. })
  578. };
  579. tasq.toString = function(){
  580. return JSON.stringify(args)
  581. };
  582. return tasq;
  583. };
  584. var perform_git_seturl = (dir) => {
  585. op['is-git-repo'](dir).then((logEntry) => {
  586. return any(serial_perform_git_seturl(dir.name).map(x))
  587. }).catch((e) => {
  588. // console.log('Failed : ' + dir.name)
  589. });
  590. };
  591. dirs(perform_git_seturl);
  592. }
  593. , 'reset' : ()=>{
  594. // Reset the whole installation pertaining to this elxr folder.
  595. }
  596. , 'remote add': (args) => {
  597. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  598. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  599. // That explicitly has a remote name prefix.
  600. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  601. // git branch branch_name -u your_new_remote/branch_name -- older versions
  602. // git branch -vv -- Detect which branch are we tracking.
  603. // default upstream should be users own fork.
  604. // Also need alias branches to
  605. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  606. // probably git merge from all remotes... and relevant branches...
  607. // alias pushall='for i in `git remote`; do git push $i; done;'
  608. // alias pullall='for i in `git remote`; do git pull $i; done;'
  609. // args === processedArgs ? args = {} : null;
  610. var __args = {
  611. remotename : args.remotename|| processedArgs._[2]
  612. , url : args.url || processedArgs._[3]
  613. , branch : args.branch || processedArgs._[4]
  614. };
  615. var remotename = __args.remotename;
  616. var url = __args.url;
  617. var branch = __args.branch;
  618. var pushable = processedArgs.pushable || false;
  619. var serial_perform_git_add = (repo) => {
  620. // console.log(repo)
  621. if (pushable) {
  622. return [
  623. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  624. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  625. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  626. ]
  627. }
  628. else {
  629. return [
  630. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  631. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  632. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  633. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  634. ]
  635. }
  636. };
  637. var x = (args) => {
  638. return () => {
  639. // console.log(args)
  640. return nodeShellExec.apply(null, args)
  641. }
  642. // return Promise.resolve(true)
  643. };
  644. var perform_git_add = (dir) => {
  645. op['is-git-repo'](dir).then((logEntry) => {
  646. // console.log(code)
  647. if (logEntry.success) {
  648. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  649. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  650. })
  651. .catch((e) => {
  652. any(serial_perform_git_add(dir.name).map(x));
  653. });
  654. }
  655. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  656. }).catch((e) => {
  657. console.log('Failed : ' + dir.name);
  658. });
  659. };
  660. require("fs").promises;
  661. dirs(perform_git_add);
  662. }
  663. , 'remote remove': (args) => {
  664. var __args = {
  665. remotename : args.remotename|| processedArgs._[2]
  666. };
  667. var remotename = __args.remotename;
  668. var serial_perform_git_remove = (repo) => {
  669. // console.log(repo)
  670. return [
  671. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  672. ]
  673. };
  674. var x = (args) => {
  675. return () => {
  676. // console.log(args)
  677. return nodeShellExec.apply(null, args)
  678. }
  679. // return Promise.resolve(true)
  680. };
  681. var perform_git_remove = (dir) => {
  682. op['is-git-repo'](dir).then((logEntry) => {
  683. // console.log(code)
  684. if (logEntry.success) {
  685. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  686. any(serial_perform_git_remove(dir.name).map(x));
  687. })
  688. .catch((e) => {
  689. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
  690. });
  691. }
  692. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  693. }).catch((e) => {
  694. // console.log('Failed : ' + dir.name)
  695. });
  696. };
  697. require("fs").promises;
  698. dirs(perform_git_remove);
  699. }
  700. , 'init-gitea': (user) => {
  701. user = user || processedArgs._[1];
  702. if (!user) throw 'User name required'
  703. var serial_perform_init_gitea = (repo) => {
  704. // console.log(repo)
  705. return [
  706. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  707. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  708. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  709. ]
  710. };
  711. var x = (args) => {
  712. return () => {
  713. // console.log(args)
  714. return nodeShellExec.apply(null, args)
  715. }
  716. // return Promise.resolve(true)
  717. };
  718. var perform_init_gitea = (dir) => {
  719. op['is-git-repo'](dir).then((logEntry) => {
  720. // console.log(code)
  721. if (logEntry.success) {
  722. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  723. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  724. })
  725. .catch((e) => {
  726. any(serial_perform_init_gitea(dir.name).map(x));
  727. });
  728. }
  729. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  730. }).catch((e) => {
  731. // console.log('Failed : ' + dir.name)
  732. });
  733. };
  734. require("fs").promises;
  735. dirs(perform_init_gitea);
  736. }
  737. , 'syncmaster': (label) => {
  738. // Usage :
  739. // elxr pull -- Defaults to run config
  740. Object.assign({}, process.env); // Shallow clone it.
  741. // console.dir(env)
  742. console.log('Running exlr pull : ' + path.dirname(__dirname));
  743. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  744. if (__isElevated) {
  745. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  746. fs.writeFileSync('run.done', 'success');
  747. }).catch(() => {
  748. fs.writeFileSync('run.done', 'error');
  749. })
  750. }
  751. else return op['runas']()
  752. }
  753. , 'repo-relocate' : function(args){
  754. // relocate a subfolder in source repo to same subfolder in target repo with history.
  755. var args = args || {
  756. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  757. , folder : processedArgs._[3] || 'server'
  758. , sourcerepo : processedArgs._[2] || 'client'
  759. , targetrepo : processedArgs._[1] || 'elixir-server'
  760. };
  761. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  762. // , stdio: ['pipe', process.stdout, process.stderr]
  763. , inherit: true,
  764. shell: true,
  765. env: process.env
  766. , runas: processedArgs.runas
  767. };
  768. return op['repo-split'](args).then(()=>{
  769. return op['repo-merge'](args).then(()=>{
  770. // cleanup folder from source.
  771. var cmdseq = [
  772. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  773. // commits have to intentional...
  774. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  775. ];
  776. return any(cmdseq.map(callsheltask))
  777. })
  778. }).catch(e=>{console.error(e);})
  779. }
  780. , 'repo-split' : function(args) {
  781. // https://gist.github.com/smdabdoub/17065c348289158277b5
  782. /**
  783. * Eg : folder, remotebase, sourcerepo, targetrepo
  784. * args.folder = 'server'
  785. * args.remotebase = 'https://git.bbh/chess/'
  786. * args.sourcerepo = 'client'
  787. * args.targetrepo = 'elixir-server'
  788. */
  789. var args = args || {
  790. folder : 'server'
  791. , remotebase : 'http://git.bbh/chess/'
  792. , sourcerepo : 'client'
  793. , targetrepo : 'elixir-server'
  794. };
  795. var options = { cwd: `${instanceroot}/relocate`
  796. // , stdio: ['pipe', process.stdout, process.stderr]
  797. , inherit: true,
  798. shell: true,
  799. env: process.env
  800. , runas: processedArgs.runas
  801. };
  802. var cmdseq = [
  803. // create a temporary working dir in current folder where we started execution.
  804. ['mkdir', [ '-p', 'relocate']]
  805. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  806. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  807. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  808. ];
  809. return any(cmdseq.map(callsheltask)).then(() => {
  810. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  811. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  812. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  813. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  814. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  815. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  816. // subtree split and filter-branch are options. We currently use repo-filter.
  817. return op['filter-repo'](args)
  818. }).catch(e=>{console.error(e); throw 'failed'})
  819. }
  820. , 'repo-merge' : function(args) {
  821. // Merge source repo into target repo
  822. var args = args || {
  823. folder : 'server'
  824. , remotebase : 'http://git.bbh/chess/'
  825. , sourcerepo : 'client'
  826. , targetrepo : 'elixir-server'
  827. };
  828. ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  829. // , stdio: ['pipe', process.stdout, process.stderr]
  830. , inherit: true,
  831. shell: true,
  832. env: process.env
  833. , runas: processedArgs.runas
  834. });
  835. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  836. // , stdio: ['pipe', process.stdout, process.stderr]
  837. , inherit: true,
  838. shell: true,
  839. env: process.env
  840. , runas: processedArgs.runas
  841. };
  842. var cmdseq = [
  843. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  844. , targetrepooptions ]
  845. // , ['git', ['push', targetrepooptions ] // manual push for now..
  846. ];
  847. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e);})
  848. }
  849. , 'filter-repo' : function(args){
  850. // Merge source repo into target repo
  851. var args = args || {
  852. folder : 'server'
  853. , remotebase : 'http://git.bbh/chess/'
  854. , targetrepo : 'elixir-server'
  855. };
  856. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  857. , inherit: true, shell: true
  858. , env: process.env
  859. , runas: processedArgs.runas
  860. };
  861. var cmdseq = [
  862. // git checkout -b feature/merge-old-project
  863. // git remote add src-project ../src-project
  864. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  865. ];
  866. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  867. }
  868. , 'filter-branch' : function(preservefolder, repo){
  869. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  870. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  871. // Preserve a specific folder.
  872. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  873. /*
  874. git clone repo reposplit
  875. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  876. git remote rm origin
  877. */
  878. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  879. }
  880. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  881. // // Merge repo2 into a subfolder in repo1
  882. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  883. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  884. // /*
  885. // cd repo1
  886. // git remote add -f tempmergesource ../{{mergesource}}/.git
  887. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  888. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  889. // git commit
  890. // // Repair History
  891. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  892. // #!/usr/bin/env bash
  893. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  894. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  895. // subdir=server
  896. // git filter-branch --tree-filter '
  897. // first='"$first"'
  898. // last='"$last"'
  899. // subdir='"$subdir"'
  900. // log_file=/tmp/filter.log
  901. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  902. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  903. // echo "=== $GIT_COMMIT: making changes"
  904. // files=$(git ls-tree --name-only $GIT_COMMIT)
  905. // mkdir -p $subdir
  906. // for i in $files; do
  907. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  908. // done
  909. // else
  910. // echo "=== $GIT_COMMIT: ignoring"
  911. // fi \
  912. // >> $log_file
  913. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  914. // status=0 # tell tree-filter never to fail
  915. // '
  916. // git remote rm tempmergesource
  917. // */
  918. // // better alternative for history
  919. // /**
  920. // *
  921. // git clone git@server.com:old-project.git
  922. // git clone git@server.com:new-project.git
  923. // cd old-project
  924. // mkdir old-project
  925. // git mv !(old-project) old-project
  926. // ls -la and gt mv hidden files ....
  927. // git commit -a -S -m “Moving old project into its own subdirectory”
  928. // cd ../new-project
  929. // git remote add old-project ../old-project
  930. // git fetch old-project
  931. // git checkout -b feature/merge-old-project
  932. // git merge -S --allow-unrelated-histories old-project/master
  933. // git push origin feature/merge-old-project
  934. // git remote rm old-project
  935. // */
  936. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  937. // }
  938. , 'pull' : (label) => {
  939. // Usage :
  940. // elxr pull -- Defaults to run config
  941. return elxr.getpulltask(selectedinstance)()
  942. }
  943. , 'isInstalled': () => {
  944. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  945. console.log(processedArgs._[1] + ' exists.');
  946. return true;
  947. });
  948. }
  949. , 'i' : () => {
  950. var tasks = [];
  951. // tasks.push(op['pull']);
  952. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  953. tasks.push(op['use']);
  954. if (!__isElevated) {
  955. tasks.push(op['npmi']);
  956. }
  957. // var tasksdefs = [
  958. // ['elxr', ['pull']]
  959. // , ['elxr', ['use', 'elixir']]
  960. // , ['elxr', ['npmi']]
  961. // ]
  962. // tasksdefs.forEach(tasksdef=>{
  963. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  964. // })
  965. return any(tasks);
  966. }
  967. , 'npmi': () => {
  968. var tasks = [];
  969. // Build fails without babel...
  970. tasks.push(getShellTask(
  971. 'npm',[ 'i', '-g', 'babel-cli' ]
  972. ) );
  973. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  974. npmbuildrepos = [];
  975. npmbuildrepos.forEach(repo => {
  976. tasks.push(() => {
  977. return nodeShellExec('npm', ['i --force'], {
  978. inherit: true, shell: true
  979. , cwd: instanceroot + '/' + repo
  980. , env: process.env
  981. , title: `npm i for ${repo}`
  982. }).catch((e) => {
  983. console.error('Ignoring Benign Error'); console.error(e);
  984. }).then(() => {
  985. console.log(`--npm run build for ${repo}--------------------`);
  986. return nodeShellExec('npm', ['run build'], {
  987. inherit: true, shell: true
  988. , cwd: instanceroot + '/' + repo
  989. , env: process.env
  990. , title: `npm run build for ${repo}`
  991. }).then(Tasq.then).catch(Tasq.catch)
  992. })
  993. });
  994. });
  995. any(tasks).then(() => {
  996. gitRepos.push('client/server');
  997. gitRepos = gitRepos.concat(elevatedRunasRepos);
  998. // gitRepos = [
  999. // // 'bbhverse', 'serververse', 'elixir-server',
  1000. // // 'clientverse',
  1001. // 'client'
  1002. // ];
  1003. var rmtasks = [];
  1004. var repotasks = [];
  1005. var env = Object.assign({}, process.env);
  1006. delete env.NODE_ENV;
  1007. gitRepos.forEach(repodef => {
  1008. rmtasks.push(
  1009. // () => {
  1010. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1011. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1012. (callShellTask(['rm', ['package-lock.json'], {
  1013. inherit: true, shell: true
  1014. , cwd: instanceroot + '/' + repodef.repo
  1015. , env: process.env
  1016. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1017. }]))()
  1018. .then(()=>{
  1019. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  1020. }).catch((e) => { console.error(e); })
  1021. // }
  1022. );
  1023. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1024. repotasks.push(
  1025. () => {
  1026. console.log(`--npm i for ${repodef.repo}--------------------`);
  1027. var p = nodeShellExec('npm', ['i', '--force'], {
  1028. inherit: true, shell: true
  1029. , cwd: instanceroot + '/' + repodef.repo
  1030. , env
  1031. , title: `npm i for ${repodef.repo}`
  1032. }).then(Tasq.then).catch(Tasq.catch);
  1033. return p;
  1034. });
  1035. }
  1036. });
  1037. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1038. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1039. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1040. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1041. // Second time try also doesnt work.
  1042. // repotasks.push(
  1043. // () => {
  1044. // var env = Object.assign({}, process.env)
  1045. // delete env.NODE_ENV
  1046. // console.log(`--------------------second time npm i for client--------------------`)
  1047. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1048. // // return nodeShellExec('npm', ['i --force'], {
  1049. // inherit: true, shell: true
  1050. // , cwd: instanceroot + '/' + 'client'
  1051. // , env
  1052. // , title: `npm i for client`
  1053. // }).then(Tasq.then).catch(Tasq.catch)
  1054. // })
  1055. var bowerRepos = [{ repo : 'client'}];
  1056. bowerRepos.forEach(repodef => {
  1057. repotasks.push(() => {
  1058. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  1059. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1060. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1061. inherit: true, shell: true
  1062. , cwd: instanceroot + '/' + repodef.repo
  1063. , env: process.env
  1064. , title: `bower i for ${repodef.repo}`
  1065. }).then(Tasq.then).catch(Tasq.catch);
  1066. return p;
  1067. });
  1068. });
  1069. // console.log('rmtasks.length : ' + rmtasks.length)
  1070. return Promise.all(rmtasks).then(() => any(repotasks));
  1071. }).catch(e => {
  1072. }).finally(statuslog.finally);
  1073. }
  1074. , 'start': (label) => {
  1075. console.log('Starting Elixir Server.');
  1076. var env = Object.assign({}, process.env); // Shallow clone it.
  1077. // console.dir(env)
  1078. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1079. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  1080. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1081. // cmd = 'node'
  1082. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  1083. var childPromise = nodeShellExec(...cmd, {
  1084. // inherit : true,
  1085. shell: true,
  1086. detached: true,
  1087. stdio: 'ignore',
  1088. cwd: instanceroot + '/' + 'elixir-server'
  1089. , env: env
  1090. });
  1091. var child = childPromise.process;
  1092. if (typeof child.pid !== 'undefined') {
  1093. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1094. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1095. encoding: 'utf8'
  1096. });
  1097. }
  1098. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1099. // inherit : true,
  1100. // shell: true, detached: true,
  1101. // cwd : 'qms/server',
  1102. // env: env,
  1103. // shell : true
  1104. // })
  1105. // nodeShellExec('ember', ['s'], {
  1106. // // inherit : true,
  1107. // shell: true, detached: true,
  1108. // cwd : 'client/',
  1109. // env: env
  1110. // })
  1111. console.log('Starting Elixir Client Host.');
  1112. var cmd = ['ember', ['s']];
  1113. var childPromise = nodeShellExec(...cmd, {
  1114. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1115. // PB : TODO -- ember debugging.
  1116. // inherit : true,
  1117. shell: true,
  1118. detached: true,
  1119. stdio: 'ignore',
  1120. cwd: instanceroot + '/' + 'client'
  1121. , env: env
  1122. });
  1123. // .catch(e=>console.error(e))
  1124. child = childPromise.process;
  1125. if (typeof child.pid !== 'undefined') {
  1126. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1127. fs.writeFileSync('.client.server.pid', child.pid, {
  1128. encoding: 'utf8'
  1129. });
  1130. }
  1131. }
  1132. , 'stop': (label) => {
  1133. const kill = require('tree-kill');
  1134. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1135. encoding: 'utf8'
  1136. });
  1137. fs.unlinkSync('.elixir-server.elixir.server.pid');
  1138. console.log(serverPid);
  1139. kill(serverPid);
  1140. serverPid = fs.readFileSync('.client.server.pid', {
  1141. encoding: 'utf8'
  1142. });
  1143. fs.unlinkSync('.client.server.pid');
  1144. console.log(serverPid);
  1145. kill(serverPid);
  1146. }
  1147. , 'model' : () => {
  1148. if (__isElevated) {
  1149. var tasks = [
  1150. () => {
  1151. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1152. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1153. inherit: true, shell: true
  1154. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1155. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1156. , env: process.env
  1157. }).catch((e) => { console.error(e); });
  1158. return p;
  1159. }
  1160. ];
  1161. return any(tasks).then(() => {
  1162. fs.writeFileSync('run.done', 'success');
  1163. }).catch(() => {
  1164. fs.writeFileSync('run.done', 'error');
  1165. })
  1166. }
  1167. else return op['runas']()
  1168. }
  1169. , 'use' : () => {
  1170. // use a certain named instance.
  1171. // Eg :
  1172. // 1) elxr use elixir
  1173. // 2) elxr use cihsr
  1174. // If environment is not specified defaults to development.
  1175. // 1) NODE=test elxr use elixir
  1176. /*// Steps
  1177. 1) Delete Config and Data symlinks
  1178. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1179. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1180. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1181. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1182. */
  1183. var runconfig = { NODE_ENV: selectedinstance.node_env };
  1184. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')); } catch (e) { }
  1185. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1186. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1187. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1188. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1189. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  1190. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  1191. return
  1192. }
  1193. var tasks = [
  1194. () => {
  1195. if (existsSync('config')) {
  1196. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1197. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  1198. return p;
  1199. }
  1200. else return Promise.resolve(true);
  1201. },
  1202. () => {
  1203. if (existsSync('data')) {
  1204. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1205. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  1206. return p;
  1207. }
  1208. else return Promise.resolve(true);
  1209. },
  1210. ];
  1211. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1212. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1213. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1214. // console.log(process.env.cwd)
  1215. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  1216. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1217. var checkoutMap = { 'development': 'master' };
  1218. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  1219. var performPullOrCloneForBranch = (def)=>{
  1220. var promise = Promise.resolve(true);
  1221. if (!branch) {
  1222. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  1223. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
  1224. .catch((e) => { console.error(e); return { error: true, message: repo } });
  1225. }
  1226. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  1227. };
  1228. var performCloneAndCheckout = null;
  1229. // cant use git checkout -b it fails when branch already exists.
  1230. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1231. return performPullOrCloneForBranch(def).then(()=>{
  1232. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1233. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1234. // inherit : true, shell: true,
  1235. cwd: instanceroot + '/' + def.repo
  1236. // , stdio : ignore // Use when we want to silence output completely.
  1237. , runas: processedArgs.runas
  1238. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1239. }).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 } });
  1240. })
  1241. };
  1242. var mergeSources = {
  1243. 'development': null,
  1244. 'test': 'master',
  1245. 'production': 'master'
  1246. };
  1247. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  1248. // Checkout is reduced to pull provided the current branch is the targetbranch
  1249. if(branch === mergesource) performCheckout = (def) => {
  1250. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  1251. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  1252. if(branch === __branch) return performCloneAndCheckout(def)
  1253. return performPullOrCloneForBranch(def)
  1254. })
  1255. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1256. };
  1257. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1258. var performPullAll = (def) => {
  1259. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1260. return nodeShellExec('git', ['pull', '--all'], {
  1261. // inherit : true, shell: true,
  1262. cwd: instanceroot + '/' + def.repo
  1263. , runas: processedArgs.runas
  1264. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1265. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1266. };
  1267. var excludeCheckouts = Object.assign(exludeMergeRepos);
  1268. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  1269. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  1270. var performMerge = (def) => {
  1271. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1272. return nodeShellExec('git', ['merge', mergesource], {
  1273. inherit: true, shell: true,
  1274. cwd: instanceroot + '/' + def.repo
  1275. , runas: processedArgs.runas
  1276. }).catch((e) => { console.error(e); })
  1277. };
  1278. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  1279. // var performRepoOperation = function(def) {
  1280. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1281. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1282. // }
  1283. return any(tasks).then(() => {
  1284. var pr = Promise.resolve(true);
  1285. if (!__isElevated) {
  1286. pr = op['runas']();
  1287. return pr.then(()=>{
  1288. //target is the env is we specify in elxr use command. Default is dev
  1289. //Switch to target branch
  1290. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1291. // pull or clone target branch
  1292. .then(() => {
  1293. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1294. return any(gitRepos.map((repo) => performPullAll(repo)))
  1295. })
  1296. // switch to source branch
  1297. .then( () => {
  1298. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1299. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1300. })
  1301. //Pull on merge source branch
  1302. .then( () => {
  1303. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1304. return any(gitRepos.map((repo) => performPullAll(repo)))
  1305. })
  1306. //Switch to target branch
  1307. .then( () => {
  1308. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1309. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1310. })
  1311. .then( //Merge source branch to target branch
  1312. () => {
  1313. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1314. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  1315. })
  1316. })
  1317. }
  1318. else {
  1319. tasks = [
  1320. () => {
  1321. // Use junctions to avoid npm package issues
  1322. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1323. inherit: true, shell: true
  1324. , cwd : instanceroot
  1325. , env: process.env
  1326. }).catch((e) => { console.error(e); });
  1327. return p;
  1328. }
  1329. ];
  1330. if (processedArgs._[1]) {
  1331. tasks = tasks.concat(
  1332. [
  1333. () => {
  1334. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1335. inherit: true, shell: true
  1336. , cwd : instanceroot
  1337. , env: process.env
  1338. }).catch((e) => { console.error(e); });
  1339. return p;
  1340. }
  1341. ]
  1342. );
  1343. }
  1344. return any(tasks).then(()=>{
  1345. // checkout target branch
  1346. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1347. // pull or clone target branch
  1348. .then(() => {
  1349. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1350. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1351. })
  1352. // switch to source branch
  1353. .then( () => {
  1354. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1355. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1356. })
  1357. //Pull on merge source branch
  1358. .then( () => {
  1359. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1360. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1361. })
  1362. //Switch to target branch
  1363. .then( () => {
  1364. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1365. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1366. })
  1367. .then( //Merge source branch to target branch
  1368. () => {
  1369. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1370. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  1371. })
  1372. .then(() => {
  1373. fs.writeFileSync('run.done', 'success');
  1374. }).catch(() => {
  1375. fs.writeFileSync('run.done', 'error');
  1376. })
  1377. })
  1378. }
  1379. }).catch(() => {
  1380. fs.writeFileSync('run.done', 'error');
  1381. })
  1382. // Antibiotic stewardship program.
  1383. // 1st use is fine.
  1384. // Max vials dispense
  1385. // 2nd use Pharmacy needs justification Form.
  1386. // Approval after a certain period of time.
  1387. }
  1388. , 'g': () => {
  1389. if (processedArgs.h) {
  1390. console.log('elxr g [modelname] => generate a model named [modelname]');
  1391. console.log('elxr g => regenerate all known models');
  1392. return
  1393. }
  1394. // nodeShellExec('npm', ['init', '-y'], options);
  1395. // nodeShellExec('npm', ['init', '-y'], options);
  1396. // })
  1397. var g = {
  1398. 'client': () => {
  1399. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1400. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1401. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1402. stdio: ['pipe', process.stdout, process.stderr],
  1403. inherit: true,
  1404. shell: true,
  1405. cwd: path.dirname(__dirname),
  1406. env: env
  1407. });
  1408. },
  1409. 'modelr': () => {
  1410. var tasks = [
  1411. () => {
  1412. var p = nodeShellExec('"ember"', [
  1413. 'g'
  1414. , 'modelr'
  1415. , processedArgs._[2]], {
  1416. inherit: true, shell: true, env: process.env
  1417. }).then(() => {
  1418. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  1419. return true;
  1420. }).catch((e) => { console.error(e); });
  1421. return p;
  1422. },
  1423. () => {
  1424. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1425. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  1426. chromeprefs = JSON.parse(chromeprefs);
  1427. var previous = chromeprefs.download.default_directory;
  1428. var parentDir = path.dirname(__dirname);
  1429. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1430. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  1431. // PB : TODO -- detect where chrome is installed.
  1432. // PB : TODO -- set the download dir to the place where files are needed.
  1433. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1434. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1435. , '--profile-directory="chess"'
  1436. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1437. inherit: true, shell: true
  1438. , env: process.env
  1439. }).then(() => {
  1440. chromeprefs.download.default_directory = previous;
  1441. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  1442. return true;
  1443. }).catch((e) => { console.error(e); });
  1444. return p;
  1445. }
  1446. ,
  1447. () => {
  1448. console.log('Browser process should have closed here....');
  1449. return true;
  1450. }
  1451. ];
  1452. any(tasks);
  1453. }
  1454. };
  1455. g[processedArgs._[1]]();
  1456. }
  1457. };
  1458. require('util');
  1459. var cliname = 'elxr';
  1460. var ver = '1.1';
  1461. var readme = `
  1462. Command syntax examples
  1463. elxr
  1464. Displays help. Same as elxr h
  1465. elxr i
  1466. Runs interactive propmts to help choose installation options.
  1467. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1468. General command syntax.
  1469. Eg: NODE_ENV=development elxr pull elixir
  1470. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1471. The specific cmd defines what the value is interpreted as.
  1472. There are several cmds that do not require an {{instancename}} parameter.
  1473. Eg: elxr remote remove origin
  1474. Git operations or passthrough external commands on all repository folders in you working directory.
  1475. Main objectives.
  1476. elxr cli is a wrapper around other shell commands and api based operations.
  1477. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1478. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1479. `;
  1480. var help = `
  1481. ${readme}
  1482. # list of commands... please refer dveloper documentation for ${cliname}
  1483. ${
  1484. // util.inspect(
  1485. [Object.keys(op)]
  1486. // )
  1487. }
  1488. `;
  1489. var elxr = {
  1490. help() {
  1491. return chalk.cyanBright(`
  1492. -------------------------------------------------------------------------------
  1493. *** BBH Elixir ***
  1494. -------------------------------------------------------------------------------
  1495. elxr ${ver}
  1496. A cli tool for chess
  1497. ${help}
  1498. -------------------------------------------------------------------------------
  1499. `)
  1500. }
  1501. , info() {
  1502. return chalk.cyanBright(`
  1503. -------------------------------------------------------------------------------
  1504. *** BBH Elixir ***
  1505. -------------------------------------------------------------------------------
  1506. elxr ${ver}
  1507. A cli tool for chess
  1508. -------------------------------------------------------------------------------
  1509. `)
  1510. }
  1511. , getpulltask(def){
  1512. // def can be an instance config
  1513. // Or an object with many repos and elevated repos
  1514. // Or a single repo ( Either Elevated or normal. )
  1515. def = def || {
  1516. repos : selectedinstance.repos,
  1517. elevated : selectedinstance.elevated
  1518. };
  1519. var elevatedpulltasks = null;
  1520. if(def.repo) {
  1521. // Single repo case.
  1522. if(def.repo.requiresElevation) {
  1523. elevatedpulltasks = function() {
  1524. return performPull(def.repo).then(() => {
  1525. return true;
  1526. }).catch((e) => {
  1527. console.error(e);
  1528. })
  1529. };
  1530. return
  1531. }
  1532. else {
  1533. var regularpulltasks = function(){
  1534. var pendingpulls = [];
  1535. pendingpulls.push(performPull(def.repo));
  1536. return Promise.all(pendingpulls).finally(Traq.finally)
  1537. };
  1538. }
  1539. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1540. else return getTaskWithoutElevation({ regularpulltasks})
  1541. }
  1542. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1543. console.dir(def);
  1544. Object.assign({}, process.env); // Shallow clone it.
  1545. console.log('Running exlr pull : ' + path.dirname(__dirname));
  1546. processedArgs.useGitPull || false;
  1547. if(def.elevated || def.repos) {
  1548. if(def.elevated) def.requiresElevation = true;
  1549. else delete def.requiresElevation;
  1550. }
  1551. else {
  1552. if(def.requiresElevation) def.elevated = [def];
  1553. else def.repos = [def];
  1554. }
  1555. var regularpulltasks = function(){ return Promise.resolve(true) };
  1556. if(def.elevated){
  1557. elevatedpulltasks = function() {
  1558. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1559. return true;
  1560. }).catch((e) => {
  1561. console.error(e);
  1562. })
  1563. };
  1564. }
  1565. if(def.repos) {
  1566. var regularpulltasks = function(){
  1567. var pendingpulls = [];
  1568. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  1569. return Promise.all(pendingpulls).finally(Traq.finally)
  1570. };
  1571. }
  1572. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1573. else return getTaskWithoutElevation({ regularpulltasks})
  1574. }
  1575. };
  1576. function preworkerconfig(){
  1577. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1578. gitRepos = selectedinstance.repos;
  1579. // gitRepos = ['chess-server-lib'];
  1580. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1581. elevatedRunasRepos = selectedinstance.elevated;
  1582. // Repos that should excluded from merge for releases...
  1583. exludeMergeRepos = selectedinstance.exludeMergeRepos;
  1584. }
  1585. // The main elxr cli process
  1586. function elxrworker() {
  1587. var subcommandlabels = {
  1588. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1589. };
  1590. var __runcmd = function (label) {
  1591. var distinquishedlabel = subcommandlabels[label] || label;
  1592. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1593. };
  1594. // --runas
  1595. if (processedArgs.runas) {
  1596. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1597. return __runcmd('runas')
  1598. }
  1599. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1600. }
  1601. function acquireChoices(selectedinstance) {
  1602. console.warn(chalk.cyan(`
  1603. -------------------------------------------------------------------------------
  1604. Warning : Cannot locate your preferred configuration since it was not specified
  1605. You should fork the default chess configuration to customize and make it
  1606. your own instance with a named config as
  1607. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1608. And then run this tool as follows
  1609. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1610. OR
  1611. Run this tool with the following command to use a quick start default.
  1612. elxr --default
  1613. OR
  1614. Choose one of the options below to run interactively.
  1615. We will run your choice at the next prompt.
  1616. -------------------------------------------------------------------------------
  1617. `));
  1618. var prompt = cli.prompter;
  1619. return prompt.ask(`Choose an option :
  1620. d) Install the default chess instance.
  1621. => elxr i chess node_env=development --default
  1622. n) Create your custom new instance interactively
  1623. => elxr i {{instanceName}} node_env={{environment}}
  1624. i) Choose an instance and environment to install
  1625. => elxr i {{instanceName}} node_env={{environment}}
  1626. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1627. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1628. h) Help
  1629. q) Quit
  1630. Default <= d
  1631. : `).then((choice) => {
  1632. if (choice && choice === 'd' || !choice) {
  1633. processedArgs._[0] = 'i';
  1634. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  1635. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  1636. selectedinstance.reposerver = 'https://git.bbh.org.in';
  1637. }
  1638. else if (choice === 'h') {
  1639. processedArgs._[0] = 'h';
  1640. fs.writeFileSync('run.done', 'noop help');
  1641. console.log(elxr.help()); process.exit();
  1642. }
  1643. else if (choice === 'n' || choice === 'i') {
  1644. var p1 = cli.prompter;
  1645. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1646. processedArgs._[0] = 'i';
  1647. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1648. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1649. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  1650. if (choice === 'n') {
  1651. selectedinstance.reposerver = 'https://git.bbh.org.in';
  1652. console.warn(
  1653. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'));
  1654. process.exit();
  1655. }
  1656. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1657. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  1658. })
  1659. })
  1660. })
  1661. } else if (choice === 'c') {
  1662. var p1 = cli.prompter;
  1663. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1664. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1665. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1666. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  1667. return p1.ask(`Enter cmd :
  1668. p) pull
  1669. Default <= p
  1670. : `).then(function (cmd) {
  1671. if (!cmd || cmd === 'p') {
  1672. processedArgs._[0] = 'pull';
  1673. }
  1674. else processedArgs._[0] = cmd;
  1675. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1676. selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  1677. })
  1678. })
  1679. })
  1680. })
  1681. } else {
  1682. 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.`));
  1683. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' });
  1684. fs.writeFileSync('run.done', 'noop quit');
  1685. process.exit();
  1686. }
  1687. })
  1688. }
  1689. var mergeObjByKey = function(arrOfObjs, keyName) {
  1690. var keyedDistinct = {};
  1691. var distinctArrOfObjs = [];
  1692. arrOfObjs.forEach( o => {
  1693. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
  1694. });
  1695. Object.keys(keyedDistinct).forEach(key => {
  1696. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ); // PB : TODO -- Shallow use utils.assign
  1697. });
  1698. return distinctArrOfObjs;
  1699. };
  1700. var cacheWriteInstanceConfig = function(chessinstances){
  1701. var instanceName = chessinstances['current_run'].instanceName;
  1702. var node_env = chessinstances['current_run'].node_env;
  1703. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1704. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1705. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  1706. };
  1707. var acquireConfig = function (selected) {
  1708. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1709. return performPull(configrepo).then(() => {
  1710. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1711. selectedinstance = require(manifestpath)();
  1712. // Config from server always override merges into selection ecept for the current selection.
  1713. // PB : TODO -- utils.assign Array merges are non-distinct...
  1714. if(!selectedinstance.repos[0].repo) {
  1715. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  1716. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  1717. }
  1718. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  1719. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  1720. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  1721. }
  1722. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance);
  1723. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
  1724. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  1725. cacheWriteInstanceConfig(chessinstances);
  1726. ENV.NODE_ENV = selectedinstance.node_env;
  1727. })
  1728. .catch((e) => {
  1729. console.error(e);
  1730. console.error('Config acquisition failed.');
  1731. })
  1732. };
  1733. var launchpath = path.normalize(process.cwd());
  1734. 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.
  1735. // The easisest would be to ask for a target directory and default to current dir....
  1736. var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  1737. var __default = {
  1738. // Default is public server only.
  1739. // All public repos are by default available.
  1740. reposervers: ['https://git.bbh.org.in']
  1741. , repos: [
  1742. { repo : 'setup' }
  1743. , { repo : 'elxr' }
  1744. , { repo : 'loopback-connector-mysql' }
  1745. , { repo : 'loopback-jsonapi-model-serializer' }
  1746. , { repo : 'loopback-component-jsonapi' }
  1747. , { repo : 'ember-service-worker' }
  1748. , { repo : 'ember-service-worker-asset-cache' }
  1749. , { repo : 'ember-service-worker-cache-fallback' }
  1750. , { repo : 'ember-service-worker-index' }
  1751. , { repo : 'ember-sw-client-route' }
  1752. ]
  1753. , elevated: []
  1754. , exludeMergeRepos: {}
  1755. , instanceName: 'chess'
  1756. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1757. , node_env: 'development'
  1758. };
  1759. var hasElxr = function(path, options, cb) {
  1760. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  1761. options = options || {};
  1762. var tasks = [
  1763. '/elxr' // Is there a subfolder named elxr
  1764. , '/elxr/.git' // which is self git repository
  1765. , '/elxr/.elxr' // and has .elxr subfolder
  1766. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  1767. ];
  1768. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  1769. var value = existsFolderSync(path + tpath);
  1770. return { value, done : acc && !value };
  1771. }).value }
  1772. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  1773. var value = existsFolderSync(path + tpath);
  1774. return { value, done : acc && !value };
  1775. }).value );
  1776. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  1777. var value = existsFolderSync(path + tpath);
  1778. return { value, done : acc && !value };
  1779. }).value);
  1780. };
  1781. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); };
  1782. var detectfromroot = function(root){
  1783. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  1784. };
  1785. var detectinstances = function () {
  1786. console.log(`launchpath = ${launchpath}`);
  1787. console.log(`thisscriptdir = ${thisscriptdir}`);
  1788. // PB : TODO -- !Postpone this.
  1789. console.log(`instanceroot = ${instanceroot}`); // Not yet confirmed...
  1790. // Note : Paths should already be normalized fefore this.
  1791. var root = instanceroot;
  1792. var detected = { root };
  1793. var instanceoptions = [clioverrides];
  1794. return hasElxr(launchpath).then( (elxrCliExists) => {
  1795. // We need a reference to the root director for elxr cli to be properly oriented.
  1796. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  1797. // We were run from the proper root with elxr cli in the subfolder.
  1798. instanceroot = root = launchpath;
  1799. instanceoptions.splice( 0, 0, detected = { root });
  1800. instanceoptions.splice( 0, 0, detectfromroot(root));
  1801. }
  1802. else {
  1803. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  1804. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  1805. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  1806. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.');
  1807. instanceroot = root = launchpath;
  1808. instanceoptions.splice( 0, 0, detected = { root });
  1809. instanceoptions.splice( 0, 0, detectfromroot(root));
  1810. }
  1811. else if (launchpath === thisscriptdir) {
  1812. var parentHasElxr = hasElxrSync(launchpath + '/..');
  1813. // PB : TODO -- verify if we have .elxr folder in the parent...
  1814. if(!parentHasElxr) {
  1815. // ! thisscriptdir is not elxr.
  1816. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.');
  1817. }
  1818. // Same directory doesn't mean we are being run from elxr sub directory.
  1819. // In standalone build script we may or not be in the same location.
  1820. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1821. // Unbuilt therefore we are in the elxr sub directory.
  1822. instanceroot = root = path.normalize(launchpath + '/..');
  1823. instanceoptions.splice( 0, 0, detected = { root });
  1824. instanceoptions.splice( 0, 0, detectfromroot(root));
  1825. }
  1826. else {
  1827. // Built version.
  1828. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  1829. if(parentHasElxr) {
  1830. // Built version was run from the full elxr subfolder. Should work
  1831. // PB : TODO -- but we should switch to the full version...
  1832. instanceroot = root = path.normalize(launchpath + '/..');
  1833. instanceoptions.splice( 0, 0, detected = { root });
  1834. instanceoptions.splice( 0, 0, detectfromroot(root));
  1835. }
  1836. else {
  1837. instanceroot = root = launchpath;
  1838. instanceoptions.splice( 0, 0, detected = { root });
  1839. instanceoptions.splice( 0, 0, detectfromroot(root));
  1840. // Assume current launchpath is a new instance and create.
  1841. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  1842. // if(clioverrides.instanceName) {
  1843. // if(clioverrides.node_env) {
  1844. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  1845. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  1846. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  1847. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  1848. // // eg : floder name can be elixir01 but instance name is elixr
  1849. // }
  1850. // else {
  1851. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  1852. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  1853. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  1854. // }
  1855. // }
  1856. // else {
  1857. // instanceroot = root = launchpath;
  1858. // if(clioverrides.node_env) {
  1859. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  1860. // instanceoptions.splice( 0, 0, detectfromroot(root))
  1861. // }
  1862. // else {
  1863. // // Nothing was specified... We only have one option from root.
  1864. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  1865. // }
  1866. // }
  1867. }
  1868. }
  1869. }
  1870. else {
  1871. if(elxrCliExists) {
  1872. instanceroot = root = launchpath;
  1873. instanceoptions.splice( 0, 0, detected = { root });
  1874. instanceoptions.splice( 0, 0, detectfromroot(root));
  1875. }
  1876. }
  1877. }
  1878. instanceroot = detected.root;
  1879. __default.root = root;
  1880. clioverrides.root = clioverrides.root || root;
  1881. // Resolves empty array when No known instances detected.
  1882. return Promise.resolve(instanceoptions)
  1883. })
  1884. };
  1885. var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
  1886. return function(prompts, k, i, a){
  1887. // No local instances config found. We use a default initialized instance available in selectedinstance
  1888. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  1889. // PB : TODO -- selectedinstance === __default check to prompt everything...
  1890. if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
  1891. || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
  1892. || reconfirm[k]) {
  1893. prompts.push(async ()=>{
  1894. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  1895. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  1896. // If latest altered state is required we can reerence this directly.
  1897. // var asyncthis = Object.assign(this);
  1898. promptables[k].choices = choices[k];
  1899. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  1900. return await target[k]
  1901. });
  1902. }
  1903. delete mustPrompt[k];
  1904. return prompts
  1905. }
  1906. };
  1907. var __interactve_promts = function( target, choices ){
  1908. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  1909. var interactionpoints = {
  1910. runchoice : {
  1911. label :
  1912. `Choose an option :
  1913. d) Install the default chess instance.
  1914. => elxr i chess node_env=development --default
  1915. n) Create your custom new instance interactively
  1916. => elxr i {{instanceName}} node_env={{environment}}
  1917. i) Choose an instance and environment to install
  1918. => elxr i {{instanceName}} node_env={{environment}}
  1919. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1920. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1921. h) Help
  1922. q) Quit
  1923. : `
  1924. , choices : []
  1925. , defaultchoice : 'c'
  1926. , interpret : function(choice){
  1927. var interpret_map = {
  1928. d : function(){
  1929. processedArgs._[0] = 'i';
  1930. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  1931. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  1932. target.reposerver = 'https://git.bbh.org.in';
  1933. }
  1934. , n : function() { processedArgs._[0] = 'i'; }
  1935. , i : function() { processedArgs._[0] = 'i'; }
  1936. , c : async function() {
  1937. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  1938. label : `Enter cmd :
  1939. p) pull
  1940. Default <= p
  1941. : `
  1942. , defaultchoice : 'pull'
  1943. }
  1944. ));
  1945. var cmd = await target['cmd'];
  1946. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull'; }
  1947. else target['cmd'] = processedArgs._[0] = cmd;
  1948. return cmd;
  1949. }
  1950. , h : function() { console.log(elxr.help()); process.exit(); } // PB : TODO -- Why do we need log.
  1951. , q : function() { process.exit(); }
  1952. };
  1953. var __interpreter = interpret_map['c'];
  1954. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  1955. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  1956. return __interpreter.call(target)
  1957. }
  1958. }
  1959. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  1960. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
  1961. , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
  1962. };
  1963. var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices);
  1964. return Object.keys(interactionpoints).reduce(eachPrompt, [])
  1965. };
  1966. var downloadsdir = '../Downloads';
  1967. var prerequisites = [
  1968. {
  1969. shellcmd: 'git',
  1970. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1971. , installer: 'Git-2.31.0-64-bit.exe'
  1972. , installcmd: ['cmd', ['/c', 'start',
  1973. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1974. , '/VERYSILENT'
  1975. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1976. ]]
  1977. , preinstallsteps: function() {
  1978. var prompt = cli.prompter;
  1979. var steps = [
  1980. () => {
  1981. if (!existsSync(downloadsdir + '/' + this.installer)) {
  1982. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  1983. }
  1984. else return Promise.resolve(true)
  1985. }
  1986. ];
  1987. var prompts = [
  1988. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1989. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1990. ];
  1991. return any([any(steps), any(prompts)])
  1992. }
  1993. , installsteps: function () {
  1994. return any([this.installcmd].map(callsheltask))
  1995. }
  1996. , postinstallsteps: function(){
  1997. cli.prompter;
  1998. var gitUser = 'guest';
  1999. var gitEmail = 'guest@bbh.org.in';
  2000. var prompts = [];
  2001. prompts.push(
  2002. ()=>{
  2003. var choices = { 0 : 'guest', 1 : 'chessdemo' };
  2004. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  2005. }
  2006. );
  2007. prompts.push(
  2008. ()=>{
  2009. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
  2010. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  2011. }
  2012. );
  2013. return any(prompts).then(()=>{
  2014. var steps = [
  2015. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2016. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2017. ];
  2018. return any(steps.map(callsheltask)).then(() => {
  2019. })
  2020. });
  2021. }
  2022. , install: function () {
  2023. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2024. }
  2025. , verifyAndInstall : function(){
  2026. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2027. if(exists) {
  2028. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  2029. return this.getUser(null, this.postinstallsteps.bind(this))
  2030. }
  2031. return this.install();
  2032. });
  2033. }
  2034. , getUser : function(repo, onNoResult){
  2035. onNoResult = onNoResult || function(){return false};
  2036. var globalOrLocal = '--global';
  2037. if(!repo) globalOrLocal = '--global';
  2038. else globalOrLocal = '--local';
  2039. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  2040. // not yet configured.
  2041. if(!result.success) return onNoResult()
  2042. else {
  2043. var users = result.messages[0].trim().split('\n');
  2044. if(users.length === 0 ||
  2045. users.length === 1 && users[0] === 'guest') {
  2046. return onNoResult()
  2047. }
  2048. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  2049. }
  2050. })
  2051. .catch((e)=>{
  2052. console.log(e);
  2053. return onNoResult()
  2054. })
  2055. }
  2056. }
  2057. ,
  2058. {
  2059. shellcmd: 'node',
  2060. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  2061. , installer: 'node-v14.16.0-x64.msi'
  2062. , installcmd: ['MSIEXEC.exe', ['/i'
  2063. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  2064. , 'ACCEPT=YES', '/passive']]
  2065. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  2066. }
  2067. ];
  2068. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  2069. function ensureDirectoryExistence(filePath) {
  2070. var dirname = path.dirname(filePath);
  2071. if (fs.existsSync(dirname)) {
  2072. return filePath;
  2073. }
  2074. ensureDirectoryExistence(dirname);
  2075. fs.mkdirSync(dirname);
  2076. return filePath;
  2077. }
  2078. var mainTasks = [];
  2079. function verifyAndInstallPrerequisites() {
  2080. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  2081. // PB : TODO include and build from files... using rollup..
  2082. var downloadbatch =
  2083. `::**************************************************************************
  2084. :Download_ <url> <File>
  2085. Powershell.exe ^
  2086. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2087. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2088. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2089. exit /b
  2090. ::**************************************************************************`;
  2091. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  2092. var windowselevate =
  2093. `
  2094. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2095. <script language="vbscript">
  2096. document.title = "elxr control panel"
  2097. self.ResizeTo 200,600
  2098. Sub Window_Onload
  2099. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2100. End Sub
  2101. Set objShell = CreateObject("WScript.Shell")
  2102. Set objENV = objShell.Environment("Process")
  2103. dim NODE_ENV
  2104. NODE_ENV = objENV("NODE_ENV")
  2105. </script>
  2106. <script language="javascript">
  2107. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2108. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2109. // alert(windowselevate.commandLine)
  2110. var args = windowselevate.commandLine.split('"').slice(3);
  2111. alert(args)
  2112. var processedArgs = { _ : [] }
  2113. var namedArgs = [];
  2114. for(var item in args){
  2115. if(args[item].charAt(0) === '-'){
  2116. namedArgs.push(args[item])
  2117. var split = args[item].split('=');
  2118. processedArgs[split[0].slice(2)] = split[1] || true;
  2119. }
  2120. else processedArgs._.push(args[item]);
  2121. }
  2122. // args = args.forEach(function(item){ })
  2123. // alert('processedArgs._ : ' + processedArgs._);
  2124. // alert(processedArgs.runas);
  2125. // PB : TODO -- Convert all the cli args back to string.
  2126. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2127. alert(cargs)
  2128. var shell = new ActiveXObject('shell.application');
  2129. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2130. // shell.ShellExecute('where', 'node', '', '', 10);
  2131. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2132. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2133. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2134. window.onload = function() {
  2135. document.body.style.backgroundColor = 'black';
  2136. document.body.style.fontFamily = 'arial';
  2137. var log = document.createElement('div');
  2138. log.innerHTML='Please Wait';
  2139. function l(msg){ log.innerHTML+= msg; };
  2140. log.style.color = 'blue';
  2141. log.style.width = '95%';
  2142. log.id = 'log';
  2143. document.body.appendChild(log);
  2144. l('<Br/>Current config : ')
  2145. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2146. l('<Br/>cmd = ' + processedArgs._[0])
  2147. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2148. l('<Br/><Br/>')
  2149. var timer = function(){
  2150. l('.');
  2151. if(fso.FileExists("run.done")) close();
  2152. else window.setTimeout(timer, 1000);
  2153. };
  2154. window.setTimeout(timer, 3000);
  2155. };
  2156. </script>
  2157. </html>
  2158. `;
  2159. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  2160. var downloadtasks = [];
  2161. var installtasks = [];
  2162. prerequisites.forEach(preq => {
  2163. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2164. if (exists) console.log(`${preq.shellcmd} exists`);
  2165. else {
  2166. console.log(`${preq.shellcmd} is not installed`);
  2167. return preq.preinstallsteps.call(preq).then(() => {
  2168. installtasks.push(preq.install.bind(preq));
  2169. })
  2170. }
  2171. }));
  2172. });
  2173. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2174. }
  2175. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  2176. return {
  2177. get (){
  2178. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  2179. var asyncprop = Promise.resolve(propValue);
  2180. if(promptable.interpret){
  2181. asyncprop = promptable.interpret(propValue);
  2182. }
  2183. return asyncprop.then(
  2184. ()=>{
  2185. Object.defineProperty(this, propName, {
  2186. value: propValue,
  2187. writable: true,
  2188. configurable : true,
  2189. enumerable : true
  2190. });
  2191. return propValue
  2192. }
  2193. )
  2194. })
  2195. }
  2196. // , set (propValue){
  2197. // Object.defineProperty(this, propName, {
  2198. // value: propValue,
  2199. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  2200. // configurable : true,
  2201. // enumerable : true
  2202. // })
  2203. // return propValue;
  2204. // }
  2205. , configurable : true
  2206. , enumerable : true
  2207. }
  2208. };
  2209. function acquirelocalinstances(selected){
  2210. // utils.assign is used to cleanup duplicates...
  2211. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2212. return chessinstances
  2213. }
  2214. function findlocalinstances(chessinstances, instanceoptions){
  2215. // We can expect a .elxr at each level.
  2216. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  2217. earlyreduce( ( value, p, i, a )=>{
  2218. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  2219. if(existsSync( localinstancesPath )) {
  2220. try {
  2221. var chessinstances = acquirelocalinstances( { localinstancesPath } );
  2222. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  2223. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  2224. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  2225. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType]);
  2226. return {
  2227. value : chessinstances[instanceName][instanceType]
  2228. , done : true
  2229. };
  2230. }
  2231. })
  2232. })
  2233. }
  2234. catch(e){
  2235. return { }
  2236. }
  2237. }
  2238. else return { }
  2239. }
  2240. );
  2241. }
  2242. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2243. var selectedinstance = null;
  2244. var chessinstances = { current_run : {} };
  2245. var promptkeys = {
  2246. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  2247. // 'instanceName' : true
  2248. // , 'node_env' : true
  2249. };
  2250. function createChessInsance( cfg ){
  2251. var inst = {};
  2252. var __new = Object.assign({}, __default, cfg);
  2253. inst[cfg.node_env] = __new; return inst;
  2254. }
  2255. acquireElevationState().then(() => {
  2256. function initinstances(selected_overrides) {
  2257. var root = selected_overrides.root; // We should always have this coz we are running at some place which is fixed by detectinstances.
  2258. var instanceName = selected_overrides.instanceName
  2259. || clioverrides.instanceName
  2260. // || processedArgs._[1]
  2261. || chessinstances.current_run.instanceName;
  2262. var node_env = selected_overrides.node_env
  2263. || clioverrides.node_env
  2264. // || processedArgs.node_env
  2265. || chessinstances.current_run.node_env;
  2266. var reposerver = selected_overrides.reposerver
  2267. || clioverrides.reposerver
  2268. // || processedArgs.node_env
  2269. || chessinstances.current_run.reposerver;
  2270. if(!instanceName) {
  2271. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  2272. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2273. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2274. }
  2275. if(!node_env) {
  2276. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2277. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2278. }
  2279. if(!reposerver) {
  2280. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2281. }
  2282. chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
  2283. instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
  2284. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root };
  2285. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  2286. 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
  2287. }
  2288. // Override sequence.
  2289. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2290. selectedinstance = utils.assign(
  2291. chessinstances[instanceName][node_env]
  2292. , clioverrides
  2293. , selected_overrides
  2294. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  2295. );
  2296. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  2297. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  2298. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  2299. // // Brand New.
  2300. // selectedinstance = Object.assign( __default, selectedinstance )
  2301. // }
  2302. if(!selectedinstance.repos[0].repo) {
  2303. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  2304. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  2305. }
  2306. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2307. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  2308. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  2309. }
  2310. // Config from server always override merges into selection except for the current selection.
  2311. // PB : TODO -- utils.assign Array merges are non-distinct...
  2312. chessinstances[instanceName][node_env] = selectedinstance;
  2313. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2314. cacheWriteInstanceConfig(chessinstances);
  2315. // PB : TODO -- We should probably write the new server config also...
  2316. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  2317. return chessinstances
  2318. }
  2319. var noprerequisites = {
  2320. add : true, 'set-url' : true, 'repo-relocate' : true
  2321. , remote : true
  2322. };
  2323. var skipprereqs = {};
  2324. var maintask = () => {
  2325. // Default cmd to run !
  2326. processedArgs._[0] === processedArgs._[0] || 'pull';
  2327. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  2328. if(!noprerequisites[processedArgs._[0]]
  2329. && !skipprereqs[processedArgs._[0]]
  2330. ) {
  2331. return prerequisites.git.verifyAndInstall().then(()=>{
  2332. return acquireConfig(selectedinstance).catch((err) => {
  2333. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  2334. console.error(err);
  2335. }).then(() => { preworkerconfig(); return elxrworker() })
  2336. // .finally(()=>{
  2337. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2338. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2339. // // return process.exit()
  2340. // })
  2341. })
  2342. }
  2343. else {
  2344. console.log('cmd has no preqs or has been configured to skip preqs');
  2345. preworkerconfig();
  2346. return elxrworker()
  2347. }
  2348. };
  2349. const retaincount = 2;
  2350. var min = runtimestamp;
  2351. var collect = [];
  2352. if(noprerequisites[processedArgs._[0]]
  2353. || skipprereqs[processedArgs._[0]]
  2354. ) {
  2355. return elxrworker()
  2356. }
  2357. var getchoices = function(detectedinstanceoptions, promptkeys){
  2358. var instances = [];
  2359. var reposervers = [];
  2360. var instnaceNames = [];
  2361. var instanceTypes = ['development', 'production'];
  2362. Object.keys( chessinstances).forEach(instanceName => {
  2363. if(instanceName === 'current_run') return;
  2364. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  2365. var instance = chessinstances[instanceName][node_env];
  2366. reposervers = reposervers.concat(instance.reposervers);
  2367. if(instance.reposerver) reposervers.push(instance.reposerver);
  2368. instances.push(instance);
  2369. instanceTypes.push(instance.node_env);
  2370. instnaceNames.push(instance.instanceName);
  2371. });
  2372. });
  2373. instances = instances.concat(detectedinstanceoptions);
  2374. if(promptkeys['instanceName']) instnaceNames.push(selectedinstance['instanceName']);
  2375. if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName']);
  2376. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers']);
  2377. var choices = {
  2378. 'instanceName' : Array.from( new Set(instnaceNames) )
  2379. , 'reposerver' : Array.from( new Set(reposervers) )
  2380. , 'instanceType' : Array.from( new Set(instanceTypes) )
  2381. };
  2382. return choices;
  2383. };
  2384. return detectinstances().then((detectedinstanceoptions)=>{
  2385. detectedinstanceoptions.splice(0,0, __default);
  2386. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  2387. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2) );
  2388. promptkeys = utils.assign(promptkeys, clioverrides);
  2389. if(clioverrides.reconfirm) {
  2390. ({ 'instanceName' : selectedinstance['instanceName'] === 'chess' });
  2391. }
  2392. try {
  2393. chessinstances = acquirelocalinstances(selectedinstance);
  2394. findlocalinstances(chessinstances, detectedinstanceoptions);
  2395. var choices = getchoices(detectedinstanceoptions, promptkeys);
  2396. var todo = any( __interactve_promts(selectedinstance, choices) ).then(()=>{
  2397. return initinstances(selectedinstance)
  2398. });
  2399. }
  2400. catch (e) {
  2401. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  2402. var choices = getchoices(detectedinstanceoptions, promptkeys);
  2403. var todo = any( __interactve_promts(selectedinstance, choices) ).then(()=>{
  2404. return initinstances(selectedinstance)
  2405. });
  2406. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2407. // Weve not been told what to do.
  2408. todo = todo.then(() => { return acquireChoices(selectedinstance) });
  2409. }
  2410. todo = todo.then(() => {
  2411. try {
  2412. chessinstances = acquirelocalinstances(selectedinstance);
  2413. findlocalinstances(chessinstances, detectedinstanceoptions);
  2414. detectedinstanceoptions.splice(0,0, __default);
  2415. initinstances(selectedinstance);
  2416. }
  2417. catch (e) {
  2418. console.error(e);
  2419. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2420. console.log('A config will be createed with the instance and environment chosen...');
  2421. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2422. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2423. // return selectedinstance = Object.assign(__default, selectedinstance);
  2424. // })
  2425. return selectedinstance
  2426. }
  2427. });
  2428. }
  2429. return todo
  2430. })
  2431. .then(()=>{
  2432. if(!__isElevated) {
  2433. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`);
  2434. // collect garbage
  2435. return dirs( (dir)=>{
  2436. var matches = /run-(.*)/gm.exec(dir.name);
  2437. if(matches) {
  2438. if(+(matches[1]) < min) {
  2439. min = matches[1];
  2440. collect.splice( 0, 0, matches[1] );
  2441. }
  2442. else collect.push(matches[1]);
  2443. }
  2444. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  2445. // delete garbage
  2446. if(collect.length > retaincount) {
  2447. var asyncs = [];
  2448. while((collect.length - asyncs.length) > retaincount) {
  2449. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  2450. }
  2451. return Promise.all(asyncs)
  2452. }
  2453. else return true
  2454. })
  2455. }
  2456. else return true;
  2457. })
  2458. .then(()=>{
  2459. // PB : TODO -- Keep only the last n runs...
  2460. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  2461. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  2462. if (!__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  2463. mainTasks.push(maintask);
  2464. return any(mainTasks);
  2465. })
  2466. });
  2467. // Sample instances config.
  2468. // var instances = {
  2469. // "elixir": {
  2470. // "production": {
  2471. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  2472. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  2473. // , "exludeMergeRepos": {
  2474. // "elixir-config-development": true, "elixir-config-test": true
  2475. // , "elixir-config-production": true, "elixir-data": true
  2476. // }
  2477. // , "instanceName": "elixir", "node_env": "production"
  2478. // }
  2479. // },
  2480. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  2481. // }
  2482. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...