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

index.js 95KB

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