Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 158KB

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