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

index.js 96KB

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