Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651
  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 __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  12. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  13. const runtimestamp = (new Date()).getTime();
  14. function getVersion() { return BUILD_VERSION; }
  15. console.log(getVersion());
  16. // 'use strict';
  17. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  18. // PB : TODO --
  19. // runas bypass non elevated tasks when we request privelege
  20. // runas message is always error needs to be fixed.
  21. // runas wait needs to be parallelized.
  22. // suppress elevation check error messages
  23. // support runas lauched directly from shell.
  24. // pass in environment in hta to shellexecute.
  25. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  26. (function () {
  27. "use strict";
  28. if (!Array.prototype.earlyreduce) {
  29. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  30. var iterable = this;
  31. var donecallback = donecallback || (a=>a)
  32. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  33. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  34. // function *earlyReduceGenerator(acc, v, i, a) {
  35. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  36. var element = iterable[i]
  37. result = eachcallback(result, element, i, iterable)
  38. if(result.done) return donecallback(result)
  39. }
  40. // }
  41. return donecallback(result)
  42. }
  43. }
  44. }());
  45. const { existsSync } = require('fs');
  46. const existsFolderSync = existsSync;
  47. const fs = require('fs')
  48. const cliargs = utils.cliargs;
  49. const processedArgs = cliargs(process.argv.slice(2));
  50. console.dir(processedArgs)
  51. // PB : TODO -- defaults for valuless arguments if passed.
  52. // Object.keys(processedArgs).forEach(a=>{
  53. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  54. // }
  55. // })
  56. //
  57. // elxr cli operations
  58. var noprerequisites = {
  59. add : true, 'set-url' : true, 'repo-relocate' : true
  60. , remote : true, 'c' : true, 'h' : true
  61. , httpget : true, getuser : true
  62. , 'switch user' : true
  63. , 'switch' : true
  64. // , 'undefined' : true
  65. }
  66. var reconfirmcmds = { create : true }
  67. var subcommandlabels = {
  68. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  69. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  70. }
  71. var cmds = {
  72. remote : {
  73. // return a interpreted set of arguments for this comd run context.
  74. interpret() {
  75. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  76. }
  77. }
  78. , switch : {
  79. interpret() {
  80. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  81. , reposerver : __default.reposerver
  82. }
  83. }
  84. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  85. }
  86. , 'switch user' : {
  87. interpret() {
  88. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  89. }
  90. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  91. }
  92. }
  93. var interpretrun = function(){
  94. var cmd = processedArgs._[0];
  95. var clioverrides = { cmd }
  96. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  97. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  98. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  99. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  100. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  101. // return clioverrides
  102. cmds[cmd] = {
  103. interpret() {
  104. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  105. }
  106. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  107. instanceName : true, instanceType : true, reposerver : true } }
  108. }
  109. return cmds[cmd].interpret()
  110. })()
  111. }
  112. var clioverrides = interpretrun()
  113. console.dir(clioverrides)
  114. // Object.keys(clioverrides).forEach( prop => { })
  115. var globSync = require('glob').sync;
  116. var ENV = Object.assign({}, process.env); // Shallow clone it.
  117. const { readdir } = require("fs").promises
  118. // Directory shallow walk and do perform on each dir.
  119. const dirs = async (perform, path) => {
  120. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  121. if (dir.isDirectory()) perform(dir)
  122. }
  123. }
  124. var getShellTask = (command, args, options) => {
  125. options = options || {}
  126. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  127. return () => {
  128. var p = callshell( [command, args, Object.assign({
  129. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  130. }, options)
  131. ])()
  132. if (options.ignorefailures) {
  133. return p.catch(e => {
  134. // Ignore. Not a major error.
  135. })
  136. }
  137. else return p;
  138. }
  139. }
  140. var callshelltask = (args) => {
  141. // console.dir(args)
  142. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  143. return args;
  144. }
  145. return getshelltask(args)()
  146. }
  147. var getshelltask = (args) => {
  148. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  149. var getgitbashtask = (args) => { return () => {
  150. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  151. }
  152. var getTaskCheckExists = (command, options) => {
  153. options = options || {}
  154. return () => {
  155. var p = nodeShellExec.apply(null, ['where', [command]])
  156. if (options.ignorefailures) {
  157. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  158. return false;
  159. })
  160. }
  161. else return p.then(() => { return true });
  162. }
  163. }
  164. var getTaskWithElevation = function(tasdef){
  165. return ()=>{
  166. if (__isElevated) {
  167. return tasdef.elevatedpulltasks().then(()=>{
  168. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  169. fs.writeFileSync('run.done', 'success')
  170. }).catch(e=>{
  171. fs.writeFileSync('run.done', 'failure')
  172. });
  173. }
  174. else {
  175. // PB : TODO -- Rename op['runas'] to 'elevate'
  176. var __runasresult = null;
  177. return op['runas']().then((r) => { return __runasresult = r; })
  178. .catch((e) => {
  179. console.error(e)
  180. })
  181. .finally(() => {
  182. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  183. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  184. })
  185. }
  186. }
  187. }
  188. var getTaskWithoutElevation = function(tasdef){
  189. return ()=>{
  190. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  191. else Promise.resolve(true)
  192. }
  193. }
  194. var gitops = {
  195. getdiscoverbranchcmd : function(repo){
  196. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  197. var cmd = [gitbash
  198. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  199. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  200. return cmd
  201. }
  202. }
  203. var getPullCmd = (repo, branch) => {
  204. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  205. // console.log(useGitPull)
  206. var pullCmd = []
  207. if(!branch) {
  208. // console.warn('No branch was specified detecting from working client.')
  209. // First check if working client exists.
  210. // if (existsSync(instanceroot + '/' + repo)) {
  211. pullCmd= gitops.getdiscoverbranchcmd(repo)
  212. // }
  213. // else performpull
  214. }
  215. // var pullCmd = [gitInstallDir
  216. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  217. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  218. if(branch) {
  219. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  220. var pullCmd = [ gitbash
  221. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  222. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  223. }
  224. // var pullCmd = ['pullall', [], { cwd : repo }]
  225. if (useGitPull) pullCmd = ['git', ['pull'], {
  226. inherit: true, shell: true,
  227. cwd: instanceroot + '/' + repo
  228. // , env: process.env
  229. , runas: processedArgs.runas
  230. , title: `git pull ${repo}`
  231. }]
  232. return pullCmd
  233. }
  234. var performPull = (repo, branch, repoowner, errHandler) => {
  235. // PB : TODO -- Handle no branch passed in case.
  236. // if(!branch) { throw 'No branch specified' }
  237. try{
  238. var exists = existsSync(instanceroot + '/' + repo)
  239. }
  240. catch(e){
  241. exists = false
  242. console.log(e)
  243. }
  244. if (exists) {
  245. var branchprint = branch ? ' branch :' + branch : '';
  246. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  247. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  248. if (__isElevated) {
  249. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  250. }
  251. else statuslog.statuslog(null, repo)
  252. return true;
  253. })
  254. .catch((e) => {
  255. e.repo = repo;
  256. if(errHandler) throw errHandler(e)
  257. if (__isElevated) {
  258. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  259. }
  260. else statuslog.statuslog(e);
  261. // console.error(e)
  262. throw e;
  263. })
  264. }
  265. else {
  266. console.log('cloning ' + repo)
  267. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  268. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
  269. {
  270. inherit: true, shell: true,
  271. env: process.env
  272. , cwd : instanceroot
  273. , runas: processedArgs.runas
  274. }).then(() => {
  275. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  276. {
  277. inherit: true, shell: true,
  278. env: process.env
  279. , cwd: instanceroot + '/' + repo
  280. , runas: processedArgs.runas
  281. , title: `'git', ${['config', '--replace-all', 'user.name', selectedinstance.username].join(' ')}`
  282. })
  283. .then(() => {
  284. if (__isElevated) {
  285. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  286. }
  287. else statuslog.statuslog(null, repo)
  288. })
  289. .catch((e) => {
  290. e.repo = repo;
  291. if (__isElevated) {
  292. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  293. }
  294. else statuslog.statuslog(e);
  295. })
  296. })
  297. .catch(e => {
  298. e.repo = repo;
  299. if(errHandler) throw errHandler(e)
  300. if (__isElevated) {
  301. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  302. }
  303. else statuslog.statuslog(e);
  304. throw e
  305. })
  306. }
  307. }
  308. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  309. // -- Currently workaround is to always run from a non-elevated shell.
  310. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  311. var acquireElevationState = () => {
  312. if (__isElevated === null) {
  313. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  314. inherit: true
  315. // , shell: true
  316. , stdio: 'ignore'
  317. , env: process.env
  318. , title: `check privileged execution mode using "fsutil dirty query C:"`
  319. }).then((exitcode) => {
  320. console.log('Elevated')
  321. __isElevated = true;
  322. return true;
  323. }).catch(() => {
  324. __isElevated = false;
  325. console.log('Not Elevated');
  326. return false;
  327. });
  328. }
  329. else return Promise.resolve(__isElevated);
  330. }
  331. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  332. var defaultRepoOwner = 'chess';
  333. var elevatedRunasRepos = null
  334. var gitRepos = null
  335. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  336. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  337. var dbForLabel = function (label) {
  338. var dbsForLabel = {
  339. devmysql: 'mysql'
  340. , development: 'mssql'
  341. , production: 'mssql'
  342. }
  343. return dbsForLabel[label] || 'mysql'
  344. }
  345. // SAM : TODO Use nodeshellexec where to detect git installation dir
  346. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  347. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  348. // Relevant git repos
  349. var exludeMergeRepos = [];
  350. var useGitPull = processedArgs.useGitPull || false;
  351. var configPromise = null
  352. var op = {
  353. 'h': () => { console.log(elxr.help()); return '-h' }
  354. , 'clean' : () => {
  355. // delete all node_module folders and links.
  356. var tasklist = [];
  357. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  358. return Promise.all(tasklist)
  359. }
  360. // , 'undefined': () => { return acquireChoices( {} ); }
  361. , 'reset': () => {
  362. // Reset NPM packages semver so major versions can be updated.
  363. const fs = require('fs')
  364. const wipeDependencies = (__package) => {
  365. const file = fs.readFileSync(__package + '/package.json')
  366. const content = JSON.parse(file)
  367. for (var devDep in content.devDependencies) {
  368. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  369. content.devDependencies[devDep] = '*';
  370. }
  371. }
  372. for (var dep in content.dependencies) {
  373. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  374. content.dependencies[dep] = '*';
  375. }
  376. }
  377. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  378. }
  379. var repos = ['client'];
  380. // repos = gitRepos;
  381. repos.forEach(wipeDependencies)
  382. // if (require.main === module) {
  383. // } else {
  384. // module.exports = wipeDependencies
  385. // }
  386. }
  387. , 'upgrade': () => {
  388. console.log('upgrade.......')
  389. var tasks = [
  390. () => {
  391. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  392. inherit: true, shell: true
  393. , env: process.env
  394. }).catch((e) => { console.error(e) })
  395. p.position = 1;
  396. console.log('One')
  397. return p;
  398. }
  399. , () => {
  400. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  401. inherit: true, shell: true
  402. , env: process.env
  403. }).catch((e) => { console.error(e) })
  404. p.position = 2;
  405. console.log('Two')
  406. return p;
  407. }
  408. , () => {
  409. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  410. inherit: true, shell: true
  411. , env: process.env
  412. }).catch((e) => { console.error(e) })
  413. p.position = 3;
  414. console.log('Three')
  415. return p;
  416. }
  417. , () => {
  418. var p = nodeShellExec('n', ['latest'], {
  419. inherit: true, shell: true
  420. , env: process.env
  421. }).catch((e) => { console.error(e) })
  422. p.position = 4;
  423. console.log('Four')
  424. return p;
  425. }
  426. ]
  427. any(tasks)
  428. console.log('.......done')
  429. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  430. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  431. console.info('Uninstalling existing ember globally');
  432. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  433. stdio: ['pipe', process.stdout, process.stderr],
  434. inherit: true,
  435. shell: true,
  436. cwd: path.dirname(__dirname),
  437. env: env
  438. })
  439. step1.on('close', () => {
  440. console.info('Installing ember globally');
  441. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  442. stdio: ['pipe', process.stdout, process.stderr],
  443. inherit: true,
  444. shell: true,
  445. cwd: path.dirname(__dirname),
  446. env: env
  447. })
  448. step2.on('close', () => {
  449. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  450. stdio: ['pipe', process.stdout, process.stderr],
  451. inherit: true,
  452. shell: true,
  453. cwd: path.dirname(__dirname),
  454. env: env
  455. })
  456. })
  457. })
  458. }
  459. , 'runas': () => {
  460. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  461. console.log('Testing Elevation')
  462. if (__isElevated) {
  463. try {
  464. op[processedArgs.label || processedArgs._[0] || 'undefined']()
  465. }
  466. catch (e) {
  467. console.error('Error Invalid command : ' + e)
  468. fs.writeFileSync('run.done', 'error')
  469. }
  470. finally {
  471. }
  472. }
  473. else {
  474. console.log('Requesting Elevated Privileges');
  475. // Wait for the runas to complete before we read it.
  476. try {
  477. fs.unlinkSync('run.done')
  478. fs.unlinkSync('run.log')
  479. }
  480. catch (e) { } //Ignore
  481. // Find node path to send to hta.
  482. return nodeShellExec('where', ['node']).then(r => {
  483. var namedArgs = [];
  484. console.log('result : ' + JSON.stringify(r))
  485. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  486. // PB : TODO -- Convert all the cli args back to string.
  487. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  488. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  489. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  490. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  491. console.dir(processedArgs)
  492. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  493. , {
  494. inherit: true
  495. , shell: true
  496. , env: ENV
  497. , runas: 'self'
  498. , title: `runas`
  499. }
  500. ).then(() => {
  501. // runas returned.
  502. try {
  503. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  504. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  505. runaslog.forEach((logEntry) => {
  506. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  507. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  508. })
  509. }
  510. catch (e) {
  511. // We must have a runas log
  512. statuslog.statuslog(e)
  513. console.error('Run log error probably was not created by runas : ' + e)
  514. }
  515. })
  516. .catch(err => console.error('Elevation failed : ' + err));
  517. })
  518. }
  519. }
  520. , 'push': () => {
  521. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  522. // init remote bare from local
  523. // pushandinitremotebare
  524. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  525. // connect to repo server -- net use 172.16.0.27
  526. // cd 172.16.0.27/repos/
  527. // mkdir repo.git
  528. // cd repo.git
  529. // git init --bare
  530. // cd localrepo
  531. // git remote rename origin githubclone
  532. // git remote add origin //172.16.0.27/repos/repo.git
  533. // git push origin master
  534. var repo = processedArgs._[1];
  535. var sequentialTaskShellCommands = [];
  536. if (!existsSync(`Z:/${repo}.git`)) {
  537. sequentialTaskShellCommands = [
  538. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  539. // inherit : true, shell: true
  540. // , env: process.env
  541. // }]
  542. ['pwd', { cwd: 'Z:', inherit: true }]
  543. , ['mkdir', [`${repo}.git`], {
  544. cwd: `Z:`
  545. , inherit: true, shell: true
  546. , env: process.env
  547. }]
  548. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  549. , ['git', ['init', '--bare'], {
  550. cwd: `Z:/${repo}.git`
  551. , inherit: true, shell: true
  552. , env: process.env
  553. }]
  554. // PB : TODO -- Do this conditionally only...
  555. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  556. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  557. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  558. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  559. // PB : TODO -- If threre is a gitbubclone origin
  560. // Set the master to pull from the local repo.
  561. ]
  562. if (!existsSync(`Z:`)) {
  563. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  564. inherit: true, shell: true
  565. , env: process.env
  566. }])
  567. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  568. // throw 'done'
  569. }
  570. }
  571. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  572. // console.dir(sequentialTaskShellCommands);
  573. var tasks = [];
  574. sequentialTaskShellCommands.forEach(shellcmd => {
  575. // console.log(shellcmd)
  576. tasks.push(() => {
  577. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  578. return p;
  579. })
  580. })
  581. any(tasks);
  582. }
  583. , 'is-git-repo': (dir) => {
  584. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  585. }
  586. // git remote equivalents...
  587. // git branch --set-upstream-to=elixir-unc/master master
  588. // git push --set-upstream elixir-unc branch..
  589. , 'remote': (args) => {
  590. // Subcommands!
  591. // PB : TODO -- we can now pass in hypehnated args...
  592. if(!processedArgs.v) return false; // Only -v is supported presently..
  593. var serial_perform = (repo) => {
  594. var options = { cwd: instanceroot + '/' + repo }
  595. return [
  596. ['git', ['remote', '-v'], options]
  597. ]
  598. }
  599. var x = (args) => {
  600. var tasq = () => {
  601. // console.log(args)
  602. return nodeShellExec.apply(null, args).catch(e => {
  603. // We continue on failure.
  604. console.error(tasq.toString())
  605. })
  606. }
  607. tasq.toString = function(){
  608. return JSON.stringify(args)
  609. }
  610. return tasq;
  611. }
  612. var perform = (dir) => {
  613. return any(serial_perform(dir.name).map(x))
  614. }
  615. dirs(perform)
  616. }
  617. , 'remote set-url': (args) => {
  618. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  619. var __args = {
  620. remotename : args.remotename || processedArgs._[2]
  621. , url : args.url || processedArgs._[3]
  622. }
  623. // pushable doesn't mean the remote doesn't support being pushed to.
  624. // 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.
  625. // PB : TODO -- change this to enablepushing.
  626. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  627. var pushable = processedArgs.pushable || false;
  628. remotename = __args.remotename
  629. url = __args.url
  630. var serial_perform_git_seturl = (repo) => {
  631. var options = { cwd: instanceroot + '/' + repo }
  632. // console.log(repo)
  633. if (pushable) {
  634. return [
  635. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  636. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  637. ]
  638. }
  639. else {
  640. return [
  641. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  642. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  643. ]
  644. }
  645. }
  646. var x = (args) => {
  647. var tasq = () => {
  648. // console.log(args)
  649. return nodeShellExec.apply(null, args).catch(e => {
  650. // We continue on failure.
  651. console.error(tasq.toString())
  652. })
  653. }
  654. tasq.toString = function(){
  655. return JSON.stringify(args)
  656. }
  657. return tasq;
  658. }
  659. var perform_git_seturl = (dir) => {
  660. op['is-git-repo'](dir).then((logEntry) => {
  661. return any(serial_perform_git_seturl(dir.name).map(x))
  662. }).catch((e) => {
  663. // console.log('Failed : ' + dir.name)
  664. })
  665. }
  666. dirs(perform_git_seturl)
  667. }
  668. // , 'reset' : ()=>{
  669. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  670. // // Reset the whole installation pertaining to this elxr folder.
  671. // }
  672. , 'remote exists': (args) => {
  673. var __args = {
  674. remotename : args.remotename|| processedArgs._[2]
  675. , url : args.url || processedArgs._[3]
  676. , branch : args.branch || processedArgs._[4]
  677. }
  678. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  679. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  680. var commands = [
  681. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  682. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  683. ['git', ['remote', '-v'], utils.assign( {
  684. evaluateResult : function(err, result){
  685. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  686. var remotes = []
  687. var found = false;
  688. console.dir(result.messages)
  689. console.log(result + '---------------')
  690. result.messages.forEach( (line)=> {
  691. console.log(line + '$$$$$$$$$$$$$$$$$$$$')
  692. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  693. if(matches) {
  694. var remote = {};
  695. remote[matches[1]] = matches[2];
  696. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  697. found = true;
  698. result.url = remote[remotename];
  699. }
  700. }
  701. })
  702. console.dir(remotes)
  703. return [
  704. found
  705. , result
  706. ]
  707. }
  708. } , options) ]
  709. , function(prevserialtaskresult) {
  710. console.log('================================')
  711. var url = __args || prevserialtaskresult.url;
  712. console.dir(prevserialtaskresult)
  713. return getshelltask(['git', ['ls-remote', url], utils.assign( {
  714. evaluateResult : function(err, result){
  715. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  716. // `fatal: repository '${__args.url}/' not found`
  717. var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  718. return [
  719. !hasfailed, result
  720. ]
  721. }
  722. } , options) ])()
  723. }
  724. ]
  725. var mapped = commands.map(callshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  726. return any(mapped).then( allresolved =>{
  727. console.dir(allresolved)
  728. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  729. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  730. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  731. : console.log('was not added as a remote but url is currently accessible.')
  732. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  733. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  734. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  735. : [0, 1] // => was not added and remote and url is accessible.
  736. })
  737. }
  738. , 'remote refresh': (args) => {
  739. var __args = {
  740. remotename : args.remotename|| processedArgs._[2]
  741. , url : args.url || processedArgs._[3]
  742. , branch : args.branch || processedArgs._[4]
  743. }
  744. // use the repo manifest to create missing remotes.
  745. function perform_remote_refresh(dir){
  746. var repo = dir.name
  747. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  748. try {
  749. var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null, selectedinstance).remotes || [];
  750. }
  751. catch(e){
  752. var remotes = []
  753. }
  754. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  755. // console.dir(remotes)
  756. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  757. console.log('Processing : ' + dir.name)
  758. var branch = __branch
  759. __args.repo = repo
  760. __args.branch = __branch
  761. var promises = []
  762. remotes.forEach(remote =>{
  763. Object.keys(remote).forEach(remotename => {
  764. __args.remotename = remotename
  765. __args.url = remote[remotename]
  766. promises.push( op['remote exists']( __args ).then( exists => {
  767. if(!exists[0]) {
  768. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ) }
  769. else return op['remote add']( { remotename,
  770. // PB : TODO -- use the most accessible remote instead of the first available.
  771. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  772. } )
  773. }
  774. })
  775. )
  776. })
  777. })
  778. return Promise.all(promises)
  779. })
  780. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  781. }
  782. return dirs(perform_remote_refresh)
  783. }
  784. , 'remote add': (args) => {
  785. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  786. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  787. // That explicitly has a remote name prefix.
  788. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  789. // git branch branch_name -u your_new_remote/branch_name -- older versions
  790. // git branch -vv -- Detect which branch are we tracking.
  791. // default upstream should be users own fork.
  792. // Also need alias branches to
  793. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  794. // probably git merge from all remotes... and relevant branches...
  795. // alias pushall='for i in `git remote`; do git push $i; done;'
  796. // alias pullall='for i in `git remote`; do git pull $i; done;'
  797. // args === processedArgs ? args = {} : null;
  798. var __args = {
  799. remotename : args.remotename|| processedArgs._[2]
  800. , url : args.url || processedArgs._[3]
  801. , branch : args.branch || processedArgs._[4]
  802. }
  803. var remotename = __args.remotename
  804. var url = __args.url
  805. var branch = __args.branch
  806. var pushable = processedArgs.pushable || false;
  807. var serial_perform_git_add = (repo) => {
  808. var options = { cwd: instanceroot + '/' + repo }
  809. // console.log(repo)
  810. if (pushable) {
  811. return [
  812. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  813. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  814. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  815. ]
  816. }
  817. else {
  818. return [
  819. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  820. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  821. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  822. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  823. ]
  824. }
  825. }
  826. var x = (args) => {
  827. return () => {
  828. // console.log(args)
  829. return nodeShellExec.apply(null, args)
  830. }
  831. // return Promise.resolve(true)
  832. }
  833. var perform_git_add = (dir) => {
  834. op['is-git-repo'](dir).then((logEntry) => {
  835. // console.log(code)
  836. if (logEntry.success) {
  837. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  838. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  839. })
  840. .catch((e) => {
  841. any(serial_perform_git_add(dir.name).map(x))
  842. })
  843. }
  844. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  845. }).catch((e) => {
  846. console.log('Failed : ' + dir.name)
  847. })
  848. }
  849. const { readdir } = require("fs").promises
  850. dirs(perform_git_add)
  851. }
  852. , 'remote remove': (args) => {
  853. var __args = {
  854. remotename : args.remotename|| processedArgs._[2]
  855. }
  856. var remotename = __args.remotename
  857. var serial_perform_git_remove = (repo) => {
  858. var options = { cwd: instanceroot + '/' + repo }
  859. // console.log(repo)
  860. return [
  861. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  862. ]
  863. }
  864. var x = (args) => {
  865. return () => {
  866. // console.log(args)
  867. return nodeShellExec.apply(null, args)
  868. }
  869. // return Promise.resolve(true)
  870. }
  871. var perform_git_remove = (dir) => {
  872. op['is-git-repo'](dir).then((logEntry) => {
  873. // console.log(code)
  874. if (logEntry.success) {
  875. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  876. any(serial_perform_git_remove(dir.name).map(x))
  877. })
  878. .catch((e) => {
  879. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  880. })
  881. }
  882. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  883. }).catch((e) => {
  884. // console.log('Failed : ' + dir.name)
  885. })
  886. }
  887. const { readdir } = require("fs").promises
  888. dirs(perform_git_remove)
  889. }
  890. , 'init-gitea': (user) => {
  891. user = user || processedArgs._[1]
  892. if (!user) throw 'User name required'
  893. var serial_perform_init_gitea = (repo) => {
  894. var options = { cwd: instanceroot + '/' + repo }
  895. // console.log(repo)
  896. return [
  897. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  898. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  899. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  900. ]
  901. }
  902. var x = (args) => {
  903. return () => {
  904. // console.log(args)
  905. return nodeShellExec.apply(null, args)
  906. }
  907. // return Promise.resolve(true)
  908. }
  909. var perform_init_gitea = (dir) => {
  910. op['is-git-repo'](dir).then((logEntry) => {
  911. // console.log(code)
  912. if (logEntry.success) {
  913. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  914. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  915. })
  916. .catch((e) => {
  917. any(serial_perform_init_gitea(dir.name).map(x))
  918. })
  919. }
  920. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  921. }).catch((e) => {
  922. // console.log('Failed : ' + dir.name)
  923. })
  924. }
  925. const { readdir } = require("fs").promises
  926. dirs(perform_init_gitea)
  927. }
  928. , 'syncmaster': (label) => {
  929. // Usage :
  930. // elxr pull -- Defaults to run config
  931. var env = Object.assign({}, process.env); // Shallow clone it.
  932. // console.dir(env)
  933. console.log('Running exlr pull : ' + path.dirname(__dirname))
  934. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  935. if (__isElevated) {
  936. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  937. fs.writeFileSync('run.done', 'success')
  938. }).catch(() => {
  939. fs.writeFileSync('run.done', 'error')
  940. })
  941. }
  942. else return op['runas']()
  943. }
  944. , 'repo-relocate' : function(args){
  945. // relocate a subfolder in source repo to same subfolder in target repo with history.
  946. var args = args || {
  947. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  948. , folder : processedArgs._[3] || 'server'
  949. , sourcerepo : processedArgs._[2] || 'client'
  950. , targetrepo : processedArgs._[1] || 'elixir-server'
  951. }
  952. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  953. // , stdio: ['pipe', process.stdout, process.stderr]
  954. , inherit: true,
  955. shell: true,
  956. env: process.env
  957. , runas: processedArgs.runas
  958. }
  959. return op['repo-split'](args).then(()=>{
  960. return op['repo-merge'](args).then(()=>{
  961. // cleanup folder from source.
  962. var cmdseq = [
  963. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  964. // commits have to intentional...
  965. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  966. ]
  967. return any(cmdseq.map(getshelltask))
  968. })
  969. }).catch(e=>{console.error(e)})
  970. }
  971. , 'repo-split' : function(args) {
  972. // https://gist.github.com/smdabdoub/17065c348289158277b5
  973. /**
  974. * Eg : folder, remotebase, sourcerepo, targetrepo
  975. * args.folder = 'server'
  976. * args.remotebase = 'https://git.bbh/chess/'
  977. * args.sourcerepo = 'client'
  978. * args.targetrepo = 'elixir-server'
  979. */
  980. var args = args || {
  981. folder : 'server'
  982. , remotebase : 'http://git.bbh/chess/'
  983. , sourcerepo : 'client'
  984. , targetrepo : 'elixir-server'
  985. }
  986. var options = { cwd: `${instanceroot}/relocate`
  987. // , stdio: ['pipe', process.stdout, process.stderr]
  988. , inherit: true,
  989. shell: true,
  990. env: process.env
  991. , runas: processedArgs.runas
  992. }
  993. var cmdseq = [
  994. // create a temporary working dir in current folder where we started execution.
  995. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  996. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  997. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  998. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  999. ]
  1000. return any(cmdseq.map(getshelltask)).then(() => {
  1001. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1002. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  1003. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1004. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  1005. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  1006. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  1007. // subtree split and filter-branch are options. We currently use repo-filter.
  1008. return op['filter-repo'](args)
  1009. }).catch(e=>{console.error(e); throw 'failed'})
  1010. }
  1011. , 'repo-merge' : function(args) {
  1012. // Merge source repo into target repo
  1013. var args = args || {
  1014. folder : 'server'
  1015. , remotebase : 'http://git.bbh/chess/'
  1016. , sourcerepo : 'client'
  1017. , targetrepo : 'elixir-server'
  1018. }
  1019. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1020. // , stdio: ['pipe', process.stdout, process.stderr]
  1021. , inherit: true,
  1022. shell: true,
  1023. env: process.env
  1024. , runas: processedArgs.runas
  1025. }
  1026. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  1027. // , stdio: ['pipe', process.stdout, process.stderr]
  1028. , inherit: true,
  1029. shell: true,
  1030. env: process.env
  1031. , runas: processedArgs.runas
  1032. }
  1033. var cmdseq = [
  1034. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  1035. , targetrepooptions ]
  1036. // , ['git', ['push', targetrepooptions ] // manual push for now..
  1037. ]
  1038. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  1039. }
  1040. , 'filter-repo' : function(args){
  1041. // Merge source repo into target repo
  1042. var args = args || {
  1043. folder : 'server'
  1044. , remotebase : 'http://git.bbh/chess/'
  1045. , targetrepo : 'elixir-server'
  1046. }
  1047. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1048. , inherit: true, shell: true
  1049. , env: process.env
  1050. , runas: processedArgs.runas
  1051. }
  1052. var cmdseq = [
  1053. // git checkout -b feature/merge-old-project
  1054. // git remote add src-project ../src-project
  1055. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  1056. ]
  1057. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  1058. }
  1059. , 'filter-branch' : function(preservefolder, repo){
  1060. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  1061. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  1062. // Preserve a specific folder.
  1063. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  1064. /*
  1065. git clone repo reposplit
  1066. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  1067. git remote rm origin
  1068. */
  1069. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  1070. }
  1071. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  1072. // // Merge repo2 into a subfolder in repo1
  1073. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  1074. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  1075. // /*
  1076. // cd repo1
  1077. // git remote add -f tempmergesource ../{{mergesource}}/.git
  1078. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  1079. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  1080. // git commit
  1081. // // Repair History
  1082. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  1083. // #!/usr/bin/env bash
  1084. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  1085. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  1086. // subdir=server
  1087. // git filter-branch --tree-filter '
  1088. // first='"$first"'
  1089. // last='"$last"'
  1090. // subdir='"$subdir"'
  1091. // log_file=/tmp/filter.log
  1092. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  1093. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  1094. // echo "=== $GIT_COMMIT: making changes"
  1095. // files=$(git ls-tree --name-only $GIT_COMMIT)
  1096. // mkdir -p $subdir
  1097. // for i in $files; do
  1098. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  1099. // done
  1100. // else
  1101. // echo "=== $GIT_COMMIT: ignoring"
  1102. // fi \
  1103. // >> $log_file
  1104. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  1105. // status=0 # tell tree-filter never to fail
  1106. // '
  1107. // git remote rm tempmergesource
  1108. // */
  1109. // // better alternative for history
  1110. // /**
  1111. // *
  1112. // git clone git@server.com:old-project.git
  1113. // git clone git@server.com:new-project.git
  1114. // cd old-project
  1115. // mkdir old-project
  1116. // git mv !(old-project) old-project
  1117. // ls -la and gt mv hidden files ....
  1118. // git commit -a -S -m “Moving old project into its own subdirectory”
  1119. // cd ../new-project
  1120. // git remote add old-project ../old-project
  1121. // git fetch old-project
  1122. // git checkout -b feature/merge-old-project
  1123. // git merge -S --allow-unrelated-histories old-project/master
  1124. // git push origin feature/merge-old-project
  1125. // git remote rm old-project
  1126. // */
  1127. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  1128. // }
  1129. , 'pull' : (label) => {
  1130. // Usage :
  1131. // elxr pull -- Defaults to run config
  1132. return elxr.getpulltask(selectedinstance)()
  1133. }
  1134. , 'isInstalled': () => {
  1135. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  1136. console.log(processedArgs._[1] + ' exists.')
  1137. return true;
  1138. });
  1139. }
  1140. , 'c' : ()=>{
  1141. }
  1142. , 'i' : () => {
  1143. var tasks = []
  1144. // tasks.push(op['pull']);
  1145. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1146. tasks.push(op['use'])
  1147. if (!__isElevated) {
  1148. tasks.push(op['npmi'])
  1149. }
  1150. // var tasksdefs = [
  1151. // ['elxr', ['pull']]
  1152. // , ['elxr', ['use', 'elixir']]
  1153. // , ['elxr', ['npmi']]
  1154. // ]
  1155. // tasksdefs.forEach(tasksdef=>{
  1156. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1157. // })
  1158. return any(tasks);
  1159. }
  1160. , 'npmi': () => {
  1161. var tasks = [];
  1162. // Build fails without babel...
  1163. tasks.push(getShellTask(
  1164. 'npm',[ 'i', '-g', 'babel-cli' ]
  1165. ) )
  1166. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1167. // npmbuildrepos = []
  1168. npmbuildrepos.forEach(repo => {
  1169. tasks.push(() => {
  1170. return nodeShellExec('npm', ['i --force'], {
  1171. inherit: true, shell: true
  1172. , cwd: instanceroot + '/' + repo
  1173. , env: process.env
  1174. , title: `npm i for ${repo}`
  1175. }).catch((e) => {
  1176. console.error('Ignoring Benign Error'); console.error(e);
  1177. }).then(() => {
  1178. console.log(`--npm run build for ${repo}--------------------`)
  1179. return nodeShellExec('npm', ['run build'], {
  1180. inherit: true, shell: true
  1181. , cwd: instanceroot + '/' + repo
  1182. , env: process.env
  1183. , title: `npm run build for ${repo}`
  1184. }).then(Tasq.then).catch(Tasq.catch)
  1185. })
  1186. })
  1187. })
  1188. return any(tasks).then(() => {
  1189. gitRepos.push('chess-server-lib/server');
  1190. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1191. // gitRepos = [
  1192. // // 'bbhverse', 'serververse', 'elixir-server',
  1193. // // 'clientverse',
  1194. // 'client'
  1195. // ];
  1196. var rmtasks = []
  1197. var repotasks = []
  1198. var env = Object.assign({}, process.env)
  1199. delete env.NODE_ENV
  1200. gitRepos.forEach(repodef => {
  1201. rmtasks.push(
  1202. // () => {
  1203. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1204. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1205. callshelltask(['rm', ['package-lock.json'], {
  1206. inherit: true, shell: true
  1207. , cwd: instanceroot + '/' + repodef.repo
  1208. , env: process.env
  1209. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1210. }])
  1211. .then(()=>{
  1212. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1213. }).catch((e) => { console.error(e) })
  1214. // }
  1215. )
  1216. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1217. repotasks.push(
  1218. () => {
  1219. console.log(`--npm i for ${repodef.repo}--------------------`)
  1220. var p = nodeShellExec('npm', ['i', '--force'], {
  1221. inherit: true, shell: true
  1222. , cwd: instanceroot + '/' + repodef.repo
  1223. , env
  1224. , title: `npm i for ${repodef.repo}`
  1225. }).then(Tasq.then).catch(Tasq.catch)
  1226. return p;
  1227. })
  1228. }
  1229. })
  1230. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1231. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1232. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1233. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1234. // Second time try also doesnt work.
  1235. // repotasks.push(
  1236. // () => {
  1237. // var env = Object.assign({}, process.env)
  1238. // delete env.NODE_ENV
  1239. // console.log(`--------------------second time npm i for client--------------------`)
  1240. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1241. // // return nodeShellExec('npm', ['i --force'], {
  1242. // inherit: true, shell: true
  1243. // , cwd: instanceroot + '/' + 'client'
  1244. // , env
  1245. // , title: `npm i for client`
  1246. // }).then(Tasq.then).catch(Tasq.catch)
  1247. // })
  1248. var bowerRepos = [{ repo : 'client'}]
  1249. bowerRepos.forEach(repodef => {
  1250. repotasks.push(() => {
  1251. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1252. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1253. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1254. inherit: true, shell: true
  1255. , cwd: instanceroot + '/' + repodef.repo
  1256. , env: process.env
  1257. , title: `bower i for ${repodef.repo}`
  1258. }).then(Tasq.then).catch(Tasq.catch)
  1259. return p;
  1260. })
  1261. })
  1262. // console.log('rmtasks.length : ' + rmtasks.length)
  1263. return Promise.all(rmtasks).then(() => any(repotasks));
  1264. }).catch(e => {
  1265. console.error(e)
  1266. }).finally(statuslog.finally)
  1267. }
  1268. , 'start': (label) => {
  1269. console.log('Starting Elixir Server.');
  1270. var env = Object.assign({}, process.env); // Shallow clone it.
  1271. // console.dir(env)
  1272. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1273. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1274. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1275. // cmd = 'node'
  1276. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1277. var childPromise = nodeShellExec(...cmd, {
  1278. // inherit : true,
  1279. shell: true,
  1280. detached: true,
  1281. stdio: 'ignore',
  1282. cwd: instanceroot + '/' + 'elixir-server'
  1283. , env: env
  1284. })
  1285. var child = childPromise.process;
  1286. if (typeof child.pid !== 'undefined') {
  1287. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1288. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1289. encoding: 'utf8'
  1290. })
  1291. }
  1292. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1293. // inherit : true,
  1294. // shell: true, detached: true,
  1295. // cwd : 'qms/server',
  1296. // env: env,
  1297. // shell : true
  1298. // })
  1299. // nodeShellExec('ember', ['s'], {
  1300. // // inherit : true,
  1301. // shell: true, detached: true,
  1302. // cwd : 'client/',
  1303. // env: env
  1304. // })
  1305. console.log('Starting Elixir Client Host.');
  1306. var cmd = ['ember', ['s']]
  1307. var childPromise = nodeShellExec(...cmd, {
  1308. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1309. // PB : TODO -- ember debugging.
  1310. // inherit : true,
  1311. shell: true,
  1312. detached: true,
  1313. stdio: 'ignore',
  1314. cwd: instanceroot + '/' + 'client'
  1315. , env: env
  1316. })
  1317. // .catch(e=>console.error(e))
  1318. child = childPromise.process;
  1319. if (typeof child.pid !== 'undefined') {
  1320. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1321. fs.writeFileSync('.client.server.pid', child.pid, {
  1322. encoding: 'utf8'
  1323. })
  1324. }
  1325. }
  1326. , 'stop': (label) => {
  1327. const kill = require('tree-kill');
  1328. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1329. encoding: 'utf8'
  1330. })
  1331. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1332. console.log(serverPid)
  1333. kill(serverPid)
  1334. serverPid = fs.readFileSync('.client.server.pid', {
  1335. encoding: 'utf8'
  1336. })
  1337. fs.unlinkSync('.client.server.pid')
  1338. console.log(serverPid)
  1339. kill(serverPid)
  1340. }
  1341. , 'model' : () => {
  1342. if (__isElevated) {
  1343. var tasks = [
  1344. () => {
  1345. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1346. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1347. inherit: true, shell: true
  1348. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1349. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1350. , env: process.env
  1351. }).catch((e) => { console.error(e) })
  1352. return p;
  1353. }
  1354. ];
  1355. return any(tasks).then(() => {
  1356. fs.writeFileSync('run.done', 'success')
  1357. }).catch(() => {
  1358. fs.writeFileSync('run.done', 'error')
  1359. })
  1360. }
  1361. else return op['runas']()
  1362. }
  1363. , 'use' : () => {
  1364. // use a certain named instance.
  1365. // Eg :
  1366. // 1) elxr use elixir
  1367. // 2) elxr use cihsr
  1368. // If environment is not specified defaults to development.
  1369. // 1) NODE=test elxr use elixir
  1370. /*// Steps
  1371. 1) Delete Config and Data symlinks
  1372. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1373. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1374. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1375. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1376. */
  1377. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1378. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1379. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1380. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1381. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1382. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1383. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1384. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1385. if (existsSync('config') && existsSync('data')){
  1386. return
  1387. }
  1388. }
  1389. var tasks = [
  1390. () => {
  1391. if (existsSync('config')) {
  1392. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1393. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1394. return p;
  1395. }
  1396. else return Promise.resolve(true);
  1397. },
  1398. () => {
  1399. if (existsSync('data')) {
  1400. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1401. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1402. return p;
  1403. }
  1404. else return Promise.resolve(true);
  1405. },
  1406. ];
  1407. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1408. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1409. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1410. // console.log(process.env.cwd)
  1411. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1412. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1413. var checkoutMap = { 'development': 'master' }
  1414. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1415. var performPullOrCloneForBranch = (def)=>{
  1416. var promise = Promise.resolve(true)
  1417. if (!branch) {
  1418. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1419. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1420. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1421. }
  1422. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1423. }
  1424. var performCloneAndCheckout = null;
  1425. // cant use git checkout -b it fails when branch already exists.
  1426. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1427. return performPullOrCloneForBranch(def).then(()=>{
  1428. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1429. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1430. // inherit : true, shell: true,
  1431. cwd: instanceroot + '/' + def.repo
  1432. // , stdio : ignore // Use when we want to silence output completely.
  1433. , runas: processedArgs.runas
  1434. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1435. }).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 } })
  1436. })
  1437. }
  1438. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1439. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1440. var elevatedqueue = [];
  1441. var enqueueOnce = (queue, task, def) => {
  1442. var found = queue.find(element => {
  1443. var keys = Object.keys( element )
  1444. for(var k=0; k < keys.length; k++) {
  1445. if(element[keys[k]] !== def[k]) return false;
  1446. }
  1447. })
  1448. queue.push(function(){ return task(this)}.bind(def));
  1449. }
  1450. var enqueue = (queue, task, def) => {
  1451. queue.push(function(){ return task(def)}.bind(def));
  1452. }
  1453. var mergeSources = {
  1454. 'development': null,
  1455. 'test': 'master',
  1456. 'production': 'master'
  1457. }
  1458. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1459. // Checkout is reduced to pull provided the current branch is the targetbranch
  1460. if(branch === mergesource) performCheckout = (def) => {
  1461. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1462. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1463. if(branch === __branch) return performCloneAndCheckout(def)
  1464. return performPullOrCloneForBranch(def)
  1465. })
  1466. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1467. }
  1468. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1469. var performPullAll = (def) => {
  1470. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1471. return nodeShellExec('git', ['pull', '--all'], {
  1472. // inherit : true, shell: true,
  1473. cwd: instanceroot + '/' + def.repo
  1474. , runas: processedArgs.runas
  1475. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1476. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1477. }
  1478. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1479. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1480. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1481. var performMerge = (def) => {
  1482. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1483. return nodeShellExec('git', ['merge', mergesource], {
  1484. inherit: true, shell: true,
  1485. cwd: instanceroot + '/' + def.repo
  1486. , runas: processedArgs.runas
  1487. }).catch((e) => { console.error(e) })
  1488. }
  1489. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1490. // var performRepoOperation = function(def) {
  1491. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1492. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1493. // }
  1494. return any(tasks).then(() => {
  1495. var pr = Promise.resolve(true)
  1496. if (!__isElevated) {
  1497. pr = op['runas']()
  1498. return pr.then(()=>{
  1499. //target is the env is we specify in elxr use command. Default is dev
  1500. //Switch to target branch
  1501. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1502. // pull or clone target branch
  1503. .then(() => {
  1504. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1505. return any(gitRepos.map((repo) => performPullAll(repo)))
  1506. })
  1507. // switch to source branch
  1508. .then( () => {
  1509. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1510. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1511. })
  1512. //Pull on merge source branch
  1513. .then( () => {
  1514. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1515. return any(gitRepos.map((repo) => performPullAll(repo)))
  1516. })
  1517. //Switch to target branch
  1518. .then( () => {
  1519. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1520. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1521. })
  1522. .then( //Merge source branch to target branch
  1523. () => {
  1524. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1525. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1526. })
  1527. })
  1528. }
  1529. else {
  1530. tasks = [
  1531. () => {
  1532. // Use junctions to avoid npm package issues
  1533. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1534. inherit: true, shell: true
  1535. , cwd : instanceroot
  1536. , env: process.env
  1537. }).catch((e) => { console.error(e) })
  1538. return p;
  1539. }
  1540. ];
  1541. if (processedArgs._[1]) {
  1542. tasks = tasks.concat(
  1543. [
  1544. () => {
  1545. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1546. inherit: true, shell: true
  1547. , cwd : instanceroot
  1548. , env: process.env
  1549. }).catch((e) => { console.error(e) })
  1550. return p;
  1551. }
  1552. ]
  1553. )
  1554. }
  1555. return any(tasks).then(()=>{
  1556. // checkout target branch
  1557. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1558. // pull or clone target branch
  1559. .then(() => {
  1560. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1561. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1562. })
  1563. // switch to source branch
  1564. .then( () => {
  1565. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1566. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1567. })
  1568. //Pull on merge source branch
  1569. .then( () => {
  1570. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1571. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1572. })
  1573. //Switch to target branch
  1574. .then( () => {
  1575. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1576. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1577. })
  1578. .then( //Merge source branch to target branch
  1579. () => {
  1580. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1581. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1582. })
  1583. .then(() => {
  1584. fs.writeFileSync('run.done', 'success')
  1585. }).catch(() => {
  1586. fs.writeFileSync('run.done', 'error')
  1587. })
  1588. })
  1589. }
  1590. }).catch(() => {
  1591. fs.writeFileSync('run.done', 'error')
  1592. })
  1593. // Antibiotic stewardship program.
  1594. // 1st use is fine.
  1595. // Max vials dispense
  1596. // 2nd use Pharmacy needs justification Form.
  1597. // Approval after a certain period of time.
  1598. }
  1599. , 'g': () => {
  1600. if (processedArgs.h) {
  1601. console.log('elxr g [modelname] => generate a model named [modelname]');
  1602. console.log('elxr g => regenerate all known models');
  1603. return
  1604. }
  1605. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1606. // console.log('Starting directory: ' + process.cwd());
  1607. // try {
  1608. // child = child.on('close', () => { process.chdir(label) } );
  1609. // console.log('New directory: ' + process.cwd());
  1610. // }
  1611. // catch (err) {
  1612. // console.log('chdir: ' + err);
  1613. // }
  1614. // child.on('close', function(){
  1615. // var options = {
  1616. // shell : true
  1617. // , inherit : true
  1618. // // , cwd : '' + process.cwd
  1619. // // , env : process.env
  1620. // };
  1621. // nodeShellExec('git', ['init'], { inherit : true});
  1622. if (0) {
  1623. // PB : TODO -- Special google chrome profile for tests etc.
  1624. nodeShellExec('pwd', { inherit: true });
  1625. // /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"
  1626. // "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
  1627. // "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
  1628. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1629. "--profile-directory=Profile 1"
  1630. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1631. }
  1632. // nodeShellExec('npm', ['init', '-y'], options);
  1633. // nodeShellExec('npm', ['init', '-y'], options);
  1634. // })
  1635. var g = {
  1636. 'client': () => {
  1637. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1638. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1639. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1640. stdio: ['pipe', process.stdout, process.stderr],
  1641. inherit: true,
  1642. shell: true,
  1643. cwd: path.dirname(__dirname),
  1644. env: env
  1645. })
  1646. },
  1647. 'modelr': () => {
  1648. var tasks = [
  1649. () => {
  1650. var p = nodeShellExec('"ember"', [
  1651. 'g'
  1652. , 'modelr'
  1653. , processedArgs._[2]], {
  1654. inherit: true, shell: true, env: process.env
  1655. }).then(() => {
  1656. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1657. return true;
  1658. }).catch((e) => { console.error(e) })
  1659. return p;
  1660. },
  1661. () => {
  1662. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1663. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1664. chromeprefs = JSON.parse(chromeprefs)
  1665. var previous = chromeprefs.download.default_directory;
  1666. var parentDir = path.dirname(__dirname);
  1667. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1668. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1669. // PB : TODO -- detect where chrome is installed.
  1670. // PB : TODO -- set the download dir to the place where files are needed.
  1671. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1672. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1673. , '--profile-directory="chess"'
  1674. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1675. inherit: true, shell: true
  1676. , env: process.env
  1677. }).then(() => {
  1678. chromeprefs.download.default_directory = previous;
  1679. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1680. return true;
  1681. }).catch((e) => { console.error(e) })
  1682. return p;
  1683. }
  1684. ,
  1685. () => {
  1686. console.log('Browser process should have closed here....')
  1687. return true;
  1688. }
  1689. ]
  1690. any(tasks)
  1691. }
  1692. }
  1693. g[processedArgs._[1]]();
  1694. }
  1695. , 'create' : () => {
  1696. return createInstance(selectedinstance) }
  1697. , 'httpget' : () => {
  1698. // RESTAPI.get({
  1699. // hostname: 'git.bbh',
  1700. // // port: 443,
  1701. // protocol : 'http:',
  1702. // path: '/',
  1703. // method: 'GET'
  1704. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  1705. return createInstance(selectedinstance)
  1706. }
  1707. , 'getuser' : ()=>{
  1708. return prerequisites.git.getuser().then(u=>{ console.log(u)})
  1709. }
  1710. , 'switch user' : (tousername)=>{
  1711. return GIT['switch user'](tousername)
  1712. }
  1713. }
  1714. var util = require('util');
  1715. var cliname = 'elxr';
  1716. var ver = '1.1';
  1717. var readme = `
  1718. Command syntax examples
  1719. elxr
  1720. Displays help. Same as elxr h
  1721. elxr i
  1722. Runs interactive propmts to help choose installation options.
  1723. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1724. General command syntax.
  1725. Eg: NODE_ENV=development elxr pull elixir
  1726. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1727. The specific cmd defines what the value is interpreted as.
  1728. There are several cmds that do not require an {{instancename}} parameter.
  1729. Eg: elxr remote remove origin
  1730. Git operations or passthrough external commands on all repository folders in you working directory.
  1731. Main objectives.
  1732. elxr cli is a wrapper around other shell commands and api based operations.
  1733. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1734. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1735. `;
  1736. var help = `
  1737. ${readme}
  1738. # list of commands... please refer dveloper documentation for ${cliname}
  1739. \r\n\t${
  1740. Object.keys(op).join('\r\n\t')
  1741. }
  1742. `;
  1743. var elxr = {
  1744. help() {
  1745. return chalk.cyanBright(`
  1746. -------------------------------------------------------------------------------
  1747. *** BBH Elixir ***
  1748. -------------------------------------------------------------------------------
  1749. elxr ${ver}
  1750. A cli tool for chess
  1751. ${help}
  1752. -------------------------------------------------------------------------------
  1753. `)
  1754. }
  1755. , info() {
  1756. return chalk.cyanBright(`
  1757. -------------------------------------------------------------------------------
  1758. *** BBH Elixir ***
  1759. -------------------------------------------------------------------------------
  1760. elxr ${ver}
  1761. A cli tool for chess
  1762. -------------------------------------------------------------------------------
  1763. `)
  1764. }
  1765. , getpulltask(args){
  1766. // def can be an instance config
  1767. // Or an object with many repos and elevated repos
  1768. // Or a single repo ( Either Elevated or normal. )
  1769. // USAGE
  1770. // elxr pull elixir origin master
  1771. // elxr pull
  1772. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  1773. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  1774. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  1775. // The branch pipline should feed back to master
  1776. // master -> test -> stage -> release[nnnn] -> production
  1777. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  1778. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  1779. var __args = {
  1780. remotename : args.remotename|| processedArgs._[2]
  1781. , url : args.url || processedArgs._[3]
  1782. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  1783. }
  1784. // var commands = [
  1785. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  1786. // ,
  1787. // ]
  1788. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1789. // var pullCmd = [ gitbash
  1790. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1791. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  1792. var def = args || {
  1793. repos : selectedinstance.repos,
  1794. elevated : selectedinstance.elevated
  1795. }
  1796. var elevatedpulltasks = null;
  1797. if(def.repo) {
  1798. // Single repo case.
  1799. if(def.repo.requiresElevation) {
  1800. elevatedpulltasks = function() {
  1801. return performPull(def.repo).then(() => {
  1802. return true;
  1803. }).catch((e) => {
  1804. console.error(e)
  1805. })
  1806. }
  1807. return
  1808. }
  1809. else {
  1810. var regularpulltasks = function(){
  1811. var pendingpulls = [];
  1812. pendingpulls.push(performPull(def.repo))
  1813. return Promise.all(pendingpulls).finally(Traq.finally)
  1814. }
  1815. }
  1816. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1817. else return getTaskWithoutElevation({ regularpulltasks})
  1818. }
  1819. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1820. console.dir(def)
  1821. var env = Object.assign({}, process.env); // Shallow clone it.
  1822. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1823. var useGitPull = processedArgs.useGitPull || false;
  1824. if(def.elevated || def.repos) {
  1825. if(def.elevated) def.requiresElevation = true;
  1826. else delete def.requiresElevation;
  1827. }
  1828. else {
  1829. if(def.requiresElevation) def.elevated = [def]
  1830. else def.repos = [def]
  1831. }
  1832. var regularpulltasks = function(){ return Promise.resolve(true) }
  1833. if(def.elevated){
  1834. elevatedpulltasks = function() {
  1835. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1836. return true;
  1837. }).catch((e) => {
  1838. console.error(e)
  1839. })
  1840. }
  1841. }
  1842. if(def.repos) {
  1843. var regularpulltasks = function(){
  1844. var pendingpulls = [];
  1845. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1846. return Promise.all(pendingpulls).finally(Traq.finally)
  1847. }
  1848. }
  1849. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1850. else return getTaskWithoutElevation({ regularpulltasks})
  1851. }
  1852. }
  1853. function preworkerconfig(){
  1854. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1855. gitRepos = selectedinstance.repos
  1856. // gitRepos = ['chess-server-lib'];
  1857. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1858. elevatedRunasRepos = selectedinstance.elevated
  1859. // Repos that should excluded from merge for releases...
  1860. exludeMergeRepos = selectedinstance.exludeMergeRepos
  1861. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1862. // mysql -u root -p db_name < drop_all_tables.sql
  1863. var mysql = '../xampp/mysql/bin/mysql'
  1864. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1865. }
  1866. // The main elxr cli process
  1867. function elxrworker() {
  1868. var __runcmd = function (label) {
  1869. var distinquishedlabel = subcommandlabels[label] || label
  1870. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1871. }
  1872. // --runas
  1873. if (processedArgs.runas) {
  1874. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1875. return __runcmd('runas')
  1876. }
  1877. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  1878. }
  1879. // function acquireChoices(selectedinstance) {
  1880. // var hasconfig = false;
  1881. // console.warn(chalk.cyan(`
  1882. // -------------------------------------------------------------------------------
  1883. // Could not locate your preferred configuration (you may not specified it)
  1884. // You should fork the default chess configuration to customize and make it
  1885. // your own instance with a named config as
  1886. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1887. // And then run this tool as follows
  1888. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1889. // OR
  1890. // Run this tool with the following command to use a quick start default.
  1891. // elxr --default
  1892. // OR
  1893. // Choose one of the options below to run interactively.
  1894. // We will run your choice at the next prompt.
  1895. // -------------------------------------------------------------------------------
  1896. // `))
  1897. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  1898. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  1899. // return initinstances(selectedinstance)
  1900. // })
  1901. // // var prompt = cli.prompter;
  1902. // // return prompt.ask(`Choose an option :
  1903. // // d) Install the default chess instance.
  1904. // // => elxr i chess node_env=development --default
  1905. // // n) Create your custom new instance interactively
  1906. // // => elxr i {{instanceName}} node_env={{environment}}
  1907. // // i) Choose an instance and environment to install
  1908. // // => elxr i {{instanceName}} node_env={{environment}}
  1909. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1910. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1911. // // h) Help
  1912. // // q) Quit
  1913. // // Default <= d
  1914. // // : `).then((choice) => {
  1915. // // if (choice && choice === 'd' || !choice) {
  1916. // // processedArgs._[0] = 'i'
  1917. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1918. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1919. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  1920. // // }
  1921. // // else if (choice === 'h') {
  1922. // // processedArgs._[0] = 'h'
  1923. // // fs.writeFileSync('run.done', 'noop help');
  1924. // // console.log(elxr.help()); process.exit()
  1925. // // }
  1926. // // else if (choice === 'n' || choice === 'i') {
  1927. // // var p1 = cli.prompter;
  1928. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1929. // // processedArgs._[0] = 'i'
  1930. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1931. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1932. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1933. // // if (choice === 'n') {
  1934. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  1935. // // console.warn(
  1936. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1937. // // process.exit();
  1938. // // }
  1939. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1940. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1941. // // })
  1942. // // })
  1943. // // })
  1944. // // } else if (choice === 'c') {
  1945. // // var p1 = cli.prompter;
  1946. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1947. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1948. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1949. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1950. // // return p1.ask(`Enter cmd :
  1951. // // p) pull
  1952. // // Default <= p
  1953. // // : `).then(function (cmd) {
  1954. // // if (!cmd || cmd === 'p') {
  1955. // // processedArgs._[0] = 'pull'
  1956. // // }
  1957. // // else processedArgs._[0] = cmd
  1958. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1959. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1960. // // })
  1961. // // })
  1962. // // })
  1963. // // })
  1964. // // } else {
  1965. // // 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.`));
  1966. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1967. // // fs.writeFileSync('run.done', 'noop quit');
  1968. // // process.exit()
  1969. // // }
  1970. // // })
  1971. // }
  1972. var mergeObjByKey = function(arrOfObjs, keyName) {
  1973. var keyedDistinct = {}
  1974. var distinctArrOfObjs = []
  1975. arrOfObjs.forEach( o => {
  1976. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1977. })
  1978. Object.keys(keyedDistinct).forEach(key => {
  1979. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1980. })
  1981. return distinctArrOfObjs;
  1982. }
  1983. var cacheWriteInstanceConfig = function(chessinstances){
  1984. var instanceName = chessinstances['current_run'].instanceName;
  1985. var node_env = chessinstances['current_run'].node_env;
  1986. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1987. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1988. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1989. }
  1990. var configs = (function(){
  1991. return {
  1992. clusterNodeInstance(selected) { var clusternodename = 'node01'
  1993. return __acquireConfig(selected, selected.username, clusternodename
  1994. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  1995. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  1996. return e; }
  1997. )
  1998. }
  1999. , ownerInstnace(selected) { return __acquireConfig(selected, selected.username, null, null
  2000. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2001. return e }
  2002. )
  2003. }
  2004. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2005. , commonInstance(selected) { return __acquireConfig(selected, defaultRepoOwner
  2006. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2007. ) }
  2008. , genericChessInstance(selected) { return __acquireConfig(selected) }
  2009. }
  2010. })()
  2011. var eNotImplemented = function(){
  2012. console.error('Not yet implemented')
  2013. process.exit()
  2014. }
  2015. var acquireConfig = function(slections){
  2016. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance', 'genericChessInstance' ]
  2017. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true)
  2018. }
  2019. var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) {
  2020. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2021. var errorHandler = (e) => {
  2022. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2023. // console.error('Could not connect to repo server. Timed Out')
  2024. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  2025. if(propValue === 'y') {
  2026. reconfirm = getReconfirmAll()
  2027. return startElxr()
  2028. }
  2029. else if(propValue === 'r'){
  2030. return acquireConfig(selected)
  2031. }
  2032. else process.exit()
  2033. })
  2034. }
  2035. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  2036. var choices = {
  2037. t : `install a new temporary local instance with this name ( will not persist ).
  2038. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2039. , e : 'exit' }
  2040. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2041. choices = utils.assign({
  2042. i : 'create a new instance with this name => will fork the default config under your username'
  2043. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2044. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2045. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2046. , p : 'create a custom config for yourself '
  2047. }, choices)
  2048. }
  2049. return cli.prompt( choices
  2050. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2051. if(propValue === 't') return createInstance()
  2052. if(propValue === 'i') return eNotImplemented()
  2053. if(propValue === 'f') return eNotImplemented()
  2054. if(propValue === 'o') return eNotImplemented()
  2055. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2056. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2057. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2058. else process.exit()
  2059. })
  2060. }
  2061. console.warn(e)
  2062. throw e; //('Config acquisition failed.')
  2063. }
  2064. var successHandler = () => {
  2065. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2066. selectedinstance = require(manifestpath)( null, selectedinstance)
  2067. // Config from server always override merges into selection except for the current selection.
  2068. // PB : TODO -- utils.assign Array merges are non-distinct...
  2069. if(!selectedinstance.repos[0].repo) {
  2070. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2071. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2072. }
  2073. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2074. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2075. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2076. }
  2077. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  2078. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2079. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2080. cacheWriteInstanceConfig(chessinstances)
  2081. ENV.NODE_ENV = selectedinstance.node_env;
  2082. }
  2083. return performPull(configrepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2084. .catch( (e)=>{
  2085. // if(e){
  2086. if(Promise.resolve(e) === e) return e;
  2087. console.error(e)
  2088. throw e; // Not a hard error but we need this for bcontinueonfailure
  2089. // }
  2090. })
  2091. }
  2092. var launchpath = path.normalize(process.cwd())
  2093. var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  2094. // The easisest would be to ask for a target directory and default to current dir....
  2095. var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  2096. // PB : TODO -- Embed this in the build instead of inlining it.
  2097. // Also attepmt to load from ../chess-config/...
  2098. var __default = ((name, options)=>{
  2099. // Default set of users in main repos.
  2100. var users = [
  2101. { username : `${options.username}`, password : `${options.password}` }
  2102. , { username : `chess` }
  2103. // , { username : `baptistdev`, password : 'encrypted' }
  2104. // , { username : `guest`, password : 'encrypted' }
  2105. ]
  2106. // ${options.reposerver} should be used to lookup current config.
  2107. // User can always add more branches and remotes as needed. Mainifest only occupies
  2108. // well defined namespaces
  2109. var remotes = {
  2110. // these are both fetch and push remotes. Use push - remotes to override push.
  2111. 'chess' : { path : `/chess/`, push : 'no-pushing' }
  2112. // Multiple urls dont tell us the current origin which may be
  2113. // different based on currently available/accessible based on device and client.
  2114. // We just treat them as different remotes and merge as needed.
  2115. //
  2116. , 'origin' : { path : `/${options.username}/` }
  2117. , 'origin-public' : { path : `/${options.username}/` }
  2118. , 'origin-unc' : { path : `/${options.username}/` }
  2119. // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
  2120. }
  2121. // , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
  2122. // We therefore need to use
  2123. // - a pullall
  2124. // - or branch alias for multiple remote branch tracking branch strategy.
  2125. // -- This is however limited to corresponding branch names
  2126. // tracking branches.
  2127. // We at least need one branch for each remote that we wish to track.
  2128. // , 'tracking-branches' : [
  2129. // { master : ['origin/master', 'chess/master'] }
  2130. // ]
  2131. var reposerverinstances = {
  2132. 'http://git.bbh' : { users, remotes }
  2133. , 'https://git.bbh.org.in' : { users, remotes, external : true }
  2134. , '//172.16.0.27/repos' : { users, remotes }
  2135. , 'https://github.com' : {
  2136. // We host a miniaml set of repositories in github.
  2137. get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
  2138. , remotes : { get 'baptistdev-public'() { return {path : `/${this.username}/`, push : 'no-pushing'} }
  2139. // , Add other remotes here.
  2140. }
  2141. , external : true, public : true
  2142. }
  2143. }
  2144. return {
  2145. reposervers : Object.keys(reposerverinstances)
  2146. , reposerverinstances
  2147. // Common baseline repos for all chess instances.
  2148. , repos : [
  2149. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  2150. , { repo : 'bbhverse' }
  2151. , { repo : 'clientverse' }
  2152. , { repo : 'serververse' }
  2153. , { repo : 'elxr' }
  2154. , { repo : 'ember-searchable-select' }
  2155. , { repo : 'loopback-component-jsonapi' }
  2156. , { repo : 'loopback-jsonapi-model-serializer' }
  2157. , { repo : 'loopback-connector-mysql' }
  2158. , { repo : 'loopback-connector-ds' }
  2159. , { repo : 'chess-server-lib' }
  2160. , { repo : 'ember-service-worker' }
  2161. , { repo : 'ember-service-worker-asset-cache' }
  2162. , { repo : 'ember-service-worker-cache-fallback' }
  2163. , { repo : 'ember-service-worker-index' }
  2164. , { repo : 'ember-sw-client-route' }
  2165. , { repo : 'global-this' }
  2166. ]
  2167. // PB : TODO -- lighter defaults for lite new instance creation..
  2168. , repos: [
  2169. { repo : 'setup' }
  2170. , { repo : 'elxr' }
  2171. , { repo : 'loopback-connector-mysql' }
  2172. , { repo : 'loopback-jsonapi-model-serializer' }
  2173. , { repo : 'loopback-component-jsonapi' }
  2174. , { repo : 'ember-service-worker' }
  2175. , { repo : 'ember-service-worker-asset-cache' }
  2176. , { repo : 'ember-service-worker-cache-fallback' }
  2177. , { repo : 'ember-service-worker-index' }
  2178. , { repo : 'ember-sw-client-route' }
  2179. ]
  2180. , elevated : [ ]
  2181. , exludeMergeRepos : { }
  2182. }
  2183. })(
  2184. '__default' // name
  2185. , { username : 'guest', instanceName : 'chess', node_env : 'development', reposerver : 'https://git.bbh.org.in' } // options
  2186. )
  2187. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2188. // Then acquire and reload and replace this default.
  2189. var hasElxr = function(path, options, cb) {
  2190. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  2191. options = options || {};
  2192. var tasks = [
  2193. '/elxr' // Is there a subfolder named elxr
  2194. , '/elxr/.git' // which is self git repository
  2195. , '/elxr/.elxr' // and has .elxr subfolder
  2196. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  2197. ]
  2198. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  2199. var value = existsFolderSync(path + tpath);
  2200. return { value, done : acc && !value };
  2201. }).value }
  2202. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  2203. var value = existsFolderSync(path + tpath);
  2204. return { value, done : acc && !value };
  2205. }).value );
  2206. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  2207. var value = existsFolderSync(path + tpath);
  2208. return { value, done : acc && !value };
  2209. }).value);
  2210. }
  2211. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  2212. var detectfromroot = function(root){
  2213. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  2214. }
  2215. var detectLocalInstances = function () {
  2216. console.log(`launchpath = ${launchpath}`)
  2217. console.log(`thisscriptdir = ${thisscriptdir}`)
  2218. // PB : TODO -- !Postpone this.
  2219. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  2220. // Note : Paths should already be normalized fefore this.
  2221. var root = instanceroot;
  2222. var detected = { root };
  2223. var instanceoptions = [clioverrides]
  2224. return hasElxr(launchpath).then( (elxrCliExists) => {
  2225. // We need a reference to the root director for elxr cli to be properly oriented.
  2226. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  2227. // We were run from the proper root with elxr cli in the subfolder.
  2228. instanceroot = root = launchpath;
  2229. instanceoptions.splice( 0, 0, detected = { root })
  2230. instanceoptions.splice( 0, 0, detectfromroot(root))
  2231. }
  2232. else {
  2233. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  2234. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  2235. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  2236. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  2237. instanceroot = root = launchpath;
  2238. instanceoptions.splice( 0, 0, detected = { root })
  2239. instanceoptions.splice( 0, 0, detectfromroot(root))
  2240. }
  2241. else if (launchpath === thisscriptdir) {
  2242. var parentHasElxr = hasElxrSync(launchpath + '/..')
  2243. // PB : TODO -- verify if we have .elxr folder in the parent...
  2244. if(!parentHasElxr) {
  2245. // ! thisscriptdir is not elxr.
  2246. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  2247. }
  2248. // Same directory doesn't mean we are being run from elxr sub directory.
  2249. // In standalone build script we may or not be in the same location.
  2250. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  2251. // Unbuilt therefore we are in the elxr sub directory.
  2252. instanceroot = root = path.normalize(launchpath + '/..');
  2253. instanceoptions.splice( 0, 0, detected = { root });
  2254. instanceoptions.splice( 0, 0, detectfromroot(root));
  2255. }
  2256. else {
  2257. // Built version.
  2258. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  2259. if(parentHasElxr) {
  2260. // Built version was run from the full elxr subfolder. Should work
  2261. // PB : TODO -- but we should switch to the full version...
  2262. instanceroot = root = path.normalize(launchpath + '/..');
  2263. instanceoptions.splice( 0, 0, detected = { root })
  2264. instanceoptions.splice( 0, 0, detectfromroot(root))
  2265. }
  2266. else {
  2267. instanceroot = root = launchpath;
  2268. instanceoptions.splice( 0, 0, detected = { root })
  2269. instanceoptions.splice( 0, 0, detectfromroot(root))
  2270. // Assume current launchpath is a new instance and create.
  2271. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  2272. // if(clioverrides.instanceName) {
  2273. // if(clioverrides.node_env) {
  2274. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  2275. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  2276. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  2277. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  2278. // // eg : floder name can be elixir01 but instance name is elixr
  2279. // }
  2280. // else {
  2281. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  2282. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  2283. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  2284. // }
  2285. // }
  2286. // else {
  2287. // instanceroot = root = launchpath;
  2288. // if(clioverrides.node_env) {
  2289. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  2290. // instanceoptions.splice( 0, 0, detectfromroot(root))
  2291. // }
  2292. // else {
  2293. // // Nothing was specified... We only have one option from root.
  2294. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  2295. // }
  2296. // }
  2297. }
  2298. }
  2299. }
  2300. else {
  2301. if(elxrCliExists) {
  2302. instanceroot = root = launchpath;
  2303. instanceoptions.splice( 0, 0, detected = { root })
  2304. instanceoptions.splice( 0, 0, detectfromroot(root))
  2305. }
  2306. }
  2307. }
  2308. instanceroot = detected.root
  2309. __default.root = root;
  2310. clioverrides.root = clioverrides.root || root;
  2311. // Resolves empty array when No known instances detected.
  2312. return Promise.resolve(instanceoptions)
  2313. })
  2314. }
  2315. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  2316. if(clioverrides.reconfirm) {
  2317. var reconfirm = getReconfirmAll()
  2318. }
  2319. else { var reconfirm = {}; }
  2320. var shouldPrompt = function(k, possiblePrompts, target){
  2321. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  2322. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  2323. || reconfirm[k])
  2324. }
  2325. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  2326. return function(prompts, k, i, a){
  2327. // No local instances config found. We use a default initialized instance available in selectedinstance
  2328. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2329. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2330. if( shouldPrompt(k, possiblePrompts, target) ) {
  2331. delete reconfirm[k];
  2332. // console.log(k)
  2333. // console.dir(possiblePrompts); //console.dir(target)
  2334. prompts.push(async ()=>{
  2335. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2336. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2337. // If latest altered state is required we can reerence this directly.
  2338. // var asyncthis = Object.assign(this);
  2339. promptables[k].choices = choices[k]
  2340. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2341. return await target[k]
  2342. })
  2343. }
  2344. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  2345. return prompts
  2346. }
  2347. }
  2348. var __interactive_prompts = function( target, choices, promptsfilter ){
  2349. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2350. var interactionpoints = {
  2351. runchoice : {
  2352. label :
  2353. `Choose an option :
  2354. d) Install the default chess instance.
  2355. => elxr i chess node_env=development --default
  2356. n) Create your custom new instance interactively
  2357. => elxr i {{instanceName}} node_env={{environment}}
  2358. i) Choose an instance and environment to install
  2359. => elxr i {{instanceName}} node_env={{environment}}
  2360. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2361. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2362. h) Help
  2363. q) Quit
  2364. : `
  2365. , choices : []
  2366. , defaultchoice : 'c'
  2367. , interpret : function(choice){
  2368. var interpret_map = {
  2369. d : function(){
  2370. processedArgs._[0] = 'i'
  2371. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2372. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2373. target.reposerver = 'https://git.bbh.org.in'
  2374. }
  2375. , n : function() { processedArgs._[0] = 'i' }
  2376. , i : function() { processedArgs._[0] = 'i' }
  2377. , c : async function() {
  2378. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2379. label : `Enter cmd :
  2380. p) pull
  2381. Default <= p
  2382. : `
  2383. , defaultchoice : 'pull'
  2384. }
  2385. ));
  2386. var cmd = await target['cmd'];
  2387. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2388. else target['cmd'] = processedArgs._[0] = cmd
  2389. return cmd;
  2390. }
  2391. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2392. , q : function() { process.exit() }
  2393. }
  2394. var __interpreter = interpret_map['c']
  2395. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2396. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2397. return __interpreter.call(target)
  2398. }
  2399. }
  2400. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  2401. , choices : choices['instanceName'], defaultchoice : 'chess'}
  2402. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  2403. , choices : choices['instanceType'], defaultchoice : 'development'}
  2404. , reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  2405. , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'}
  2406. , username : { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  2407. , choices : choices['username'], defaultchoice : 'chess'}
  2408. , password : { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  2409. , choices : choices['password'], defaultchoice : '***'}
  2410. , email : { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  2411. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in'}
  2412. }
  2413. function getPromptKeys() {
  2414. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  2415. return promptkeys
  2416. }
  2417. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  2418. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  2419. }
  2420. var downloadsdir = '../Downloads';
  2421. var prerequisites = [
  2422. {
  2423. shellcmd: 'git',
  2424. name : 'git',
  2425. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2426. , installer: 'Git-2.31.0-64-bit.exe'
  2427. , installcmd: ['cmd', ['/c', 'start',
  2428. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2429. , '/VERYSILENT'
  2430. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2431. ]]
  2432. , preinstallsteps: function() {
  2433. var steps = [
  2434. () => {
  2435. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2436. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2437. }
  2438. else return Promise.resolve(true)
  2439. }
  2440. ]
  2441. var prompts = this.getuser(null, ()=>{
  2442. // console.log('preinstallsteps')
  2443. // var gitUser = 'guest';
  2444. // var gitEmail = 'guest@bbh.org.in';
  2445. // var prompts = [];
  2446. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  2447. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  2448. // console.log('prompting in preinstallsteps')
  2449. // return any(prompts).then(()=>{
  2450. // var steps = [
  2451. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2452. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2453. // ]
  2454. // return any(steps.map(getshelltask)).then(() => {
  2455. // })
  2456. // });
  2457. return Promise.resolve(true)
  2458. })
  2459. return any([any(steps), prompts])
  2460. }
  2461. , installsteps: function () {
  2462. return any([this.installcmd].map(getshelltask))
  2463. }
  2464. , postinstallsteps: function(err, users){
  2465. return this.getuser(null, (err, data)=>{
  2466. // ignore err and proceed with data as guest.
  2467. console.dir(data)
  2468. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  2469. return username = data[0];
  2470. }
  2471. data = data || ['guest']
  2472. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2473. console.log('prompting in postinstallsteps')
  2474. var username = 'guest';
  2475. var email = 'guest@bbh.org.in';
  2476. var password = '***';
  2477. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  2478. if(!data.find(e => e === selectedinstance.username)) {
  2479. var steps = [
  2480. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  2481. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  2482. ]
  2483. return any(steps.map(getshelltask)).then(() => {
  2484. })
  2485. }
  2486. else {
  2487. return Promise.resolve(true)
  2488. }
  2489. });
  2490. })
  2491. }
  2492. , install: function () {
  2493. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2494. }
  2495. , verifyAndInstall : function(){
  2496. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2497. if(exists) {
  2498. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2499. return this.postinstallsteps.bind(this)()
  2500. }
  2501. return this.install();
  2502. });
  2503. }
  2504. , getuser : function(repo, onResult){
  2505. var __onResult = onResult || function(e, data){
  2506. data = data || []
  2507. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2508. // console.dir(choices)
  2509. return data[0]
  2510. }
  2511. var globalOrLocal = '--global';
  2512. if(repo) globalOrLocal = '--local'
  2513. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  2514. // not yet configured.
  2515. if(!result.success) return __onResult(result)
  2516. else {
  2517. var users = result.messages[0].trim().split('\n');
  2518. if(users.length === 0 ||
  2519. users.length === 1 && users[0] === 'guest') {
  2520. return __onResult(result)
  2521. }
  2522. else {
  2523. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  2524. }
  2525. })
  2526. .catch((e)=>{
  2527. console.log(e)
  2528. return __onResult(e)
  2529. })
  2530. }
  2531. }
  2532. ,
  2533. {
  2534. shellcmd: 'node',
  2535. name : 'ndoe',
  2536. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  2537. , installer: 'node-v14.16.0-x64.msi'
  2538. , installcmd: ['MSIEXEC.exe', ['/i'
  2539. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  2540. , 'ACCEPT=YES', '/passive']]
  2541. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  2542. }
  2543. ]
  2544. for(var i=0; i<prerequisites.length; i++) {
  2545. prerequisites[prerequisites[i].name] = prerequisites[i];
  2546. }
  2547. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  2548. function ensureDirectoryExistence(filePath) {
  2549. var dirname = path.dirname(filePath);
  2550. if (fs.existsSync(dirname)) {
  2551. return filePath;
  2552. }
  2553. ensureDirectoryExistence(dirname);
  2554. fs.mkdirSync(dirname);
  2555. return filePath;
  2556. }
  2557. var mainTasks = [];
  2558. function verifyAndInstallPrerequisites() {
  2559. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  2560. // PB : TODO include and build from files... using rollup..
  2561. var downloadbatch =
  2562. `::**************************************************************************
  2563. :Download_ <url> <File>
  2564. Powershell.exe ^
  2565. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2566. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2567. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2568. exit /b
  2569. ::**************************************************************************`
  2570. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  2571. var windowselevate =
  2572. `
  2573. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2574. <script language="vbscript">
  2575. document.title = "elxr control panel"
  2576. self.ResizeTo 200,600
  2577. Sub Window_Onload
  2578. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2579. End Sub
  2580. Set objShell = CreateObject("WScript.Shell")
  2581. Set objENV = objShell.Environment("Process")
  2582. dim NODE_ENV
  2583. NODE_ENV = objENV("NODE_ENV")
  2584. </script>
  2585. <script language="javascript">
  2586. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2587. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2588. // alert(windowselevate.commandLine)
  2589. var args = windowselevate.commandLine.split('"').slice(3);
  2590. // alert(args)
  2591. var processedArgs = { _ : [] }
  2592. var namedArgs = [];
  2593. for(var item in args){
  2594. if(args[item].charAt(0) === '-'){
  2595. namedArgs.push(args[item])
  2596. var split = args[item].split('=');
  2597. processedArgs[split[0].slice(2)] = split[1] || true;
  2598. }
  2599. else processedArgs._.push(args[item]);
  2600. }
  2601. // args = args.forEach(function(item){ })
  2602. // alert('processedArgs._ : ' + processedArgs._);
  2603. // alert(processedArgs.runas);
  2604. // PB : TODO -- Convert all the cli args back to string.
  2605. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2606. // alert(cargs)
  2607. var shell = new ActiveXObject('shell.application');
  2608. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2609. // shell.ShellExecute('where', 'node', '', '', 10);
  2610. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2611. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2612. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2613. window.onload = function() {
  2614. document.body.style.backgroundColor = 'black';
  2615. document.body.style.fontFamily = 'arial';
  2616. var log = document.createElement('div');
  2617. log.innerHTML='Please Wait';
  2618. function l(msg){ log.innerHTML+= msg; };
  2619. log.style.color = 'blue';
  2620. log.style.width = '95%';
  2621. log.id = 'log';
  2622. document.body.appendChild(log);
  2623. l('<Br/>Current config : ')
  2624. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2625. l('<Br/>cmd = ' + processedArgs._[0])
  2626. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2627. l('<Br/><Br/>')
  2628. var timer = function(){
  2629. l('.');
  2630. if(fso.FileExists("run.done")) close();
  2631. else window.setTimeout(timer, 1000);
  2632. };
  2633. window.setTimeout(timer, 3000);
  2634. };
  2635. </script>
  2636. </html>
  2637. `
  2638. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2639. var downloadtasks = [];
  2640. var installtasks = [];
  2641. prerequisites.forEach(preq => {
  2642. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2643. if (exists) console.log(`${preq.shellcmd} exists`)
  2644. else {
  2645. console.log(`${preq.shellcmd} is not installed`)
  2646. return preq.preinstallsteps.call(preq).then(() => {
  2647. installtasks.push(preq.install.bind(preq))
  2648. })
  2649. }
  2650. }))
  2651. })
  2652. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2653. }
  2654. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  2655. return {
  2656. get (){
  2657. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  2658. var asyncprop = Promise.resolve(propValue)
  2659. if(promptable.interpret){
  2660. asyncprop = promptable.interpret(propValue)
  2661. }
  2662. return asyncprop.then(
  2663. ()=>{
  2664. Object.defineProperty(this, propName, {
  2665. value: propValue,
  2666. writable: true,
  2667. configurable : true,
  2668. enumerable : true
  2669. });
  2670. return propValue
  2671. }
  2672. )
  2673. })
  2674. }
  2675. // , set (propValue){
  2676. // Object.defineProperty(this, propName, {
  2677. // value: propValue,
  2678. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  2679. // configurable : true,
  2680. // enumerable : true
  2681. // })
  2682. // return propValue;
  2683. // }
  2684. , configurable : true
  2685. , enumerable : true
  2686. }
  2687. }
  2688. function acquirelocalinstances(selected){
  2689. // utils.assign is used to cleanup duplicates...
  2690. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2691. return chessinstances
  2692. }
  2693. function findlocalinstances(chessinstances, instanceoptions){
  2694. // We can expect a .elxr at each level.
  2695. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  2696. earlyreduce( ( value, p, i, a )=>{
  2697. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  2698. if(existsSync( localinstancesPath )) {
  2699. try {
  2700. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  2701. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  2702. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  2703. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  2704. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  2705. return {
  2706. value : chessinstances[instanceName][instanceType]
  2707. , done : true
  2708. };
  2709. }
  2710. })
  2711. })
  2712. }
  2713. catch(e){
  2714. return { }
  2715. }
  2716. }
  2717. else return { }
  2718. }
  2719. )
  2720. }
  2721. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2722. var selectedinstance = null;
  2723. var chessinstances = { current_run : {} };
  2724. var promptkeys = {
  2725. cmd : processedArgs._[0] || 'pull'
  2726. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  2727. // 'instanceName' : true
  2728. // , 'node_env' : true
  2729. // , username : ''
  2730. // , runchoice : 'c'
  2731. }
  2732. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  2733. function createLocalChessInstance( cfg ){
  2734. // return createInstance(cfg)
  2735. reconfirm = getReconfirmAll()
  2736. var inst = {};
  2737. var __new = Object.assign({}, __default, cfg)
  2738. inst[cfg.node_env] = __new; return inst;
  2739. }
  2740. var choices = {
  2741. 'instanceName' : []
  2742. , 'reposerver' : []
  2743. , 'instanceType' : []
  2744. , username : ['guest', 'chessdemo', 'demo']
  2745. }
  2746. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  2747. var instances = []
  2748. var reposervers = [];
  2749. var instanceNames = []
  2750. var instanceTypes = ['development', 'production'];
  2751. Object.keys( chessinstances).forEach(instanceName => {
  2752. if(instanceName === 'current_run') return;
  2753. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  2754. var instance = chessinstances[instanceName][node_env];
  2755. reposervers = reposervers.concat(instance.reposervers)
  2756. if(instance.reposerver) reposervers.push(instance.reposerver)
  2757. instances.push(instance)
  2758. instanceTypes.push(instance.node_env)
  2759. instanceNames.push(instance.instanceName)
  2760. })
  2761. })
  2762. instances = instances.concat(detectedinstanceoptions)
  2763. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  2764. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  2765. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  2766. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  2767. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  2768. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  2769. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  2770. }
  2771. var detection_state = {
  2772. localInstanceDetected : false
  2773. }
  2774. const https = require('https')
  2775. const http = require('http')
  2776. const RESTAPI = (function(){
  2777. // Singleton
  2778. function RESTAPI(){}
  2779. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  2780. // const options = {
  2781. // hostname: 'whatever.com',
  2782. // port: 443,
  2783. // path: '/todos',
  2784. // method: 'POST',
  2785. // headers: {
  2786. // 'Content-Type': 'application/json',
  2787. // 'Content-Length': data.length
  2788. // }
  2789. // }
  2790. RESTAPI.method = function(options, resolve, reject){
  2791. var __method = function() {
  2792. options.headers = options.headers || { 'Content-Type': 'application/json' }
  2793. if(options.payload) {
  2794. const data = new TextEncoder().encode( JSON.stringify(options.payload) )
  2795. options.headers = options.headers || {
  2796. 'Content-Type': 'application/json',
  2797. 'Content-Length': data.length
  2798. }
  2799. }
  2800. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  2801. var acquirer = getHTTPorS(options)
  2802. const req = acquirer.request(options, res => {
  2803. if (res.statusCode < 200 || res.statusCode >= 300) {
  2804. return reject(new Error('statusCode=' + res.statusCode));
  2805. }
  2806. var body = [];
  2807. // res.setEncoding('utf8');
  2808. res.on('data', function(chunk) {
  2809. body.push(chunk);
  2810. });
  2811. res.on('end', function() {
  2812. try {
  2813. body = JSON.parse(Buffer.concat(body).toString());
  2814. } catch(e) {
  2815. reject(e);
  2816. }
  2817. resolve(body);
  2818. });
  2819. });
  2820. req.on('error', error => {
  2821. console.error(error)
  2822. reject(error)
  2823. })
  2824. if(options.payload) req.write(data)
  2825. req.end()
  2826. }
  2827. if(!options.authenticatepost && !usertokens[options.username]) {
  2828. RESTAPI.authenticate(options, function(tokenresp){
  2829. usertokens[options.username] = tokenresp.sha1
  2830. __method(options, resolve, reject)
  2831. },
  2832. function(err){ throw err}
  2833. )
  2834. }
  2835. else __method(options, resolve, reject)
  2836. }
  2837. RESTAPI.post = RESTAPI.method
  2838. var usertokens = {}
  2839. RESTAPI.authenticate = function(options, resolve, reject){
  2840. options.headers = options.headers || { 'Content-Type': 'application/json' }
  2841. if(!usertokens[options.username]) {
  2842. // Authenticate and acquire token.
  2843. // https://git.bbh/api/v1/users/<username>/tokens
  2844. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  2845. var _options = Object.assign({}, options)
  2846. // _options.username = 'demo'
  2847. // _options.password = 'demo123'
  2848. _options.method = 'POST'
  2849. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  2850. _options.path = `/api/v1/users/${_options.username}/tokens`
  2851. _options.authenticatepost = true
  2852. var postoptions = { name : _options.username }
  2853. delete _options.username
  2854. delete _options.password
  2855. _options.payload = postoptions
  2856. RESTAPI.post( _options, function(tokenresp){
  2857. // tokenresp = JSON.parse(tokenresp)
  2858. usertokens[options.username] = tokenresp.sha1
  2859. resolve(tokenresp)
  2860. },
  2861. function(err){ reject(err) }
  2862. )
  2863. }
  2864. else resolve(tokenresp.sha1)
  2865. }
  2866. RESTAPI.get = RESTAPI.post = RESTAPI.method
  2867. return RESTAPI
  2868. })();
  2869. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  2870. const GITEA = (function(){
  2871. function GITEA(){}
  2872. GITEA.repository = {
  2873. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  2874. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  2875. // giteaoptions = {
  2876. // organization string
  2877. // --- organization name, if forking into an organization
  2878. // }
  2879. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  2880. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  2881. httpoptions.method = 'POST'
  2882. httpoptions.payload = giteaoptions;
  2883. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  2884. }
  2885. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  2886. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  2887. httpoptions.method = 'PATCH'
  2888. httpoptions.payload = giteaoptions;
  2889. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  2890. }
  2891. }
  2892. GITEA.user = {
  2893. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  2894. // ​/users​/{username} // Get a user
  2895. httpoptions.path = `/api/v1/users/${httpoptions.username}`
  2896. httpoptions.method = 'GET'
  2897. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  2898. }
  2899. }
  2900. return GITEA
  2901. })();
  2902. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  2903. const GIT = (function(){
  2904. function GIT(){}
  2905. Object.assign(GIT, {
  2906. 'switch user'(username){
  2907. var server = new URL(selectedinstance.reposerver);
  2908. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  2909. , username : selectedinstance.username, password : selectedinstance.password
  2910. }).then(()=>{
  2911. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  2912. {
  2913. inherit: true, shell: true,
  2914. env: process.env
  2915. , cwd: instanceroot + '/' + repo
  2916. , runas: processedArgs.runas
  2917. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  2918. })
  2919. }
  2920. )
  2921. .catch(e => {
  2922. console.error(e + 'Could not switch. Probably no such user.')
  2923. })
  2924. }
  2925. })
  2926. return GIT
  2927. })();
  2928. function createInstance(selectedinstance) {
  2929. console.dir(selectedinstance)
  2930. if(selectedinstance.local) {
  2931. selectedinstance
  2932. var args = {
  2933. remotebase : selectedinstance.reposerver + '/chess/'
  2934. , sourcerepo : 'chess-config'
  2935. , targetrepo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`
  2936. }
  2937. cmdseq = ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  2938. return any(cmdseq.map(getshelltask)).then(() => {
  2939. return true
  2940. })
  2941. }
  2942. else {
  2943. // http://try.gitea.io/api/v1/org/{org}/repos
  2944. var server = new URL(selectedinstance.reposerver);
  2945. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  2946. , username : selectedinstance.username, password : selectedinstance.password
  2947. }
  2948. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  2949. , { repo : `chess-config`, owner : 'chess' }, {}, function( repository ){
  2950. return GITEA.repository.updateattributes( {
  2951. hostname : server.host, protocol : server.protocol
  2952. , username : selectedinstance.username, password : selectedinstance.password
  2953. }
  2954. , { repo : `chess-config`, owner : selectedinstance.username }
  2955. , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  2956. )
  2957. }
  2958. )
  2959. }
  2960. // GITEA.repository.updateattributes( {
  2961. // hostname : server.host, protocol : server.protocol
  2962. // , username : selectedinstance.username, password : selectedinstance.password
  2963. // }
  2964. // , { repo : `chess-config`, owner : selectedinstance.username }
  2965. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  2966. // )
  2967. // return selectedinstance
  2968. }
  2969. var skipprerequisites = false;
  2970. function initinstances(selected_overrides) {
  2971. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  2972. var instanceName = selected_overrides.instanceName
  2973. || clioverrides.instanceName
  2974. // || processedArgs._[1]
  2975. || chessinstances.current_run.instanceName
  2976. var node_env = selected_overrides.node_env
  2977. || clioverrides.node_env
  2978. // || processedArgs.node_env
  2979. || chessinstances.current_run.node_env
  2980. var reposerver = selected_overrides.reposerver
  2981. || clioverrides.reposerver
  2982. // || processedArgs.node_env
  2983. || chessinstances.current_run.reposerver
  2984. if(!instanceName) {
  2985. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  2986. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2987. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2988. }
  2989. if(!node_env) {
  2990. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2991. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2992. }
  2993. if(!reposerver) {
  2994. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2995. }
  2996. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  2997. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  2998. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  2999. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  3000. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  3001. }
  3002. // Override sequence.
  3003. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  3004. selectedinstance = utils.assign(
  3005. chessinstances[instanceName][node_env]
  3006. , clioverrides
  3007. , selected_overrides
  3008. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  3009. );
  3010. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  3011. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  3012. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  3013. // // Brand New.
  3014. // selectedinstance = Object.assign( __default, selectedinstance )
  3015. // }
  3016. if(!selectedinstance.repos[0].repo) {
  3017. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3018. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3019. }
  3020. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  3021. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3022. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3023. }
  3024. // Config from server always override merges into selection except for the current selection.
  3025. // PB : TODO -- utils.assign Array merges are non-distinct...
  3026. chessinstances[instanceName][node_env] = selectedinstance;
  3027. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3028. cacheWriteInstanceConfig(chessinstances)
  3029. // PB : TODO -- We should probably write the new server config also...
  3030. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3031. return chessinstances
  3032. }
  3033. var skipprereqs = {}
  3034. var maintask = () => {
  3035. // Default cmd to run !
  3036. processedArgs._[0] === processedArgs._[0] || 'pull';
  3037. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  3038. if(!noprerequisites[processedArgs._[0]]
  3039. && !skipprereqs[processedArgs._[0]]
  3040. ) {
  3041. return prerequisites.git.verifyAndInstall().then(()=>{
  3042. var e = { message : 'verifyAndInstall', success : true}
  3043. var inittasks = []
  3044. if(!detection_state.localInstanceDetected) {
  3045. inittasks.push(createInstance(selectedinstance).then(() => { preworkerconfig(); return elxrworker(true) }))
  3046. }
  3047. else {
  3048. inittasks.push(acquireConfig(selectedinstance).catch((err) => {
  3049. e = err;
  3050. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  3051. console.error(err)
  3052. }).then(() => { preworkerconfig(); return elxrworker(true) })
  3053. // .finally(()=>{
  3054. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  3055. // if(!e.success) fs.writeFileSync('run.done', 'error');
  3056. // // return process.exit()
  3057. // }))
  3058. )
  3059. }
  3060. return any(inittasks)
  3061. })
  3062. }
  3063. else {
  3064. console.log('cmd has no preqs or has been configured to skip preqs')
  3065. preworkerconfig()
  3066. return elxrworker()
  3067. }
  3068. }
  3069. var startElxr = function() {
  3070. const retaincount = 2
  3071. var min = runtimestamp;
  3072. var collect = []
  3073. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  3074. reconfirm = getReconfirmAll()
  3075. }
  3076. return detectLocalInstances().then((detectedinstanceoptions)=>{
  3077. detectedinstanceoptions.splice(0,0, __default)
  3078. var cmdinstance = cmds[clioverrides.cmd]
  3079. var cmdprompts = cmdinstance.getPossiblePrompts()
  3080. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  3081. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2), promptkeys )
  3082. // promptkeys = utils.assign(promptkeys, clioverrides)
  3083. if(cmdprompts.instanceName) {
  3084. // not an instanceless cmd.
  3085. console.dir(selectedinstance)
  3086. try {
  3087. chessinstances = acquirelocalinstances(selectedinstance);
  3088. findlocalinstances(chessinstances, detectedinstanceoptions)
  3089. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  3090. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3091. var inst = initinstances(selectedinstance)
  3092. detection_state.localInstanceDetected = true;
  3093. return inst;
  3094. })
  3095. }
  3096. catch (e) {
  3097. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  3098. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3099. return initinstances(selectedinstance)
  3100. })
  3101. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  3102. // // Weve not been told what to do.
  3103. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  3104. // }
  3105. todo = todo.then(() => {
  3106. try {
  3107. chessinstances = acquirelocalinstances(selectedinstance)
  3108. findlocalinstances(chessinstances, detectedinstanceoptions)
  3109. detectedinstanceoptions.splice(0,0, __default)
  3110. initinstances(selectedinstance)
  3111. detection_state.localInstanceDetected = true;
  3112. }
  3113. catch (e) {
  3114. // console.error(e)
  3115. console.log('No local instances config found in current root = ' + selectedinstance.root);
  3116. console.log('A config will be createed with the instance and environment chosen...')
  3117. // return (async ()=>{return await __default.reposerver})().then(()=>{
  3118. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  3119. // return selectedinstance = Object.assign(__default, selectedinstance);
  3120. // })
  3121. detection_state.localInstanceDetected = false;
  3122. return selectedinstance
  3123. }
  3124. })
  3125. }
  3126. return todo
  3127. }
  3128. else return Promise.resolve(true)
  3129. })
  3130. .then(()=>{
  3131. if(noprerequisites[processedArgs._[0]]
  3132. || skipprereqs[processedArgs._[0]]
  3133. ) {
  3134. return elxrworker()
  3135. }
  3136. if(!__isElevated) {
  3137. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  3138. // collect garbage
  3139. return dirs( (dir)=>{
  3140. var matches = /run-(.*)/gm.exec(dir.name)
  3141. if(matches) {
  3142. if(+(matches[1]) < min) {
  3143. min = matches[1]
  3144. collect.splice( 0, 0, matches[1] )
  3145. }
  3146. else collect.push(matches[1])
  3147. }
  3148. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  3149. // delete garbage
  3150. if(collect.length > retaincount) {
  3151. var asyncs = [];
  3152. while((collect.length - asyncs.length) > retaincount) {
  3153. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  3154. }
  3155. return Promise.all(asyncs)
  3156. }
  3157. else return true
  3158. })
  3159. }
  3160. else return true;
  3161. })
  3162. .then(()=>{
  3163. // PB : TODO -- Keep only the last n runs...
  3164. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3165. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3166. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  3167. mainTasks.push(maintask)
  3168. return any(mainTasks);
  3169. })
  3170. }
  3171. acquireElevationState().then(() => {
  3172. return startElxr()
  3173. })
  3174. // detect if alread installed -> Take no action.
  3175. // download if no installer avalable -> next()
  3176. // install
  3177. function chackandinstall(items) {
  3178. var tasks = []
  3179. items.forEach(item => {
  3180. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  3181. })
  3182. return Promise.all(tasks).then(existances => {
  3183. existances.forEach((exists, i) => {
  3184. if (!exists) {
  3185. return downloadandinstall([items[i]])
  3186. }
  3187. })
  3188. })
  3189. }
  3190. function downloadandinstall(items) {
  3191. var tasks = []
  3192. items.forEach(item => {
  3193. tasks.push(getTaskDownload(item))
  3194. })
  3195. return Promise.all(tasks)
  3196. }
  3197. // Sample instances config.
  3198. // var instances = {
  3199. // "elixir": {
  3200. // "production": {
  3201. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  3202. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  3203. // , "exludeMergeRepos": {
  3204. // "elixir-config-development": true, "elixir-config-test": true
  3205. // , "elixir-config-production": true, "elixir-data": true
  3206. // }
  3207. // , "instanceName": "elixir", "node_env": "production"
  3208. // }
  3209. // },
  3210. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  3211. // }
  3212. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...