index.js 47KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. var statuslog = require('./result')
  2. var path = require('path');
  3. var utils = require('bbhverse');
  4. var any = utils.any;
  5. // 'use strict';
  6. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  7. // --------------
  8. // elxr
  9. // A cli tool for elixr.
  10. // PB : TODO --
  11. // runas bypass non elevated tasks when we request privelege
  12. // runas message is always error needs to be fixed.
  13. // runas wait needs to be parallelized.
  14. // suppress elevation check error messages
  15. // support runas lauched directly from shell.
  16. // pass in environment in hta to shellexecute.
  17. const { existsSync } = require('fs');
  18. const fs = require('fs')
  19. const { spawn, spawnSync } = require('child_process');
  20. const cliargs = utils.cliargs;
  21. const processedArgs = cliargs(process.argv.slice(2));
  22. console.dir(processedArgs)
  23. var globSync = require('glob').sync;
  24. var path = require('path');
  25. const { isMaster } = require('cluster');
  26. // Default Config...
  27. var reposervers = [
  28. 'http://git.bbh'
  29. , 'https://git.bbh.org.in'
  30. , '//172.16.0.27/repos'
  31. ]
  32. var defaultRepoServer = reposervers[0]
  33. var currentGitAuthUser ; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  34. var defaultRepoOwner = 'chess';
  35. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  36. // -- Currently workaround is to always run from a non-elevated shell.
  37. var __isElevated = null;
  38. var isRunningElevated = ()=>{
  39. if(__isElevated === null) {
  40. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  41. inherit : true
  42. // , shell: true
  43. , stdio: 'ignore'
  44. , env: process.env
  45. , title : `check privileged execution mode using "fsutil dirty query C:"`
  46. }).then((exitcode)=>{
  47. console.log('Elevated')
  48. __isElevated = true;
  49. return true;
  50. }).catch(()=>{
  51. __isElevated = false;
  52. console.log('Not Elevated');
  53. throw false;
  54. });
  55. }
  56. else return Promise.resolve(__isElevated);
  57. }
  58. var cli = 'elxr';
  59. var ver = '#unversioned';
  60. var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
  61. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  62. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  63. var dbForLabel = function(label){
  64. var dbsForLabel = {
  65. devmysql : 'mysql'
  66. , development : 'mssql'
  67. , production : 'mssql'
  68. }
  69. return dbsForLabel[label] || 'mysql'
  70. }
  71. var gitInstallDir = "C:\\Program Files\\Git\\bin\\sh.exe"
  72. // var gitInstallDir = "G:\\Installed\\Git\\bin\\sh.exe"
  73. // Relevant git repos
  74. var gitRepos = [
  75. 'ember-masonry-grid'
  76. , 'bbhverse'
  77. , 'clientverse'
  78. , 'serververse'
  79. , 'client'
  80. // , 'client/server'
  81. , 'elxr'
  82. , 'ember-searchable-select'
  83. , 'loopback-component-jsonapi'
  84. , 'loopback-jsonapi-model-serializer'
  85. , 'loopback-connector-mysql'
  86. , 'elixir-config-development'
  87. , 'elixir-config-test'
  88. , 'cihsr-config-development'
  89. , 'cihsr-data'
  90. , 'elixir-data'
  91. , 'loopback-connector-ds'
  92. , 'chess-server-lib'
  93. , 'setup'
  94. , 'elixir-client-todos'
  95. , 'elixir-client-unlinked'
  96. , 'elixir-client'
  97. , 'ember-service-worker'
  98. , 'ember-service-worker-asset-cache'
  99. , 'ember-service-worker-cache-fallback'
  100. , 'ember-service-worker-index'
  101. , 'ember-sw-client-route'
  102. , 'global-this'
  103. ]
  104. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  105. //
  106. var elevatedRunasRepos = [
  107. 'elixir-server'
  108. , 'cihsr-server'
  109. , 'chess-server'
  110. ]
  111. var exludeMergeRepos = {
  112. 'elixir-config-development' : true, 'elixir-config-test': true, 'elixir-config-production' : true
  113. , 'elixir-data' : true
  114. ,'cihsr-config-development' : true, 'cihsr-config-test': true, 'cihsr-config-production' : true
  115. , 'cihsr-data' : true
  116. }
  117. var productionRepos = [
  118. 'elixir-config-production'
  119. ]
  120. var productionIsAllowed = (process.env.NODE_ENV === 'production');
  121. if(productionIsAllowed) gitRepos = gitRepos.concat(productionRepos)
  122. var env = Object.assign({}, process.env); // Shallow clone it.
  123. var __runcmd = function(label){
  124. var op = {
  125. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  126. , 'undefined' : ()=>{ return op.h(); }
  127. , 'reset' : ()=>{
  128. // Reset NPM packages semver so major versions can be updated.
  129. const fs = require('fs')
  130. const wipeDependencies = (package) => {
  131. const file = fs.readFileSync(package + '/package.json')
  132. const content = JSON.parse(file)
  133. for (var devDep in content.devDependencies) {
  134. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  135. content.devDependencies[devDep] = '*';
  136. }
  137. }
  138. for (var dep in content.dependencies) {
  139. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  140. content.dependencies[dep] = '*';
  141. }
  142. }
  143. fs.writeFileSync(package + '/package.json', JSON.stringify(content))
  144. }
  145. var repos = ['client'];
  146. // repos = gitRepos;
  147. repos.forEach(wipeDependencies)
  148. // if (require.main === module) {
  149. // } else {
  150. // module.exports = wipeDependencies
  151. // }
  152. }
  153. , 'upgrade' : ()=>{
  154. console.log('upgrade.......')
  155. var tasks = [
  156. ()=>{
  157. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  158. inherit : true, shell: true
  159. , env: process.env
  160. }).catch((e)=>{ console.error(e) })
  161. p.position = 1;
  162. console.log('One')
  163. return p;
  164. }
  165. , ()=>{
  166. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  167. inherit : true, shell: true
  168. , env: process.env
  169. }).catch((e)=>{ console.error(e) })
  170. p.position = 2;
  171. console.log('Two')
  172. return p;
  173. }
  174. , ()=>{
  175. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  176. inherit : true, shell: true
  177. , env: process.env
  178. }).catch((e)=>{ console.error(e) })
  179. p.position = 3;
  180. console.log('Three')
  181. return p;
  182. }
  183. , ()=>{
  184. var p = nodeShellExec('n', ['latest'], {
  185. inherit : true, shell: true
  186. , env: process.env
  187. }).catch((e)=>{ console.error(e) })
  188. p.position = 4;
  189. console.log('Four')
  190. return p;
  191. }
  192. ]
  193. any(tasks)
  194. console.log('.......done')
  195. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  196. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  197. console.info('Uninstalling existing ember globally') ;
  198. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  199. stdio: ['pipe', process.stdout, process.stderr],
  200. inherit : true,
  201. shell: true,
  202. cwd : path.dirname(__dirname),
  203. env: env
  204. })
  205. step1.on('close', ()=>{
  206. console.info('Installing ember globally') ;
  207. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  208. stdio: ['pipe', process.stdout, process.stderr],
  209. inherit : true,
  210. shell: true,
  211. cwd : path.dirname(__dirname),
  212. env: env
  213. })
  214. step2.on('close', ()=>{
  215. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  216. stdio: ['pipe', process.stdout, process.stderr],
  217. inherit : true,
  218. shell: true,
  219. cwd : path.dirname(__dirname),
  220. env: env
  221. })
  222. })
  223. })
  224. }
  225. , 'runas' : ()=>{
  226. console.log('Testing Elevation')
  227. return isRunningElevated().then(
  228. (isElevated) => {
  229. if(isElevated) {
  230. try {
  231. op[ processedArgs.label || processedArgs._[0] || 'h']()
  232. }
  233. catch(e){
  234. console.error('Error Invalid command : ' + e)
  235. fs.writeFileSync('run.done', 'success')
  236. }
  237. finally {
  238. }
  239. } else throw false;
  240. }
  241. )
  242. .catch(()=>{
  243. console.log('Requesting Elevated Privileges');
  244. // Wait for the runas to complete before we read it.
  245. try {
  246. fs.unlinkSync('run.done')
  247. fs.unlinkSync('run.log')
  248. }
  249. catch(e) { } //Ignore
  250. // Find node path to send to hta.
  251. nodeShellExec('where', ['node']).then(r => {
  252. console.log('result : ' + r)
  253. // throw 'rrrrrrrrrrrrrrrrr'
  254. // PB : TODO -- Convert all the cli args back to string.
  255. var namedArgs = [];
  256. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  257. //console.log(' namedArgs : ' + namedArgs)
  258. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  259. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  260. args.push('--nodepath='+r[r.length-1])
  261. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  262. , {
  263. inherit : true
  264. , shell: true
  265. , env: process.env
  266. , runas : 'self'
  267. , title : `runas`
  268. }
  269. ).then(()=>{
  270. // runas returned.
  271. try {
  272. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  273. runaslog.forEach((logEntry)=>{
  274. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  275. })
  276. }
  277. catch(e){
  278. // Ignore nonexistent log
  279. console.warn('Run log error probably was not created by runas : ' + e)
  280. }
  281. })
  282. .catch(err => console.error('Elevation failed : ' + err));
  283. })
  284. })
  285. }
  286. , 'push' : ()=>{
  287. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  288. // init remote bare from local
  289. // pushandinitremotebare
  290. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  291. // connect to repo server -- net use 172.16.0.27
  292. // cd 172.16.0.27/repos/
  293. // mkdir repo.git
  294. // cd repo.git
  295. // git init --bare
  296. // cd localrepo
  297. // git remote rename origin githubclone
  298. // git remote add origin //172.16.0.27/repos/repo.git
  299. // git push origin master
  300. var repo = processedArgs._[1];
  301. var sequentialTaskShellCommands = [];
  302. if(!existsSync(`Z:/${repo}.git`)){
  303. sequentialTaskShellCommands = [
  304. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  305. // inherit : true, shell: true
  306. // , env: process.env
  307. // }]
  308. ['pwd', { cwd : 'Z:', inherit : true}]
  309. , ['mkdir', [`${repo}.git`], {
  310. cwd : `Z:`
  311. , inherit : true, shell: true
  312. , env: process.env
  313. }]
  314. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  315. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  316. , inherit : true, shell: true
  317. , env: process.env
  318. }]
  319. // PB : TODO -- Do this conditionally only...
  320. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  321. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  322. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  323. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  324. // PB : TODO -- If threre is a gitbubclone origin
  325. // Set the master to pull from the local repo.
  326. ]
  327. if(!existsSync(`Z:`)){
  328. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  329. inherit : true, shell: true
  330. , env: process.env
  331. }])
  332. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  333. // throw 'done'
  334. }
  335. }
  336. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  337. // console.dir(sequentialTaskShellCommands);
  338. var tasks = [];
  339. sequentialTaskShellCommands.forEach(shellcmd => {
  340. // console.log(shellcmd)
  341. tasks.push(()=>{
  342. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  343. return p;
  344. })
  345. })
  346. any(tasks);
  347. }
  348. , 'is-git-repo' : (dir)=>{
  349. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio : 'ignore'})
  350. }
  351. , 'set-url' : (remotename, url) => {
  352. var pushable = processedArgs.pushable || false;
  353. remotename = remotename || processedArgs._[1]
  354. url = url || processedArgs._[2]
  355. var serial_perform_git_seturl = (repo)=>{
  356. var options = { cwd : repo }
  357. // console.log(repo)
  358. if(pushable) {
  359. return [
  360. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd : repo }]
  361. ]
  362. }
  363. else {
  364. console.error('not supported for non-pushable')
  365. }
  366. }
  367. var x = (args)=>{
  368. return ()=>{
  369. // console.log(args)
  370. return nodeShellExec.apply(null, args)
  371. }
  372. // return Promise.resolve(true)
  373. }
  374. var perform_git_seturl = (dir)=>{
  375. op['is-git-repo'](dir).then((code)=>{
  376. any( serial_perform_git_seturl(dir.name).map(x) )
  377. }).catch((e)=>{
  378. // console.log('Failed : ' + dir.name)
  379. })
  380. }
  381. const { readdir } = require("fs").promises
  382. const dirs = async (perform, path) => {
  383. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  384. if (dir.isDirectory()) perform(dir)
  385. }
  386. }
  387. dirs( perform_git_seturl)
  388. }
  389. , 'add' : (remotename, url, branch) => {
  390. var pushable = processedArgs.pushable || false;
  391. remotename = remotename || processedArgs._[1]
  392. url = url || processedArgs._[2]
  393. branch = branch || processedArgs._[3]
  394. var serial_perform_git_add = (repo)=>{
  395. var options = { cwd : repo }
  396. // console.log(repo)
  397. if(pushable) {
  398. return [
  399. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  400. , ['git', ['pull', remotename, branch], { cwd : repo }]
  401. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  402. ]
  403. }
  404. else {
  405. return [
  406. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  407. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd : repo }]
  408. , ['git', ['pull', remotename, branch], { cwd : repo }]
  409. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  410. ]
  411. }
  412. }
  413. var x = (args)=>{
  414. return ()=>{
  415. // console.log(args)
  416. return nodeShellExec.apply(null, args)
  417. }
  418. // return Promise.resolve(true)
  419. }
  420. var perform_git_add = (dir)=>{
  421. op['is-git-repo'](dir).then((code)=>{
  422. // console.log(code)
  423. if(code) {
  424. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  425. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  426. })
  427. .catch((e)=>{
  428. any( serial_perform_git_add(dir.name).map(x) )
  429. })
  430. }
  431. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  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_add)
  443. }
  444. , 'remove' : (remotename) => {
  445. remotename = remotename || processedArgs._[1]
  446. var serial_perform_git_remove = (repo)=>{
  447. var options = { cwd : repo }
  448. // console.log(repo)
  449. return [
  450. ['git', ['remote', 'remove', remotename], { cwd : repo }]
  451. ]
  452. }
  453. var x = (args)=>{
  454. return ()=>{
  455. // console.log(args)
  456. return nodeShellExec.apply(null, args)
  457. }
  458. // return Promise.resolve(true)
  459. }
  460. var perform_git_remove = (dir)=>{
  461. op['is-git-repo'](dir).then((code)=>{
  462. // console.log(code)
  463. if(code) {
  464. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  465. any( serial_perform_git_remove(dir.name).map(x) )
  466. })
  467. .catch((e)=>{
  468. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  469. })
  470. }
  471. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  472. }).catch((e)=>{
  473. // console.log('Failed : ' + dir.name)
  474. })
  475. }
  476. const { readdir } = require("fs").promises
  477. const dirs = async (perform, path) => {
  478. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  479. if (dir.isDirectory()) perform(dir)
  480. }
  481. }
  482. dirs(perform_git_remove)
  483. }
  484. , 'init-gitea' : (user) => {
  485. user = user || processedArgs._[1]
  486. if(!user) throw 'User name required'
  487. var serial_perform_init_gitea = (repo)=>{
  488. var options = { cwd : repo }
  489. // console.log(repo)
  490. return [
  491. ['git', ['remote', 'add', 'chess', `${defaultRepoServer}/${user}/${repo}.git`], { cwd : repo }]
  492. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd : repo }]
  493. , ['git', ['remote', 'set-url', 'origin', `${defaultRepoServer}/${user}/${repo}.git`], { cwd : repo }]
  494. ]}
  495. var x = (args)=>{
  496. return ()=>{
  497. // console.log(args)
  498. return nodeShellExec.apply(null, args)
  499. }
  500. // return Promise.resolve(true)
  501. }
  502. var perform_init_gitea = (dir)=>{
  503. op['is-git-repo'](dir).then((code)=>{
  504. // console.log(code)
  505. if(code) {
  506. nodeShellExec('git',['remote', 'get-url', 'chess'], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  507. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  508. })
  509. .catch((e)=>{
  510. any( serial_perform_init_gitea(dir.name).map(x) )
  511. })
  512. }
  513. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  514. }).catch((e)=>{
  515. // console.log('Failed : ' + dir.name)
  516. })
  517. }
  518. const { readdir } = require("fs").promises
  519. const dirs = async (perform, path) => {
  520. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  521. if (dir.isDirectory()) perform(dir)
  522. }
  523. }
  524. dirs(perform_init_gitea)
  525. }
  526. , 'syncmaster' : (label) => {
  527. // Usage :
  528. // elxr pull -- Defaults to run config
  529. var env = Object.assign({}, process.env); // Shallow clone it.
  530. // console.dir(env)
  531. console.log('Running exlr pull : ' + path.dirname(__dirname))
  532. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  533. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  534. // stdio: ['pipe', process.stdout, process.stderr],
  535. // inherit : true,
  536. // shell: true,
  537. // cwd : path.dirname(__dirname),
  538. // env: env
  539. // })
  540. var useGitPull = processedArgs.useGitPull || false;
  541. var getPullCmd = (repo)=>{
  542. // console.log(useGitPull)
  543. var pullCmd = [ gitInstallDir
  544. , ['-c', 'for i in `git remote`; do git pull $i master; done;']
  545. , { cwd : repo, title : 'pull all origins for ' + repo }]
  546. // var pullCmd = ['pullall', [], { cwd : repo }]
  547. if(useGitPull) pullCmd = ['git', ['pull'], {
  548. inherit : true, shell: true,
  549. cwd : repo
  550. // , env: process.env
  551. , runas : processedArgs.runas
  552. , title : `git pull ${repo}`
  553. }]
  554. return pullCmd
  555. }
  556. var performPull = (repo) => {
  557. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  558. if(existsSync(repo)) {
  559. console.log('pulling ' + repo)
  560. return nodeShellExec.apply(null, getPullCmd(repo)).catch((e)=>{ console.error(e) })
  561. }
  562. else {
  563. console.log('cloning ' + repo)
  564. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  565. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  566. {
  567. inherit : true, shell: true,
  568. env: process.env
  569. , runas : processedArgs.runas
  570. }).catch((e)=>{ console.error(e) }).then(()=>{
  571. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  572. {
  573. inherit : true, shell: true,
  574. env: process.env
  575. , cwd : repo
  576. , runas : processedArgs.runas
  577. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  578. })
  579. })
  580. }
  581. }
  582. if(!processedArgs.runas) gitRepos.forEach(performPull)
  583. return isRunningElevated().then(
  584. (isElevated) => {
  585. if(isElevated) {
  586. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  587. fs.writeFileSync('run.done', 'success')
  588. }).catch(()=>{
  589. fs.writeFileSync('run.done', 'error')
  590. })
  591. }
  592. else throw false;
  593. }
  594. ).catch(
  595. () => {
  596. op['runas']()
  597. }
  598. )
  599. }
  600. , 'pull' : (label) => {
  601. // Usage :
  602. // elxr pull -- Defaults to run config
  603. var env = Object.assign({}, process.env); // Shallow clone it.
  604. // console.dir(env)
  605. console.log('Running exlr pull : ' + path.dirname(__dirname))
  606. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  607. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  608. // stdio: ['pipe', process.stdout, process.stderr],
  609. // inherit : true,
  610. // shell: true,
  611. // cwd : path.dirname(__dirname),
  612. // env: env
  613. // })
  614. var useGitPull = processedArgs.useGitPull || false;
  615. var getPullCmd = (repo)=>{
  616. // console.log(useGitPull)
  617. var pullCmd = [ gitInstallDir
  618. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  619. , { cwd : repo, title : 'pull all origins for ' + repo }]
  620. // var pullCmd = ['pullall', [], { cwd : repo }]
  621. if(useGitPull) pullCmd = ['git', ['pull'], {
  622. inherit : true, shell: true,
  623. cwd : repo
  624. // , env: process.env
  625. , runas : processedArgs.runas
  626. , title : `git pull ${repo}`
  627. }]
  628. return pullCmd
  629. }
  630. var errors = [];
  631. var performPull = (repo) => {
  632. if(existsSync(repo)) {
  633. console.log('pulling ' + repo)
  634. return nodeShellExec.apply(null, getPullCmd(repo)).then((srepo)=>{
  635. statuslog.statuslog(null, srepo)}).catch((e)=>{ statuslog.statuslog(e, srepo); console.error(e) })
  636. }
  637. else {
  638. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  639. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  640. {
  641. inherit : true, shell: true,
  642. env: process.env
  643. , runas : processedArgs.runas
  644. }).catch((e)=>{
  645. errors.push({ repo , e})
  646. console.error(e)
  647. }).then(()=>{
  648. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  649. {
  650. inherit : true, shell: true,
  651. env: process.env
  652. , cwd : repo
  653. , runas : processedArgs.runas
  654. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  655. })
  656. })
  657. }
  658. }
  659. if(!processedArgs.runas) {
  660. var pendingpulls = [];
  661. gitRepos.forEach( (r)=>{
  662. pendingpulls.push(performPull(r))
  663. } )
  664. Promise.all(pendingpulls).then(results =>{
  665. // console.log(statuslog.log.SUCCESS)
  666. console.log('Total : ' + (statuslog.log.SKIPPED.length + statuslog.log.SUCCESS.length + statuslog.log.FAILURE.length))
  667. console.log('Pass : ' + statuslog.log.SUCCESS.length )
  668. console.log('Fail : ' + statuslog.log.FAILURE.length)
  669. console.log('Skipped : ' + statuslog.log.SKIPPED.length)
  670. })
  671. }
  672. return isRunningElevated().then(
  673. (isElevated) => {
  674. if(isElevated) {
  675. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  676. fs.writeFileSync('run.done', 'success')
  677. }).catch(()=>{
  678. fs.writeFileSync('run.done', 'error')
  679. })
  680. }
  681. else throw false;
  682. }
  683. ).catch(
  684. () => {
  685. op['runas']()
  686. }
  687. )
  688. }
  689. , 'isInstalled' : ()=>{
  690. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  691. console.log(processedArgs._[1] + ' exists.')
  692. return true;
  693. });
  694. }
  695. , 'npmi' : ()=>{
  696. var tasks = [];
  697. var bowerRepos = ['client']
  698. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  699. npmbuildrepos.forEach(repo => {
  700. tasks.push(()=>{
  701. var p = nodeShellExec('npm', ['run build'], {
  702. inherit : true, shell: true
  703. , cwd : repo
  704. , env: process.env
  705. , title : `npm build for ${repo}`
  706. }).catch((e)=>{ console.error(e) })
  707. return p;
  708. })
  709. })
  710. bowerRepos.forEach(repo => {
  711. tasks.push(()=>{
  712. var p = nodeShellExec('bower', ['install'], {
  713. inherit : true, shell: true
  714. , cwd : repo
  715. , env: process.env
  716. , title : `bower i for ${repo}`
  717. }).catch((e)=>{ console.error(e) })
  718. return p;
  719. })
  720. })
  721. gitRepos = gitRepos.concat(elevatedRunasRepos);
  722. gitRepos.push('client/server');
  723. gitRepos.forEach(repo => {
  724. console.log('npm i for ' + repo)
  725. // nodeShellExec('pwd', [], {
  726. // // inherit : true, shell: true
  727. // cwd : repo
  728. // // , env: process.env
  729. // , title : `pwd for ${repo}`
  730. // }).catch((e)=>{ console.error(e) })
  731. nodeShellExec('rm', ['package-lock.json'], {
  732. inherit : true, shell: true
  733. , cwd : repo
  734. , env: process.env
  735. , title : `rm 'package-lock.json' for ${repo}`
  736. }).catch((e)=>{ console.error(e) })
  737. if( npmbuildrepos.indexOf(repo) < 0) {
  738. tasks.push(()=>{
  739. var p = nodeShellExec('npm', ['i --force'], {
  740. inherit : true, shell: true
  741. , cwd : repo
  742. , env: process.env
  743. , title : `npm i for ${repo}`
  744. }).catch((e)=>{ console.error(e) })
  745. return p;
  746. })
  747. }
  748. })
  749. any(tasks);
  750. }
  751. , 'start' : (label)=>{
  752. console.log('Starting Elixir Server.');
  753. var env = Object.assign({}, process.env); // Shallow clone it.
  754. // console.dir(env)
  755. env.NODE_ENV = process.env.NODE_ENV || 'development';
  756. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  757. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  758. // cmd = 'node'
  759. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  760. var childPromise = nodeShellExec(...cmd, {
  761. // inherit : true,
  762. shell: true,
  763. detached: true,
  764. stdio: 'ignore',
  765. cwd : 'elixir-server'
  766. , env: env
  767. })
  768. var child = childPromise.process;
  769. if (typeof child.pid !== 'undefined') {
  770. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  771. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  772. encoding: 'utf8'
  773. })
  774. }
  775. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  776. // inherit : true,
  777. // shell: true, detached: true,
  778. // cwd : 'qms/server',
  779. // env: env,
  780. // shell : true
  781. // })
  782. // nodeShellExec('ember', ['s'], {
  783. // // inherit : true,
  784. // shell: true, detached: true,
  785. // cwd : 'client/',
  786. // env: env
  787. // })
  788. console.log('Starting Elixir Client Host.');
  789. var cmd = ['ember', ['s']]
  790. var childPromise = nodeShellExec(...cmd, {
  791. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  792. // PB : TODO -- ember debugging.
  793. // inherit : true,
  794. shell: true,
  795. detached: true,
  796. stdio: 'ignore',
  797. cwd : 'client'
  798. , env: env
  799. })
  800. // .catch(e=>console.error(e))
  801. child = childPromise.process;
  802. if (typeof child.pid !== 'undefined') {
  803. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  804. fs.writeFileSync('.client.server.pid', child.pid, {
  805. encoding: 'utf8'
  806. })
  807. }
  808. }
  809. , 'stop' : (label)=>{
  810. const kill = require('tree-kill');
  811. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  812. encoding: 'utf8'
  813. })
  814. fs.unlinkSync('.elixir-server.elixir.server.pid')
  815. console.log(serverPid)
  816. kill(serverPid)
  817. serverPid = fs.readFileSync('.client.server.pid', {
  818. encoding: 'utf8'
  819. })
  820. fs.unlinkSync('.client.server.pid')
  821. console.log(serverPid)
  822. kill(serverPid)
  823. }
  824. , 'use' : ()=>{
  825. // use a certain named instance.
  826. // Eg :
  827. // 1) elxr use elixir
  828. // 2) elxr use cihsr
  829. // If environment is not specified defaults to development.
  830. // 1) NODE=test elxr use elixir
  831. /*// Steps
  832. 1) Delete Config and Data symlinks
  833. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  834. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  835. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  836. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  837. */
  838. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  839. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  840. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  841. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  842. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  843. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  844. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  845. return
  846. }
  847. var tasks = [
  848. ()=>{
  849. if(existsSync('config')) {
  850. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  851. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  852. return p;
  853. }
  854. else return Promise.resolve(true);
  855. },
  856. ()=>{
  857. if(existsSync('data')) {
  858. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  859. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  860. return p;
  861. }
  862. else return Promise.resolve(true);
  863. },
  864. ];
  865. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  866. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  867. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  868. // console.log(process.env.cwd)
  869. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  870. var checkoutMap = {
  871. 'development' : 'master',
  872. }
  873. // cant use git checkout -b it fails with branch already exists.
  874. var performCheckout = (repo, branch)=>{
  875. if(!branch) return Promise.resolve({ 'skipped' : true })
  876. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  877. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  878. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  879. // inherit : true, shell: true,
  880. cwd : repo
  881. // , stdio : ignore // Use when we want to silcence output completely.
  882. , runas : processedArgs.runas
  883. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  884. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  885. }
  886. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  887. var performPullAll = (repo)=>{
  888. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  889. return nodeShellExec('git', ['pull', '--all'], {
  890. // inherit : true, shell: true,
  891. cwd : repo
  892. , runas : processedArgs.runas
  893. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  894. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  895. }
  896. var mergeSources = {
  897. 'development' : null,
  898. 'test' : 'master',
  899. 'production' : 'master'
  900. }
  901. var excludeCheckouts = Object.assign(exludeMergeRepos)
  902. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  903. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  904. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  905. var performMerge = (repo)=>{
  906. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  907. return nodeShellExec('git', ['merge', mergeSource], {
  908. inherit : true, shell: true,
  909. cwd : repo
  910. , runas : processedArgs.runas
  911. }).catch((e)=>{ console.error(e) })
  912. }
  913. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  914. any(tasks).then(()=>{
  915. if(!processedArgs.runas) return op['runas']()
  916. tasks = [
  917. ()=>{
  918. // Use junctions to avoid npm package issues
  919. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  920. inherit : true, shell: true
  921. , env: process.env
  922. }).catch((e)=>{ console.error(e) })
  923. return p;
  924. }
  925. ];
  926. if(processedArgs._[1]) {
  927. tasks = tasks.concat(
  928. [
  929. ()=>{
  930. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  931. inherit : true, shell: true
  932. , env: process.env
  933. }).catch((e)=>{ console.error(e) })
  934. return p;
  935. }
  936. ]
  937. )
  938. }
  939. return any(tasks)
  940. //target is the env is we specify in elxr use command. Default is dev
  941. .then( //Switch to target branch
  942. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  943. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  944. .then( //PULL from target branch
  945. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  946. .then( //Switch to merge source branch
  947. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  948. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  949. .then( //Pull on merge source branch
  950. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  951. .then( //Switch to target branch
  952. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  953. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  954. .then( //Merge source branch to target branch
  955. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  956. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  957. .then( () => {
  958. // Move test config from dev.
  959. // if(process.env.NODE_ENV === 'test'){
  960. // var devcfgreponame = runconfig.use + '-config' + '-development';
  961. // var testcfgreponame = runconfig.use + '-config' + '-test';
  962. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  963. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  964. // return any([
  965. // ()=>{
  966. // return nodeShellExec('git', ['checkout', 'test'], {
  967. // inherit : true, shell: true,
  968. // cwd : testcfgdir
  969. // // , env: process.env
  970. // , runas : processedArgs.runas
  971. // , title : `git checkout test for ${testcfgreponame}`
  972. // }).catch((e)=>{ console.error(e) })
  973. // }
  974. // , ()=> {
  975. // return nodeShellExec('git', ['checkout', 'master'], {
  976. // inherit : true, shell: true,
  977. // cwd : devcfgdir
  978. // // , env: process.env
  979. // , runas : processedArgs.runas
  980. // , title : `git checkout master for ${devcfgreponame}`
  981. // }).catch((e)=>{ console.error(e) })
  982. // }
  983. // , ()=> {
  984. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  985. // console.log('File found : ' + devcfgdir + filename)
  986. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  987. // })
  988. // return nodeShellExec('git', ['checkout', 'test'], {
  989. // inherit : true, shell: true,
  990. // cwd : devcfgdir
  991. // // , env: process.env
  992. // , runas : processedArgs.runas
  993. // , title : `git checkout test for ${devcfgreponame}`
  994. // }).catch((e)=>{ console.error(e) })
  995. // }
  996. // ])
  997. // }
  998. // else {
  999. return Promise.resolve(true)
  1000. // }
  1001. })
  1002. .then(()=>{
  1003. fs.writeFileSync('run.done', 'success')
  1004. }).catch(()=>{
  1005. fs.writeFileSync('run.done', 'error')
  1006. })
  1007. }).catch(()=>{
  1008. fs.writeFileSync('run.done', 'error')
  1009. })
  1010. // Antibiotic stewardship program.
  1011. // 1st use is fine.
  1012. // Max vials dispense
  1013. // 2nd use Pharmacy needs justification Form.
  1014. // Approval after a certain period of time.
  1015. }
  1016. , 'g' : ()=>{
  1017. if(processedArgs.h) {
  1018. console.log('elxr g [modelname] => generate a model named [modelname]');
  1019. console.log('elxr g => regenerate all known models');
  1020. return
  1021. }
  1022. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1023. // console.log('Starting directory: ' + process.cwd());
  1024. // try {
  1025. // child = child.on('close', () => { process.chdir(label) } );
  1026. // console.log('New directory: ' + process.cwd());
  1027. // }
  1028. // catch (err) {
  1029. // console.log('chdir: ' + err);
  1030. // }
  1031. // child.on('close', function(){
  1032. // var options = {
  1033. // shell : true
  1034. // , inherit : true
  1035. // // , cwd : '' + process.cwd
  1036. // // , env : process.env
  1037. // };
  1038. // nodeShellExec('git', ['init'], { inherit : true});
  1039. if(0){
  1040. // PB : TODO -- Special google chrome profile for tests etc.
  1041. nodeShellExec('pwd', { inherit : true});
  1042. // /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"
  1043. // "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
  1044. // "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
  1045. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1046. "--profile-directory=Profile 1"
  1047. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1048. }
  1049. // nodeShellExec('npm', ['init', '-y'], options);
  1050. // nodeShellExec('npm', ['init', '-y'], options);
  1051. // })
  1052. var g = {
  1053. 'client' : ()=>{
  1054. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  1055. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1056. stdio: ['pipe', process.stdout, process.stderr],
  1057. inherit : true,
  1058. shell: true,
  1059. cwd : path.dirname(__dirname),
  1060. env: env
  1061. })
  1062. },
  1063. 'modelr' : ()=>{
  1064. var tasks = [
  1065. ()=>{
  1066. var p = nodeShellExec('"ember"', [
  1067. 'g'
  1068. , 'modelr'
  1069. , processedArgs._[2]], {
  1070. inherit : true, shell: true, env: process.env
  1071. }).then(()=>{
  1072. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1073. return true;
  1074. }).catch((e)=>{ console.error(e) })
  1075. return p;
  1076. },
  1077. ()=>{
  1078. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1079. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1080. chromeprefs = JSON.parse(chromeprefs)
  1081. var previous = chromeprefs.download.default_directory;
  1082. var parentDir = path.dirname(__dirname);
  1083. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1084. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1085. // PB : TODO -- detect where chrome is installed.
  1086. // PB : TODO -- set the download dir to the place where files are needed.
  1087. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1088. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1089. , '--profile-directory="chess"'
  1090. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1091. inherit : true, shell: true
  1092. , env: process.env
  1093. }).then(()=>{
  1094. chromeprefs.download.default_directory = previous;
  1095. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1096. return true;
  1097. }).catch((e)=>{ console.error(e) })
  1098. return p;
  1099. }
  1100. ,
  1101. ()=>{
  1102. console.log('Browser process should have closed here....')
  1103. return true;
  1104. }
  1105. ]
  1106. any(tasks)
  1107. }
  1108. }
  1109. g[processedArgs._[1]]();
  1110. }
  1111. }
  1112. return op[label] ? op[label]() : null;
  1113. }
  1114. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1115. // mysql -u root -p db_name < drop_all_tables.sql
  1116. var mysql = '../xampp/mysql/bin/mysql'
  1117. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1118. // --runas
  1119. if(processedArgs.runas) {
  1120. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1121. __runcmd('runas')
  1122. }
  1123. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1124. function nodeShellExec() {
  1125. var args = Array.from(arguments);
  1126. var opts = args[2] = args[2] || {}
  1127. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  1128. const child = spawn(...arguments);
  1129. var p = new Promise(function(resolve, reject){
  1130. if(!opts.detached) {
  1131. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  1132. var success = true;
  1133. if(opts.stdio !== 'ignore') {
  1134. child.stdout.setEncoding('utf8');
  1135. child.stderr.setEncoding('utf8');
  1136. child.stdout.on('data', (chunk) => { chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */ });
  1137. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  1138. child.stderr.on('data', (chunk) => { messages.push(chunk);
  1139. // console.error('stderr e: ' + chunk)
  1140. });
  1141. }
  1142. child.on('close', (code) => {
  1143. if(+code !== 0) success = false;
  1144. if(opts.stdio !== 'ignore') {
  1145. if(opts.runas){
  1146. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  1147. success ? logEntry.success = true : null;
  1148. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  1149. }
  1150. else {
  1151. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  1152. // console.log( messages.join('') )
  1153. process.stdout.write( messages.join('') )
  1154. }
  1155. }
  1156. if(code !== 0) return reject(code)
  1157. resolve(messages)
  1158. });
  1159. }
  1160. else {
  1161. child.unref()
  1162. resolve(true);
  1163. }
  1164. });
  1165. p.process = child;
  1166. return p;
  1167. }