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

index.js 91KB

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