555
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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