Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 53KB

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