Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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