|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620 |
- 'use strict';
-
- global.env = process.env;
- global.env.NODE_ENV = global.env.NODE_ENV || 'development';
-
- const fs = require('fs');
- var path = require('path');
- var utils = require('bbhverse');
- var any = utils.any;
- var Tasq = utils.Tasq;
- var statuslog = utils.Traq;
- var Traq = utils.Traq;
- Tasq.addlistener(statuslog.statuslog);
-
- Tasq.addlistener((e)=>{ fs.writeFileSync('run.log', ', ' + JSON.stringify( e ), { 'flag': 'a+' }); });
- var cli = require('./cliverse');
- function isWin(){ return /^win/.test(process.platform) }
- if(isWin()) {
- var win_verse = require('./win_verse');
- var shell_verse = win_verse;
- }
- else {
- var lin_verse = require('./lin_verse');
- var shell_verse = lin_verse;
- }
-
-
-
- var nodeShellExec = cli.nodeShellExec;
- var chalk = require('chalk');
- const homedir = require('os').homedir();
-
-
- function sysAddPathVar(addpath){
-
-
-
-
-
- var etask = ()=>{
- return nodeShellExec('Powershell.exe', [
- `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
- $newpath = $path + ';${addpath}'
- [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
- ]).then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- };
- etask.statuslog = statuslog;
- etask.selectedinstance = selectedinstance;
- etask.processedArgs = processedArgs;
- etask.runtimestamp = runtimestamp;
- etask.ENV = ENV;
- return shell_verse.runElevated(etask)
-
-
-
-
-
-
-
-
-
- }
-
-
- var getCredentials = function(){
-
-
- var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
- var creds = creds.split('\n').map( c => c.trim() && new URL(c));
- console.log(creds);
- creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username );} );
-
-
- getCredentials = ()=>{ return creds };
- return getCredentials();
- };
-
- const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b';
- const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
- const runtimestamp = (new Date()).getTime();
- function getVersion() { return BUILD_VERSION; }
- console.log(getVersion());
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- (function () {
- if (!Array.prototype.earlyreduce) {
- Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
- var iterable = this;
- var donecallback = donecallback || (a=>a);
- var result = { value : initialValue === undefined ? iterable[0] : initialValue };
- initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
-
- for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
- var element = iterable[i];
- result = eachcallback(result, element, i, iterable);
- if(result.done) return donecallback(result)
- }
-
- return donecallback(result)
- };
- }
- }());
-
- const { existsSync } = require('fs');
- const existslink = function(name, cb){
- fs.lstat(name, (error, stats) => {
- if (error) {
- console.log(error);
- cb(error);
- }
- else {
- console.log("Stats object for: example_directory.txt");
- console.log(stats);
-
-
- console.log("Path is file:", stats.isFile());
- console.log("Path is directory:", stats.isDirectory());
- cb(null, true);
- }
- });
- };
- const existsFolderSync = existsSync;
-
- const cliargs = utils.cliargs;
- const processedArgs = cliargs(process.argv.slice(2));
- if(!processedArgs.wd){
- if(process.env.wd);
- else {
- process.env.wd = process.cwd();
- if(process.cwd() === __dirname) {
-
-
- process.env.wd = path.dirname( process.env.wd );
- }
- }
- }
- else process.env.wd = processedArgs.wd;
- var ENV = Object.assign({}, process.env);
-
-
-
- console.dir(processedArgs);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- require('glob').sync;
-
- const { readdir } = require("fs").promises;
-
-
- const dirs = async (perform, src, target, options) => {
- var rs = [];
- for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
- if (dir.isDirectory()) rs.push( perform(dir, src, target, options) );
- }
- return any(rs)
- };
-
- var fsMove = async function(from, to, options) {
-
- if(!options?.innernode) {
- var exists = fs.existsSync(from);
- var stats = exists && fs.statSync(from);
- var isDirectory = exists && stats.isDirectory();
- }
- else {
- var isDirectory = options.innernode.isDirectory();
- }
-
- if(!isDirectory) return fs.renameSync(from, to)
-
- fs.mkdirSync(to, { recursive : true });
-
- var rs = [];
- for (const innernode of await readdir(from, { withFileTypes: true })) {
- rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) );
- }
-
- return any(rs)
- };
-
-
-
-
- var copyrecursive = async function(src, target, options) {
-
- if(!options?.innernode) {
- var exists = fs.existsSync(src);
- var stats = exists && fs.statSync(src);
- var isDirectory = exists && stats.isDirectory();
- }
- else {
- var isDirectory = options.innernode.isDirectory();
- }
-
- if(!isDirectory) return fs.copyFileSync(src, target)
-
- fs.mkdirSync(target, { recursive : true });
-
- var rs = [];
- for (const innernode of await readdir(src, { withFileTypes: true })) {
- rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
-
-
-
- );
- }
-
- return any(rs)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var regexreplaceall = function(content, ps){
- var repmatches;
- var replaced = content;
- while (repmatches = ps.strOrregexp.exec(content)) {
-
- if(content.length > 0) {
- var replacement = repmatches[0];
- for(var m = 1; m < repmatches.length; m++) {
- replacement = replacement.replace(repmatches[m], ps.substitutes[m-1]);
- }
- replaced = replaced.replace( repmatches[0], replacement );
- }
- }
- return replaced
- };
-
-
- const fswalk = async (pathToWalk, options, actions) => {
-
-
- if(!options.innernode) {
- var exists = fs.existsSync(pathToWalk);
- var stats = exists && fs.statSync(pathToWalk);
- var isDirectory = exists && stats.isDirectory();
- }
- else {
- var isDirectory = options.innernode.isDirectory();
- }
-
- if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
- , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
-
- var rs = [];
- for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
- rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
-
-
-
- );
- }
-
- Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
- , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ));
-
- return any(rs)
- };
-
-
- var fslink = function(to, options){ fs.symlinkSync( to, options.from ); };
-
- var fsrename = function(target, options){
-
-
- var targetname = options.innernode?.name || path.parse(target).base;
- var replaced = targetname;
-
- options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ); });
- if(replaced && replaced !== targetname) {
- var tr = target.replace( targetname, replaced );
- fs.renameSync(target, tr);
- return tr;
- }
- else return replaced
- };
-
- var fscontentreplace = function( target, options ){
-
- if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
- var content = fs.readFileSync(target, { encoding: 'utf8' });
- options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ); });
- fs.writeFileSync(target, content);
- }
- };
-
- var templatelink = function(target, options){
- var targetSubPath = target.replace(options.workingtarget + '/', '' );
- var targetSubPathsplit = targetSubPath.split("/");
- var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`;
-
- var linkToSubPathReplacement = `${options.base}-server-lib/common`;
-
-
- var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g");
- var linkToSubPath = targetSubPath;
- var b = target.match(rgxp);
- var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } );
- linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot);
-
- if( b ) {
-
- linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } );
- }
-
- options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ); });
- var linkToName = `${options.destinationroot}/${linkToSubPath}`;
-
- if(b){
- linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement);
-
-
- fs.unlinkSync( target );
- fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } );
- }
- else {
- fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName );
-
- }
- };
-
- var getShellTask = (command, args, options) => {
- options = options || {};
- var callshell = command === 'rm' ? getgitbashtask : getshelltask;
- return () => {
- var p = callshell( [command, args, Object.assign({
- inherit: true, shell: true, env: ENV, title: `${command} ${args}`
- }, options)
- ])();
- if (options.ignorefailures) {
- return p.catch(e => {
-
- })
- }
- else return p;
- }
- };
-
- var callshelltask = (args) => {
-
- if( Object.prototype.toString.call(args) === '[object Function]' ) {
- return args;
- }
- return getshelltask(args)()
- };
-
- var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` };
-
- var getshelltask = (args) => {
- return args[0] === 'rm' ? getgitbashtask(args) : () => {
- return nodeShellExec.apply(null, args).catch(function(e){
- e.benign = args[2].benign;
- if(!e.benign) { console.error(e); }
- throw e
- })
- }
- };
- var getgitbashtask = (args, onEachError) => { return () => {
- return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e); }) }
- };
-
- var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }};
- var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) };
-
- var getTaskCheckExists = shell_verse.getTaskCheckExists;
-
-
-
-
-
-
-
-
-
- var gitops = {
-
- getdiscoverbranchcmd : function(repo){
-
- var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
- var cmd = [gitbash
- , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }];
- return cmd
- }
- };
-
- var getPullCmd = (repodef, branch) => {
-
-
- var repo = repodef.repo;
- var pullCmd = [];
- if(!branch) {
-
-
-
- pullCmd= gitops.getdiscoverbranchcmd(repo);
-
-
- }
-
-
-
- if(branch) {
- var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
- var pullCmd = [ gitbash
- , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
- , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
- }
-
- if (useGitPull) pullCmd = ['git', ['pull'], {
- inherit: true, shell: true,
- cwd: instanceroot + '/' + repo
-
- , runas: processedArgs.runas
- , title: `git pull ${repo}`
- }];
- return pullCmd
- };
-
-
- var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
- var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch);
-
-
-
-
-
-
- return pT()
- };
-
- var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
-
-
- var repo = repodef.repo;
- elevatedBatch = elevatedBatch || [];
- regularBatch = regularBatch || [];
- try{
-
-
-
- var exists = existsSync(instanceroot + '/' + repo);
- }
- catch(e){
- exists = false;
- console.log(e);
- }
-
- function initTask(etask){
- etask.info = { repo };
- etask.errHandler = errHandler;
- etask.statuslog = statuslog;
- etask.processedArgs = processedArgs;
- etask.selectedinstance = selectedinstance;
- etask.runtimestamp = runtimestamp;
- etask.ENV = ENV;
- }
-
- function initElevatedBatch(){
- elevatedBatch.info = { repo };
- elevatedBatch.errHandler = errHandler;
- elevatedBatch.statuslog = statuslog;
- elevatedBatch.processedArgs = processedArgs;
- elevatedBatch.selectedinstance = selectedinstance;
- elevatedBatch.runtimestamp = runtimestamp;
- elevatedBatch.ENV = ENV;
- }
-
- if (exists) {
-
- var tasks = [];
- return (()=>{
-
- if(selectedinstance.addremotes) {
- return op['get-remotes']({repo}).then(( remotes )=>{
- return op['get-upstream']({repo, remotes}).then(( upstream ) => {
- return __addremotesandpull({ upstream, remotes})
- })
- })
- }
- else return __pull();
- })()
-
- function __pull(){
- var branchprint = branch ? ' branch :' + branch : '';
- var task = ()=>{
- console.log('pulling ' + instanceroot + '/' + repo + branchprint );
- return any(tasks).then( ()=>{
- return nodeShellExec.apply(null, getPullCmd(repodef, branch)).then(() => {
- return true;
- })
- })
- };
- initTask(task);
-
- if(repodef.requiresElevation) {
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]); }
- else initTask(elevatedBatch[elevatedBatch.length-1]);
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ));
- return regularBatch[regularBatch.length-1]
- }
- }
-
- function __addremotesandpull(options){
-
-
-
- var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
- if(selectedremotes.length > 0) ;
-
- var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
-
-
-
-
- Object.keys(repoRemotes).forEach((remotename)=>{
- });
-
- __pull();
- }
- }
- else {
-
- console.log('cloning ' + repo);
-
-
- var task = ()=>{
- return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
- {
- inherit: true, shell: true,
- env: process.env
- , cwd : instanceroot
- , runas: processedArgs.runas
- }).then(() => {
-
- var task = ()=>{
- return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
- {
- inherit: true, shell: true,
- env: process.env
- , cwd: instanceroot + '/' + repo
- , runas: processedArgs.runas
- , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
- })
- };
-
- initTask(task);
-
- if(repodef.requiresElevation) {
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ));
- return regularBatch[regularBatch.length-1]
- }
- })
- };
-
- initTask(task);
- if(repodef.requiresElevation) {
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ));
- return regularBatch[regularBatch.length-1]
- }
- }
- };
- var defaultRepoOwner = 'chess';
- var elevatedRunasRepos = null;
- var gitRepos = null;
-
-
-
-
- var dbForLabel = function (label) {
- var dbsForLabel = {
- devmysql: 'mysql'
- , development: 'mssql'
- , production: 'mssql'
- };
- return dbsForLabel[label] || 'mysql'
- };
-
-
- var checkoutMap = { 'development': 'master' };
-
-
-
- var gitbash = shell_verse.getbash();
-
-
- var exludeMergeRepos = [];
- var useGitPull = processedArgs.useGitPull || false;
-
- var op = {
- 'h': () => { console.log(elxr.help()); return '-h' }
- , 'clean' : () => {
-
- var tasklist = [];
- dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
- return Promise.all(tasklist)
- }
-
- , 'reset': () => {
-
-
-
- const fs = require('fs');
- const wipeDependencies = (__package) => {
- const file = fs.readFileSync(__package + '/package.json');
- const content = JSON.parse(file);
- for (var devDep in content.devDependencies) {
- if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
- content.devDependencies[devDep] = '*';
- }
- }
- for (var dep in content.dependencies) {
- if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
- content.dependencies[dep] = '*';
- }
- }
- fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
- };
-
- var repos = ['client'];
-
- repos.forEach(wipeDependencies);
-
-
-
-
-
- }
- , 'upgrade': () => {
- console.log('upgrade.......');
- var tasks = [
- () => {
- var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
- p.position = 1;
- console.log('One');
- return p;
- }
- , () => {
- var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
-
- p.position = 2;
- console.log('Two');
- return p;
- }
- , () => {
- var p = nodeShellExec('npm', ['install', '-g', 'n'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
- p.position = 3;
- console.log('Three');
- return p;
- }
- , () => {
- var p = nodeShellExec('n', ['latest'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
- p.position = 4;
- console.log('Four');
- return p;
- }
- ];
- any(tasks);
- console.log('.......done');
- console.log('Running exlr upgrade in : ' + path.dirname(__dirname));
- console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
- console.info('Uninstalling existing ember globally');
- var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env: env
- });
- step1.on('close', () => {
- console.info('Installing ember globally');
- var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env: env
- });
-
- step2.on('close', () => {
- nodeShellExec('cmd', ['/c', 'ember', '--version'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env: env
- });
- });
- });
- }
- , 'push': () => {
- if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
-
-
-
-
-
-
-
-
-
-
-
-
-
- var repo = processedArgs._[1];
- var remote = 'origin';
-
- var sequentialTaskShellCommands = [];
- if (!existsSync(`Z:/${repo}.git`)) {
- sequentialTaskShellCommands = [
-
-
-
-
- ['pwd', { cwd: 'Z:', inherit: true }]
- , ['mkdir', [`${repo}.git`], {
- cwd: `Z:`
- , inherit: true, shell: true
- , env: process.env
- }]
- , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
- , ['git', ['init', '--bare'], {
- cwd: `Z:/${repo}.git`
- , inherit: true, shell: true
- , env: process.env
- }]
-
- , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
- console.log(`Ignoring ${remote} rename error : ` + err); return true;
- }]
- , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
-
-
- ];
- if (!existsSync(`Z:`)) {
- sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
- inherit: true, shell: true
- , env: process.env
- }]);
- console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
-
- }
- }
-
- sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
-
-
- var tasks = [];
- sequentialTaskShellCommands.forEach(shellcmd => {
-
- tasks.push(() => {
-
- var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
- return p;
- });
- });
- any(tasks);
-
- }
- , 'is-git-repo': (dir) => {
- return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
- }
-
-
-
- , 'remote': (args) => {
-
-
-
- if(!processedArgs.v) return false;
-
- var serial_perform = (repo) => {
- var options = { cwd: instanceroot + '/' + repo };
-
- return [
- ['git', ['remote', '-v'], options]
- ]
- };
-
- var x = (args) => {
- var tasq = () => {
-
- return nodeShellExec.apply(null, args).catch(e => {
-
- console.error(tasq.toString());
- })
- };
- tasq.toString = function(){
- return JSON.stringify(args)
- };
- return tasq;
- };
-
- var perform = (dir) => {
- return any(serial_perform(dir.name).map(x))
- };
-
- dirs(perform);
- }
-
- , 'remote set-url': (args) => {
-
- var __args = {
- remotename : args.remotename || processedArgs._[2]
- , url : args.url || processedArgs._[3]
- };
-
-
-
-
-
- var pushable = processedArgs.pushable || false;
- remotename = __args.remotename;
- url = __args.url;
- var serial_perform_git_seturl = (repo) => {
-
- if (pushable) {
- return [
- ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- ]
- }
- else {
- return [
- ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
- ]
- }
-
- };
-
- var x = (args) => {
- var tasq = () => {
-
- return nodeShellExec.apply(null, args).catch(e => {
-
- console.error(tasq.toString());
- })
- };
- tasq.toString = function(){
- return JSON.stringify(args)
- };
- return tasq;
- };
- var perform_git_seturl = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- return any(serial_perform_git_seturl(dir.name).map(x))
- }).catch((e) => {
-
- });
- };
-
- dirs(perform_git_seturl);
- }
-
-
-
-
-
-
- , 'remote exists': (args) => {
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- };
-
- var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {};
-
-
- var commands = [
-
-
- [
-
- 'git', ['config', `remote.${__args.remotename}.url`]
- , utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- benign : args.benign, ignorefailures : args.ignorefailures,
- evaluateResult : function(err, result){
- return [
- +result.code === 0
- , result
- ]
- }
- } , options) ]
- ];
- var mapped = commands.map(getshelltask);
- mapped.push( function(prevserialtaskresult) {
- var pt = [false , null];
- if(prevserialtaskresult.error) {
-
- pt[1] = prevserialtaskresult.error[1];
- }
- else pt = prevserialtaskresult;
-
- console.dir(prevserialtaskresult);
- return getshelltask(['git', ['ls-remote', `${__args.url}`], utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- benign : args.benign, ignorefailures : args.ignorefailures,
- evaluateResult : function(err, result){
- if(+result.code !== 0) return [pt, [ false, result]]
-
- return [pt, [true, result] ]
- }
- } , options) ])().catch( e => {
- console.error(e);
- return [pt, [ false, null]]
- })
- });
- return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
-
- console.dir(allresolved);
- !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
- : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
- : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
- : console.log('was not added as a remote but url is currently accessible.');
-
- return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
- : allresolved[0][0] && allresolved[1][0] ? [1, 1]
- : allresolved[0][0] && !allresolved[1][0] ? [1, 0]
- : [0, 1]
- }).catch(e => {
- console.log(e);
- return [0, 0]
- })
- }
-
- , 'remote refresh': (args) => {
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- };
-
-
- function perform_remote_refresh(dir){
- var repo = dir.name;
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
- try {
- var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null
- , { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' }
-
- ).remotes || [];
- }
- catch(e){
- var remotes = [];
- }
-
-
-
- return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
- console.log('Processing : ' + dir.name);
- var branch = __branch;
- __args.repo = repo;
- __args.branch = __branch;
- var promises = [];
-
- remotes.forEach(remote =>{
- Object.keys(remote).forEach(remotename => {
- __args.remotename = remotename;
- __args.url = remote[remotename];
- __args.benign = true;
- __args.ignorefailures = true;
- promises.push( op['remote exists']( __args ).then( exists => {
- if(!exists[0]) {
- if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ); }
- else return op['remote add']( { remotename,
-
- url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
- } )
- }
- })
- );
- });
- });
-
- return Promise.all(promises)
- })
- .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
- }
-
- return dirs(perform_remote_refresh)
- }
- , 'remote add': (args) => {
-
-
-
-
-
-
-
-
-
-
-
-
-
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , repo : args.repo
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- , 'set-upstream' : args['set-upstream'] || processedArgs._[5]
- };
-
- var remotename = __args.remotename;
- var url = __args.url;
- var branch = __args.branch;
-
- var pushable = processedArgs.pushable || false;
-
- var serial_perform_git_add = (repo) => {
-
- if (pushable) {
- var gacmds = [
- ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
-
- ];
- }
- else {
-
- var gacmds = [
- ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
- , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
-
-
- ];
- }
- if(args['set-upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]);
- return gacmds
- };
-
-
- var perform_git_add = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
-
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
- })
- .catch((e) => {
- perform( serial_perform_git_add, dir.name );
- });
- }
-
- }).catch((e) => {
- console.log('Failed : ' + dir.name);
- });
- };
-
- if(args.repo) { perform_git_add( { name : args.repo} ); }
- else return dirs(perform_git_add)
- }
- , 'remote remove': (args) => {
-
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- };
- var remotename = __args.remotename;
- var serial_perform_git_remove = (repo) => {
-
- return [
- ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
- ]
- };
-
- var perform_git_remove = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
-
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- any(serial_perform_git_remove(dir.name).map(getnodeshellexectask));
- })
- .catch((e) => {
- console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
- });
- }
-
- }).catch((e) => {
-
- });
- };
-
- require("fs").promises;
-
- dirs(perform_git_remove);
- }
- , 'get-remotes' : (args) => {
-
-
-
-
- var repo = args.repo;
-
- var serial_perform = (repo) => {
- return [
- ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
- evaluateResult : function( issuccess, result){
- if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
-
- var lines = result.messages.join('').split('\n');
- var remotes = {};
- lines.forEach(line => {
-
- var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line);
- if(match) {
- var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] });
- if(match[3] === 'push') { r.push = match[2]; }
- else r.url = match[2];
- }
- });
- return remotes
- }}]
- ]
- };
-
- return perform( serial_perform, repo )
- }
- , 'get-remote' : (upstream) => {
-
-
-
-
- var repo = upstream.repo;
-
- var serial_perform = (repo) => {
- return [
- ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
- evaluateResult : function( issuccess, result){
- if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
-
-
- var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '));
- if(match) { upstream.url = match[1]; }
- else throw Object.assign( new Error('No upstream found for active branch'), result)
- return upstream
- }}]
- ]
- };
-
- return perform( serial_perform, repo )
- }
- , 'get-upstream' : (args) => {
-
- var __args = {
- repo : args?.repo || processedArgs._[1]
- };
-
- var repo = __args.repo;
-
- var serial_perform = (repo) => {
- return [
- ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
- evaluateResult : function( issuccess, result){
- if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
-
- var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '));
- if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] }; }
- else throw Object.assign( new Error('No upstream found for active branch'), result)
-
- if(args?.remotes) {
- var r = args.remotes[upstream.remotename];
- if(!r) return op['get-remote'](upstream)
-
- r.branch = upstream.branch;
- r.remotebranch = upstream.remotebranch;
- return r
- }
- return op['get-remote'](upstream)
- }}]
- ]
- };
-
- return perform( serial_perform, repo )
- }
- , 'init-gitea': (user) => {
- user = user || processedArgs._[1];
- if (!user) throw 'User name required'
- var serial_perform_init_gitea = (repo) => {
-
- return [
- ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
- ]
- };
-
- var perform_init_gitea = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
-
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
- })
- .catch((e) => {
- perform( serial_perform_init_gitea, dir.name );
- });
- }
-
- }).catch((e) => {
-
- });
- };
-
- dirs(perform_init_gitea);
- }
- , 'syncmaster': (label) => {
-
-
-
- Object.assign({}, process.env);
-
- console.log('Running exlr pull : ' + path.dirname(__dirname));
-
- if (!processedArgs.runas) gitRepos.map((def) => performPull(def, def.branch || 'master'));
- var etask = ()=>{
- return any(elevatedRunasRepos.map((def) => performPull(def, def.branch || 'master'))).then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- };
- etask.statuslog = statuslog;
- etask.selectedinstance = selectedinstance;
- etask.processedArgs = processedArgs;
- etask.runtimestamp = runtimestamp;
- etask.ENV = ENV;
- return shell_verse.runElevated(etask)
- }
-
- , 'repo-relocate' : function(args){
-
-
- var args = args || {
- remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
- , folder : processedArgs._[3] || 'server'
- , sourcerepo : processedArgs._[2] || 'client'
- , targetrepo : processedArgs._[1] || 'elixir-server'
- };
- var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
-
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- };
-
- return op['repo-split'](args).then(()=>{
- return op['repo-merge'](args).then(()=>{
-
-
- var cmdseq = [
- ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
-
-
- ];
-
- return any(cmdseq.map(getshelltask))
- })
- }).catch(e=>{console.error(e);})
- }
-
- , 'repo-split' : function(args) {
-
-
-
-
-
-
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , sourcerepo : 'client'
- , targetrepo : 'elixir-server'
- };
-
- var options = { cwd: `${instanceroot}/relocate`
-
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- };
-
- var cmdseq = [
-
- ['mkdir', [ '-p', `${instanceroot}/relocate`]]
- , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
- , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
- , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
- ];
-
- return any(cmdseq.map(getshelltask)).then(() => {
-
-
-
-
-
-
-
-
-
- return op['filter-repo'](args)
- }).catch(e=>{console.error(e); throw 'failed'})
- }
-
- , 'repo-merge' : function(args) {
-
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , sourcerepo : 'client'
- , targetrepo : 'elixir-server'
- };
-
- ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
-
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- });
- var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
-
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- };
-
- var cmdseq = [
- ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
- , targetrepooptions ]
-
- ];
- return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e);})
- }
-
- , 'filter-repo' : function(args){
-
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , targetrepo : 'elixir-server'
- };
-
- var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
- , inherit: true, shell: true
- , env: process.env
- , runas: processedArgs.runas
- };
-
- var cmdseq = [
-
-
- ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
- ];
- return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
- }
-
- , 'filter-branch' : function(preservefolder, repo){
-
-
-
-
-
-
-
- throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- , 'pull' : (label) => {
-
-
-
- return elxr.getpulltask(selectedinstance)
- }
- , 'isInstalled': () => {
- return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
- console.log(processedArgs._[1] + ' exists.');
- return true;
- });
- }
- , 'c' : ()=>{
-
- }
- , 'i' : () => {
- var tasks = [];
-
- tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
- tasks.push(op['use']);
- op['npmi'].statuslog = statuslog;
- tasks.push(shell_verse.getNonElevatedTask(op['npmi']));
-
-
-
-
-
-
-
-
-
-
-
-
-
- return any(tasks);
-
- }
- , 'npmi': () => {
- var tasks = [];
-
-
- tasks.push(getShellTask(
- 'npm',[ 'i', '-g', 'babel-cli' ]
- ) );
-
- var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
-
- npmbuildrepos.forEach(repo => {
- tasks.push(() => {
- return nodeShellExec('npm', ['i --force'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repo
- , env: process.env
- , title: `npm i for ${repo}`
- }).catch((e) => {
- console.error('Ignoring Benign Error'); console.error(e);
- }).then(() => {
- console.log(`--npm run build for ${repo}--------------------`);
- return nodeShellExec('npm', ['run build'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repo
- , env: process.env
- , title: `npm run build for ${repo}`
- }).then(Tasq.then).catch(Tasq.catch)
- })
- });
- });
-
- return any(tasks).then(() => {
-
- gitRepos.push({ repo : 'chess-server-lib/server'});
- gitRepos = gitRepos.concat(elevatedRunasRepos);
-
-
-
-
-
-
-
-
- var rmtasks = [];
- var repotasks = [];
- var env = Object.assign({}, process.env);
- delete env.NODE_ENV;
- gitRepos.forEach(repodef => {
- rmtasks.push(
-
-
-
- callshelltask(['rm', ['package-lock.json'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env: process.env
- , title: `rm 'package-lock.json' for ${repodef.repo}`
- }])
- .then(()=>{
- console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
- }).catch((e) => { console.error(e); })
-
- );
-
- if (npmbuildrepos.indexOf(repodef.repo) < 0) {
- repotasks.push(
- () => {
- console.log(`--npm i for ${repodef.repo}--------------------`);
- var p = nodeShellExec('npm', ['i', '--force'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env
- , title: `npm i for ${repodef.repo}`
- }).then(Tasq.then).catch(Tasq.catch);
- return p;
- });
- }
- });
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var bowerRepos = [{ repo : 'client'}];
- var bowertasks = [];
- bowerRepos.forEach(repodef => {
- bowertasks.push(() => {
- console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
-
- var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
-
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env: process.env
- , title: `bower i for ${repodef.repo}`
- }).then(Tasq.then).catch(Tasq.catch);
- return p;
- });
- });
-
- return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
- }).catch(e => {
- console.error(e);
- }).finally(statuslog.finally)
-
- }
- , 'start': (args) => {
-
- var label = clioverrides.cmd;
- var env = Object.assign({}, process.env);
- env.NODE_ENV = clioverrides.node_env || 'development';
- var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
-
- function startFn( o ){
- var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]];
- console.log(`Starting ${o.name}.`);
- var childPromise = nodeShellExec('cmd', ['/k', getCmdString(cmd) ], {
-
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + o.path
- , env: env
- });
-
- var child = childPromise.process;
- var cpid = child.pid;
- if (typeof child.pid !== 'undefined') {
- childPromise.then(()=>{
- console.log(` *** started Elixir Loopback Server PID(${cpid}) : NODE_ENV=${clioverrides.node_env} ${cmd}`);
- fs.writeFileSync('.elixir-server.elixir.server.pid', '' + cpid);
- })
- .catch(e => console.errror(e) );
- }
- }
-
- if(clioverrides.node_env === 'development') {
- env.DEBUG = 'loopback:connector:' + dbForLabel(label);
-
- startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server' } );
- startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server' } );
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- console.log('Starting Elixir Client Host.');
- var cmd = ['ember', ['s']];
- var childPromise = nodeShellExec(...cmd, {
-
-
-
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + '/' + 'client'
- , env: env
- });
-
-
- child = childPromise.process;
- if (typeof child.pid !== 'undefined') {
- console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
- fs.writeFileSync('.client.server.pid', child.pid, {
- encoding: 'utf8'
- });
- }
- }
-
- }
- , 'stop': (label) => {
- const kill = require('tree-kill');
-
- var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
- encoding: 'utf8'
- });
- fs.unlinkSync('.elixir-server.elixir.server.pid');
- console.log(serverPid);
- kill(serverPid);
-
- serverPid = fs.readFileSync('.express.server.pid', {
- encoding: 'utf8'
- });
- fs.unlinkSync('.express.server.pid');
- console.log(serverPid);
- kill(serverPid);
- }
- , 'model' : () => {
- var etask = ()=>{
- var tasks = [
- () => {
- var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
- , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
- inherit: true, shell: true
- , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
- , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
- , env: process.env
- }).catch((e) => { console.error(e); });
- return p;
- }
- ];
- return any(tasks).then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- };
- etask.statuslog = statuslog;
- etask.selectedinstance = selectedinstance;
- etask.processedArgs = processedArgs;
- etask.runtimestamp = runtimestamp;
- etask.ENV = ENV;
- return shell_verse.runElevated(etask)
- }
-
-
- , 'use' : () => {
-
-
-
-
-
-
-
-
-
-
- if (( !processedArgs.force) &&
- runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
- selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
-
- console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
- if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
- if (existsSync('config') && existsSync('data')){
- return
- }
- }
-
- var tasks = [
- () => {
- var promise = new Promise((resolve, reject)=>{
- existslink('config', function(err, data){
- if(data) {
- shell_verse.removeJuncionOrLink('config')
- .then(()=>{resolve(true);})
- .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); });
- }
- else resolve(false);
- });
- });
- return promise;
- },
- () => {
- var promise = new Promise((resolve, reject)=>{
- existslink('data', function(err, data){
- if(data) {
- shell_verse.removeJuncionOrLink('data')
- .then(()=>{resolve(true);})
- .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); });
- }
- else resolve(false);
- });
- });
- return promise;
- },
- ];
- runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
- if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
- if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
- if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
-
- fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
-
- var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
-
- var performPullOrCloneForBranch = (def)=>{
- var promise = Promise.resolve(true);
- if (!branch) {
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
-
- promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch;})
- .catch((e) => { console.error(e); return { error: true, message: repo } });
-
- }
-
- return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
- };
-
- var performCloneAndCheckout = null;
-
- var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
-
- return performPullOrCloneForBranch(def).then(()=>{
- nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
-
-
- cwd: instanceroot + '/' + def.repo
-
- , runas: processedArgs.runas
- , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
- }).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 } });
- })
- };
-
- var mergeSources = {
- 'development': null,
- 'test': 'master',
- 'production': 'master'
- };
- var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
-
-
- if(branch === mergesource) performCheckout = (def) => {
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
- return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
-
- if(branch === __branch) return performCloneAndCheckout(def)
- return performPullOrCloneForBranch(def)
- })
- .catch((e) => { console.error(e); return { error: true, message: repo } })
- };
-
-
- var performPullAll = (def) => {
- if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
- return nodeShellExec('git', ['pull', '--all'], {
-
- cwd: instanceroot + '/' + def.repo
- , runas: processedArgs.runas
- , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
- }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
- };
-
- var excludeCheckouts = Object.assign(exludeMergeRepos);
- delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
- delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
-
- var performMerge = (def) => {
- if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
- return nodeShellExec('git', ['merge', mergesource], {
- inherit: true, shell: true,
- cwd: instanceroot + '/' + def.repo
- , runas: processedArgs.runas
- }).catch((e) => { console.error(e); })
- };
- if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
-
-
-
-
-
-
- return any(tasks).then(() => {
-
- var task = ()=>{
-
-
-
- return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
-
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullAll(repo)))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullAll(repo)))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
- })
- .then(
- () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
- })
- };
- task.statuslog = statuslog;
- var netask = shell_verse.getNonElevatedTask(task);
-
- var eltask = ()=> {
- var opts = {
- inherit: true, shell: true
- , cwd : instanceroot
- , env: process.env
- };
- var tasks = [
- () => {
-
- var target = runconfig.use + '-' + 'config' + '-' + process.env.NODE_ENV;
- var p = shell_verse.createJuntionOrLink('config', target, opts);
- return p;
- }
- ];
-
- tasks = tasks.concat( [
- () => {
- var dataToLink = runconfig.use + '-data' + '-' + process.env.NODE_ENV;
- if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
- var p = shell_verse.createJuntionOrLink('data', dataToLink, opts);
- return p;
- }
- ]
- );
-
-
- return any(tasks).then(()=>{
-
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
-
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
- })
- .then(
- () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
- })
- .then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- })
- };
- eltask.statuslog = statuslog;
- eltask.selectedinstance = selectedinstance;
- eltask.processedArgs = processedArgs;
- var etask = shell_verse.getElevatedTask(eltask);
-
- return etask().then( ()=>{ return netask() })
-
- }).catch((e) => {
- fs.writeFileSync('run.done', 'error : ' + e);
- })
-
-
-
-
-
-
- }
- , 'g' : () => {
- if (processedArgs.h) {
-
- console.log('elxr g model [modelname] => generate a model named [modelname]');
- console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
- console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
- console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
- console.log('elxr g => regenerate all known models');
- return
- }
-
-
-
-
- var g = {
- 'client': () => {
-
-
- console.info('Creating new ember client named : ' + processedArgs._[2]);
- nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env: env
- });
- },
-
- 'modelr': () => {
- var tasks = [
- () => {
- var p = nodeShellExec('"ember"', [
- 'g'
- , 'modelr'
- , processedArgs._[2]], {
- inherit: true, shell: true, env: process.env
- }).then(() => {
- console.log('Blueprint generation complete for : ' + processedArgs._[2]);
- return true;
- }).catch((e) => { console.error(e); });
- return p;
- },
- () => {
- var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
- var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
- chromeprefs = JSON.parse(chromeprefs);
- var previous = chromeprefs.download.default_directory;
- var parentDir = path.dirname(__dirname);
- chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
- fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
-
-
- var p = nodeShellExec('"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/' + processedArgs._[2]], {
- inherit: true, shell: true
- , env: process.env
- }).then(() => {
- chromeprefs.download.default_directory = previous;
- fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
- return true;
- }).catch((e) => { console.error(e); });
- return p;
- }
- ,
- () => {
- console.log('Browser process should have closed here....');
- return true;
- }
- ];
- any(tasks);
-
- }
-
- , 'undefined' : ()=>{
- console.warn('Are you sure you want to refresh all the models.');
- throw 'NOT YET IMPLMENTED'
- }
-
- , 'vmodel' : (options)=>{
-
- options = options || {
- generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
- };
-
- if(!options.generate) return 'Nothing specified for generation'
-
- var name = processedArgs._[2];
- if(!name) return 'No name specified for generation'
- var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`;
-
-
- var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`;
- var destination = `${selectedinstance.root}`;
-
-
- return copyrecursive(templateverse, workingtarget).then( r => {
-
- var base = 'chess';
- var patternsubstitutions = [
- { strOrregexp : /(__name__)/g, substitutes : [name]}
- , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
- , { strOrregexp : /(__base__)/g, substitutes : [base]}
- , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
- , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']}
- ];
- var options = { source : templateverse, target : workingtarget
- , base , destinationroot : destination, workingtarget
- , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions };
-
- var actions = [
- fswalk( workingtarget, options
- , [ function(t, o){
-
-
- return any([
-
- ()=>{ return fscontentreplace( t, o ) }
- , ()=>{ return fsrename( t, o ) }
- ])
- }] )
-
- , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
- , workingtarget, null, options)
-
-
-
-
- ];
-
- return any(actions);
-
- })
-
- }
- };
-
- g[processedArgs._[1]]();
- }
-
- , 'create' : () => { return createInstance(selectedinstance) }
-
- , 'httpget' : () => {
-
-
-
-
-
-
-
- return createInstance(selectedinstance)
- }
-
- , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u);}) }
- , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
- };
-
-
- var noprerequisites = {
- add : true, 'set-url' : true, 'repo-relocate' : true
- , remote : true, 'c' : true, 'h' : true
- , httpget : true, getuser : true
- , 'switch user' : true
- , 'switch' : true
-
- };
-
- var reconfirmcmds = { create : true };
-
- var subcommandlabels = {
- remote : (`remote ${processedArgs._[1] || ''}`).trim()
- , switch : (`switch ${processedArgs._[1] || ''}`).trim()
- };
-
- var cmds = {
- remote : {
-
- interpret() {
- return { cmd : subcommandlabels['remote'], runchoice : 'c' }
- }
- }
- , resetgitconfig : {
-
- cmdFn : resetgitconfig
- , interpret() { return { cmd : 'resetgitconfig' } }
- , getPossiblePrompts(){ return {} }
- , noprerequisites : true
- , independentcmd : true
- }
- , reinit : {
-
- cmdFn : reinit
- , interpret() { return { cmd : 'reinit' } }
- , getPossiblePrompts(){ return {} }
- , noprerequisites : true
- , independentcmd : true
- , requiresElevation : true
- , requires : [ generateDependencies ]
- }
- , init : {
-
- cmdFn : init
- , interpret() { return { cmd : 'init' } }
- , getPossiblePrompts(){ return {} }
- , noprerequisites : true
- , independentcmd : true
- , requiresElevation : true
- , requires : [ generateDependencies ]
- }
- , switch : {
- interpret() {
- return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
- , reposerver : __default.reposerver
- }
- }
- , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } }
- }
- , 'switch user' : {
- interpret() {
- return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
- }
- , getPossiblePrompts(){ return { username : true } }
- }
-
-
- , 'users' : {
-
- subcommands : { list : {} }
- , cmdFn : ()=>getCredentials()
- , cmd : 'users'
- , noprerequisites : true
- }
- , 'users list' : {
- cmdFn : ()=>getCredentials()
- , cmd : 'users list'
- , noprerequisites : true
- }
- , 'get-upstream' :{
- cmdFn : op['get-upstream']
- , cmd : 'get-upstream'
- , noprerequisites : true
- , independentcmd : true
- , interpret() { return { cmd : 'get-upstream' } }
- , getPossiblePrompts(){ return {} }
- }
- , 'g' : {
- cmdFn : op['g']
- , cmd : 'g'
- , noprerequisites : true
- , getPossiblePrompts(){ return {} }
- }
- , 'link' : {
- 'cmd' : 'link'
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- , cmdFn : function( cmdopts ){
-
- targetfilename = cmdopts.targetfilename || processedArgs._[1];
-
- if(!targetfilename) return Promise.reject('error no file provided for linking')
- targetdir = cmdopts.targetdir || process.env.wd;
- sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`);
-
- var tasks = [
- () => {
-
- var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
- inherit: true, shell: true
- , cwd : targetdir
- , env: process.env
- }).catch((e) => { console.error(e); });
- return p;
- }
- ];
- var etask = ()=>{
- return any(tasks).then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- };
- etask.statuslog = statuslog;
- etask.selectedinstance = selectedinstance;
- etask.processedArgs = processedArgs;
- etask.runtimestamp = runtimestamp;
- etask.ENV = ENV;
- return shell_verse.runElevated(etask)
- }
- , noprerequisites : true
- , privileged : true
- }
- };
-
- var elxrcmd = (function(){
-
- var __cmdprototype = function(){};
- function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
-
- var __cmd = {
- interpret() { return { cmd : this.cmd } }
- , getPossiblePrompts(){ return {} }
- , cmdFn : ()=>{ throw "Elxr Unknown command."}
- , finalized : true
- };
-
- function __createO(o){
- if(o.finalized) return o;
- var subs = Object.keys(cmds[o.cmd].subcommands || {});
-
-
- subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ));
-
- var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {}, __cmd, cmds[o.cmd], o);
- cmds[o.cmd] = created;
- op[o.cmd] = created.cmdFn;
- noprerequisites[o.cmd] = created.noprerequisites;
- return created.cmdFn;
- }
-
- function create(o){ return __createO(o) }
-
- __cmdprototype.create = create;
-
- return __cmdprototype;
- })();
-
- elxrcmd.create(cmds['users']);
- elxrcmd.create(cmds['g']);
- elxrcmd.create(cmds['link']);
-
- var interpretrun = function(){
-
- var cmd = processedArgs._[0];
- var clioverrides = { cmd };
- processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
- : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
- ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
-
-
- return cmds[cmd] ? cmds[cmd].interpret() : (function(){
- processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
-
- cmds[cmd] = {
- interpret() {
- return Object.assign(clioverrides, { cmd, runchoice : 'c' })
- }
- , getPossiblePrompts(){ return { cmd, username : true, password : true,
- instanceName : true, instanceType : true, reposerver : true } }
- };
- return cmds[cmd].interpret()
- })()
- };
-
- var clioverrides = interpretrun();
- console.dir(clioverrides);
-
- var util = require('util');
- var cliname = 'elxr';
- var ver = '1.1';
- var readme = `
- Command syntax examples
-
- elxr
- Displays help. Same as elxr h
-
- elxr i
- Runs interactive propmts to help choose installation options.
-
- NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
- General command syntax.
- Eg: NODE_ENV=development elxr pull elixir
-
- Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
- The specific cmd defines what the value is interpreted as.
- There are several cmds that do not require an {{instancename}} parameter.
- Eg: elxr remote remove origin
- Git operations or passthrough external commands on all repository folders in you working directory.
-
- Main objectives.
- elxr cli is a wrapper around other shell commands and api based operations.
- One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
- Eg: A git operation like pull can be repeated consistently on a set of git repositories.
-
- `;
- var help = `
- ${readme}
-
-
- # list of commands... please refer dveloper documentation for ${cliname}
- \r\n\t${
- Object.keys(op).join('\r\n\t')
- }
- `;
-
- var elxr = {
- help() {
- return chalk.cyanBright(`
- -------------------------------------------------------------------------------
- *** BBH Elixir ***
- -------------------------------------------------------------------------------
- elxr ${ver}
- A cli tool for chess
- ${help}
- -------------------------------------------------------------------------------
- `)
- }
- , info() {
- return chalk.cyanBright(`
- -------------------------------------------------------------------------------
- *** BBH Elixir ***
- -------------------------------------------------------------------------------
- elxr ${ver}
- A cli tool for chess
- -------------------------------------------------------------------------------
- `)
- }
- , getpulltask(args){
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ({
- remotename : args.remotename|| processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- });
-
-
-
-
-
-
-
-
-
-
-
-
-
- var def = args || {
- repos : selectedinstance.repos,
- elevated : selectedinstance.elevated
- };
-
- var elevatedpulltasks = null;
- if(def.repo) {
-
- if(def.repo.requiresElevation) {
- var t1 = function() {
- return performPull(def).then(() => {
- return true;
- }).catch((e) => {
- console.error(e);
- }).finally(Traq.finally)
- };
- t1.statuslog = statuslog;
- t1.selectedinstance = selectedinstance;
- t1.processedArgs = processedArgs;
- elevatedpulltasks = shell_verse.getElevatedTask( t1 );
- }
- else {
- var t2 = function(){
- return performPull(def).then(() => {
- console.log('pulled ' + JSON.stringify(def.repo));
- return true;
- }).catch((e) => {
- console.error(e);
- }).finally(Traq.finally)
- };
- t2.statuslog = statuslog;
- var regularpulltasks = shell_verse.getNonElevatedTask( t2 );
- }
- if(elevatedpulltasks) return elevatedpulltasks
- else return regularpulltasks
- }
-
-
- console.dir(def);
-
- Object.assign({}, process.env);
- console.log('Running exlr pull : ' + path.dirname(__dirname));
-
- processedArgs.useGitPull || false;
-
- if(def.elevated || def.repos) {
- if(def.elevated) def.requiresElevation = true;
- else delete def.requiresElevation;
- }
- else {
- if(def.requiresElevation) def.elevated = [def];
- else def.repos = [def];
- }
-
-
- var regularpulltasks = function(){ return Promise.resolve(true) };
- if(def.elevated){
- elevatedpulltasks = function() {
- var eBatch = [];
- def.elevated.map((def) => getPullTask(def, null, null, null, eBatch));
- return shell_verse.runElevatedBatch(eBatch).then(() => {
- return true;
- }).catch((e) => {
- console.error(e);
- })
- };
- elevatedpulltasks.statuslog = statuslog;
- }
- if(def.repos) {
- var regularpulltasks = function(){
- var pendingpulls = [];
- def.repos.forEach((def) => {
- pendingpulls.push(
- performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)); })
- .catch(e => { console.log(e); throw e })
- );
- });
- return any(pendingpulls).finally(Traq.finally)
- };
- regularpulltasks.statuslog = statuslog;
- }
-
-
- return any([ elevatedpulltasks, regularpulltasks ])
- }
- };
-
- function preworkerconfig(){
-
- gitRepos = selectedinstance.repos;
-
-
-
- elevatedRunasRepos = selectedinstance.elevated;
-
- exludeMergeRepos = selectedinstance.exludeMergeRepos;
- }
-
-
-
- function elxrworker() {
-
- var __runcmd = function (label) {
- var distinquishedlabel = subcommandlabels[label] || label;
- return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
- };
-
-
-
- if (processedArgs.runas) {
-
-
-
-
-
- return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
- }
- else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var mergeObjByKey = function(arrOfObjs, keyName) {
-
- var keyedDistinct = {};
- var distinctArrOfObjs = [];
-
- arrOfObjs.forEach( o => {
- if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
- });
- Object.keys(keyedDistinct).forEach(key => {
- distinctArrOfObjs.push( utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , ...keyedDistinct[key] ) );
- });
-
- return distinctArrOfObjs;
- };
-
- var cacheWriteInstanceConfig = function(chessinstances){
- var instanceName = chessinstances['current_run'].instanceName;
- var node_env = chessinstances['current_run'].node_env;
-
- chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
- chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
- fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
- };
-
-
- var os = require("os");
- var hostname = os.hostname();
- var clustername = null;
- var configs = (function(){
-
-
-
-
- return {
- ownerClusterNodeConfig(selected) {
-
-
- var clusternodename = hostname || `CHESS0001${selected.username}`;
- clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
- return __acquireConfig(selected, { remote : 'userfork' }
- , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
- , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
- return e; }
- )
- }
- , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
- , selected.instanceName + '-config-' + selected.node_env
- , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
- return e }
- )
- }
-
- , commonInstance(selected) { return __acquireConfig(selected, { defaultRepoOwner }
- , undefined
- , function(e){
-
- statuslog.statuslog(e, e);
- var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
- utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ));
- console.dir(selectedinstance.repos);
-
-
- if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
- }
- if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
- }
- chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selected, selectedinstance);
- chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0];
- cacheWriteInstanceConfig(chessinstances);
-
- throw e
- }
- ) }
-
- }
- })();
-
- var eNotImplemented = function(){
- console.error('Not yet implemented');
- process.exit();
- };
-
-
- var acquireConfig = function(slections){
- var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' ];
- return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
- return acquireData(slections)
- })
- };
-
- var instanceData = (function(){
- return {
- ownerClusterNodeData(selected) {
- var clusternodename = hostname || `CHESS0001${selected.username}`;
- clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
- return __acquireData(selected, { remote : 'userfork' }
- , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
- , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
- return e; }
- )
- }
- , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
- , selected.instanceName + '-data-' + selected.node_env
- , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
- return e }
- )
- }
-
- , commonInstance(selected) { return __acquireData(selected, { defaultRepoOwner }
-
-
- ) }
- , genericChessInstance(selected) { return __acquireData(selected) }
- }
- })();
-
- var acquireData = function(slections){
- var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' ];
- return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
- };
-
-
- function reinit(){
- sysAddPathVar('%AppData%\\npm');
- resetgitconfig();
- }
-
- function init(){
- sysAddPathVar('%AppData%\\npm');
- resetgitconfig();
- }
-
-
- function resetgitconfig(){
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var options = {
- inherit: true, shell: true
- , cwd: instanceroot
- , runas: processedArgs.runas
- };
-
- var task = ['git', ['config'], options];
-
- var tasklist = [
-
-
-
-
- ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
- , ['--global', '--replace-all', 'user.name', 'pb']
- , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
-
-
-
- ];
- var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n');
- var shellT = (args) => { return getgitbashtask(args, onEachError)
-
- };
- execserial(tasklist, task, shellT);
- }
-
- var createTasq = (args, shellT, onEachError) => {
- var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e); } ) });
- tasq.toString = function(){ return JSON.stringify(args)};
- return tasq;
- };
-
- var execserial = function(tasklist, task, shellT){
- var exec = (taskArgs)=>{
- var thistask = task.concat();
- thistask[1] = thistask[1].concat();
- thistask[1].push.apply(thistask[1], taskArgs);
- return createTasq(thistask, shellT)
- };
-
- return any(tasklist.map(exec))
- };
-
-
- var __acquireConfig = function (selected, options, configrepo, errHandler) {
-
- configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
-
- var errorHandler = (e) => {
- if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
-
- 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 => {
-
- if(propValue === 'y') {
- reconfirm = getReconfirmAll();
- return startElxr()
- }
- else if(propValue === 'r'){
- return acquireConfig(selected)
- }
- else process.exit();
- })
- }
-
- if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${configrepo}.git/' not found`))){
- var choices = {
- t : `install a new temporary local instance with this name ( will not persist ).
- Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
- , e : 'exit' };
-
- if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
- choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- i : 'create a new instance with this name => will fork the default config under your username'
- , f : 'fork a new instance with this name for yourself for this node from another instance'
- , o : 'fork a new instance with this name for your organization from another instance'
- , c : 'create a custom config for yourself for this node'
- , p : 'create a custom config for yourself '
- }, choices);
- }
-
- return cli.prompt( choices
- , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
-
- if(propValue === 't') {
- selectedinstance.local = true; return createInstance(selectedinstance)
- }
- if(propValue === 'i') return eNotImplemented()
- if(propValue === 'f') return eNotImplemented()
- if(propValue === 'o') return eNotImplemented()
- if(propValue === 'c') return eNotImplemented()
- if(propValue === 'p') return eNotImplemented()
-
- else process.exit();
- })
- }
-
- console.warn(e);
- throw e;
- };
-
- var successHandler = () => {
-
- var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
- utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' }));
- console.dir(selectedinstance.repos);
-
-
- if(!selectedinstance.repos[0].repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
- }
- if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
- }
- chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selected, selectedinstance);
- chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0];
- cacheWriteInstanceConfig(chessinstances);
- ENV.NODE_ENV = selectedinstance.node_env;
- };
-
- return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
- , null, selected.username || options.defaultRepoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
- .catch( (e)=>{
-
- if(Promise.resolve(e) === e) return e;
-
- e.benign = true;
- throw e;
-
- })
- };
-
- var __acquireData = function (selected, options, datarepo, errHandler) {
-
- datarepo = datarepo || selected.instanceName + '-data';
-
- var errorHandler = (e) => {
- if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
-
- 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 => {
-
- if(propValue === 'y') {
- reconfirm = getReconfirmAll();
- return startElxr()
- }
- else if(propValue === 'r'){
- return acquireConfig(selected)
- }
- else process.exit();
- })
- }
-
- if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${datarepo}.git/' not found`))){
- var choices = {
- t : `install a temporary local data folder.
- For more options. Request and use a personal username at chess@bbh.org.in )`
- , e : 'exit' };
-
- if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
- choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- i : 'create a new instance with this name => will fork the default config under your username'
- , f : 'fork a new instance with this name for yourself for this node from another instance'
- , o : 'fork a new instance with this name for your organization from another instance'
- , c : 'create a custom config for yourself for this node'
- , p : 'create a custom config for yourself '
- }, choices);
- }
-
- return cli.prompt( choices
- , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
-
- if(propValue === 't') {
- selectedinstance.local = true; return createInstanceData(selectedinstance)
- }
- if(propValue === 'i') return eNotImplemented()
- if(propValue === 'f') return eNotImplemented()
- if(propValue === 'o') return eNotImplemented()
- if(propValue === 'c') return eNotImplemented()
- if(propValue === 'p') return eNotImplemented()
-
- else process.exit();
- })
- }
-
- console.warn(e);
- throw e;
- };
-
- var successHandler = () => {
-
- };
-
- return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
- , null, selected.username || options.defaultRepoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
- .catch( (e)=>{
-
- if(Promise.resolve(e) === e) return e;
-
- e.benign = true;
- throw e;
-
- })
- };
-
- var launchpath = path.resolve(path.normalize(process.env.wd));
- var thisscriptdir = path.normalize(__dirname);
-
-
-
- var parent = path.dirname(launchpath);
- var pp = launchpath;
- var instancediscoverytasks = [];
- while(parent !== pp){
- instancediscoverytasks.push(
- ((pa)=>{
- var p = pa;
- return function(){
- return hasElxr(p).then((value)=>{
- if(value) return p
-
- throw Object.assign( new Error('Benign Failure in Batch')
- , { value : false, benign : true });
- })
- }
- })(pp)
- );
- pp = parent;
- parent = path.dirname(parent);
- }
-
- var instanceroot = null;
- var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
- if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
- else instanceroot = ir.pVal;
- return instanceroot
- }).catch(()=>{
- instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
- });
-
-
-
-
- var hasElxr = function(path, options, cb) {
-
- options = options || {};
-
-
- var tasks = [
- '/elxr'
- , '/elxr/.git'
-
- , '/elxr/' + __ALIAS__STAMP__
- ];
-
- if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value }
-
- if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value );
-
- return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value);
- };
-
- var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); };
-
- var detectfromroot = function(root){
- return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
- };
-
- var detectLocalInstances = function () {
- console.log(`launchpath = ${launchpath}`);
- console.log(`thisscriptdir = ${thisscriptdir}`);
-
-
- console.log(`instanceroot = ${instanceroot}`);
-
-
-
- var root = instanceroot;
- var detected = { root };
- var instanceoptions = [clioverrides];
-
- return hasElxr(launchpath).then( (elxrCliExists) => {
-
-
- if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
-
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else {
- if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
-
-
- console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.');
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else if (launchpath === thisscriptdir) {
-
- var parentHasElxr = hasElxrSync(launchpath + '/..');
-
- if(!parentHasElxr) {
-
- console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.');
- }
-
-
-
- if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
-
-
- instanceroot = root = path.normalize(launchpath + '/..');
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else {
-
-
- if(parentHasElxr) {
-
-
- instanceroot = root = path.normalize(launchpath + '/..');
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else {
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- }
- }
- else {
- if(elxrCliExists) {
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- }
- }
-
- instanceroot = detected.root;
- __default.root = root;
- clioverrides.root = clioverrides.root || root;
-
-
- return Promise.resolve(instanceoptions)
- })
-
- };
-
- var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } };
- if(clioverrides.reconfirm) {
- var reconfirm = getReconfirmAll();
- }
- else { var reconfirm = {}; }
-
- var shouldPrompt = function(k, possiblePrompts, target){
- return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
- || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
- || reconfirm[k])
- };
-
- var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
- return function(prompts, k, i, a){
-
-
-
-
-
- if( shouldPrompt(k, possiblePrompts, target) ) {
- delete reconfirm[k];
-
-
- prompts.push(async ()=>{
-
-
-
-
- promptables[k].choices = choices[k];
- Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
- return await target[k]
- });
- }
- delete possiblePrompts[k];
- return prompts
- }
- };
-
- var __interactive_prompts = function( target, choices, promptsfilter ){
-
- Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
-
- var interactionpoints = {
- runchoice : {
- label :
- `Choose an option :
- d) Install the default chess instance.
- => elxr i chess node_env=development --default
- n) Create your custom new instance interactively
- => elxr i {{instanceName}} node_env={{environment}}
- i) Choose an instance and environment to install
- => elxr i {{instanceName}} node_env={{environment}}
- c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
- => elxr {{cmd}} {{instanceName}} node_env={{environment}}
- h) Help
- q) Quit
- : `
- , choices : []
- , defaultchoice : 'c'
- , selectedchoice : target.runchoice
- , interpret : function(choice){
- var interpret_map = {
- d : function(){
- processedArgs._[0] = 'i';
- target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
- target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
- target.reposerver = 'https://git.bbh.org.in';
- }
- , n : function() { processedArgs._[0] = 'i'; }
- , i : function() {
- processedArgs._[0] = 'i';
-
- }
- , c : async function() {
-
- Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
- label : `Enter cmd :
- p) pull
- Default <= p
- : `
- , defaultchoice : 'pull'
- }
- ));
-
- var cmd = await target['cmd'];
- if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull'; }
- else target['cmd'] = processedArgs._[0] = cmd;
- return cmd;
- }
- , h : function() { console.log(elxr.help()); process.exit(); }
- , q : function() { process.exit(); }
- };
-
- if(Promise.resolve(choice) === choice){
- return choice.then( resolvedchoice => {
- return (interpret_map[choice] || interpret_map['c']).call(target)
- })
- }
- else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(target) )
-
-
-
-
-
-
- }
- }
- , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
- , choices : choices['instanceName'], defaultchoice : 'chess'
- , selectedchoice : target.instanceName
- }
- , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
- , choices : choices['instanceType'], defaultchoice : 'development'
- , selectedchoice : target.instanceType || 'development'
- }
- , reposerver : { label : `Enter Repo Server Base Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
- , get choices() {
- choices['reposerver'].forEach( rs => {
- var __rs = new URL(rs);
- __rs.hostname = __rs.host;
- __rs.path = '/';
- __rs.method = 'GET';
- RESTAPI.get(__rs, function(data){ rs.accessibility = 'unaccessible'; }
- , function(error){ rs.accessibility = 'unaccessible'; } );
- });
- return choices['reposerver']
- }
- , defaultchoice : 'https://git.bbh.org.in'
- , selectedchoice : target.reposerver
- }
- , 'upstream-remote' : { label : `Enter Remote Name ( <= ${target['upstream-remote'] || 'chess'} ) : `
- , get choices() {
- var reposerver = target['reposerver'];
- var remotes = [];
- var trs = target.reposervers || [];
- trs.forEach(rs => {
- if(rs.server === reposerver){
- remotes.push(remote);
-
- }
- });
- return remotes
- }
- , defaultchoice : 'userfork'
- , selectedchoice : target['upstream-remote'] || 'userfork'
-
- }
- , 'remote-type' : { label : `Enter Remote Type ( <= ${target['remote-type'] || 'public'} ) : `
- , get choices() {
- return ['public', 'private', 'github', 'unc']
- }
- , defaultchoice : 'public'
- , selectedchoice : target['remote-type'] || 'public'
-
- }
- , 'selectedremotes' : { label : `Chose Remote Names ( <= ${target['selectedremotes'] || 'chess'} ) : `
- , get choices() {
- var reposerver = target['reposerver'];
- var remotenames = [];
- Object.entries(target.remotes || []).forEach( ([rname, r]) => {
- if(r.server === reposerver && r.accessibility.find( target[ 'remote-type' ] )){
- remotes.push(rname);
-
- }
- });
-
-
- var _remotechoices = [];
- remotenames.forEach( r => {
- var __rcs = [];
- _remotechoices.forEach(rc => {
- __rcs.push( rc.concat(r) );
- });
- Array.prototype.push.apply( _remotechoices, __rcs);
- _remotechoices.push(r);
- });
-
- return _remotechoices
- }
- , defaultchoice : ['userfork-public', 'chess-public']
- , selectedchoice : target['selectedremotes'] || ['userfork-public', 'chess-public']
-
-
-
-
- }
- , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
- , choices : choices['username'], defaultchoice : 'chess', selectedchoice : target.username } }
- , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
- , choices : choices['password'], defaultchoice : '***', selectedchoice : target.password } }
- , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
- , choices : choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : target.email } }
-
- };
-
-
- function getPromptKeys() {
- if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
-
- return promptkeys
- }
- var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices);
- return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
- };
-
-
- var downloadsdir = '../Downloads';
- var prerequisites = [
- {
- shellcmd: 'git',
- name : 'git',
- url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
- , installer: 'Git-2.31.0-64-bit.exe'
- , installcmd: ['cmd', ['/c', 'start',
- '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
- , '/VERYSILENT'
-
- ]]
- , preinstallsteps: function() {
- var steps = [
- () => {
- if (!existsSync(downloadsdir + '/' + this.installer)) {
- return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
- }
- else return Promise.resolve(true)
- }
- ];
- var prompts = this.getuser(null, ()=>{
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- return Promise.resolve(true)
- });
-
- return any([any(steps), prompts])
- }
- , installsteps: function () {
- return any([this.installcmd].map(getshelltask))
- }
- , postinstallsteps: function(err, users){
- return this.getuser(null, (err, data)=>{
-
- console.dir(data);
- if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
- return username = data[0];
- }
-
- data = data || ['guest'];
- choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) );
-
- console.log('prompting in postinstallsteps');
-
- var username = 'guest';
- var email = 'guest@bbh.org.in';
- var password = '***';
-
- return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
- if(!data.find(e => e === selectedinstance.username)) {
- var steps = [
- ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
- , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
- ];
- return any(steps.map(getshelltask)).then(() => {
-
- })
- }
- else {
- return Promise.resolve(true)
- }
- });
- })
- }
- , install: function () {
- return any([ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
- }
- , verifyAndInstall : function(){
- return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
- if(exists) {
-
- return this.postinstallsteps.bind(this)()
- }
- return this.install();
- });
- }
- , getuser : function(repo, onResult){
-
- var __onResult = onResult || function(e, data){
- data = data || [];
- choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) );
-
- return data[0]
- };
-
- var globalOrLocal = '--global';
- if(repo) globalOrLocal = '--local';
-
- return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
-
- if(!result.success) return __onResult(result)
- else {
- var users = result.messages[0].trim().split('\n');
- if(users.length === 0 ||
- users.length === 1 && users[0] === 'guest') {
-
- return __onResult(result)
- }
- else {
- return __onResult(null, Array.from( new Set( users ) ) ); }
- }
- })
- .catch((e)=>{
- console.log(e);
- return __onResult(e)
- })
- }
- }
- ,
- {
- shellcmd: 'node',
- name : 'node',
- url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
- , installer: 'node-v14.16.0-x64.msi'
- , installcmd: ['MSIEXEC.exe', ['/i'
- , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
- , 'ACCEPT=YES', '/passive']]
- , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
- }
- ];
- for(var i=0; i<prerequisites.length; i++) {
- prerequisites[prerequisites[i].name] = prerequisites[i];
- }
-
- prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
-
- function ensureDirectoryExistence(filePath) {
- var dirname = path.dirname(filePath);
- if (fs.existsSync(dirname)) {
- return filePath;
- }
- ensureDirectoryExistence(dirname);
- fs.mkdirSync(dirname);
- return filePath;
- }
-
- var mainTasks = [];
- function verifyAndInstallPrerequisites() {
- var downloadtasks = [];
- var installtasks = [];
- prerequisites.forEach(preq => {
- downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
- if (exists) console.log(`${preq.shellcmd} exists`);
- else {
- console.log(`${preq.shellcmd} is not installed`);
- return preq.preinstallsteps.call(preq).then(() => {
- installtasks.push(preq.install.bind(preq));
- })
- }
- }));
- });
- return Promise.all(downloadtasks).then(() => { return any(installtasks) })
- }
-
- var getPromptableAsyncPropDescriptor = function(propName, promptable){
- return {
- get (){
- return any( promptable.dependencies || [] ).then(()=>{
-
- return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
-
- var asyncprop = Promise.resolve(propValue);
- if(promptable.interpret){
- asyncprop = promptable.interpret(propValue);
- }
-
- return asyncprop.then(
- ()=>{
- Object.defineProperty(this, propName, {
- value: propValue,
- writable: true,
- configurable : true,
- enumerable : true
- });
- return propValue
- }
- )
- })
- } )
-
- }
-
-
-
-
-
-
-
-
-
- , configurable : true
- , enumerable : true
- }
- };
-
-
-
-
- function acquirelocalinstances(selected){
-
- var chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , require(path.normalize(selected.root + '/chessinstances.js')));
- return chessinstances
- }
-
- function findlocalinstances(chessinstances, instanceoptions){
-
- ['' , '../' , '../..' ].
- earlyreduce( ( value, p, i, a )=>{
- var localinstancesPath = `${instanceroot}/${p}.elxr`;
- if(existsSync( localinstancesPath )) {
- try {
- var chessinstances = acquirelocalinstances( { localinstancesPath } );
- return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
- return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
- if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
- instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType]);
- return {
- value : chessinstances[instanceName][instanceType]
- , done : true
- };
- }
- })
- })
- }
- catch(e){
- return { }
- }
- }
- else return { }
- }
- );
- }
-
-
-
- var selectedinstance = { root : process.env.wd };
- var runconfig = null;
-
- var chessinstances = { current_run : {} };
- var promptkeys = {
- cmd : processedArgs._[0] || 'pull'
-
-
-
-
-
- };
-
-
- function createLocalChessInstance( cfg ){
-
- reconfirm = getReconfirmAll();
- var inst = {};
- var __new = Object.assign({}, __default, cfg);
- inst[cfg.node_env] = __new; return inst;
- }
-
-
- var choices = {
- 'instanceName' : []
- , 'reposerver' : []
- , 'upstream-remote' : []
- , 'instanceType' : []
- , username : ['guest', 'chessdemo', 'demo']
- };
-
- var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
-
- var instances = [];
- var reposervers = [];
- var remotes = [];
- var instanceNames = [];
- var instanceTypes = ['development', 'production'];
- Object.keys( chessinstances).forEach(instanceName => {
- if(instanceName === 'current_run') return;
- Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
- var instance = chessinstances[instanceName][node_env];
- reposervers = reposervers.concat(instance.reposervers);
- if(instance.reposerver) reposervers.push(instance.reposerver);
- instances.push(instance);
- instanceTypes.push(instance.node_env);
- instanceNames.push(instance.instanceName);
- Array.prototype.push.apply(remotes, Object.keys(instance.reposerverinstances[instance.reposerver].remotes));
- });
- });
- instances = instances.concat(detectedinstanceoptions);
-
- if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName']);
- if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName']);
- if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers']);
-
- choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) );
- choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) );
-
- choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) );
-
- return __interactive_prompts(selectedinstance, choices, promptsfilter)
- };
-
- var detection_state = {
- localInstanceDetected : false
- };
-
- const https = require('https');
- const http = require('http');
- require('path');
- require('console');
- const RESTAPI = (function(){
-
-
- function RESTAPI(){}
-
-
-
-
-
-
-
-
-
-
-
- RESTAPI.method = function(options, resolve, reject){
- var __method = function() {
- options.headers = options.headers || { 'Content-Type': 'application/json' };
- if(options.payload) {
- const data = new TextEncoder().encode( JSON.stringify(options.payload) );
- options.headers = options.headers || {
- 'Content-Type': 'application/json',
- 'Content-Length': data.length
- };
- }
- if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`;
-
- var acquirer = getHTTPorS(options);
- const req = acquirer.request(options, res => {
- if (res.statusCode < 200 || res.statusCode >= 300) {
- return reject(new Error('statusCode=' + res.statusCode));
- }
- var body = [];
-
- res.on('data', function(chunk) {
- body.push(chunk);
- });
- res.on('end', function() {
- try {
- body = JSON.parse(Buffer.concat(body).toString());
- } catch(e) {
- reject(e);
- }
- resolve(body);
- });
- });
-
- req.on('error', error => {
- console.error(error);
- reject(error);
- });
-
- if(options.payload) req.write(data);
- req.end();
- };
-
- if(!options.authenticatepost && !usertokens[options.username]) {
- RESTAPI.authenticate(options, function(tokenresp){
- usertokens[options.username] = tokenresp.sha1;
- __method();
- },
- function(err){ throw err}
- );
- }
- else __method();
- };
-
- RESTAPI.post = RESTAPI.method;
-
- var usertokens = {};
-
- RESTAPI.authenticate = function(options, resolve, reject){
- options.headers = options.headers || { 'Content-Type': 'application/json' };
-
- if(!usertokens[options.username]) {
-
-
-
- var _options = Object.assign({}, options);
-
-
- _options.method = 'POST';
- _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`;
- _options.path = `/api/v1/users/${_options.username}/tokens`;
- _options.authenticatepost = true;
-
- var postoptions = { name : _options.username };
- delete _options.username;
- delete _options.password;
- _options.payload = postoptions;
- RESTAPI.post( _options, function(tokenresp){
-
- usertokens[options.username] = tokenresp.sha1;
- resolve(tokenresp);
- },
- function(err){ reject(err); }
- );
- }
- else resolve(tokenresp.sha1);
- };
-
- RESTAPI.get = RESTAPI.post = RESTAPI.method;
-
- return RESTAPI
- })();
-
- var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; };
-
- const GITEA = (function(){
-
- function GITEA(){}
- GITEA.repository = {
- fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
-
-
-
-
-
-
- httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`;
- httpoptions.method = 'POST';
- httpoptions.payload = giteaoptions;
- return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
- }
- , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
- httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`;
- httpoptions.method = 'PATCH';
- httpoptions.payload = giteaoptions;
- return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
- }
- };
-
- GITEA.user = {
- getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
-
- httpoptions.path = `/api/v1/users/${httpoptions.username}`;
- httpoptions.method = 'GET';
- return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
- }
- };
-
- return GITEA
- })();
-
-
- const GIT = (function(){
- function GIT(){}
-
- Object.assign(GIT, {
- 'switch user'(username){
- var server = new URL(selectedinstance.reposerver);
-
- return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
- , username : selectedinstance.username, password : selectedinstance.password
- }).then(()=>{
- return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
- {
- inherit: true, shell: true,
- env: process.env
- , cwd: instanceroot + '/' + repo
- , runas: processedArgs.runas
- , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
- })
- }
- )
- .catch(e => {
- console.error(e + 'Could not switch. Probably no such user.');
- })
-
- }
- });
-
- return GIT
- })();
-
- function createInstanceData(target, source) {
-
- var sourceinstance = source || target;
- console.dir(sourceinstance);
- var args = {
- remotebase : sourceinstance.reposerver + '/chess/'
- , sourcerepo : sourceinstance.repo || 'chess-data'
- , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
- };
-
- if(sourceinstance.local) {
-
- var options = {
- inherit: true, shell: true,
- env: process.env
- , cwd : instanceroot
- , runas: processedArgs.runas
- };
- var cmdseq = [
- ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
- ];
- return any(cmdseq.map(getshelltask)).then(() => { return true })
- }
- else {
-
-
- if(source.reposerver !== target.reposerver && source.username !== target.username) {
- throw 'createInstanceData is possible only within the same repository server.'
- }
-
- var server = new URL(target.reposerver);
- return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
-
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
- return GITEA.repository.updateattributes( {
- hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
- , { name : `${args.targetrepo}`}
- )
- }
- )
- }
-
-
-
-
-
-
-
-
-
-
- }
-
-
- function createInstance(target, source) {
-
- var sourceinstance = source || target;
- console.dir(sourceinstance);
- var args = {
- remotebase : sourceinstance.reposerver + '/chess/'
- , sourcerepo : sourceinstance.repo || 'chess-config'
- , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
- };
-
- if(sourceinstance.local) {
-
- var options = {
- inherit: true, shell: true,
- env: process.env
- , cwd : instanceroot
- , runas: processedArgs.runas
- };
- var cmdseq = [
- ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
- ];
- return any(cmdseq.map(getshelltask)).then(() => { return true })
- }
- else {
-
-
- if(source.reposerver !== target.reposerver && source.username !== target.username) {
- throw 'createInstance is possible only within the same repository server.'
- }
-
- var server = new URL(target.reposerver);
- return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
-
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
- return GITEA.repository.updateattributes( {
- hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
- , { name : `${args.targetrepo}`}
- )
- }
- )
- }
-
-
-
-
-
-
-
-
-
-
- }
- function initinstances(selected_overrides) {
- var root = selected_overrides.root;
-
- var instanceName = selected_overrides.instanceName
- || clioverrides.instanceName
-
- || chessinstances.current_run.instanceName;
-
- var node_env = selected_overrides.node_env
- || clioverrides.node_env
-
- || chessinstances.current_run.node_env;
-
- var reposerver = selected_overrides.reposerver
- || clioverrides.reposerver
-
- || chessinstances.current_run.reposerver;
-
- if(!instanceName) {
- promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
- promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
- promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
- }
-
- if(!node_env) {
- promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
- promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
- }
-
- if(!reposerver) {
- promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
- }
-
- chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
- instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver } );
- chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root };
-
- if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
- 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
- }
-
-
-
-
-
- if(selected_overrides.node_env === undefined) delete selected_overrides.node_env;
-
- selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , __default
- , chessinstances[instanceName][node_env]
- , clioverrides
- , selected_overrides
-
- );
-
-
-
-
-
-
-
-
-
- if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
- }
- if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
- }
-
-
-
- chessinstances[instanceName][node_env] = selectedinstance;
-
- cacheWriteInstanceConfig(chessinstances);
-
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0];
-
- return chessinstances
- }
-
- var skipprereqs = {};
- var maintask = () => {
-
-
- processedArgs._[0] === processedArgs._[0] || 'pull';
-
-
- if(!noprerequisites[processedArgs._[0]]
- && !skipprereqs[processedArgs._[0]]
- ) {
- return prerequisites.git.verifyAndInstall().then(()=>{
- var inittasks = [];
- var commontask = () => { preworkerconfig(); return elxrworker() };
- if(!detection_state.localInstanceDetected) {
- var t1 = ()=>{ return createInstance(selectedinstance) };
- t1.statuslog = statuslog;
- var specifictask = shell_verse.getNonElevatedTask(t1);
- }
- else {
- var t2 = ()=>{ return acquireConfig(selectedinstance) };
- t2.statuslog = statuslog;
- var specifictask = shell_verse.getNonElevatedTask(t2);
- }
- inittasks.push( specifictask().catch((err) => {
- console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
- console.error(err);
- }).then( commontask )
-
-
-
-
-
- );
-
- return any(inittasks)
- })
- }
- else {
- console.log('cmd has no preqs or has been configured to skip preqs');
- preworkerconfig();
- return elxrworker()
- }
-
- };
-
- function generateDependencies(){
-
-
-
- ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
- fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
-
-
- var downloadbatch =
- `::**************************************************************************
- :Download_ <url> <File>
- Powershell.exe ^
- $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
- [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
- (New-Object System.Net.WebClient).DownloadFile('%1','%2')
- exit /b
- ::**************************************************************************`;
- fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
-
-
- var windowselevate =
- `
- <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
- <script language="vbscript">
- document.title = "elxr control panel"
- self.ResizeTo 200,600
-
- Sub Window_Onload
- self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
- End Sub
-
- Set objShell = CreateObject("WScript.Shell")
- Set objENV = objShell.Environment("Process")
- dim NODE_ENV
- NODE_ENV = objENV("NODE_ENV")
-
- </script>
-
- <script language="javascript">
- //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
- // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
- // alert(windowselevate.commandLine)
- var args = windowselevate.commandLine.split('"').slice(3);
- // alert(args)
- var processedArgs = { _ : [] }
- var namedArgs = [];
- namedArgs.push('--wd=' + objENV('wd'))
- // alert(namedArgs)
- for(var item in args){
- if(args[item].charAt(0) === '-'){
- namedArgs.push(args[item])
- var split = args[item].split('=');
- processedArgs[split[0].slice(2)] = split[1] || true;
- }
- else processedArgs._.push(args[item]);
- }
- // args = args.forEach(function(item){ })
- // alert('processedArgs._ : ' + processedArgs._);
- // alert(processedArgs.runas);
- // alert(objENV('wd'))
- // PB : TODO -- Convert all the cli args back to string.
- // __filename will sure we are launhed using the same entry point.
- var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
- var shell = new ActiveXObject('shell.application');
- // alert('launching node privilged. ' + processedArgs['nodepath'])
- // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
- // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
- // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
- // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
- shell.ShellExecute('node', cargs, '', 'runas', 1);
- // alert('/k node ' + cargs + '')
- // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
- var fso = new ActiveXObject('Scripting.FileSystemObject');
-
- window.onload = function() {
- document.body.style.backgroundColor = 'black';
- document.body.style.fontFamily = 'arial';
- var log = document.createElement('div');
- log.innerHTML='Please Wait';
- function l(msg){ log.innerHTML+= msg; };
- log.style.color = 'blue';
- log.style.width = '95%';
- log.id = 'log';
- document.body.appendChild(log);
-
- l('<Br/>Current config : ')
- l('<Br/>NODE_ENV = ' + NODE_ENV)
- l('<Br/>cmd = ' + processedArgs._[0])
- processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
- l('<Br/><Br/>')
- // alert(fso.GetAbsolutePathName("."))
-
- var timer = function(){
- l('.');
- if(fso.FileExists("run.done")) {
- fso.DeleteFile('run.done')
- close();
- }
- else window.setTimeout(timer, 1000);
- };
- window.setTimeout(timer, 3000);
- };
-
- </script>
- </html>
-
- `;
- fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
- }
-
- var startElxr = function() {
- const retaincount = 2;
- var min = runtimestamp;
- var collect = [];
-
- if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
- reconfirm = getReconfirmAll();
- }
-
- return detectLocalInstances().then((detectedinstanceoptions)=>{
-
- detectedinstanceoptions.splice(0,0, __default);
-
- var cmdinstance = cmds[clioverrides.cmd];
- cmdinstance.getPossiblePrompts();
- selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env;
-
- selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , ...detectedinstanceoptions.slice(-2), promptkeys );
-
-
-
-
-
-
- console.dir(selectedinstance);
- try {
-
- chessinstances = acquirelocalinstances(selectedinstance);
- findlocalinstances(chessinstances, detectedinstanceoptions);
- initinstances(selectedinstance);
- var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
- var inst = initinstances(selectedinstance);
- detection_state.localInstanceDetected = true;
- return inst;
- });
- }
- catch (e) {
-
- var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
- return initinstances(selectedinstance)
- });
-
-
-
-
-
-
- todo = todo.then(() => {
- try {
- chessinstances = acquirelocalinstances(selectedinstance);
- findlocalinstances(chessinstances, detectedinstanceoptions);
- detectedinstanceoptions.splice(0,0, __default);
- initinstances(selectedinstance);
- detection_state.localInstanceDetected = true;
- }
- catch (e) {
-
- console.log('No local instances config found in current root = ' + selectedinstance.root);
- console.log('A config will be createed with the instance and environment chosen...');
-
-
-
-
- detection_state.localInstanceDetected = false;
- return selectedinstance
- }
- });
- }
- return todo.then( ()=>{
-
-
- var __repo_manifest = (require(path.normalize(instanceroot + '/elxr/repo-manifest.js')))(
- 'defaultmanifest'
- , { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' }
- );
-
- __default = Object.assign(__default, __repo_manifest, {
-
- repos : (()=> {
- var __repos = [
- { repo : 'ember-masonry-grid' }
- , { repo : 'bbhverse' }
- , { repo : 'clientverse' }
- , { repo : 'serververse' }
- , { repo : 'elxr' }
- , { repo : 'ember-searchable-select' }
- , { repo : 'loopback-component-jsonapi' }
- , { repo : 'loopback-jsonapi-model-serializer' }
- , { repo : 'loopback-connector-mysql' }
- , { repo : 'loopback-connector-ds' }
-
- , { repo : 'ember-service-worker' }
- , { repo : 'ember-service-worker-asset-cache' }
- , { repo : 'ember-service-worker-cache-fallback' }
- , { repo : 'ember-service-worker-index' }
- , { repo : 'ember-sw-client-route' }
- , { repo : 'global-this' }
- ];
- Array.prototype.push.apply( __repos, __repo_manifest.repos);
- return __repos;
- })()
-
- , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
- , exludeMergeRepos : { }
- });
-
- initinstances(selectedinstance);
- return selectedinstance
- })
-
-
- })
- .then(()=>{
- runconfig = { NODE_ENV: selectedinstance.node_env };
- try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')); } catch (e) { }
- generateDependencies();
- if(noprerequisites[processedArgs._[0]]
- || skipprereqs[processedArgs._[0]]
- ) {
- return elxrworker()
- }
-
- var neTask = ()=>{
- ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`);
-
- return dirs( (dir)=>{
- var matches = /run-(.*)/gm.exec(dir.name);
- if(matches) {
- if(+(matches[1]) < min) {
- min = matches[1];
- collect.splice( 0, 0, matches[1] );
- }
- else collect.push(matches[1]);
- }
- return Promise.resolve(collect);
- }, `${selectedinstance.root}/.elxr` )
- .then(()=>{
-
- if(collect.length > retaincount) {
-
- var asyncs = [];
- while((collect.length - asyncs.length) > retaincount) {
- asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
- }
- return Promise.all(asyncs)
- }
- else return true
- })
- .catch(e => {
- })
- };
- neTask.statuslog = statuslog;
-
- shell_verse.getNonElevatedTask( neTask )();
-
- var commonTask = ()=>{
- verifyAndInstallPrerequisites.statuslog = statuslog;
- mainTasks.push(verifyAndInstallPrerequisites);
- mainTasks.push(maintask);
- return any(mainTasks);
- };
- return commonTask()
- })
- };
-
- var __default = {};
-
-
- shell_verse.acquireElevationState().then((elevationstate) => {
- return detectInstanceRoot.then(()=>{
- var cmdobj = cmds[clioverrides.cmd];
- return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
- if(cmdobj.independentcmd) {
- if(cmdobj.requiresElevation) {
- return cmdobj.cmdFn()
- }
- else return cmdobj.cmdFn()
- }
- else return startElxr()
- })
- .catch(e => {
- if(typeof e === 'symbol') console.log('error : ' + 'symbol');
- else console.log('error : ' + e);
- })
- })
- });
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
|