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

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