|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712 |
- 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)
- var cli = require('./cliverse')
- var nodeShellExec = cli.nodeShellExec;
- var chalk = require('chalk')
-
-
- const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
- const runtimestamp = (new Date()).getTime();
- function getVersion() { return BUILD_VERSION; }
- console.log(getVersion());
-
- // 'use strict';
-
- // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
-
- // PB : TODO --
- // runas bypass non elevated tasks when we request privelege
- // runas message is always error needs to be fixed.
- // runas wait needs to be parallelized.
- // suppress elevation check error messages
- // support runas lauched directly from shell.
- // pass in environment in hta to shellexecute.
-
- // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
- (function () {
- "use strict";
- 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);
- // function *earlyReduceGenerator(acc, v, i, a) {
- 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 fs = require('fs')
-
- const cliargs = utils.cliargs;
- const processedArgs = cliargs(process.argv.slice(2));
- console.dir(processedArgs)
- // PB : TODO -- defaults for valuless arguments if passed.
- // Object.keys(processedArgs).forEach(a=>{
- // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
-
- // }
- // })
-
- var clioverrides = { }
- processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
- 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;
-
- Object.keys(clioverrides).forEach( prop => { })
-
- var globSync = require('glob').sync;
-
- var ENV = Object.assign({}, process.env); // Shallow clone it.
-
- const { readdir } = require("fs").promises
-
- // Directory shallow walk and do perform on each dir.
- const dirs = async (perform, path) => {
- for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
- if (dir.isDirectory()) perform(dir)
- }
- }
-
- var getShellTask = (command, args, options) => {
- options = options || {}
- var callshell = command === 'rm' ? callgitbashtask : callsheltask;
- 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 => {
- // Ignore. Not a major error.
- })
- }
- else return p;
- }
- }
-
- var callsheltask = (args) => {
- return args[0] === 'rm' ? callgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
- var callgitbashtask = (args) => { return () => {
- return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
- }
-
- var getTaskCheckExists = (command, options) => {
- options = options || {}
- return () => {
- var p = nodeShellExec.apply(null, ['where', [command]])
- if (options.ignorefailures) {
- return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
- return false;
- })
- }
- else return p.then(() => { return true });
- }
- }
-
- var getTaskWithElevation = function(tasdef){
- return ()=>{
- if (__isElevated) {
- return tasdef.elevatedpulltasks().then(()=>{
- // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
- fs.writeFileSync('run.done', 'success')
- }).catch(e=>{
- fs.writeFileSync('run.done', 'failure')
- });
- }
- else {
- // PB : TODO -- Rename op['runas'] to 'elevate'
-
- var __runasresult = null;
-
- return op['runas']().then((r) => { return __runasresult = r; })
- .catch((e) => {
- console.error(e)
- })
- .finally(() => {
- if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
- if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
- })
- }
- }
- }
-
- var getTaskWithoutElevation = function(tasdef){
- return ()=>{
- if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
- else Promise.resolve(true)
- }
- }
-
- 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: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
- return cmd
- }
- }
-
- var getPullCmd = (repo, branch) => {
- // console.log(useGitPull)var getPullCmd = (repo, branch) => {
- // console.log(useGitPull)
-
- // var pullCmd = [gitInstallDir
- // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + 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 origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
- }
- else {
- // console.warn('No branch was specified detecting from working client.')
- // First check if working client exits.
- // if (existsSync(instanceroot + '/' + repo)) {
- var pullCmd = gitops.getdiscoverbranchcmd(repo)
- // }
- // else performpull
- }
- // var pullCmd = ['pullall', [], { cwd : repo }]
- if (useGitPull) pullCmd = ['git', ['pull'], {
- inherit: true, shell: true,
- cwd: instanceroot + '/' + repo
- // , env: process.env
- , runas: processedArgs.runas
- , title: `git pull ${repo}`
- }]
- return pullCmd
- }
-
- var performPull = (repo, branch) => {
- // PB : TODO -- Handle no branch passed in case.
- // if(!branch) { throw 'No branch specified' }
-
- if (existsSync(instanceroot + '/' + repo)) {
- var branchprint = branch ? ' branch :' + branch : '';
- console.log('pulling ' + instanceroot + '/' + repo + branchprint )
- return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
- }
- else statuslog.statuslog(null, repo)
- return true;
- })
- .catch((e) => {
- e.repo = repo;
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
- }
- else statuslog.statuslog(e); console.error(e)
- })
- }
- else {
- console.log('cloning ' + repo)
- // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
- return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
- {
- inherit: true, shell: true,
- env: process.env
- , cwd : instanceroot
- , runas: processedArgs.runas
- }).catch((e) => {
- throw e;
- }).then(() => {
-
- return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
- {
- inherit: true, shell: true,
- env: process.env
- , cwd: instanceroot + '/' + repo
- , runas: processedArgs.runas
- , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
- })
- .then(() => {
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
- }
- else statuslog.statuslog(null, repo)
- })
- .catch((e) => {
- e.repo = repo;
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
- }
- else statuslog.statuslog(e);
- })
- })
- .catch(e => {
- e.repo = repo;
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
- }
- else statuslog.statuslog(e);
- })
- }
- }
-
- // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
- // -- Currently workaround is to always run from a non-elevated shell.
- var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
- var acquireElevationState = () => {
- if (__isElevated === null) {
- return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
- inherit: true
- // , shell: true
- , stdio: 'ignore'
- , env: process.env
- , title: `check privileged execution mode using "fsutil dirty query C:"`
- }).then((exitcode) => {
- console.log('Elevated')
- __isElevated = true;
- return true;
- }).catch(() => {
- __isElevated = false;
- console.log('Not Elevated');
- return false;
- });
- }
- else return Promise.resolve(__isElevated);
- }
-
-
- var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
- var defaultRepoOwner = 'chess';
- var elevatedRunasRepos = null
- var gitRepos = null
-
- // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
-
-
- // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
-
- var dbForLabel = function (label) {
- var dbsForLabel = {
- devmysql: 'mysql'
- , development: 'mssql'
- , production: 'mssql'
- }
- return dbsForLabel[label] || 'mysql'
- }
-
- // SAM : TODO Use nodeshellexec where to detect git installation dir
- var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
- // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
- // Relevant git repos
- var exludeMergeRepos = [];
- var useGitPull = processedArgs.useGitPull || false;
- var configPromise = null
-
- // elxr cli operations
- var op = {
- 'h': () => { console.log(elxr.help()); return '-h' }
- , 'clean' : () => {
- // delete all node_module folders and links.
- var tasklist = [];
- dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
- return Promise.all(tasklist)
- }
- , 'undefined': () => { return op.h(); }
- , 'reset': () => {
-
- // Reset NPM packages semver so major versions can be updated.
-
- 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 = gitRepos;
- repos.forEach(wipeDependencies)
- // if (require.main === module) {
- // } else {
- // module.exports = 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
- })
- })
- })
- }
- , 'runas': () => {
-
- if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
-
- console.log('Testing Elevation')
-
- if (__isElevated) {
- try {
- op[processedArgs.label || processedArgs._[0] || 'h']()
- }
- catch (e) {
- console.error('Error Invalid command : ' + e)
- fs.writeFileSync('run.done', 'error')
- }
- finally {
- }
- }
- else {
- console.log('Requesting Elevated Privileges');
- // Wait for the runas to complete before we read it.
- try {
- fs.unlinkSync('run.done')
- fs.unlinkSync('run.log')
- }
- catch (e) { } //Ignore
-
- // Find node path to send to hta.
- return nodeShellExec('where', ['node']).then(r => {
- var namedArgs = [];
- console.log('result : ' + JSON.stringify(r))
- Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
- // PB : TODO -- Convert all the cli args back to string.
- var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
- args.push('--nodepath=' + r[r.length - 1])
- if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
- if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
-
- return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
- , {
- inherit: true
- , shell: true
- , env: ENV
- , runas: 'self'
- , title: `runas`
- }
- ).then(() => {
- // runas returned.
- try {
- // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
- var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
- runaslog.forEach((logEntry) => {
- statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
- logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
- })
- }
- catch (e) {
- // We must have a runas log
- statuslog.statuslog(e)
- console.error('Run log error probably was not created by runas : ' + e)
- }
- })
- .catch(err => console.error('Elevation failed : ' + err));
- })
-
- }
- }
- , 'push': () => {
- if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
- // init remote bare from local
- // pushandinitremotebare
- // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
- // connect to repo server -- net use 172.16.0.27
- // cd 172.16.0.27/repos/
- // mkdir repo.git
- // cd repo.git
- // git init --bare
- // cd localrepo
- // git remote rename origin githubclone
- // git remote add origin //172.16.0.27/repos/repo.git
- // git push origin master
-
- var repo = processedArgs._[1];
-
- var sequentialTaskShellCommands = [];
- if (!existsSync(`Z:/${repo}.git`)) {
- sequentialTaskShellCommands = [
- // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
- // inherit : true, shell: true
- // , env: process.env
- // }]
- ['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
- }]
- // PB : TODO -- Do this conditionally only...
- , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
- console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
- }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
- , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
- // PB : TODO -- If threre is a gitbubclone origin
- // Set the master to pull from the local 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])
- // throw 'done'
- }
- }
-
- sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
- // console.dir(sequentialTaskShellCommands);
-
- var tasks = [];
- sequentialTaskShellCommands.forEach(shellcmd => {
- // console.log(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' })
- }
- // git remote equivalents...
- // git branch --set-upstream-to=elixir-unc/master master
- // git push --set-upstream elixir-unc branch..
- , 'remote': (args) => {
-
- // Subcommands!
- if(!processedArgs.v) return false; // Only -v is supported presently..
-
- var serial_perform = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
-
- return [
- ['git', ['remote', '-v'], options]
- ]
- }
-
- var x = (args) => {
- var tasq = () => {
- // console.log(args)
- return nodeShellExec.apply(null, args).catch(e => {
- // We continue on failure.
- 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) => {
- // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
- var __args = {
- remotename : args.remotename || processedArgs._[2]
- , url : args.url || processedArgs._[3]
- }
-
- // pushable doesn't mean the remote doesn't support being pushed to.
- // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
- // PB : TODO -- change this to enablepushing.
- // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
- var pushable = processedArgs.pushable || false;
- remotename = __args.remotename
- url = __args.url
- var serial_perform_git_seturl = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
- // console.log(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 = () => {
- // console.log(args)
- return nodeShellExec.apply(null, args).catch(e => {
- // We continue on failure.
- 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) => {
- // console.log('Failed : ' + dir.name)
- })
- }
-
- dirs(perform_git_seturl)
- }
- , 'reset' : ()=>{
- // Reset the whole installation pertaining to this elxr folder.
-
- }
- , 'remote add': (args) => {
- // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
- // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
- // That explicitly has a remote name prefix.
- // git branch branch_name --set-upstream-to your_new_remote/branch_name
- // git branch branch_name -u your_new_remote/branch_name -- older versions
- // git branch -vv -- Detect which branch are we tracking.
- // default upstream should be users own fork.
- // Also need alias branches to
- // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
- // probably git merge from all remotes... and relevant branches...
- // alias pushall='for i in `git remote`; do git push $i; done;'
- // alias pullall='for i in `git remote`; do git pull $i; done;'
- // args === processedArgs ? args = {} : null;
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- }
-
- var remotename = __args.remotename
- var url = __args.url
- var branch = __args.branch
-
- var pushable = processedArgs.pushable || false;
-
-
- var serial_perform_git_add = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
- // console.log(repo)
- if (pushable) {
- return [
- ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
- , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
- ]
- }
- else {
-
- return [
- ['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 }]
- , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
- ]
- }
-
- }
- var x = (args) => {
- return () => {
- // console.log(args)
- return nodeShellExec.apply(null, args)
- }
- // return Promise.resolve(true)
- }
- var perform_git_add = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- // console.log(code)
- 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) => {
- any(serial_perform_git_add(dir.name).map(x))
- })
- }
- // else console.log('Skipped : Not a Git Repo : ' + dir.name)
- }).catch((e) => {
- console.log('Failed : ' + dir.name)
- })
- }
-
- const { readdir } = require("fs").promises
-
- dirs(perform_git_add)
- }
- , 'remote remove': (args) => {
-
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- }
- var remotename = __args.remotename
- var serial_perform_git_remove = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
- // console.log(repo)
- return [
- ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
- ]
- }
- var x = (args) => {
- return () => {
- // console.log(args)
- return nodeShellExec.apply(null, args)
- }
- // return Promise.resolve(true)
- }
- var perform_git_remove = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- // console.log(code)
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- any(serial_perform_git_remove(dir.name).map(x))
- })
- .catch((e) => {
- console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
- })
- }
- // else console.log('Skipped : Not a Git Repo : ' + dir.name)
- }).catch((e) => {
- // console.log('Failed : ' + dir.name)
- })
- }
-
- const { readdir } = require("fs").promises
-
- dirs(perform_git_remove)
- }
- , 'init-gitea': (user) => {
- user = user || processedArgs._[1]
- if (!user) throw 'User name required'
- var serial_perform_init_gitea = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
- // console.log(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', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
- ]
- }
- var x = (args) => {
- return () => {
- // console.log(args)
- return nodeShellExec.apply(null, args)
- }
- // return Promise.resolve(true)
- }
- var perform_init_gitea = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- // console.log(code)
- 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) => {
- any(serial_perform_init_gitea(dir.name).map(x))
- })
- }
- // else console.log('Skipped : Not a Git Repo : ' + dir.name)
- }).catch((e) => {
- // console.log('Failed : ' + dir.name)
- })
- }
-
- const { readdir } = require("fs").promises
-
- dirs(perform_init_gitea)
- }
- , 'syncmaster': (label) => {
- // Usage :
- // elxr pull -- Defaults to run config
-
- var env = Object.assign({}, process.env); // Shallow clone it.
- // console.dir(env)
- console.log('Running exlr pull : ' + path.dirname(__dirname))
-
- if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
- if (__isElevated) {
- return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
- fs.writeFileSync('run.done', 'success')
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
- }
- else return op['runas']()
- }
-
- , 'repo-relocate' : function(args){
- // relocate a subfolder in source repo to same subfolder in target repo with history.
-
- 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}`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- }
-
- return op['repo-split'](args).then(()=>{
- return op['repo-merge'](args).then(()=>{
-
- // cleanup folder from source.
- var cmdseq = [
- ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
- // commits have to intentional...
- // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
- ]
-
- return any(cmdseq.map(callsheltask))
- })
- }).catch(e=>{console.error(e)})
- }
-
- , 'repo-split' : function(args) {
-
- // https://gist.github.com/smdabdoub/17065c348289158277b5
-
- /**
- * Eg : folder, remotebase, sourcerepo, targetrepo
- * args.folder = 'server'
- * args.remotebase = 'https://git.bbh/chess/'
- * args.sourcerepo = 'client'
- * args.targetrepo = 'elixir-server'
- */
-
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , sourcerepo : 'client'
- , targetrepo : 'elixir-server'
- }
-
- var options = { cwd: `${instanceroot}/relocate`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- }
-
- var cmdseq = [
- // create a temporary working dir in current folder where we started execution.
- ['mkdir', [ '-p', '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(callsheltask)).then(() => {
- // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
- // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
- // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
- // , ['mkdir', [`${args.folder}`], sourcerepooptions]
- // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
- // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
-
-
- // subtree split and filter-branch are options. We currently use repo-filter.
- return op['filter-repo'](args)
- }).catch(e=>{console.error(e); throw 'failed'})
- }
-
- , 'repo-merge' : function(args) {
- // Merge source repo into target repo
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , sourcerepo : 'client'
- , targetrepo : 'elixir-server'
- }
-
- var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- }
- var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- }
-
- var cmdseq = [
- ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
- , targetrepooptions ]
- // , ['git', ['push', targetrepooptions ] // manual push for now..
- ]
- return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e)})
- }
-
- , 'filter-repo' : function(args){
- // Merge source repo into target repo
- 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 checkout -b feature/merge-old-project
- // git remote add src-project ../src-project
- ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
- ]
- return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
- }
-
- , 'filter-branch' : function(preservefolder, repo){
- // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
- // git subtree split -P <name-of-folder> -b <name-of-new-branch>
- // Preserve a specific folder.
- // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
- /*
- git clone repo reposplit
- git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
- git remote rm origin
- */
-
- throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
- }
-
- // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
- // // Merge repo2 into a subfolder in repo1
- // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
- // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
- // /*
- // cd repo1
- // git remote add -f tempmergesource ../{{mergesource}}/.git
- // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
- // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
- // git commit
-
- // // Repair History
- // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
-
- // #!/usr/bin/env bash
-
- // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
- // last=038e26e21bd60fa265d6637261f3bc918780d2e8
- // subdir=server
-
- // git filter-branch --tree-filter '
- // first='"$first"'
- // last='"$last"'
-
- // subdir='"$subdir"'
- // log_file=/tmp/filter.log
-
- // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
-
- // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
- // echo "=== $GIT_COMMIT: making changes"
- // files=$(git ls-tree --name-only $GIT_COMMIT)
- // mkdir -p $subdir
- // for i in $files; do
- // mv $i $subdir || echo "ERR: mv $i $subdir failed"
- // done
- // else
- // echo "=== $GIT_COMMIT: ignoring"
- // fi \
- // >> $log_file
-
- // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
-
- // status=0 # tell tree-filter never to fail
- // '
-
- // git remote rm tempmergesource
- // */
- // // better alternative for history
- // /**
- // *
- // git clone git@server.com:old-project.git
- // git clone git@server.com:new-project.git
-
- // cd old-project
- // mkdir old-project
- // git mv !(old-project) old-project
- // ls -la and gt mv hidden files ....
- // git commit -a -S -m “Moving old project into its own subdirectory”
-
- // cd ../new-project
- // git remote add old-project ../old-project
- // git fetch old-project
- // git checkout -b feature/merge-old-project
- // git merge -S --allow-unrelated-histories old-project/master
- // git push origin feature/merge-old-project
- // git remote rm old-project
- // */
-
- // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
- // }
-
- , 'pull' : (label) => {
- // Usage :
- // elxr pull -- Defaults to run config
-
- return elxr.getpulltask(selectedinstance)()
- }
- , 'isInstalled': () => {
- return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
- console.log(processedArgs._[1] + ' exists.')
- return true;
- });
- }
- , 'i' : () => {
-
- var tasks = []
- // tasks.push(op['pull']);
- tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
- tasks.push(op['use'])
- if (!__isElevated) {
- tasks.push(op['npmi'])
- }
-
- // var tasksdefs = [
- // ['elxr', ['pull']]
- // , ['elxr', ['use', 'elixir']]
- // , ['elxr', ['npmi']]
- // ]
-
-
- // tasksdefs.forEach(tasksdef=>{
- // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
- // })
-
- return any(tasks);
-
- }
- , 'npmi': () => {
- var tasks = [];
-
- // Build fails without babel...
- tasks.push(getShellTask(
- 'npm',[ 'i', '-g', 'babel-cli' ]
- ) )
-
- var npmbuildrepos = ['loopback-jsonapi-model-serializer']
- npmbuildrepos = []
- 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)
- })
- })
- })
-
- any(tasks).then(() => {
-
- gitRepos.push('client/server');
- gitRepos = gitRepos.concat(elevatedRunasRepos);
-
- // gitRepos = [
- // // 'bbhverse', 'serververse', 'elixir-server',
- // // 'clientverse',
- // 'client'
- // ];
- var rmtasks = []
- var repotasks = []
- var env = Object.assign({}, process.env)
- delete env.NODE_ENV
- gitRepos.forEach(repodef => {
-
- rmtasks.push(
- // () => {
- // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
- // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
- (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;
- })
- }
- })
-
-
- // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
- // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
- // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
- // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
- // Second time try also doesnt work.
- // repotasks.push(
- // () => {
- // var env = Object.assign({}, process.env)
- // delete env.NODE_ENV
- // console.log(`--------------------second time npm i for client--------------------`)
- // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
- // // return nodeShellExec('npm', ['i --force'], {
- // inherit: true, shell: true
- // , cwd: instanceroot + '/' + 'client'
- // , env
- // , title: `npm i for client`
- // }).then(Tasq.then).catch(Tasq.catch)
- // })
-
- var bowerRepos = [{ repo : 'client'}]
- bowerRepos.forEach(repodef => {
- repotasks.push(() => {
- console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
- // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
- 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;
- })
- })
- // console.log('rmtasks.length : ' + rmtasks.length)
- return Promise.all(rmtasks).then(() => any(repotasks));
- }).catch(e => {
-
- }).finally(statuslog.finally)
-
- }
- , 'start': (label) => {
- console.log('Starting Elixir Server.');
- var env = Object.assign({}, process.env); // Shallow clone it.
- // console.dir(env)
- env.NODE_ENV = process.env.NODE_ENV || 'development';
- env.DEBUG = 'loopback:connector:' + dbForLabel(label)
- var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
- // cmd = 'node'
- cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
- var childPromise = nodeShellExec(...cmd, {
- // inherit : true,
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + '/' + 'elixir-server'
- , env: env
- })
-
- var child = childPromise.process;
- if (typeof child.pid !== 'undefined') {
- console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
- fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
- encoding: 'utf8'
- })
- }
-
- // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
- // inherit : true,
- // shell: true, detached: true,
- // cwd : 'qms/server',
- // env: env,
- // shell : true
- // })
-
- // nodeShellExec('ember', ['s'], {
- // // inherit : true,
- // shell: true, detached: true,
- // cwd : 'client/',
- // env: env
- // })
- console.log('Starting Elixir Client Host.');
- var cmd = ['ember', ['s']]
- var childPromise = nodeShellExec(...cmd, {
- // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
- // PB : TODO -- ember debugging.
- // inherit : true,
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + '/' + 'client'
- , env: env
- })
- // .catch(e=>console.error(e))
-
- 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('.client.server.pid', {
- encoding: 'utf8'
- })
- fs.unlinkSync('.client.server.pid')
- console.log(serverPid)
- kill(serverPid)
- }
- , 'model' : () => {
- if (__isElevated) {
- 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')
- })
- }
- else return op['runas']()
- }
- , 'use' : () => {
- // use a certain named instance.
- // Eg :
- // 1) elxr use elixir
- // 2) elxr use cihsr
- // If environment is not specified defaults to development.
- // 1) NODE=test elxr use elixir
-
- /*// Steps
- 1) Delete Config and Data symlinks
- 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
- 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
- 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
- 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
- */
- var runconfig = { NODE_ENV: selectedinstance.node_env }
- try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
- // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
- if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !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') }
- return
- }
-
- var tasks = [
- () => {
- if (existsSync('config')) {
- var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
- ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
- return p;
- }
- else return Promise.resolve(true);
- },
- () => {
- if (existsSync('data')) {
- var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
- ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
- return p;
- }
- else return Promise.resolve(true);
- },
- ];
- 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) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
- // console.log(process.env.cwd)
- fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
-
- // Maps an environment to a branch. Not required if the branch is appropriately named.
- var checkoutMap = { 'development': 'master' }
-
- 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(repo)).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;
- // cant use git checkout -b it fails when branch already exists.
- 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], {
- // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
- // inherit : true, shell: true,
- cwd: instanceroot + '/' + def.repo
- // , stdio : ignore // Use when we want to silence output completely.
- , 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 enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
- // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
-
- var elevatedqueue = [];
- var enqueueOnce = (queue, task, def) => {
- var found = queue.find(element => {
- var keys = Object.keys( element )
- for(var k=0; k < keys.length; k++) {
- if(element[keys[k]] !== def[k]) return false;
- }
- })
- queue.push(function(){ return task(this)}.bind(def));
- }
- var enqueue = (queue, task, def) => {
- queue.push(function(){ return task(def)}.bind(def));
- }
-
- var mergeSources = {
- 'development': null,
- 'test': 'master',
- 'production': 'master'
- }
- var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
-
- // Checkout is reduced to pull provided the current branch is the targetbranch
- if(branch === mergesource) performCheckout = (def) => {
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
- return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
-
- if(branch === __branch) return performCloneAndCheckout(def)
- return performPullOrCloneForBranch(def)
- })
- .catch((e) => { console.error(e); return { error: true, message: repo } })
- }
- // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
-
- var performPullAll = (def) => {
- if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
- return nodeShellExec('git', ['pull', '--all'], {
- // inherit : true, shell: true,
- 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) }
-
- // var performRepoOperation = function(def) {
- // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
- // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
- // }
-
- return any(tasks).then(() => {
- var pr = Promise.resolve(true)
- if (!__isElevated) {
- pr = op['runas']()
- return pr.then(()=>{
-
- //target is the env is we specify in elxr use command. Default is dev
- //Switch to target branch
- return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
- // pull or clone target branch
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullAll(repo)))
- })
- // switch to source branch
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
- return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
- })
- //Pull on merge source branch
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullAll(repo)))
- })
- //Switch to target branch
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
- })
- .then( //Merge source branch to target branch
- () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
- })
- })
- }
- else {
- tasks = [
- () => {
- // Use junctions to avoid npm package issues
- var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
- inherit: true, shell: true
- , cwd : instanceroot
- , env: process.env
- }).catch((e) => { console.error(e) })
- return p;
- }
- ];
- if (processedArgs._[1]) {
- tasks = tasks.concat(
- [
- () => {
- var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
- inherit: true, shell: true
- , cwd : instanceroot
- , env: process.env
- }).catch((e) => { console.error(e) })
- return p;
- }
- ]
- )
- }
-
- return any(tasks).then(()=>{
- // checkout target branch
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
- // pull or clone target branch
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
- })
- // switch to source branch
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
- })
- //Pull on merge source branch
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
- })
- //Switch to target branch
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
- })
- .then( //Merge source branch to target branch
- () => {
- 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')
- })
- })
- }
-
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
-
- // Antibiotic stewardship program.
- // 1st use is fine.
- // Max vials dispense
- // 2nd use Pharmacy needs justification Form.
- // Approval after a certain period of time.
- }
- , 'g': () => {
- if (processedArgs.h) {
-
- console.log('elxr g [modelname] => generate a model named [modelname]');
- console.log('elxr g => regenerate all known models');
- return
- }
- // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
- // console.log('Starting directory: ' + process.cwd());
- // try {
- // child = child.on('close', () => { process.chdir(label) } );
- // console.log('New directory: ' + process.cwd());
- // }
- // catch (err) {
- // console.log('chdir: ' + err);
- // }
- // child.on('close', function(){
- // var options = {
- // shell : true
- // , inherit : true
- // // , cwd : '' + process.cwd
- // // , env : process.env
- // };
- // nodeShellExec('git', ['init'], { inherit : true});
- if (0) {
- // PB : TODO -- Special google chrome profile for tests etc.
- nodeShellExec('pwd', { inherit: true });
- // /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"
- // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/admin/crud/create/item
- // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/tests/index.html?grep=loopback
- nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
- "--profile-directory=Profile 1"
- , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
-
- }
- // nodeShellExec('npm', ['init', '-y'], options);
- // nodeShellExec('npm', ['init', '-y'], options);
- // })
-
- var g = {
- 'client': () => {
- // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
-
- console.info('Creating new ember client named : ' + processedArgs._[2]);
- var step1 = 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))
- // PB : TODO -- detect where chrome is installed.
- // PB : TODO -- set the download dir to the place where files are needed.
- 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)
-
- }
-
- }
-
- g[processedArgs._[1]]();
- }
- }
-
- 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}
- ${
- // util.inspect(
- [Object.keys(op)]
- // )
- }
- `;
-
- 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(def){
-
- // def can be an instance config
- // Or an object with many repos and elevated repos
- // Or a single repo ( Either Elevated or normal. )
-
-
- def = def || {
- repos : selectedinstance.repos,
- elevated : selectedinstance.elevated
- }
-
- var elevatedpulltasks = null;
- if(def.repo) {
- // Single repo case.
- if(def.repo.requiresElevation) {
- elevatedpulltasks = function() {
- return performPull(def.repo).then(() => {
- return true;
- }).catch((e) => {
- console.error(e)
- })
- }
- return
- }
- else {
- var regularpulltasks = function(){
- var pendingpulls = [];
- pendingpulls.push(performPull(def.repo))
- return Promise.all(pendingpulls).finally(Traq.finally)
- }
- }
- if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
- else return getTaskWithoutElevation({ regularpulltasks})
- }
-
- // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
- console.dir(def)
-
- var env = Object.assign({}, process.env); // Shallow clone it.
- console.log('Running exlr pull : ' + path.dirname(__dirname))
-
- var useGitPull = 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() {
- return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
- return true;
- }).catch((e) => {
- console.error(e)
- })
- }
- }
- if(def.repos) {
- var regularpulltasks = function(){
- var pendingpulls = [];
- def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
- return Promise.all(pendingpulls).finally(Traq.finally)
- }
- }
- if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
- else return getTaskWithoutElevation({ regularpulltasks})
- }
- }
-
- function preworkerconfig(){
- // Everything runs after this check is completed. Elevation occurs out of process when needed.
- gitRepos = selectedinstance.repos
- // gitRepos = ['chess-server-lib'];
-
- // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
- elevatedRunasRepos = selectedinstance.elevated
- // Repos that should excluded from merge for releases...
- exludeMergeRepos = selectedinstance.exludeMergeRepos
-
- // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
- // mysql -u root -p db_name < drop_all_tables.sql
-
- var mysql = '../xampp/mysql/bin/mysql'
- var mysqldump = '../xampp/mysql/bin/mysqldump'
- }
-
-
- // The main elxr cli process
- function elxrworker() {
- var subcommandlabels = {
- remote : (`remote ${processedArgs._[1] || ''}`).trim()
- }
-
- var __runcmd = function (label) {
- var distinquishedlabel = subcommandlabels[label] || label
- return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
- }
-
-
- // --runas
- if (processedArgs.runas) {
- // Weve been asked to run in priviledged mode. Check if we already are privileged.
- return __runcmd('runas')
- }
- else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
- }
-
- function acquireChoices(selectedinstance) {
-
- var hasconfig = false;
- console.warn(chalk.yellow(`
- -------------------------------------------------------------------------------
- Warning : Cannot locate your preferred configuration since it was not specified
- You should fork the default chess configuration to customize and make it
- your own instance with a named config as
- {{yourowninstancename}}-config-{{yourchosenenvironment}}
- And then run this tool as follows
- NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
- OR
- Run this tool with the following command to use a quick start default.
- elxr --default
- OR
- Choose one of the options below to run interactively.
-
- We will run your choice at the next prompt.
- -------------------------------------------------------------------------------
- `))
- var prompt = cli.prompter;
- return prompt.ask(`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
- Default <= d
- : `).then((choice) => {
- if (choice && choice === 'd' || !choice) {
- processedArgs._[0] = 'i'
- selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
- selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
- selectedinstance.reposerver = 'https://git.bbh.org.in'
- }
- else if (choice === 'h') {
- processedArgs._[0] = 'h'
- fs.writeFileSync('run.done', 'noop help');
- console.log(elxr.help()); process.exit()
- }
- else if (choice === 'n' || choice === 'i') {
- var p1 = cli.prompter;
- return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
- processedArgs._[0] = 'i'
- selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
- return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
- selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
- if (choice === 'n') {
- selectedinstance.reposerver = 'https://git.bbh.org.in'
- console.warn(
- chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
- process.exit();
- }
-
- return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
- selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
- })
- })
- })
- } else if (choice === 'c') {
- var p1 = cli.prompter;
- return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
- selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
- return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
- selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
- return p1.ask(`Enter cmd :
- p) pull
- Default <= p
- : `).then(function (cmd) {
- if (!cmd || cmd === 'p') {
- processedArgs._[0] = 'pull'
- }
- else processedArgs._[0] = cmd
- return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
- selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
- })
- })
- })
- })
- } else {
- console.log(chalk.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
- fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
- fs.writeFileSync('run.done', 'noop quit');
- process.exit()
- }
- })
- }
-
- 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( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
- })
-
- 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 acquireConfig = function (selected) {
-
- var configrepo = selected.instanceName + '-config-' + selected.node_env;
-
- return performPull(configrepo).then(() => {
- var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
- selectedinstance = require(manifestpath)()
- // Config from server always override merges into selection ecept for the current selection.
- // PB : TODO -- utils.assign Array merges are non-distinct...
- 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(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] // PB : TODO -- Attempt first one that is available and online...
- cacheWriteInstanceConfig(chessinstances)
- ENV.NODE_ENV = selectedinstance.node_env;
- })
- .catch((e) => {
- console.error(e)
- console.error('Config acquisition failed.')
- })
- }
-
- var launchpath = process.cwd().replace(/\\/, '/')
- var thisscriptdir = __dirname; // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
- // The easisest would be to ask for a target directory and default to current dir....
- var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? thisscriptdir + '/..' : launchpath ;
-
- var __default = {
-
- // Default is public server only.
- // All public repos are by default available.
- reposervers: ['https://git.bbh.org.in']
- , repos: [
- { repo : 'setup' }
- , { repo : 'elxr' }
- , { repo : 'loopback-connector-mysql' }
- , { repo : 'loopback-jsonapi-model-serializer' }
- , { repo : 'loopback-component-jsonapi' }
- , { 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' }
- ]
-
- , elevated: []
- , exludeMergeRepos: {}
- , instanceName: 'chess'
- // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
- , node_env: 'development'
- }
-
- var detectInstance = function () {
- console.log(`launchpath = ${launchpath}`)
- console.log(`thisscriptdir = ${thisscriptdir}`)
- console.log(`instanceroot = ${instanceroot}`)
-
- var root = instanceroot;
-
- // We need a reference to the root director for elxr cli to be properly oriented.
- if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
- // We ran from the proper root with elxr subfolder.
- // PB : TODO --- Additional checks required to verify elxr is the right folder
- // should be a git repo. has elxr signature
- // and .elxr folder signature... in the launchpath.
- console.log(`Instance Path : ${root}`)
- instanceroot = root = launchpath
- }
- else {
- if (launchpath === thisscriptdir) {
- // Same directory doesn't mean we are being run from elxr directory or the root directory.
- // It could be a standalone elxr build which may or maynot be in the proper location.
- if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
- // Unbuilt therefore we are in the elxr directory.
- instanceroot = root = path.normalize(launchpath + '/..');
- }
- else {
- // Built version.
- // check if we have a elxr subfolder.
- if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
- // Probably in the right place.
- instanceroot = root = path.normalize(launchpath + '/..');
- }
- else {
- // Assume launchpath is meaningless.
- // Figure it out from the input instance name and environment parameters if we are in the right location.
- instanceroot = root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
- }
- }
- }
- }
- instanceroot = root.replace(/\\/g, '/');
- __default.root = root;
- clioverrides.root = clioverrides.root || root;
-
- // Resolves undefined when No known instances detected.
- return Promise.resolve(
- // We can expect a .elxr at each level.
- ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].earlyreduce( ( acc, p, i, a )=>{
- var root = `${instanceroot}/${p}.elxr`;
- if(existsSync( root )) {
- try {
- var chessinstances = acquirelocalinstances( { root } )
- return Object.keys(chessinstances).earlyreduce( ( acc, instanceName) => {
- return Object.keys(chessinstances[instanceName]).earlyreduce( (acc, instanceType) => {
- if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize(root) ) return {
- value : chessinstances[instanceName][instanceType]
- , done : true
- };s
- })
- })
- }
- catch(e){
- return {}
- }
- }
- else return {}
- }).value
- )
- }
-
- var __interactve_promts = {
- get reposerver(){
- return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
- Object.defineProperty(this, 'reposerver', {
- value: reposerver,
- writable: false,
- configurable : true,
- enumerable : true
- });
- return reposerver
- })
- }
- , set reposerver(reposerver){
- Object.defineProperty(this, 'reposerver', {
- value: reposerver,
- writable: false,
- configurable : true,
- enumerable : true
- });
- return reposerver
- }
- }
-
- var downloadsdir = '../Downloads';
- var prerequisites = [
- {
- shellcmd: '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'
- // , '/MERGETASKS=!runcode' // This is required only for vscode...
- ]]
- , preinstallsteps: function() {
- var prompt = cli.prompter;
- 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 = [
- () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
- , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
- ]
- return any([any(steps), any(prompts)])
- }
- , installsteps: function () {
- return any([this.installcmd].map(callsheltask))
- }
- , postinstallsteps: function(){
-
- var prompt = cli.prompter;
-
- var gitUser = 'guest';
- var gitEmail = 'guest@bbh.org.in';
- var prompts = [];
- prompts.push(
- ()=>{
- var choices = { 0 : 'guest', 1 : 'chessdemo' }
- return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
- }
- )
-
- prompts.push(
- ()=>{
- var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
- return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
- }
- )
-
- return any(prompts).then(()=>{
- var steps = [
- ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
- , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
- ]
- return any(steps.map(callsheltask)).then(() => {
-
- })
- });
- }
- , install: function () {
- return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
- }
- , verifyAndInstall : function(){
- return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
- if(exists) {
- // return any(['git', ['config', '--global', '-l']].map(callsheltask))
- return this.getUser(null, this.postinstallsteps.bind(this))
- }
- return this.install();
- });
- }
- , getUser : function(repo, onNoResult){
-
-
- onNoResult = onNoResult || function(){return false}
- var globalOrLocal = '--global';
- if(!repo) globalOrLocal = '--global';
- else globalOrLocal = '--local'
-
- return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
- // not yet configured.
- if(!result.success) return onNoResult()
- else {
- var users = result.messages[0].trim().split('\n');
- if(users.length === 0 ||
- users.length === 1 && users[0] === 'guest') {
-
- return onNoResult()
- }
- else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
- }
- })
- .catch((e)=>{
- console.log(e)
- return onNoResult()
- })
- }
- }
- ,
- {
- shellcmd: '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(callsheltask)).then(() => { }) }
- }
- ]
-
- 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() {
- fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
-
- // PB : TODO include and build from files... using rollup..
- 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 = [];
- 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);
-
- // PB : TODO -- Convert all the cli args back to string.
- var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
- // alert(cargs)
- var shell = new ActiveXObject('shell.application');
- // alert('launching node privilged. ' + processedArgs['nodepath'])
- // shell.ShellExecute('where', 'node', '', '', 10);
- shell.ShellExecute('node', cargs, '', 'runas', 1);
- // 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/>')
-
- var timer = function(){
- l('.');
- if(fso.FileExists("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 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, choices, defaultchoise){
- return {
- get (){
- return cli.prompt( choices, propName, defaultchoise).then(propValue => {
- Object.defineProperty(this, propName, {
- value: propValue,
- writable: false,
- configurable : true,
- enumerable : true
- });
- return propValue
- })
- }
- // , set (propValue){
- // Object.defineProperty(this, propName, {
- // value: propValue,
- // writable: false,
- // configurable : true,
- // enumerable : true
- // })
- // return propValue;
- // }
- , configurable : true
- , enumerable : true
- }
- }
-
-
-
-
- function acquirelocalinstances(selected){
- var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
- return chessinstances
- }
-
-
- // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
- var selectedinstance = null;
- var chessinstances = { current_run : {} };
- var promptkeys = {
- // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
- // 'instanceName' : true
- // , 'node_env' : true
- }
-
- function createChessInsance( cfg ){
- var inst = {};
- var __new = Object.assign({}, __default, cfg)
- inst[cfg.node_env] = __new; return inst;
- }
-
- acquireElevationState().then(() => {
- var skipprerequisites = false;
- function initinstances(selected) {
- // PB : TODO -- processedArgs should already be part of selected.
- var instanceName = processedArgs._[1]
- || chessinstances.current_run.instanceName
- || selected.instanceName
- || clioverrides.instanceName;
-
- var node_env = processedArgs.node_env
- || chessinstances.current_run.node_env
- || selected.node_env
- || clioverrides.node_env;
-
- 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'] = 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'] = promptkeys['reposerver'] || __default.reposervers[0];
- }
-
- chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
- instanceName, node_env, root : selected.root, reposerver : promptkeys['reposerver'] } );
- chessinstances['current_run'] = { instanceName: instanceName, node_env: node_env }
-
- if(path.normalize(selected.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
- throw "Mismatched chessinstances config found " + chessinstances[instanceName][node_env].root + ' does not match ' + selected.root
- }
- // Override sequence.
- // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
- selectedinstance = utils.assign(
- selected
- , chessinstances[instanceName][node_env]
- , clioverrides
- // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
- );
-
- // chessinstances[instanceName] = chessinstances[instanceName] || {}
- // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
-
- // if(!selectedinstance.repos || selectedinstance.instanceName) {
- // // Brand New.
- // selectedinstance = Object.assign( __default, selectedinstance )
- // }
-
- 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 } })
- }
-
- // Config from server always override merges into selection except for the current selection.
- // PB : TODO -- utils.assign Array merges are non-distinct...
- chessinstances[instanceName][node_env] = selectedinstance = utils.assign(selected, selectedinstance)
- // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
- cacheWriteInstanceConfig(chessinstances)
- // PB : TODO -- We should probably write the new server config also...
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
-
- return chessinstances
- }
-
- var noprerequisites = {
- add : true, 'set-url' : true, 'repo-relocate' : true
- , remote : true
- }
- var skipprereqs = {}
- var maintask = () => {
-
- // Default cmd to run !
- processedArgs._[0] === processedArgs._[0] || 'pull';
- // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
-
- if(!noprerequisites[processedArgs._[0]]
- && !skipprereqs[processedArgs._[0]]
- ) {
- return prerequisites.git.verifyAndInstall().then(()=>{
- var e = { message : 'verifyAndInstall', success : true}
- return acquireConfig(selectedinstance).catch((err) => {
- e = err;
- console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
- console.error(err)
- }).then(() => { preworkerconfig(); return elxrworker(true) })
- // .finally(()=>{
- // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
- // if(!e.success) fs.writeFileSync('run.done', 'error');
- // // return process.exit()
- // })
- })
- }
- else {
- console.log('cmd has no preqs or has been configured to skip preqs')
- preworkerconfig()
- return elxrworker()
- }
-
- }
-
- const retaincount = 2
- var min = runtimestamp;
- var collect = []
-
- if(noprerequisites[processedArgs._[0]]
- || skipprereqs[processedArgs._[0]]
- ) {
- return elxrworker()
- }
-
- return detectInstance().then((detectedInstance)=>{
-
- selectedinstance = utils.assign(detectedInstance || {}, clioverrides)
- promptkeys = utils.assign(promptkeys, { 'instanceName' : clioverrides.instanceName, 'node_env' : clioverrides.node_env })
-
- if(clioverrides.reconfirm) {
- var reconfirm = { 'instanceName' : selectedinstance['instanceName'] === 'chess' }
- }
- else { var reconfirm = {}; }
-
- var prompts = [];
- var eachPrompt = function(k, i, a){
-
- // No local instances config found. We use a default initialized instance available in selectedinstance
- // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
- // PB : TODO -- selectedinstance === __default check to prompt everything...
- if( (promptkeys[k] !== undefined && promptkeys[k] !== null) && selectedinstance[k] !== promptkeys[k]
- || (promptkeys[k] === undefined || promptkeys[k] === null) && (selectedinstance[k] === undefined || selectedinstance[k] === null)
- || reconfirm[k]) {
- prompts.push(async ()=>{
- // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
- // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
- // If latest altered state is required we can reerence this directly.
- // var asyncthis = Object.assign(this);
- Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
- return await selectedinstance[k]
- })
- }
- delete promptkeys[k]
- }
- try {
-
- chessinstances = acquirelocalinstances(selectedinstance);
- initinstances(selectedinstance)
-
- var todo = Promise.resolve(true);
- var instanceNameChoices = new Set(Object.keys( chessinstances) )
- instanceNameChoices.delete('current_run')
- instanceNameChoices.add(selectedinstance['instanceName'])
- if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
-
- var choices = {
- 'instanceName' : Array.from(instanceNameChoices)
- , 'reposerver' : selectedinstance['reposervers']
- }
-
- Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
- Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
-
- todo = any(prompts).then(()=>{ return selectedinstance })
- }
- catch (e) {
- // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
- initinstances(selectedinstance)
-
- var instanceNameChoices = new Set(Object.keys( chessinstances) )
- instanceNameChoices.delete('current_run')
- instanceNameChoices.add(selectedinstance['instanceName'])
- if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
-
- var choices = {
- 'instanceName' : Array.from(instanceNameChoices)
- , 'reposerver' : selectedinstance['reposervers']
- , 'instanceType' : ['development', 'production']
- }
-
- Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
- Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
-
- todo = any(prompts).then(()=>{ return selectedinstance })
-
- if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
- // Weve been told what to do.
- todo = todo.then(() => { return acquireChoices(selectedinstance) })
- }
-
- todo = todo.then(() => {
- try {
- chessinstances = acquirelocalinstances(selectedinstance)
- initinstances(selectedinstance)
- }
- catch (e) {
- console.error(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...')
- // return (async ()=>{return await __default.reposerver})().then(()=>{
- // // selectedinstance = Object.assign(detectedInstance, clioverrides);
- // return selectedinstance = Object.assign(__default, selectedinstance);
- // })
- return selectedinstance
- }
- })
- }
-
- return todo
- })
- .then(()=>{
-
- if(!__isElevated) {
- ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`)
- // collect garbage
- 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])
- }
-
- }, `${selectedinstance.root}/.elxr` ).then(()=>{
- // delete garbage
- 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
- })
- }
- else return true;
- })
- .then(()=>{
- // PB : TODO -- Keep only the last n runs...
- // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
- ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
-
- if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
- mainTasks.push(maintask)
- return any(mainTasks);
- })
- })
-
- // detect if alread installed -> Take no action.
- // download if no installer avalable -> next()
- // install
- function chackandinstall(items) {
- var tasks = []
- items.forEach(item => {
- tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
- })
-
- return Promise.all(tasks).then(existances => {
- existances.forEach((exists, i) => {
- if (!exists) {
- return downloadandinstall([items[i]])
- }
- })
- })
- }
-
- function downloadandinstall(items) {
- var tasks = []
- items.forEach(item => {
- tasks.push(getTaskDownload(item))
- })
- return Promise.all(tasks)
- }
-
-
-
-
- // Sample instances config.
- // var instances = {
- // "elixir": {
- // "production": {
- // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
- // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
- // , "exludeMergeRepos": {
- // "elixir-config-development": true, "elixir-config-test": true
- // , "elixir-config-production": true, "elixir-data": true
- // }
- // , "instanceName": "elixir", "node_env": "production"
- // }
- // },
- // "current_run": { "instanceName": "elixir", "node_env": "production" }
- // }
-
- // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
|