Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 61KB

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