您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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