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

3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
4 jaren geleden
4 jaren geleden
3 jaren geleden
3 jaren geleden
5 jaren geleden
6 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
6 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
4 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
4 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
5 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
5 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
6 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
3 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  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. function getVersion() { return BUILD_VERSION; }
  13. console.log(getVersion())
  14. // 'use strict';
  15. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  16. // PB : TODO --
  17. // runas bypass non elevated tasks when we request privelege
  18. // runas message is always error needs to be fixed.
  19. // runas wait needs to be parallelized.
  20. // suppress elevation check error messages
  21. // support runas lauched directly from shell.
  22. // pass in environment in hta to shellexecute.
  23. const { existsSync } = require('fs');
  24. const fs = require('fs')
  25. const cliargs = utils.cliargs;
  26. const processedArgs = cliargs(process.argv.slice(2));
  27. console.dir(processedArgs)
  28. var globSync = require('glob').sync;
  29. var ENV = Object.assign({}, process.env); // Shallow clone it.
  30. const { readdir } = require("fs").promises
  31. // Directory shallow walk and do perform on each dir.
  32. const dirs = async (perform, path) => {
  33. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  34. if (dir.isDirectory()) perform(dir)
  35. }
  36. }
  37. var getShellTask = (command, args, options) => {
  38. options = options || {}
  39. return () => {
  40. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  41. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  42. }, options)
  43. ])
  44. if (options.ignorefailures) {
  45. return p.catch(e => {
  46. // Ignore. Not a major error.
  47. })
  48. }
  49. else return p;
  50. }
  51. }
  52. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } }
  53. var getTaskCheckExists = (command, options) => {
  54. options = options || {}
  55. return () => {
  56. var p = nodeShellExec.apply(null, ['where', [command]])
  57. if (options.ignorefailures) {
  58. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  59. return false;
  60. })
  61. }
  62. else return p.then(() => { return true });
  63. }
  64. }
  65. var getPullCmd = (repo, branch) => {
  66. // console.log(useGitPull)
  67. if(branch) {
  68. var pullCmd = [ gitInstallDir
  69. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  70. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + repo }]
  71. }
  72. else {
  73. var pullCmd = [gitbash
  74. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  75. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  76. }
  77. // var pullCmd = ['pullall', [], { cwd : repo }]
  78. if (useGitPull) pullCmd = ['git', ['pull'], {
  79. inherit: true, shell: true,
  80. cwd: instanceroot + '/' + repo
  81. // , env: process.env
  82. , runas: processedArgs.runas
  83. , title: `git pull ${repo}`
  84. }]
  85. return pullCmd
  86. }
  87. var performPull = (repo, branch) => {
  88. if (existsSync(instanceroot + '/' + repo)) {
  89. var branchprint = branch ? ' branch :' + branch : '';
  90. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  91. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  92. if (__isElevated) {
  93. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  94. }
  95. else statuslog.statuslog(null, repo)
  96. return true;
  97. })
  98. .catch((e) => {
  99. e.repo = repo;
  100. if (__isElevated) {
  101. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  102. }
  103. else statuslog.statuslog(e); console.error(e)
  104. })
  105. }
  106. else {
  107. console.log('cloning ' + repo)
  108. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  109. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  110. {
  111. inherit: true, shell: true,
  112. env: process.env
  113. , cwd : instanceroot
  114. , runas: processedArgs.runas
  115. }).catch((e) => {
  116. throw e;
  117. }).then(() => {
  118. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  119. {
  120. inherit: true, shell: true,
  121. env: process.env
  122. , cwd: instanceroot + '/' + repo
  123. , runas: processedArgs.runas
  124. , title: `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  125. })
  126. .then(() => {
  127. if (__isElevated) {
  128. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  129. }
  130. else statuslog.statuslog(null, repo)
  131. })
  132. .catch((e) => {
  133. e.repo = repo;
  134. if (__isElevated) {
  135. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  136. }
  137. else statuslog.statuslog(e);
  138. })
  139. })
  140. .catch(e => {
  141. e.repo = repo;
  142. if (__isElevated) {
  143. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  144. }
  145. else statuslog.statuslog(e);
  146. })
  147. }
  148. }
  149. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  150. // -- Currently workaround is to always run from a non-elevated shell.
  151. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  152. var acquireElevationState = () => {
  153. if (__isElevated === null) {
  154. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  155. inherit: true
  156. // , shell: true
  157. , stdio: 'ignore'
  158. , env: process.env
  159. , title: `check privileged execution mode using "fsutil dirty query C:"`
  160. }).then((exitcode) => {
  161. console.log('Elevated')
  162. __isElevated = true;
  163. return true;
  164. }).catch(() => {
  165. __isElevated = false;
  166. console.log('Not Elevated');
  167. return false;
  168. });
  169. }
  170. else return Promise.resolve(__isElevated);
  171. }
  172. var repomanifest = null;
  173. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  174. var defaultRepoOwner = 'chess';
  175. var elevatedRunasRepos = null
  176. var gitRepos = null
  177. var defaultRepoServer = null
  178. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  179. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  180. var dbForLabel = function (label) {
  181. var dbsForLabel = {
  182. devmysql: 'mysql'
  183. , development: 'mssql'
  184. , production: 'mssql'
  185. }
  186. return dbsForLabel[label] || 'mysql'
  187. }
  188. // SAM : TODO Use nodeshellexec where to detect git installation dir
  189. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  190. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  191. // Relevant git repos
  192. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  193. var exludeMergeRepos = [];
  194. var useGitPull = processedArgs.useGitPull || false;
  195. var configPromise = null
  196. // elxr cli operations
  197. var op = {
  198. 'h': () => { console.log(elxr.help()); return '-h' }
  199. , 'clean' : () => {
  200. // delete all node_module folders and links.
  201. var tasklist = [];
  202. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  203. return Promise.all(tasklist)
  204. }
  205. , 'undefined': () => { return op.h(); }
  206. , 'reset': () => {
  207. // Reset NPM packages semver so major versions can be updated.
  208. const fs = require('fs')
  209. const wipeDependencies = (__package) => {
  210. const file = fs.readFileSync(__package + '/package.json')
  211. const content = JSON.parse(file)
  212. for (var devDep in content.devDependencies) {
  213. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  214. content.devDependencies[devDep] = '*';
  215. }
  216. }
  217. for (var dep in content.dependencies) {
  218. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  219. content.dependencies[dep] = '*';
  220. }
  221. }
  222. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  223. }
  224. var repos = ['client'];
  225. // repos = gitRepos;
  226. repos.forEach(wipeDependencies)
  227. // if (require.main === module) {
  228. // } else {
  229. // module.exports = wipeDependencies
  230. // }
  231. }
  232. , 'upgrade': () => {
  233. console.log('upgrade.......')
  234. var tasks = [
  235. () => {
  236. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  237. inherit: true, shell: true
  238. , env: process.env
  239. }).catch((e) => { console.error(e) })
  240. p.position = 1;
  241. console.log('One')
  242. return p;
  243. }
  244. , () => {
  245. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  246. inherit: true, shell: true
  247. , env: process.env
  248. }).catch((e) => { console.error(e) })
  249. p.position = 2;
  250. console.log('Two')
  251. return p;
  252. }
  253. , () => {
  254. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  255. inherit: true, shell: true
  256. , env: process.env
  257. }).catch((e) => { console.error(e) })
  258. p.position = 3;
  259. console.log('Three')
  260. return p;
  261. }
  262. , () => {
  263. var p = nodeShellExec('n', ['latest'], {
  264. inherit: true, shell: true
  265. , env: process.env
  266. }).catch((e) => { console.error(e) })
  267. p.position = 4;
  268. console.log('Four')
  269. return p;
  270. }
  271. ]
  272. any(tasks)
  273. console.log('.......done')
  274. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  275. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  276. console.info('Uninstalling existing ember globally');
  277. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  278. stdio: ['pipe', process.stdout, process.stderr],
  279. inherit: true,
  280. shell: true,
  281. cwd: path.dirname(__dirname),
  282. env: env
  283. })
  284. step1.on('close', () => {
  285. console.info('Installing ember globally');
  286. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  287. stdio: ['pipe', process.stdout, process.stderr],
  288. inherit: true,
  289. shell: true,
  290. cwd: path.dirname(__dirname),
  291. env: env
  292. })
  293. step2.on('close', () => {
  294. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  295. stdio: ['pipe', process.stdout, process.stderr],
  296. inherit: true,
  297. shell: true,
  298. cwd: path.dirname(__dirname),
  299. env: env
  300. })
  301. })
  302. })
  303. }
  304. , 'runas': () => {
  305. console.log('Testing Elevation')
  306. if (__isElevated) {
  307. try {
  308. op[processedArgs.label || processedArgs._[0] || 'h']()
  309. }
  310. catch (e) {
  311. console.error('Error Invalid command : ' + e)
  312. fs.writeFileSync('run.done', 'error')
  313. }
  314. finally {
  315. }
  316. }
  317. else {
  318. console.log('Requesting Elevated Privileges');
  319. // Wait for the runas to complete before we read it.
  320. try {
  321. fs.unlinkSync('run.done')
  322. fs.unlinkSync('run.log')
  323. }
  324. catch (e) { } //Ignore
  325. // Find node path to send to hta.
  326. return nodeShellExec('where', ['node']).then(r => {
  327. var namedArgs = [];
  328. console.log('result : ' + JSON.stringify(r))
  329. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  330. // PB : TODO -- Convert all the cli args back to string.
  331. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  332. args.push('--nodepath=' + r[r.length - 1])
  333. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  334. if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  335. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  336. , {
  337. inherit: true
  338. , shell: true
  339. , env: ENV
  340. , runas: 'self'
  341. , title: `runas`
  342. }
  343. ).then(() => {
  344. // runas returned.
  345. try {
  346. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  347. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  348. runaslog.forEach((logEntry) => {
  349. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  350. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  351. })
  352. }
  353. catch (e) {
  354. // We must have a runas log
  355. statuslog.statuslog(e)
  356. console.error('Run log error probably was not created by runas : ' + e)
  357. }
  358. })
  359. .catch(err => console.error('Elevation failed : ' + err));
  360. })
  361. }
  362. }
  363. , 'push': () => {
  364. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  365. // init remote bare from local
  366. // pushandinitremotebare
  367. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  368. // connect to repo server -- net use 172.16.0.27
  369. // cd 172.16.0.27/repos/
  370. // mkdir repo.git
  371. // cd repo.git
  372. // git init --bare
  373. // cd localrepo
  374. // git remote rename origin githubclone
  375. // git remote add origin //172.16.0.27/repos/repo.git
  376. // git push origin master
  377. var repo = processedArgs._[1];
  378. var sequentialTaskShellCommands = [];
  379. if (!existsSync(`Z:/${repo}.git`)) {
  380. sequentialTaskShellCommands = [
  381. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  382. // inherit : true, shell: true
  383. // , env: process.env
  384. // }]
  385. ['pwd', { cwd: 'Z:', inherit: true }]
  386. , ['mkdir', [`${repo}.git`], {
  387. cwd: `Z:`
  388. , inherit: true, shell: true
  389. , env: process.env
  390. }]
  391. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  392. , ['git', ['init', '--bare'], {
  393. cwd: `Z:/${repo}.git`
  394. , inherit: true, shell: true
  395. , env: process.env
  396. }]
  397. // PB : TODO -- Do this conditionally only...
  398. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  399. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  400. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  401. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  402. // PB : TODO -- If threre is a gitbubclone origin
  403. // Set the master to pull from the local repo.
  404. ]
  405. if (!existsSync(`Z:`)) {
  406. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm, '\\')], {
  407. inherit: true, shell: true
  408. , env: process.env
  409. }])
  410. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  411. // throw 'done'
  412. }
  413. }
  414. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  415. // console.dir(sequentialTaskShellCommands);
  416. var tasks = [];
  417. sequentialTaskShellCommands.forEach(shellcmd => {
  418. // console.log(shellcmd)
  419. tasks.push(() => {
  420. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  421. return p;
  422. })
  423. })
  424. any(tasks);
  425. }
  426. , 'is-git-repo': (dir) => {
  427. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  428. }
  429. , 'set-url': (remotename, url) => {
  430. var pushable = processedArgs.pushable || false;
  431. remotename = remotename || processedArgs._[1]
  432. url = url || processedArgs._[2]
  433. var serial_perform_git_seturl = (repo) => {
  434. var options = { cwd: instanceroot + '/' + repo }
  435. // console.log(repo)
  436. if (pushable) {
  437. return [
  438. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  439. ]
  440. }
  441. else {
  442. console.error('not supported for non-pushable')
  443. }
  444. }
  445. var perform_git_seturl = (dir) => {
  446. op['is-git-repo'](dir).then((code) => {
  447. any(serial_perform_git_seturl(dir.name).map(x))
  448. }).catch((e) => {
  449. // console.log('Failed : ' + dir.name)
  450. })
  451. }
  452. dirs(perform_git_seturl)
  453. }
  454. , 'add': (remotename, url, branch) => {
  455. var pushable = processedArgs.pushable || false;
  456. remotename = remotename || processedArgs._[1]
  457. url = url || processedArgs._[2]
  458. branch = branch || processedArgs._[3]
  459. var serial_perform_git_add = (repo) => {
  460. var options = { cwd: instanceroot + '/' + repo }
  461. // console.log(repo)
  462. if (pushable) {
  463. return [
  464. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  465. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  466. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  467. ]
  468. }
  469. else {
  470. return [
  471. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  472. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  473. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  474. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  475. ]
  476. }
  477. }
  478. var x = (args) => {
  479. return () => {
  480. // console.log(args)
  481. return nodeShellExec.apply(null, args)
  482. }
  483. // return Promise.resolve(true)
  484. }
  485. var perform_git_add = (dir) => {
  486. op['is-git-repo'](dir).then((code) => {
  487. // console.log(code)
  488. if (code) {
  489. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  490. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  491. })
  492. .catch((e) => {
  493. any(serial_perform_git_add(dir.name).map(x))
  494. })
  495. }
  496. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  497. }).catch((e) => {
  498. // console.log('Failed : ' + dir.name)
  499. })
  500. }
  501. const { readdir } = require("fs").promises
  502. const dirs = async (perform, path) => {
  503. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  504. if (dir.isDirectory()) perform(dir)
  505. }
  506. }
  507. dirs(perform_git_add)
  508. }
  509. , 'remove': (remotename) => {
  510. remotename = remotename || processedArgs._[1]
  511. var serial_perform_git_remove = (repo) => {
  512. var options = { cwd: instanceroot + '/' + repo }
  513. // console.log(repo)
  514. return [
  515. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  516. ]
  517. }
  518. var x = (args) => {
  519. return () => {
  520. // console.log(args)
  521. return nodeShellExec.apply(null, args)
  522. }
  523. // return Promise.resolve(true)
  524. }
  525. var perform_git_remove = (dir) => {
  526. op['is-git-repo'](dir).then((code) => {
  527. // console.log(code)
  528. if (code) {
  529. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  530. any(serial_perform_git_remove(dir.name).map(x))
  531. })
  532. .catch((e) => {
  533. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  534. })
  535. }
  536. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  537. }).catch((e) => {
  538. // console.log('Failed : ' + dir.name)
  539. })
  540. }
  541. const { readdir } = require("fs").promises
  542. const dirs = async (perform, path) => {
  543. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  544. if (dir.isDirectory()) perform(dir)
  545. }
  546. }
  547. dirs(perform_git_remove)
  548. }
  549. , 'init-gitea': (user) => {
  550. user = user || processedArgs._[1]
  551. if (!user) throw 'User name required'
  552. var serial_perform_init_gitea = (repo) => {
  553. var options = { cwd: instanceroot + '/' + repo }
  554. // console.log(repo)
  555. return [
  556. ['git', ['remote', 'add', 'chess', `${defaultRepoServer}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  557. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  558. , ['git', ['remote', 'set-url', 'origin', `${defaultRepoServer}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  559. ]
  560. }
  561. var x = (args) => {
  562. return () => {
  563. // console.log(args)
  564. return nodeShellExec.apply(null, args)
  565. }
  566. // return Promise.resolve(true)
  567. }
  568. var perform_init_gitea = (dir) => {
  569. op['is-git-repo'](dir).then((code) => {
  570. // console.log(code)
  571. if (code) {
  572. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  573. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  574. })
  575. .catch((e) => {
  576. any(serial_perform_init_gitea(dir.name).map(x))
  577. })
  578. }
  579. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  580. }).catch((e) => {
  581. // console.log('Failed : ' + dir.name)
  582. })
  583. }
  584. const { readdir } = require("fs").promises
  585. const dirs = async (perform, path) => {
  586. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  587. if (dir.isDirectory()) perform(dir)
  588. }
  589. }
  590. dirs(perform_init_gitea)
  591. }
  592. , 'syncmaster': (label) => {
  593. // Usage :
  594. // elxr pull -- Defaults to run config
  595. var env = Object.assign({}, process.env); // Shallow clone it.
  596. // console.dir(env)
  597. console.log('Running exlr pull : ' + path.dirname(__dirname))
  598. if (!processedArgs.runas) gitRepos.map((repo) => performPull(repo, 'master'))
  599. if (__isElevated) {
  600. return any(elevatedRunasRepos.map((repo) => performPull(repo, 'master'))).then(() => {
  601. fs.writeFileSync('run.done', 'success')
  602. }).catch(() => {
  603. fs.writeFileSync('run.done', 'error')
  604. })
  605. }
  606. else return op['runas']()
  607. }
  608. , 'pull': (label) => {
  609. // Usage :
  610. // elxr pull -- Defaults to run config
  611. var env = Object.assign({}, process.env); // Shallow clone it.
  612. console.log('Running exlr pull : ' + path.dirname(__dirname))
  613. var useGitPull = processedArgs.useGitPull || false;
  614. if (__isElevated) {
  615. return any(elevatedRunasRepos.map((repo) => performPull(repo))).then(() => {
  616. fs.writeFileSync('run.done', 'success')
  617. return true;
  618. }).catch(() => {
  619. fs.writeFileSync('run.done', 'error')
  620. })
  621. }
  622. else {
  623. // PB : TODO -- Rename op['runas'] to 'elevate'
  624. return op['runas']().then(() => { return true; })
  625. .catch((e) => {
  626. console.error(e)
  627. })
  628. .finally(() => {
  629. if (!processedArgs.runas) {
  630. var pendingpulls = [];
  631. gitRepos.forEach((r) => { pendingpulls.push(performPull(r)) })
  632. return Promise.all(pendingpulls).then(results => {
  633. return true;
  634. }).finally(Traq.finally)
  635. }
  636. })
  637. }
  638. }
  639. , 'isInstalled': () => {
  640. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  641. console.log(processedArgs._[1] + ' exists.')
  642. return true;
  643. });
  644. }
  645. , 'i': () => {
  646. var tasks = []
  647. tasks.push(op['pull']);
  648. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  649. tasks.push(op['use'])
  650. if (!__isElevated) {
  651. tasks.push(op['npmi'])
  652. }
  653. // var tasksdefs = [
  654. // ['elxr', ['pull']]
  655. // , ['elxr', ['use', 'elixir']]
  656. // , ['elxr', ['npmi']]
  657. // ]
  658. // tasksdefs.forEach(tasksdef=>{
  659. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  660. // })
  661. return any(tasks);
  662. }
  663. , 'npmi': () => {
  664. var tasks = [];
  665. // Build fails without babel...
  666. tasks.push(getShellTask(
  667. 'npm',[ 'i', '-g', 'babel-cli' ]
  668. ) )
  669. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  670. npmbuildrepos = []
  671. npmbuildrepos.forEach(repo => {
  672. tasks.push(() => {
  673. return nodeShellExec('npm', ['i --force'], {
  674. inherit: true, shell: true
  675. , cwd: instanceroot + '/' + repo
  676. , env: process.env
  677. , title: `npm i for ${repo}`
  678. }).catch((e) => {
  679. console.error('Ignoring Benign Error'); console.error(e);
  680. }).then(() => {
  681. console.log(`--------------------npm run build for ${repo}--------------------`)
  682. return nodeShellExec('npm', ['run build'], {
  683. inherit: true, shell: true
  684. , cwd: instanceroot + '/' + repo
  685. , env: process.env
  686. , title: `npm run build for ${repo}`
  687. }).then(Tasq.then).catch(Tasq.catch)
  688. })
  689. })
  690. })
  691. any(tasks).then(() => {
  692. gitRepos.push('client/server');
  693. gitRepos = gitRepos.concat(elevatedRunasRepos);
  694. // gitRepos = [
  695. // 'bbhverse', 'serververse', 'elixir-server',
  696. // 'client'
  697. // ];
  698. var rmtasks = []
  699. var repotasks = []
  700. gitRepos.forEach(repo => {
  701. rmtasks.push(
  702. // () => {
  703. // console.log(`--------------------rm package-lock.json for ${repo}--------------------`)
  704. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  705. nodeShellExec('rm', ['package-lock.json'], {
  706. inherit: true, shell: true
  707. , cwd: instanceroot + '/' + repo
  708. , env: process.env
  709. , title: `rm 'package-lock.json' for ${repo}`
  710. })
  711. .then(()=>{
  712. console.log(`--------------------rm package-lock.json for ${repo}--------------------`)
  713. }).catch((e) => { console.error(e) })
  714. // }
  715. )
  716. if (npmbuildrepos.indexOf(repo) < 0) {
  717. repotasks.push(
  718. () => {
  719. console.log(`--------------------npm i for ${repo}--------------------`)
  720. var p = nodeShellExec('npm', ['i', '--force'], {
  721. inherit: true, shell: true
  722. , cwd: instanceroot + '/' + repo
  723. , env: process.env
  724. , title: `npm i for ${repo}`
  725. }).then(Tasq.then).catch(Tasq.catch)
  726. return p;
  727. })
  728. }
  729. })
  730. // PB : TODO -- npm i for client is for some reason not complete so bower doesn't get installed !!!
  731. // Second time try also doesnt work.
  732. // repotasks.push(
  733. // () => {
  734. // console.log(`--------------------second time npm i for client--------------------`)
  735. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i"'], {
  736. // // return nodeShellExec('npm', ['i --force'], {
  737. // inherit: true, shell: true
  738. // , cwd: instanceroot + '/' + 'client'
  739. // , env: process.env
  740. // , title: `npm i for client`
  741. // }).then(Tasq.then).catch(Tasq.catch)
  742. // })
  743. var bowerRepos = ['client']
  744. bowerRepos.forEach(repo => {
  745. repotasks.push(() => {
  746. console.log(instanceroot + '/' + repo + '/node_modules/bower/bin/bower')
  747. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  748. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  749. inherit: true, shell: true
  750. , cwd: instanceroot + '/' + repo
  751. , env: process.env
  752. , title: `bower i for ${repo}`
  753. }).then(Tasq.then).catch(Tasq.catch)
  754. return p;
  755. })
  756. })
  757. // console.log('rmtasks.length : ' + rmtasks.length)
  758. return Promise.all(rmtasks).then(() => any(repotasks));
  759. }).catch(e => {
  760. }).finally(statuslog.finally)
  761. }
  762. , 'start': (label) => {
  763. console.log('Starting Elixir Server.');
  764. var env = Object.assign({}, process.env); // Shallow clone it.
  765. // console.dir(env)
  766. env.NODE_ENV = process.env.NODE_ENV || 'development';
  767. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  768. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  769. // cmd = 'node'
  770. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  771. var childPromise = nodeShellExec(...cmd, {
  772. // inherit : true,
  773. shell: true,
  774. detached: true,
  775. stdio: 'ignore',
  776. cwd: instanceroot + '/' + 'elixir-server'
  777. , env: env
  778. })
  779. var child = childPromise.process;
  780. if (typeof child.pid !== 'undefined') {
  781. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  782. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  783. encoding: 'utf8'
  784. })
  785. }
  786. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  787. // inherit : true,
  788. // shell: true, detached: true,
  789. // cwd : 'qms/server',
  790. // env: env,
  791. // shell : true
  792. // })
  793. // nodeShellExec('ember', ['s'], {
  794. // // inherit : true,
  795. // shell: true, detached: true,
  796. // cwd : 'client/',
  797. // env: env
  798. // })
  799. console.log('Starting Elixir Client Host.');
  800. var cmd = ['ember', ['s']]
  801. var childPromise = nodeShellExec(...cmd, {
  802. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  803. // PB : TODO -- ember debugging.
  804. // inherit : true,
  805. shell: true,
  806. detached: true,
  807. stdio: 'ignore',
  808. cwd: instanceroot + '/' + 'client'
  809. , env: env
  810. })
  811. // .catch(e=>console.error(e))
  812. child = childPromise.process;
  813. if (typeof child.pid !== 'undefined') {
  814. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  815. fs.writeFileSync('.client.server.pid', child.pid, {
  816. encoding: 'utf8'
  817. })
  818. }
  819. }
  820. , 'stop': (label) => {
  821. const kill = require('tree-kill');
  822. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  823. encoding: 'utf8'
  824. })
  825. fs.unlinkSync('.elixir-server.elixir.server.pid')
  826. console.log(serverPid)
  827. kill(serverPid)
  828. serverPid = fs.readFileSync('.client.server.pid', {
  829. encoding: 'utf8'
  830. })
  831. fs.unlinkSync('.client.server.pid')
  832. console.log(serverPid)
  833. kill(serverPid)
  834. }
  835. , 'use': () => {
  836. // use a certain named instance.
  837. // Eg :
  838. // 1) elxr use elixir
  839. // 2) elxr use cihsr
  840. // If environment is not specified defaults to development.
  841. // 1) NODE=test elxr use elixir
  842. /*// Steps
  843. 1) Delete Config and Data symlinks
  844. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  845. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  846. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  847. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  848. */
  849. var runconfig = { NODE_ENV: repomanifest.node_env }
  850. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  851. if ((!processedArgs.runas || processedArgs.runas !== 'self') &&
  852. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  853. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  854. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  855. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  856. return
  857. }
  858. var tasks = [
  859. () => {
  860. if (existsSync('config')) {
  861. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  862. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  863. return p;
  864. }
  865. else return Promise.resolve(true);
  866. },
  867. () => {
  868. if (existsSync('data')) {
  869. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  870. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  871. return p;
  872. }
  873. else return Promise.resolve(true);
  874. },
  875. ];
  876. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  877. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  878. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  879. // console.log(process.env.cwd)
  880. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  881. // Maps an environment to a branch. Not required if the branch is appropriately named.
  882. var checkoutMap = { 'development': 'master' }
  883. // cant use git checkout -b it fails with branch already exists.
  884. var performCheckout = (repo, branch) => {
  885. if (!branch) return Promise.resolve({ 'skipped': true })
  886. if (excludeCheckouts[repo]) return Promise.resolve({ 'skipped': true })
  887. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  888. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  889. // inherit : true, shell: true,
  890. cwd: repoinstanceroot + '/' + repo
  891. // , stdio : ignore // Use when we want to silcence output completely.
  892. , runas: processedArgs.runas
  893. , title: `git checkout ${branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  894. }).catch((e) => { console.error(e); return { error: true, message: repo } })
  895. }
  896. if (runconfig.NODE_ENV === 'development') performCheckout = () => { return Promise.resolve(true) }
  897. var performPullAll = (repo) => {
  898. if (excludeCheckouts[repo]) return Promise.resolve({ 'skipped': true })
  899. return nodeShellExec('git', ['pull', '--all'], {
  900. // inherit : true, shell: true,
  901. cwd: instanceroot + '/' + repo
  902. , runas: processedArgs.runas
  903. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  904. }).catch((e) => { console.error(e); return { error: true, message: repo } })
  905. }
  906. var mergeSources = {
  907. 'development': null,
  908. 'test': 'master',
  909. 'production': 'master'
  910. }
  911. var excludeCheckouts = Object.assign(exludeMergeRepos)
  912. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  913. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  914. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  915. var performMerge = (repo) => {
  916. if (exludeMergeRepos[repo]) return Promise.resolve({ 'skipped': true })
  917. return nodeShellExec('git', ['merge', mergeSource], {
  918. inherit: true, shell: true,
  919. cwd: instanceroot + '/' + repo
  920. , runas: processedArgs.runas
  921. }).catch((e) => { console.error(e) })
  922. }
  923. if (runconfig.NODE_ENV === 'development') performMerge = () => { return Promise.resolve(true) }
  924. return any(tasks).then(() => {
  925. if (!processedArgs.runas) return op['runas']()
  926. tasks = [
  927. () => {
  928. // Use junctions to avoid npm package issues
  929. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  930. inherit: true, shell: true
  931. , cwd : instanceroot
  932. , env: process.env
  933. }).catch((e) => { console.error(e) })
  934. return p;
  935. }
  936. ];
  937. if (processedArgs._[1]) {
  938. tasks = tasks.concat(
  939. [
  940. () => {
  941. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  942. inherit: true, shell: true
  943. , cwd : instanceroot
  944. , env: process.env
  945. }).catch((e) => { console.error(e) })
  946. return p;
  947. }
  948. ]
  949. )
  950. }
  951. return any(tasks)
  952. //target is the env is we specify in elxr use command. Default is dev
  953. .then( //Switch to target branch
  954. () => any([any(gitRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))
  955. , any(elevatedRunasRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))]))
  956. .then( //PULL from target branch
  957. () => any([any(gitRepos.map((repo) => performPullAll(repo))), any(elevatedRunasRepos.map((repo) => performPullAll(repo)))]))
  958. .then( //Switch to merge source branch
  959. () => any([any(gitRepos.map((repo) => performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))
  960. , any(elevatedRunasRepos.map((repo) => performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]))
  961. .then( //Pull on merge source branch
  962. () => any([any(gitRepos.map((repo) => performPullAll(repo))), any(elevatedRunasRepos.map((repo) => performPullAll(repo)))]))
  963. .then( //Switch to target branch
  964. () => any([any(gitRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))
  965. , any(elevatedRunasRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))]))
  966. .then( //Merge source branch to target branch
  967. () => any([any(gitRepos.map((repo) => performMerge(repo))).catch(err => { console.error('error in performMerge ' + err) }),
  968. any(elevatedRunasRepos.map((repo) => performMerge(repo))).catch(err => { console.error('error in performMerge ' + err) })]))
  969. .then(() => {
  970. // Move test config from dev.
  971. // if(process.env.NODE_ENV === 'test'){
  972. // var devcfgreponame = runconfig.use + '-config' + '-development';
  973. // var testcfgreponame = runconfig.use + '-config' + '-test';
  974. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  975. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  976. // return any([
  977. // ()=>{
  978. // return nodeShellExec('git', ['checkout', 'test'], {
  979. // inherit : true, shell: true,
  980. // cwd : testcfgdir
  981. // // , env: process.env
  982. // , runas : processedArgs.runas
  983. // , title : `git checkout test for ${testcfgreponame}`
  984. // }).catch((e)=>{ console.error(e) })
  985. // }
  986. // , ()=> {
  987. // return nodeShellExec('git', ['checkout', 'master'], {
  988. // inherit : true, shell: true,
  989. // cwd : devcfgdir
  990. // // , env: process.env
  991. // , runas : processedArgs.runas
  992. // , title : `git checkout master for ${devcfgreponame}`
  993. // }).catch((e)=>{ console.error(e) })
  994. // }
  995. // , ()=> {
  996. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  997. // console.log('File found : ' + devcfgdir + filename)
  998. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  999. // })
  1000. // return nodeShellExec('git', ['checkout', 'test'], {
  1001. // inherit : true, shell: true,
  1002. // cwd : devcfgdir
  1003. // // , env: process.env
  1004. // , runas : processedArgs.runas
  1005. // , title : `git checkout test for ${devcfgreponame}`
  1006. // }).catch((e)=>{ console.error(e) })
  1007. // }
  1008. // ])
  1009. // }
  1010. // else {
  1011. return Promise.resolve(true)
  1012. // }
  1013. })
  1014. .then(() => {
  1015. fs.writeFileSync('run.done', 'success')
  1016. }).catch(() => {
  1017. fs.writeFileSync('run.done', 'error')
  1018. })
  1019. }).catch(() => {
  1020. fs.writeFileSync('run.done', 'error')
  1021. })
  1022. // Antibiotic stewardship program.
  1023. // 1st use is fine.
  1024. // Max vials dispense
  1025. // 2nd use Pharmacy needs justification Form.
  1026. // Approval after a certain period of time.
  1027. }
  1028. , 'g': () => {
  1029. if (processedArgs.h) {
  1030. console.log('elxr g [modelname] => generate a model named [modelname]');
  1031. console.log('elxr g => regenerate all known models');
  1032. return
  1033. }
  1034. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1035. // console.log('Starting directory: ' + process.cwd());
  1036. // try {
  1037. // child = child.on('close', () => { process.chdir(label) } );
  1038. // console.log('New directory: ' + process.cwd());
  1039. // }
  1040. // catch (err) {
  1041. // console.log('chdir: ' + err);
  1042. // }
  1043. // child.on('close', function(){
  1044. // var options = {
  1045. // shell : true
  1046. // , inherit : true
  1047. // // , cwd : '' + process.cwd
  1048. // // , env : process.env
  1049. // };
  1050. // nodeShellExec('git', ['init'], { inherit : true});
  1051. if (0) {
  1052. // PB : TODO -- Special google chrome profile for tests etc.
  1053. nodeShellExec('pwd', { inherit: true });
  1054. // /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"
  1055. // "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
  1056. // "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
  1057. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1058. "--profile-directory=Profile 1"
  1059. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1060. }
  1061. // nodeShellExec('npm', ['init', '-y'], options);
  1062. // nodeShellExec('npm', ['init', '-y'], options);
  1063. // })
  1064. var g = {
  1065. 'client': () => {
  1066. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1067. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1068. stdio: ['pipe', process.stdout, process.stderr],
  1069. inherit: true,
  1070. shell: true,
  1071. cwd: path.dirname(__dirname),
  1072. env: env
  1073. })
  1074. },
  1075. 'modelr': () => {
  1076. var tasks = [
  1077. () => {
  1078. var p = nodeShellExec('"ember"', [
  1079. 'g'
  1080. , 'modelr'
  1081. , processedArgs._[2]], {
  1082. inherit: true, shell: true, env: process.env
  1083. }).then(() => {
  1084. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1085. return true;
  1086. }).catch((e) => { console.error(e) })
  1087. return p;
  1088. },
  1089. () => {
  1090. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1091. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1092. chromeprefs = JSON.parse(chromeprefs)
  1093. var previous = chromeprefs.download.default_directory;
  1094. var parentDir = path.dirname(__dirname);
  1095. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1096. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1097. // PB : TODO -- detect where chrome is installed.
  1098. // PB : TODO -- set the download dir to the place where files are needed.
  1099. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1100. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1101. , '--profile-directory="chess"'
  1102. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1103. inherit: true, shell: true
  1104. , env: process.env
  1105. }).then(() => {
  1106. chromeprefs.download.default_directory = previous;
  1107. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1108. return true;
  1109. }).catch((e) => { console.error(e) })
  1110. return p;
  1111. }
  1112. ,
  1113. () => {
  1114. console.log('Browser process should have closed here....')
  1115. return true;
  1116. }
  1117. ]
  1118. any(tasks)
  1119. }
  1120. }
  1121. g[processedArgs._[1]]();
  1122. }
  1123. }
  1124. var util = require('util')
  1125. var cliname = 'elxr';
  1126. var ver = '1.1';
  1127. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  1128. ${
  1129. // util.inspect(
  1130. [Object.keys(op)]
  1131. // )
  1132. }
  1133. `;
  1134. var elxr = {
  1135. help() {
  1136. return chalk.cyanBright(`
  1137. -------------------------------------------------------------------------------
  1138. *** BBH Elixir ***
  1139. -------------------------------------------------------------------------------
  1140. elxr ${ver}
  1141. A cli tool for chess
  1142. ${help}
  1143. -------------------------------------------------------------------------------
  1144. `)
  1145. }
  1146. , info() {
  1147. return chalk.cyanBright(`
  1148. -------------------------------------------------------------------------------
  1149. *** BBH Elixir ***
  1150. -------------------------------------------------------------------------------
  1151. elxr ${ver}
  1152. A cli tool for chess
  1153. -------------------------------------------------------------------------------
  1154. `)
  1155. }
  1156. }
  1157. // The main elxr cli process
  1158. function elxrworker(hasconfig) {
  1159. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1160. gitRepos = repomanifest.repos
  1161. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1162. elevatedRunasRepos = repomanifest.elevated
  1163. // Repos that should excluded from merge for releases...
  1164. exludeMergeRepos = repomanifest.exludeMergeRepos
  1165. var env = Object.assign({}, process.env); // Shallow clone it.
  1166. var __runcmd = function (label) {
  1167. return op[label] ? op[label]() : null;
  1168. }
  1169. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1170. // mysql -u root -p db_name < drop_all_tables.sql
  1171. var mysql = '../xampp/mysql/bin/mysql'
  1172. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1173. // --runas
  1174. if (processedArgs.runas) {
  1175. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1176. return __runcmd('runas')
  1177. }
  1178. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1179. }
  1180. var getManifest = function () {
  1181. // Once choices are made we need to load config according to those choices.
  1182. // No trace of a previous run...
  1183. // Default Config...
  1184. return repomanifest = selectedinstance;
  1185. }
  1186. function acquireChoices(selectedinstance) {
  1187. var hasconfig = false;
  1188. console.warn(chalk.yellow(`
  1189. -------------------------------------------------------------------------------
  1190. Warning : Cannot locate your preferred configuration since it was not specified
  1191. You should fork the default chess configuration to customize and make it
  1192. your own instance with a named config as
  1193. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  1194. And then run this tool as follows
  1195. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  1196. OR
  1197. Run this tool with the following command to use a quick start default.
  1198. node elxr --default
  1199. OR
  1200. Choose the the option to create a new instance for you interactively.
  1201. We will run your choice of default or create your own at the next prompt.
  1202. -------------------------------------------------------------------------------
  1203. `))
  1204. var prompt = cli.prompt;
  1205. return prompt.ask(`Choose an option :
  1206. d) Install the default chess instance.
  1207. => elxr i chess node_env=development --default
  1208. n) Create your custom new instance interactively
  1209. => elxr i {{instanceName}} node_env={{environment}}
  1210. i) Choose an instance and environment to install
  1211. => elxr i {{instanceName}} node_env={{environment}}
  1212. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1213. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1214. h) Help
  1215. q) Quit
  1216. Default <= d
  1217. : `).then((choice) => {
  1218. prompt.close();
  1219. if (choice && choice === 'd' || !choice) {
  1220. processedArgs._[0] = 'i'
  1221. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1222. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1223. defaultRepoServer = 'https://git.bbh.org.in'
  1224. getManifest() // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  1225. // This is because the manifest at any server location can redirect to the preferred server..
  1226. }
  1227. else if (choice === 'h') {
  1228. processedArgs._[0] = 'h'
  1229. fs.writeFileSync('run.done', 'noop help');
  1230. console.log(elxr.help()); process.exit()
  1231. }
  1232. else if (choice === 'n' || choice === 'i') {
  1233. var p1 = cli.prompt;
  1234. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1235. processedArgs._[0] = 'i'
  1236. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1237. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1238. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1239. if (choice === 'n') {
  1240. defaultRepoServer = 'https://git.bbh.org.in'
  1241. console.warn(
  1242. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1243. process.exit();
  1244. }
  1245. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1246. p1.close()
  1247. defaultRepoServer = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1248. })
  1249. })
  1250. })
  1251. } else if (choice === 'c') {
  1252. var p1 = cli.prompt;
  1253. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1254. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1255. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1256. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1257. return p1.ask(`Enter cmd :
  1258. p) pull
  1259. Default <= p
  1260. : `).then(function (cmd) {
  1261. if (!cmd || cmd === 'p') {
  1262. processedArgs._[0] = 'pull'
  1263. }
  1264. else processedArgs._[0] = cmd
  1265. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1266. defaultRepoServer = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1267. p1.close()
  1268. })
  1269. })
  1270. })
  1271. })
  1272. } else {
  1273. 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.`));
  1274. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1275. fs.writeFileSync('run.done', 'noop quit');
  1276. process.exit()
  1277. }
  1278. })
  1279. }
  1280. var acquireConfig = function (selected, chessinstances) {
  1281. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1282. return performPull(configrepo).then(() => {
  1283. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1284. repomanifest = require(manifestpath)()
  1285. chessinstances = chessinstances || {};
  1286. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {}
  1287. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {}
  1288. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env }
  1289. // Config from server always override merges into selection ecept for the current selection.
  1290. selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest)
  1291. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances) + '', { 'flag': 'w' })
  1292. // PB : TODO -- We should probably write the new server config also...
  1293. defaultRepoServer = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1294. ENV.NODE_ENV = selectedinstance.node_env;
  1295. })
  1296. .catch((e) => {
  1297. console.error(e)
  1298. console.error('Config acquisition failed.')
  1299. })
  1300. }
  1301. var launchpath = process.cwd().replace(/\\/, '/')
  1302. var thisscriptdir = __dirname
  1303. var instanceroot = launchpath;
  1304. var detectInstance = function () {
  1305. console.log(`launchpath = ${launchpath}`)
  1306. console.log(`thisscriptdir = ${thisscriptdir}`)
  1307. var root = launchpath;
  1308. // We need a reference to the root director for elxr cli to be properly oriented.
  1309. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1310. // We ran unbuilt from the proper root with elxr subfolder.
  1311. console.log(`Instance Path : ${root}`)
  1312. }
  1313. else {
  1314. if (launchpath === thisscriptdir) {
  1315. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1316. // It could be a standalone elxr build which may or maynot be in the proper location.
  1317. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1318. // Unbuilt therefore we are in the elxr directory.
  1319. root = path.normalize(launchpath + '/..');
  1320. }
  1321. else {
  1322. // Built version.
  1323. // check if we have a elxr subfolder.
  1324. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1325. // Probably in the right place.
  1326. root = path.normalize(launchpath + '/..');
  1327. }
  1328. else {
  1329. // Assume launchpath is meaningless.
  1330. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1331. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1332. }
  1333. }
  1334. }
  1335. }
  1336. instanceroot = root.replace(/\\/, '/');
  1337. var __default = {
  1338. // Default is public server only.
  1339. reposervers: ['https://git.bbh.org.in']
  1340. // All public repos are by default available.
  1341. , repos: [
  1342. 'setup'
  1343. , 'elxr'
  1344. , 'loopback-connector-mysql'
  1345. , 'loopback-jsonapi-model-serializer'
  1346. , 'loopback-component-jsonapi'
  1347. , 'ember-service-worker'
  1348. , 'ember-service-worker-asset-cache'
  1349. , 'ember-service-worker-cache-fallback'
  1350. , 'ember-service-worker-index'
  1351. , 'ember-sw-client-route'
  1352. ]
  1353. , elevated: []
  1354. , exludeMergeRepos: {}
  1355. , instanceName: 'chess'
  1356. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1357. , node_env: 'development'
  1358. }
  1359. return Object.assign({ root }, __default);
  1360. }
  1361. var gitUser = 'chessdemo';
  1362. var gitEmail = 'chessdemo@bbh.org.in'
  1363. var downloadsdir = '../Downloads';
  1364. var prerequisites = [
  1365. {
  1366. shellcmd: 'git',
  1367. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1368. , installer: 'Git-2.31.0-64-bit.exe'
  1369. , installcmd: ['cmd', ['/c', 'start',
  1370. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1371. , '/VERYSILENT'
  1372. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1373. ]]
  1374. , preinstallsteps: () => {
  1375. var prompt = cli.prompt;
  1376. var steps = [
  1377. () => {
  1378. if (!existsSync(downloadsdir + '/' + preq.installer)) {
  1379. return nodeShellExec('download.bat', [preq.url, downloadsdir + '/' + preq.installer])
  1380. }
  1381. else return Promise.resolve(true)
  1382. }
  1383. ]
  1384. var prompts = [
  1385. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1386. , () => prompt.ask(`git user name : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1387. ]
  1388. return Promise.all([any(steps), any(prompts)]).finally(() => { prompt.close() })
  1389. }
  1390. , installsteps: function () {
  1391. return any([this.installcmd].map(callsheltask))
  1392. }
  1393. , postinstallsteps: () => {
  1394. var steps = [
  1395. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1396. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1397. ]
  1398. return any(steps.map(callsheltask)).then(() => { })
  1399. }
  1400. , install: function () {
  1401. return any([ /*this.preinstallsteps,*/ this.installsteps, this.postinstallsteps])
  1402. }
  1403. }
  1404. ,
  1405. {
  1406. shellcmd: 'node',
  1407. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1408. , installer: 'node-v14.16.0-x64.msi'
  1409. , installcmd: ['MSIEXEC.exe', ['/i'
  1410. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1411. , 'ACCEPT=YES', '/passive']]
  1412. }
  1413. ]
  1414. function ensureDirectoryExistence(filePath) {
  1415. var dirname = path.dirname(filePath);
  1416. if (fs.existsSync(dirname)) {
  1417. return filePath;
  1418. }
  1419. ensureDirectoryExistence(dirname);
  1420. fs.mkdirSync(dirname);
  1421. return filePath;
  1422. }
  1423. var mainTasks = [];
  1424. function verifyAndInstallPrerequisites() {
  1425. fs.writeFileSync(ensureDirectoryExistence(path.normalize(downloadsdir + '/readme.txt')), `${getVersion()} Your local downloads for this instance`)
  1426. var downloadbatch =
  1427. `::**************************************************************************
  1428. :Download_ <url> <File>
  1429. Powershell.exe ^
  1430. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  1431. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  1432. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  1433. exit /b
  1434. ::**************************************************************************`
  1435. fs.writeFileSync('download.bat', downloadbatch)
  1436. var downloadtasks = [];
  1437. var installtasks = [];
  1438. prerequisites.forEach(preq => {
  1439. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  1440. if (exists) console.log(`${preq.shellcmd} exists`)
  1441. else {
  1442. console.log(`${preq.shellcmd} is not installed`)
  1443. return preq.preinstallsteps().then(() => {
  1444. installtasks.push(task.install)
  1445. })
  1446. }
  1447. }))
  1448. })
  1449. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  1450. }
  1451. function initinstances(chessinstances, selected) {
  1452. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  1453. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  1454. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  1455. selectedinstance = Object.assign(selected, chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env], clioverrides);
  1456. repomanifest = selectedinstance
  1457. return chessinstances
  1458. }
  1459. function acquirelocalinstances(selected){
  1460. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  1461. return initinstances(chessinstances, selected)
  1462. }
  1463. function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  1464. var detectedInstance = detectInstance(); // From launch location etc.
  1465. var selectedinstance = detectedInstance
  1466. var clioverrides = { }
  1467. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1468. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  1469. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  1470. var maintask = () => {
  1471. try {
  1472. // Default cmd to run !
  1473. var chessinstances = acquirelocalinstances(selectedinstance);
  1474. processedArgs._[0] === processedArgs._[0] || 'pull';
  1475. // defaultRepoServer = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  1476. return acquireConfig(selectedinstance, chessinstances).catch((e) => {
  1477. console.error('Exisitng config Failed. Fix config and rerun or chose another.')
  1478. console.error(e);
  1479. }).then(() => { return elxrworker(true) })
  1480. }
  1481. catch (e) {
  1482. console.error(e)
  1483. // No local instances config found. We acquire user choices and proceed to reattempt.
  1484. chessinstances = {}
  1485. chessinstances.current_run = {}
  1486. initinstances(chessinstances, selectedinstance)
  1487. return acquireChoices(selectedinstance).then(() => {
  1488. try {
  1489. var chessinstances = acquirelocalinstances(selectedinstance)
  1490. }
  1491. catch (e) {
  1492. console.error(e)
  1493. console.error('No local instances config found in current root = ' + selectedinstance.root);
  1494. console.log('A config will be createed with the instance and environment chosen...')
  1495. }
  1496. finally {
  1497. return acquireConfig(selectedinstance, chessinstances).catch((e) => {
  1498. console.error('Chosen cofiguraton failed or not found')
  1499. console.error(e)
  1500. }).then(() => { return elxrworker(true) })
  1501. .finally(()=>{
  1502. fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  1503. fs.writeFileSync('run.done', 'error');
  1504. // return process.exit()
  1505. })
  1506. }
  1507. })
  1508. }
  1509. }
  1510. acquireElevationState().then(() => {
  1511. var skipprerequisites = false
  1512. if (!skipprerequisites && !__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
  1513. mainTasks.push(maintask)
  1514. return any(mainTasks);
  1515. })
  1516. // detect if alread installed -> Take no action.
  1517. // download if no installer avalable -> next()
  1518. // install
  1519. function chackandinstall(items) {
  1520. var tasks = []
  1521. items.forEach(item => {
  1522. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  1523. })
  1524. return Promise.all(tasks).then(existances => {
  1525. existances.forEach((exists, i) => {
  1526. if (!exists) {
  1527. return downloadandinstall([items[i]])
  1528. }
  1529. })
  1530. })
  1531. }
  1532. function downloadandinstall(items) {
  1533. var tasks = []
  1534. items.forEach(item => {
  1535. tasks.push(getTaskDownload(item))
  1536. })
  1537. return Promise.all(tasks)
  1538. }
  1539. // Sample instances config.
  1540. // var instances = {
  1541. // "elixir": {
  1542. // "production": {
  1543. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  1544. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  1545. // , "exludeMergeRepos": {
  1546. // "elixir-config-development": true, "elixir-config-test": true
  1547. // , "elixir-config-production": true, "elixir-data": true
  1548. // }
  1549. // , "instanceName": "elixir", "node_env": "production"
  1550. // }
  1551. // },
  1552. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  1553. // }