You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
4 年之前
4 年之前
3 年之前
3 年之前
5 年之前
6 年之前
3 年之前
3 年之前
3 年之前
6 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
4 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
5 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
5 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
6 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992
  1. var path = require('path');
  2. var utils = require('bbhverse');
  3. var any = utils.any;
  4. var Tasq = utils.Tasq
  5. var statuslog = utils.Traq
  6. var Traq = utils.Traq
  7. Tasq.addlistener(statuslog.statuslog)
  8. var cli = require('./cliverse')
  9. var nodeShellExec = cli.nodeShellExec;
  10. var chalk = require('chalk')
  11. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  12. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  13. const runtimestamp = (new Date()).getTime();
  14. function getVersion() { return BUILD_VERSION; }
  15. console.log(getVersion());
  16. // 'use strict';
  17. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  18. // PB : TODO --
  19. // runas bypass non elevated tasks when we request privelege
  20. // runas message is always error needs to be fixed.
  21. // runas wait needs to be parallelized.
  22. // suppress elevation check error messages
  23. // support runas lauched directly from shell.
  24. // pass in environment in hta to shellexecute.
  25. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  26. (function () {
  27. "use strict";
  28. if (!Array.prototype.earlyreduce) {
  29. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  30. var iterable = this;
  31. var donecallback = donecallback || (a=>a)
  32. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  33. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  34. // function *earlyReduceGenerator(acc, v, i, a) {
  35. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  36. var element = iterable[i]
  37. result = eachcallback(result, element, i, iterable)
  38. if(result.done) return donecallback(result)
  39. }
  40. // }
  41. return donecallback(result)
  42. }
  43. }
  44. }());
  45. const { existsSync } = require('fs');
  46. const existsFolderSync = existsSync;
  47. const fs = require('fs')
  48. const cliargs = utils.cliargs;
  49. const processedArgs = cliargs(process.argv.slice(2));
  50. console.dir(processedArgs)
  51. // PB : TODO -- defaults for valuless arguments if passed.
  52. // Object.keys(processedArgs).forEach(a=>{
  53. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  54. // }
  55. // })
  56. var clioverrides = { }
  57. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  58. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  59. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  60. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  61. Object.keys(clioverrides).forEach( prop => { })
  62. var globSync = require('glob').sync;
  63. var ENV = Object.assign({}, process.env); // Shallow clone it.
  64. const { readdir } = require("fs").promises
  65. // Directory shallow walk and do perform on each dir.
  66. const dirs = async (perform, path) => {
  67. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  68. if (dir.isDirectory()) perform(dir)
  69. }
  70. }
  71. var getShellTask = (command, args, options) => {
  72. options = options || {}
  73. var callshell = command === 'rm' ? callgitbashtask : callsheltask;
  74. return () => {
  75. var p = callshell( [command, args, Object.assign({
  76. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  77. }, options)
  78. ])
  79. if (options.ignorefailures) {
  80. return p.catch(e => {
  81. // Ignore. Not a major error.
  82. })
  83. }
  84. else return p;
  85. }
  86. }
  87. var callsheltask = (args) => {
  88. return args[0] === 'rm' ? callgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  89. var callgitbashtask = (args) => { return () => {
  90. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  91. }
  92. var getTaskCheckExists = (command, options) => {
  93. options = options || {}
  94. return () => {
  95. var p = nodeShellExec.apply(null, ['where', [command]])
  96. if (options.ignorefailures) {
  97. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  98. return false;
  99. })
  100. }
  101. else return p.then(() => { return true });
  102. }
  103. }
  104. var getTaskWithElevation = function(tasdef){
  105. return ()=>{
  106. if (__isElevated) {
  107. return tasdef.elevatedpulltasks().then(()=>{
  108. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  109. fs.writeFileSync('run.done', 'success')
  110. }).catch(e=>{
  111. fs.writeFileSync('run.done', 'failure')
  112. });
  113. }
  114. else {
  115. // PB : TODO -- Rename op['runas'] to 'elevate'
  116. var __runasresult = null;
  117. return op['runas']().then((r) => { return __runasresult = r; })
  118. .catch((e) => {
  119. console.error(e)
  120. })
  121. .finally(() => {
  122. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  123. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  124. })
  125. }
  126. }
  127. }
  128. var getTaskWithoutElevation = function(tasdef){
  129. return ()=>{
  130. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  131. else Promise.resolve(true)
  132. }
  133. }
  134. var gitops = {
  135. getdiscoverbranchcmd : function(repo){
  136. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  137. var cmd = [gitbash
  138. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  139. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
  140. return cmd
  141. }
  142. }
  143. var getPullCmd = (repo, branch) => {
  144. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  145. // console.log(useGitPull)
  146. var pullCmd = []
  147. if(!branch) {
  148. // console.warn('No branch was specified detecting from working client.')
  149. // First check if working client exits.
  150. // if (existsSync(instanceroot + '/' + repo)) {
  151. pullCmd= gitops.getdiscoverbranchcmd(repo)
  152. // }
  153. // else performpull
  154. }
  155. // var pullCmd = [gitInstallDir
  156. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  157. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  158. if(branch) {
  159. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  160. var pullCmd = [ gitbash
  161. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  162. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  163. }
  164. // var pullCmd = ['pullall', [], { cwd : repo }]
  165. if (useGitPull) pullCmd = ['git', ['pull'], {
  166. inherit: true, shell: true,
  167. cwd: instanceroot + '/' + repo
  168. // , env: process.env
  169. , runas: processedArgs.runas
  170. , title: `git pull ${repo}`
  171. }]
  172. return pullCmd
  173. }
  174. var performPull = (repo, branch) => {
  175. // PB : TODO -- Handle no branch passed in case.
  176. // if(!branch) { throw 'No branch specified' }
  177. if (existsSync(instanceroot + '/' + repo)) {
  178. var branchprint = branch ? ' branch :' + branch : '';
  179. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  180. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  181. if (__isElevated) {
  182. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  183. }
  184. else statuslog.statuslog(null, repo)
  185. return true;
  186. })
  187. .catch((e) => {
  188. e.repo = repo;
  189. if (__isElevated) {
  190. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  191. }
  192. else statuslog.statuslog(e); console.error(e)
  193. })
  194. }
  195. else {
  196. console.log('cloning ' + repo)
  197. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  198. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  199. {
  200. inherit: true, shell: true,
  201. env: process.env
  202. , cwd : instanceroot
  203. , runas: processedArgs.runas
  204. }).catch((e) => {
  205. throw e;
  206. }).then(() => {
  207. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  208. {
  209. inherit: true, shell: true,
  210. env: process.env
  211. , cwd: instanceroot + '/' + repo
  212. , runas: processedArgs.runas
  213. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  214. })
  215. .then(() => {
  216. if (__isElevated) {
  217. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  218. }
  219. else statuslog.statuslog(null, repo)
  220. })
  221. .catch((e) => {
  222. e.repo = repo;
  223. if (__isElevated) {
  224. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  225. }
  226. else statuslog.statuslog(e);
  227. })
  228. })
  229. .catch(e => {
  230. e.repo = repo;
  231. if (__isElevated) {
  232. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  233. }
  234. else statuslog.statuslog(e);
  235. })
  236. }
  237. }
  238. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  239. // -- Currently workaround is to always run from a non-elevated shell.
  240. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  241. var acquireElevationState = () => {
  242. if (__isElevated === null) {
  243. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  244. inherit: true
  245. // , shell: true
  246. , stdio: 'ignore'
  247. , env: process.env
  248. , title: `check privileged execution mode using "fsutil dirty query C:"`
  249. }).then((exitcode) => {
  250. console.log('Elevated')
  251. __isElevated = true;
  252. return true;
  253. }).catch(() => {
  254. __isElevated = false;
  255. console.log('Not Elevated');
  256. return false;
  257. });
  258. }
  259. else return Promise.resolve(__isElevated);
  260. }
  261. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  262. var defaultRepoOwner = 'chess';
  263. var elevatedRunasRepos = null
  264. var gitRepos = null
  265. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  266. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  267. var dbForLabel = function (label) {
  268. var dbsForLabel = {
  269. devmysql: 'mysql'
  270. , development: 'mssql'
  271. , production: 'mssql'
  272. }
  273. return dbsForLabel[label] || 'mysql'
  274. }
  275. // SAM : TODO Use nodeshellexec where to detect git installation dir
  276. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  277. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  278. // Relevant git repos
  279. var exludeMergeRepos = [];
  280. var useGitPull = processedArgs.useGitPull || false;
  281. var configPromise = null
  282. // elxr cli operations
  283. var op = {
  284. 'h': () => { console.log(elxr.help()); return '-h' }
  285. , 'clean' : () => {
  286. // delete all node_module folders and links.
  287. var tasklist = [];
  288. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  289. return Promise.all(tasklist)
  290. }
  291. , 'undefined': () => { return op.h(); }
  292. , 'reset': () => {
  293. // Reset NPM packages semver so major versions can be updated.
  294. const fs = require('fs')
  295. const wipeDependencies = (__package) => {
  296. const file = fs.readFileSync(__package + '/package.json')
  297. const content = JSON.parse(file)
  298. for (var devDep in content.devDependencies) {
  299. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  300. content.devDependencies[devDep] = '*';
  301. }
  302. }
  303. for (var dep in content.dependencies) {
  304. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  305. content.dependencies[dep] = '*';
  306. }
  307. }
  308. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  309. }
  310. var repos = ['client'];
  311. // repos = gitRepos;
  312. repos.forEach(wipeDependencies)
  313. // if (require.main === module) {
  314. // } else {
  315. // module.exports = wipeDependencies
  316. // }
  317. }
  318. , 'upgrade': () => {
  319. console.log('upgrade.......')
  320. var tasks = [
  321. () => {
  322. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  323. inherit: true, shell: true
  324. , env: process.env
  325. }).catch((e) => { console.error(e) })
  326. p.position = 1;
  327. console.log('One')
  328. return p;
  329. }
  330. , () => {
  331. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  332. inherit: true, shell: true
  333. , env: process.env
  334. }).catch((e) => { console.error(e) })
  335. p.position = 2;
  336. console.log('Two')
  337. return p;
  338. }
  339. , () => {
  340. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  341. inherit: true, shell: true
  342. , env: process.env
  343. }).catch((e) => { console.error(e) })
  344. p.position = 3;
  345. console.log('Three')
  346. return p;
  347. }
  348. , () => {
  349. var p = nodeShellExec('n', ['latest'], {
  350. inherit: true, shell: true
  351. , env: process.env
  352. }).catch((e) => { console.error(e) })
  353. p.position = 4;
  354. console.log('Four')
  355. return p;
  356. }
  357. ]
  358. any(tasks)
  359. console.log('.......done')
  360. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  361. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  362. console.info('Uninstalling existing ember globally');
  363. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  364. stdio: ['pipe', process.stdout, process.stderr],
  365. inherit: true,
  366. shell: true,
  367. cwd: path.dirname(__dirname),
  368. env: env
  369. })
  370. step1.on('close', () => {
  371. console.info('Installing ember globally');
  372. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  373. stdio: ['pipe', process.stdout, process.stderr],
  374. inherit: true,
  375. shell: true,
  376. cwd: path.dirname(__dirname),
  377. env: env
  378. })
  379. step2.on('close', () => {
  380. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  381. stdio: ['pipe', process.stdout, process.stderr],
  382. inherit: true,
  383. shell: true,
  384. cwd: path.dirname(__dirname),
  385. env: env
  386. })
  387. })
  388. })
  389. }
  390. , 'runas': () => {
  391. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  392. console.log('Testing Elevation')
  393. if (__isElevated) {
  394. try {
  395. op[processedArgs.label || processedArgs._[0] || 'h']()
  396. }
  397. catch (e) {
  398. console.error('Error Invalid command : ' + e)
  399. fs.writeFileSync('run.done', 'error')
  400. }
  401. finally {
  402. }
  403. }
  404. else {
  405. console.log('Requesting Elevated Privileges');
  406. // Wait for the runas to complete before we read it.
  407. try {
  408. fs.unlinkSync('run.done')
  409. fs.unlinkSync('run.log')
  410. }
  411. catch (e) { } //Ignore
  412. // Find node path to send to hta.
  413. return nodeShellExec('where', ['node']).then(r => {
  414. var namedArgs = [];
  415. console.log('result : ' + JSON.stringify(r))
  416. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  417. // PB : TODO -- Convert all the cli args back to string.
  418. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  419. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  420. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  421. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  422. console.dir(processedArgs)
  423. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  424. , {
  425. inherit: true
  426. , shell: true
  427. , env: ENV
  428. , runas: 'self'
  429. , title: `runas`
  430. }
  431. ).then(() => {
  432. // runas returned.
  433. try {
  434. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  435. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  436. runaslog.forEach((logEntry) => {
  437. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  438. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  439. })
  440. }
  441. catch (e) {
  442. // We must have a runas log
  443. statuslog.statuslog(e)
  444. console.error('Run log error probably was not created by runas : ' + e)
  445. }
  446. })
  447. .catch(err => console.error('Elevation failed : ' + err));
  448. })
  449. }
  450. }
  451. , 'push': () => {
  452. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  453. // init remote bare from local
  454. // pushandinitremotebare
  455. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  456. // connect to repo server -- net use 172.16.0.27
  457. // cd 172.16.0.27/repos/
  458. // mkdir repo.git
  459. // cd repo.git
  460. // git init --bare
  461. // cd localrepo
  462. // git remote rename origin githubclone
  463. // git remote add origin //172.16.0.27/repos/repo.git
  464. // git push origin master
  465. var repo = processedArgs._[1];
  466. var sequentialTaskShellCommands = [];
  467. if (!existsSync(`Z:/${repo}.git`)) {
  468. sequentialTaskShellCommands = [
  469. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  470. // inherit : true, shell: true
  471. // , env: process.env
  472. // }]
  473. ['pwd', { cwd: 'Z:', inherit: true }]
  474. , ['mkdir', [`${repo}.git`], {
  475. cwd: `Z:`
  476. , inherit: true, shell: true
  477. , env: process.env
  478. }]
  479. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  480. , ['git', ['init', '--bare'], {
  481. cwd: `Z:/${repo}.git`
  482. , inherit: true, shell: true
  483. , env: process.env
  484. }]
  485. // PB : TODO -- Do this conditionally only...
  486. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  487. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  488. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  489. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  490. // PB : TODO -- If threre is a gitbubclone origin
  491. // Set the master to pull from the local repo.
  492. ]
  493. if (!existsSync(`Z:`)) {
  494. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  495. inherit: true, shell: true
  496. , env: process.env
  497. }])
  498. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  499. // throw 'done'
  500. }
  501. }
  502. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  503. // console.dir(sequentialTaskShellCommands);
  504. var tasks = [];
  505. sequentialTaskShellCommands.forEach(shellcmd => {
  506. // console.log(shellcmd)
  507. tasks.push(() => {
  508. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  509. return p;
  510. })
  511. })
  512. any(tasks);
  513. }
  514. , 'is-git-repo': (dir) => {
  515. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  516. }
  517. // git remote equivalents...
  518. // git branch --set-upstream-to=elixir-unc/master master
  519. // git push --set-upstream elixir-unc branch..
  520. , 'remote': (args) => {
  521. // Subcommands!
  522. if(!processedArgs.v) return false; // Only -v is supported presently..
  523. var serial_perform = (repo) => {
  524. var options = { cwd: instanceroot + '/' + repo }
  525. return [
  526. ['git', ['remote', '-v'], options]
  527. ]
  528. }
  529. var x = (args) => {
  530. var tasq = () => {
  531. // console.log(args)
  532. return nodeShellExec.apply(null, args).catch(e => {
  533. // We continue on failure.
  534. console.error(tasq.toString())
  535. })
  536. }
  537. tasq.toString = function(){
  538. return JSON.stringify(args)
  539. }
  540. return tasq;
  541. }
  542. var perform = (dir) => {
  543. return any(serial_perform(dir.name).map(x))
  544. }
  545. dirs(perform)
  546. }
  547. , 'remote set-url': (args) => {
  548. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  549. var __args = {
  550. remotename : args.remotename || processedArgs._[2]
  551. , url : args.url || processedArgs._[3]
  552. }
  553. // pushable doesn't mean the remote doesn't support being pushed to.
  554. // 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.
  555. // PB : TODO -- change this to enablepushing.
  556. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  557. var pushable = processedArgs.pushable || false;
  558. remotename = __args.remotename
  559. url = __args.url
  560. var serial_perform_git_seturl = (repo) => {
  561. var options = { cwd: instanceroot + '/' + repo }
  562. // console.log(repo)
  563. if (pushable) {
  564. return [
  565. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  566. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  567. ]
  568. }
  569. else {
  570. return [
  571. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  572. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  573. ]
  574. }
  575. }
  576. var x = (args) => {
  577. var tasq = () => {
  578. // console.log(args)
  579. return nodeShellExec.apply(null, args).catch(e => {
  580. // We continue on failure.
  581. console.error(tasq.toString())
  582. })
  583. }
  584. tasq.toString = function(){
  585. return JSON.stringify(args)
  586. }
  587. return tasq;
  588. }
  589. var perform_git_seturl = (dir) => {
  590. op['is-git-repo'](dir).then((logEntry) => {
  591. return any(serial_perform_git_seturl(dir.name).map(x))
  592. }).catch((e) => {
  593. // console.log('Failed : ' + dir.name)
  594. })
  595. }
  596. dirs(perform_git_seturl)
  597. }
  598. , 'reset' : ()=>{
  599. // Reset the whole installation pertaining to this elxr folder.
  600. }
  601. , 'remote exists': (args) => {
  602. var __args = {
  603. remotename : args.remotename|| processedArgs._[2]
  604. , url : args.url || processedArgs._[3]
  605. , branch : args.branch || processedArgs._[4]
  606. }
  607. var command = ['git', ['remote', '-v']]
  608. return nodeShellExec.apply(null, command).then(result=>{
  609. return result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  610. })
  611. }
  612. , 'remote refresh': (args) => {
  613. var __args = {
  614. remotename : args.remotename|| processedArgs._[2]
  615. , url : args.url || processedArgs._[3]
  616. , branch : args.branch || processedArgs._[4]
  617. }
  618. // use the repo manifest to create missing remotes.
  619. function perform_remote_refresh(dir){
  620. var repo = dir.name
  621. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  622. var remotes = require(`${dir.name}/repo-manifest.js`)( null, { repouser : selectedinstance.repouser }).remotes;
  623. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  624. var branch = __branch
  625. var promises = []
  626. remotes.foreach(remote =>{
  627. Object.keys(remote).forEach(remotename => {
  628. promises.push( op['remote exists'].then( exists => {
  629. if(!exits) {
  630. return op['remote add']( { remotename,
  631. // PB : TODO -- use the most accessible remote instead of the first available.
  632. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  633. } )
  634. }
  635. })
  636. )
  637. })
  638. })
  639. return Promise.all(promises)
  640. })
  641. .catch((e) => { console.error(e); return { error: true, message: repo } })
  642. }
  643. dirs(perform_remote_refresh)
  644. }
  645. , 'remote add': (args) => {
  646. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  647. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  648. // That explicitly has a remote name prefix.
  649. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  650. // git branch branch_name -u your_new_remote/branch_name -- older versions
  651. // git branch -vv -- Detect which branch are we tracking.
  652. // default upstream should be users own fork.
  653. // Also need alias branches to
  654. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  655. // probably git merge from all remotes... and relevant branches...
  656. // alias pushall='for i in `git remote`; do git push $i; done;'
  657. // alias pullall='for i in `git remote`; do git pull $i; done;'
  658. // args === processedArgs ? args = {} : null;
  659. var __args = {
  660. remotename : args.remotename|| processedArgs._[2]
  661. , url : args.url || processedArgs._[3]
  662. , branch : args.branch || processedArgs._[4]
  663. }
  664. var remotename = __args.remotename
  665. var url = __args.url
  666. var branch = __args.branch
  667. var pushable = processedArgs.pushable || false;
  668. var serial_perform_git_add = (repo) => {
  669. var options = { cwd: instanceroot + '/' + repo }
  670. // console.log(repo)
  671. if (pushable) {
  672. return [
  673. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  674. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  675. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  676. ]
  677. }
  678. else {
  679. return [
  680. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  681. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  682. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  683. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  684. ]
  685. }
  686. }
  687. var x = (args) => {
  688. return () => {
  689. // console.log(args)
  690. return nodeShellExec.apply(null, args)
  691. }
  692. // return Promise.resolve(true)
  693. }
  694. var perform_git_add = (dir) => {
  695. op['is-git-repo'](dir).then((logEntry) => {
  696. // console.log(code)
  697. if (logEntry.success) {
  698. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  699. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  700. })
  701. .catch((e) => {
  702. any(serial_perform_git_add(dir.name).map(x))
  703. })
  704. }
  705. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  706. }).catch((e) => {
  707. console.log('Failed : ' + dir.name)
  708. })
  709. }
  710. const { readdir } = require("fs").promises
  711. dirs(perform_git_add)
  712. }
  713. , 'remote remove': (args) => {
  714. var __args = {
  715. remotename : args.remotename|| processedArgs._[2]
  716. }
  717. var remotename = __args.remotename
  718. var serial_perform_git_remove = (repo) => {
  719. var options = { cwd: instanceroot + '/' + repo }
  720. // console.log(repo)
  721. return [
  722. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  723. ]
  724. }
  725. var x = (args) => {
  726. return () => {
  727. // console.log(args)
  728. return nodeShellExec.apply(null, args)
  729. }
  730. // return Promise.resolve(true)
  731. }
  732. var perform_git_remove = (dir) => {
  733. op['is-git-repo'](dir).then((logEntry) => {
  734. // console.log(code)
  735. if (logEntry.success) {
  736. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  737. any(serial_perform_git_remove(dir.name).map(x))
  738. })
  739. .catch((e) => {
  740. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  741. })
  742. }
  743. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  744. }).catch((e) => {
  745. // console.log('Failed : ' + dir.name)
  746. })
  747. }
  748. const { readdir } = require("fs").promises
  749. dirs(perform_git_remove)
  750. }
  751. , 'init-gitea': (user) => {
  752. user = user || processedArgs._[1]
  753. if (!user) throw 'User name required'
  754. var serial_perform_init_gitea = (repo) => {
  755. var options = { cwd: instanceroot + '/' + repo }
  756. // console.log(repo)
  757. return [
  758. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  759. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  760. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  761. ]
  762. }
  763. var x = (args) => {
  764. return () => {
  765. // console.log(args)
  766. return nodeShellExec.apply(null, args)
  767. }
  768. // return Promise.resolve(true)
  769. }
  770. var perform_init_gitea = (dir) => {
  771. op['is-git-repo'](dir).then((logEntry) => {
  772. // console.log(code)
  773. if (logEntry.success) {
  774. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  775. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  776. })
  777. .catch((e) => {
  778. any(serial_perform_init_gitea(dir.name).map(x))
  779. })
  780. }
  781. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  782. }).catch((e) => {
  783. // console.log('Failed : ' + dir.name)
  784. })
  785. }
  786. const { readdir } = require("fs").promises
  787. dirs(perform_init_gitea)
  788. }
  789. , 'syncmaster': (label) => {
  790. // Usage :
  791. // elxr pull -- Defaults to run config
  792. var env = Object.assign({}, process.env); // Shallow clone it.
  793. // console.dir(env)
  794. console.log('Running exlr pull : ' + path.dirname(__dirname))
  795. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  796. if (__isElevated) {
  797. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  798. fs.writeFileSync('run.done', 'success')
  799. }).catch(() => {
  800. fs.writeFileSync('run.done', 'error')
  801. })
  802. }
  803. else return op['runas']()
  804. }
  805. , 'repo-relocate' : function(args){
  806. // relocate a subfolder in source repo to same subfolder in target repo with history.
  807. var args = args || {
  808. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  809. , folder : processedArgs._[3] || 'server'
  810. , sourcerepo : processedArgs._[2] || 'client'
  811. , targetrepo : processedArgs._[1] || 'elixir-server'
  812. }
  813. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  814. // , stdio: ['pipe', process.stdout, process.stderr]
  815. , inherit: true,
  816. shell: true,
  817. env: process.env
  818. , runas: processedArgs.runas
  819. }
  820. return op['repo-split'](args).then(()=>{
  821. return op['repo-merge'](args).then(()=>{
  822. // cleanup folder from source.
  823. var cmdseq = [
  824. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  825. // commits have to intentional...
  826. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  827. ]
  828. return any(cmdseq.map(callsheltask))
  829. })
  830. }).catch(e=>{console.error(e)})
  831. }
  832. , 'repo-split' : function(args) {
  833. // https://gist.github.com/smdabdoub/17065c348289158277b5
  834. /**
  835. * Eg : folder, remotebase, sourcerepo, targetrepo
  836. * args.folder = 'server'
  837. * args.remotebase = 'https://git.bbh/chess/'
  838. * args.sourcerepo = 'client'
  839. * args.targetrepo = 'elixir-server'
  840. */
  841. var args = args || {
  842. folder : 'server'
  843. , remotebase : 'http://git.bbh/chess/'
  844. , sourcerepo : 'client'
  845. , targetrepo : 'elixir-server'
  846. }
  847. var options = { cwd: `${instanceroot}/relocate`
  848. // , stdio: ['pipe', process.stdout, process.stderr]
  849. , inherit: true,
  850. shell: true,
  851. env: process.env
  852. , runas: processedArgs.runas
  853. }
  854. var cmdseq = [
  855. // create a temporary working dir in current folder where we started execution.
  856. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  857. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  858. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  859. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  860. ]
  861. return any(cmdseq.map(callsheltask)).then(() => {
  862. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  863. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  864. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  865. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  866. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  867. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  868. // subtree split and filter-branch are options. We currently use repo-filter.
  869. return op['filter-repo'](args)
  870. }).catch(e=>{console.error(e); throw 'failed'})
  871. }
  872. , 'repo-merge' : function(args) {
  873. // Merge source repo into target repo
  874. var args = args || {
  875. folder : 'server'
  876. , remotebase : 'http://git.bbh/chess/'
  877. , sourcerepo : 'client'
  878. , targetrepo : 'elixir-server'
  879. }
  880. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  881. // , stdio: ['pipe', process.stdout, process.stderr]
  882. , inherit: true,
  883. shell: true,
  884. env: process.env
  885. , runas: processedArgs.runas
  886. }
  887. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  888. // , stdio: ['pipe', process.stdout, process.stderr]
  889. , inherit: true,
  890. shell: true,
  891. env: process.env
  892. , runas: processedArgs.runas
  893. }
  894. var cmdseq = [
  895. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  896. , targetrepooptions ]
  897. // , ['git', ['push', targetrepooptions ] // manual push for now..
  898. ]
  899. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e)})
  900. }
  901. , 'filter-repo' : function(args){
  902. // Merge source repo into target repo
  903. var args = args || {
  904. folder : 'server'
  905. , remotebase : 'http://git.bbh/chess/'
  906. , targetrepo : 'elixir-server'
  907. }
  908. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  909. , inherit: true, shell: true
  910. , env: process.env
  911. , runas: processedArgs.runas
  912. }
  913. var cmdseq = [
  914. // git checkout -b feature/merge-old-project
  915. // git remote add src-project ../src-project
  916. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  917. ]
  918. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  919. }
  920. , 'filter-branch' : function(preservefolder, repo){
  921. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  922. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  923. // Preserve a specific folder.
  924. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  925. /*
  926. git clone repo reposplit
  927. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  928. git remote rm origin
  929. */
  930. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  931. }
  932. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  933. // // Merge repo2 into a subfolder in repo1
  934. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  935. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  936. // /*
  937. // cd repo1
  938. // git remote add -f tempmergesource ../{{mergesource}}/.git
  939. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  940. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  941. // git commit
  942. // // Repair History
  943. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  944. // #!/usr/bin/env bash
  945. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  946. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  947. // subdir=server
  948. // git filter-branch --tree-filter '
  949. // first='"$first"'
  950. // last='"$last"'
  951. // subdir='"$subdir"'
  952. // log_file=/tmp/filter.log
  953. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  954. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  955. // echo "=== $GIT_COMMIT: making changes"
  956. // files=$(git ls-tree --name-only $GIT_COMMIT)
  957. // mkdir -p $subdir
  958. // for i in $files; do
  959. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  960. // done
  961. // else
  962. // echo "=== $GIT_COMMIT: ignoring"
  963. // fi \
  964. // >> $log_file
  965. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  966. // status=0 # tell tree-filter never to fail
  967. // '
  968. // git remote rm tempmergesource
  969. // */
  970. // // better alternative for history
  971. // /**
  972. // *
  973. // git clone git@server.com:old-project.git
  974. // git clone git@server.com:new-project.git
  975. // cd old-project
  976. // mkdir old-project
  977. // git mv !(old-project) old-project
  978. // ls -la and gt mv hidden files ....
  979. // git commit -a -S -m “Moving old project into its own subdirectory”
  980. // cd ../new-project
  981. // git remote add old-project ../old-project
  982. // git fetch old-project
  983. // git checkout -b feature/merge-old-project
  984. // git merge -S --allow-unrelated-histories old-project/master
  985. // git push origin feature/merge-old-project
  986. // git remote rm old-project
  987. // */
  988. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  989. // }
  990. , 'pull' : (label) => {
  991. // Usage :
  992. // elxr pull -- Defaults to run config
  993. return elxr.getpulltask(selectedinstance)()
  994. }
  995. , 'isInstalled': () => {
  996. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  997. console.log(processedArgs._[1] + ' exists.')
  998. return true;
  999. });
  1000. }
  1001. , 'i' : () => {
  1002. var tasks = []
  1003. // tasks.push(op['pull']);
  1004. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1005. tasks.push(op['use'])
  1006. if (!__isElevated) {
  1007. tasks.push(op['npmi'])
  1008. }
  1009. // var tasksdefs = [
  1010. // ['elxr', ['pull']]
  1011. // , ['elxr', ['use', 'elixir']]
  1012. // , ['elxr', ['npmi']]
  1013. // ]
  1014. // tasksdefs.forEach(tasksdef=>{
  1015. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1016. // })
  1017. return any(tasks);
  1018. }
  1019. , 'npmi': () => {
  1020. var tasks = [];
  1021. // Build fails without babel...
  1022. tasks.push(getShellTask(
  1023. 'npm',[ 'i', '-g', 'babel-cli' ]
  1024. ) )
  1025. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1026. npmbuildrepos = []
  1027. npmbuildrepos.forEach(repo => {
  1028. tasks.push(() => {
  1029. return nodeShellExec('npm', ['i --force'], {
  1030. inherit: true, shell: true
  1031. , cwd: instanceroot + '/' + repo
  1032. , env: process.env
  1033. , title: `npm i for ${repo}`
  1034. }).catch((e) => {
  1035. console.error('Ignoring Benign Error'); console.error(e);
  1036. }).then(() => {
  1037. console.log(`--npm run build for ${repo}--------------------`)
  1038. return nodeShellExec('npm', ['run build'], {
  1039. inherit: true, shell: true
  1040. , cwd: instanceroot + '/' + repo
  1041. , env: process.env
  1042. , title: `npm run build for ${repo}`
  1043. }).then(Tasq.then).catch(Tasq.catch)
  1044. })
  1045. })
  1046. })
  1047. any(tasks).then(() => {
  1048. gitRepos.push('client/server');
  1049. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1050. // gitRepos = [
  1051. // // 'bbhverse', 'serververse', 'elixir-server',
  1052. // // 'clientverse',
  1053. // 'client'
  1054. // ];
  1055. var rmtasks = []
  1056. var repotasks = []
  1057. var env = Object.assign({}, process.env)
  1058. delete env.NODE_ENV
  1059. gitRepos.forEach(repodef => {
  1060. rmtasks.push(
  1061. // () => {
  1062. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1063. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1064. (callShellTask(['rm', ['package-lock.json'], {
  1065. inherit: true, shell: true
  1066. , cwd: instanceroot + '/' + repodef.repo
  1067. , env: process.env
  1068. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1069. }]))()
  1070. .then(()=>{
  1071. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1072. }).catch((e) => { console.error(e) })
  1073. // }
  1074. )
  1075. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1076. repotasks.push(
  1077. () => {
  1078. console.log(`--npm i for ${repodef.repo}--------------------`)
  1079. var p = nodeShellExec('npm', ['i', '--force'], {
  1080. inherit: true, shell: true
  1081. , cwd: instanceroot + '/' + repodef.repo
  1082. , env
  1083. , title: `npm i for ${repodef.repo}`
  1084. }).then(Tasq.then).catch(Tasq.catch)
  1085. return p;
  1086. })
  1087. }
  1088. })
  1089. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1090. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1091. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1092. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1093. // Second time try also doesnt work.
  1094. // repotasks.push(
  1095. // () => {
  1096. // var env = Object.assign({}, process.env)
  1097. // delete env.NODE_ENV
  1098. // console.log(`--------------------second time npm i for client--------------------`)
  1099. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1100. // // return nodeShellExec('npm', ['i --force'], {
  1101. // inherit: true, shell: true
  1102. // , cwd: instanceroot + '/' + 'client'
  1103. // , env
  1104. // , title: `npm i for client`
  1105. // }).then(Tasq.then).catch(Tasq.catch)
  1106. // })
  1107. var bowerRepos = [{ repo : 'client'}]
  1108. bowerRepos.forEach(repodef => {
  1109. repotasks.push(() => {
  1110. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1111. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1112. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1113. inherit: true, shell: true
  1114. , cwd: instanceroot + '/' + repodef.repo
  1115. , env: process.env
  1116. , title: `bower i for ${repodef.repo}`
  1117. }).then(Tasq.then).catch(Tasq.catch)
  1118. return p;
  1119. })
  1120. })
  1121. // console.log('rmtasks.length : ' + rmtasks.length)
  1122. return Promise.all(rmtasks).then(() => any(repotasks));
  1123. }).catch(e => {
  1124. }).finally(statuslog.finally)
  1125. }
  1126. , 'start': (label) => {
  1127. console.log('Starting Elixir Server.');
  1128. var env = Object.assign({}, process.env); // Shallow clone it.
  1129. // console.dir(env)
  1130. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1131. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1132. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1133. // cmd = 'node'
  1134. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1135. var childPromise = nodeShellExec(...cmd, {
  1136. // inherit : true,
  1137. shell: true,
  1138. detached: true,
  1139. stdio: 'ignore',
  1140. cwd: instanceroot + '/' + 'elixir-server'
  1141. , env: env
  1142. })
  1143. var child = childPromise.process;
  1144. if (typeof child.pid !== 'undefined') {
  1145. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1146. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1147. encoding: 'utf8'
  1148. })
  1149. }
  1150. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1151. // inherit : true,
  1152. // shell: true, detached: true,
  1153. // cwd : 'qms/server',
  1154. // env: env,
  1155. // shell : true
  1156. // })
  1157. // nodeShellExec('ember', ['s'], {
  1158. // // inherit : true,
  1159. // shell: true, detached: true,
  1160. // cwd : 'client/',
  1161. // env: env
  1162. // })
  1163. console.log('Starting Elixir Client Host.');
  1164. var cmd = ['ember', ['s']]
  1165. var childPromise = nodeShellExec(...cmd, {
  1166. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1167. // PB : TODO -- ember debugging.
  1168. // inherit : true,
  1169. shell: true,
  1170. detached: true,
  1171. stdio: 'ignore',
  1172. cwd: instanceroot + '/' + 'client'
  1173. , env: env
  1174. })
  1175. // .catch(e=>console.error(e))
  1176. child = childPromise.process;
  1177. if (typeof child.pid !== 'undefined') {
  1178. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1179. fs.writeFileSync('.client.server.pid', child.pid, {
  1180. encoding: 'utf8'
  1181. })
  1182. }
  1183. }
  1184. , 'stop': (label) => {
  1185. const kill = require('tree-kill');
  1186. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1187. encoding: 'utf8'
  1188. })
  1189. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1190. console.log(serverPid)
  1191. kill(serverPid)
  1192. serverPid = fs.readFileSync('.client.server.pid', {
  1193. encoding: 'utf8'
  1194. })
  1195. fs.unlinkSync('.client.server.pid')
  1196. console.log(serverPid)
  1197. kill(serverPid)
  1198. }
  1199. , 'model' : () => {
  1200. if (__isElevated) {
  1201. var tasks = [
  1202. () => {
  1203. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1204. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1205. inherit: true, shell: true
  1206. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1207. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1208. , env: process.env
  1209. }).catch((e) => { console.error(e) })
  1210. return p;
  1211. }
  1212. ];
  1213. return any(tasks).then(() => {
  1214. fs.writeFileSync('run.done', 'success')
  1215. }).catch(() => {
  1216. fs.writeFileSync('run.done', 'error')
  1217. })
  1218. }
  1219. else return op['runas']()
  1220. }
  1221. , 'use' : () => {
  1222. // use a certain named instance.
  1223. // Eg :
  1224. // 1) elxr use elixir
  1225. // 2) elxr use cihsr
  1226. // If environment is not specified defaults to development.
  1227. // 1) NODE=test elxr use elixir
  1228. /*// Steps
  1229. 1) Delete Config and Data symlinks
  1230. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1231. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1232. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1233. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1234. */
  1235. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1236. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1237. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1238. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1239. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1240. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1241. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1242. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1243. return
  1244. }
  1245. var tasks = [
  1246. () => {
  1247. if (existsSync('config')) {
  1248. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1249. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1250. return p;
  1251. }
  1252. else return Promise.resolve(true);
  1253. },
  1254. () => {
  1255. if (existsSync('data')) {
  1256. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1257. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1258. return p;
  1259. }
  1260. else return Promise.resolve(true);
  1261. },
  1262. ];
  1263. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1264. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1265. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1266. // console.log(process.env.cwd)
  1267. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1268. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1269. var checkoutMap = { 'development': 'master' }
  1270. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1271. var performPullOrCloneForBranch = (def)=>{
  1272. var promise = Promise.resolve(true)
  1273. if (!branch) {
  1274. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1275. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  1276. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1277. }
  1278. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1279. }
  1280. var performCloneAndCheckout = null;
  1281. // cant use git checkout -b it fails when branch already exists.
  1282. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1283. return performPullOrCloneForBranch(def).then(()=>{
  1284. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1285. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1286. // inherit : true, shell: true,
  1287. cwd: instanceroot + '/' + def.repo
  1288. // , stdio : ignore // Use when we want to silence output completely.
  1289. , runas: processedArgs.runas
  1290. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1291. }).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 } })
  1292. })
  1293. }
  1294. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1295. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1296. var elevatedqueue = [];
  1297. var enqueueOnce = (queue, task, def) => {
  1298. var found = queue.find(element => {
  1299. var keys = Object.keys( element )
  1300. for(var k=0; k < keys.length; k++) {
  1301. if(element[keys[k]] !== def[k]) return false;
  1302. }
  1303. })
  1304. queue.push(function(){ return task(this)}.bind(def));
  1305. }
  1306. var enqueue = (queue, task, def) => {
  1307. queue.push(function(){ return task(def)}.bind(def));
  1308. }
  1309. var mergeSources = {
  1310. 'development': null,
  1311. 'test': 'master',
  1312. 'production': 'master'
  1313. }
  1314. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1315. // Checkout is reduced to pull provided the current branch is the targetbranch
  1316. if(branch === mergesource) performCheckout = (def) => {
  1317. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1318. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  1319. if(branch === __branch) return performCloneAndCheckout(def)
  1320. return performPullOrCloneForBranch(def)
  1321. })
  1322. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1323. }
  1324. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1325. var performPullAll = (def) => {
  1326. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1327. return nodeShellExec('git', ['pull', '--all'], {
  1328. // inherit : true, shell: true,
  1329. cwd: instanceroot + '/' + def.repo
  1330. , runas: processedArgs.runas
  1331. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1332. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1333. }
  1334. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1335. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1336. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1337. var performMerge = (def) => {
  1338. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1339. return nodeShellExec('git', ['merge', mergesource], {
  1340. inherit: true, shell: true,
  1341. cwd: instanceroot + '/' + def.repo
  1342. , runas: processedArgs.runas
  1343. }).catch((e) => { console.error(e) })
  1344. }
  1345. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1346. // var performRepoOperation = function(def) {
  1347. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1348. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1349. // }
  1350. return any(tasks).then(() => {
  1351. var pr = Promise.resolve(true)
  1352. if (!__isElevated) {
  1353. pr = op['runas']()
  1354. return pr.then(()=>{
  1355. //target is the env is we specify in elxr use command. Default is dev
  1356. //Switch to target branch
  1357. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1358. // pull or clone target branch
  1359. .then(() => {
  1360. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1361. return any(gitRepos.map((repo) => performPullAll(repo)))
  1362. })
  1363. // switch to source branch
  1364. .then( () => {
  1365. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1366. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1367. })
  1368. //Pull on merge source branch
  1369. .then( () => {
  1370. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1371. return any(gitRepos.map((repo) => performPullAll(repo)))
  1372. })
  1373. //Switch to target branch
  1374. .then( () => {
  1375. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1376. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1377. })
  1378. .then( //Merge source branch to target branch
  1379. () => {
  1380. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1381. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1382. })
  1383. })
  1384. }
  1385. else {
  1386. tasks = [
  1387. () => {
  1388. // Use junctions to avoid npm package issues
  1389. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1390. inherit: true, shell: true
  1391. , cwd : instanceroot
  1392. , env: process.env
  1393. }).catch((e) => { console.error(e) })
  1394. return p;
  1395. }
  1396. ];
  1397. if (processedArgs._[1]) {
  1398. tasks = tasks.concat(
  1399. [
  1400. () => {
  1401. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1402. inherit: true, shell: true
  1403. , cwd : instanceroot
  1404. , env: process.env
  1405. }).catch((e) => { console.error(e) })
  1406. return p;
  1407. }
  1408. ]
  1409. )
  1410. }
  1411. return any(tasks).then(()=>{
  1412. // checkout target branch
  1413. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1414. // pull or clone target branch
  1415. .then(() => {
  1416. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1417. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1418. })
  1419. // switch to source branch
  1420. .then( () => {
  1421. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1422. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1423. })
  1424. //Pull on merge source branch
  1425. .then( () => {
  1426. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1427. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1428. })
  1429. //Switch to target branch
  1430. .then( () => {
  1431. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1432. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1433. })
  1434. .then( //Merge source branch to target branch
  1435. () => {
  1436. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1437. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1438. })
  1439. .then(() => {
  1440. fs.writeFileSync('run.done', 'success')
  1441. }).catch(() => {
  1442. fs.writeFileSync('run.done', 'error')
  1443. })
  1444. })
  1445. }
  1446. }).catch(() => {
  1447. fs.writeFileSync('run.done', 'error')
  1448. })
  1449. // Antibiotic stewardship program.
  1450. // 1st use is fine.
  1451. // Max vials dispense
  1452. // 2nd use Pharmacy needs justification Form.
  1453. // Approval after a certain period of time.
  1454. }
  1455. , 'g': () => {
  1456. if (processedArgs.h) {
  1457. console.log('elxr g [modelname] => generate a model named [modelname]');
  1458. console.log('elxr g => regenerate all known models');
  1459. return
  1460. }
  1461. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1462. // console.log('Starting directory: ' + process.cwd());
  1463. // try {
  1464. // child = child.on('close', () => { process.chdir(label) } );
  1465. // console.log('New directory: ' + process.cwd());
  1466. // }
  1467. // catch (err) {
  1468. // console.log('chdir: ' + err);
  1469. // }
  1470. // child.on('close', function(){
  1471. // var options = {
  1472. // shell : true
  1473. // , inherit : true
  1474. // // , cwd : '' + process.cwd
  1475. // // , env : process.env
  1476. // };
  1477. // nodeShellExec('git', ['init'], { inherit : true});
  1478. if (0) {
  1479. // PB : TODO -- Special google chrome profile for tests etc.
  1480. nodeShellExec('pwd', { inherit: true });
  1481. // /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"
  1482. // "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
  1483. // "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
  1484. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1485. "--profile-directory=Profile 1"
  1486. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1487. }
  1488. // nodeShellExec('npm', ['init', '-y'], options);
  1489. // nodeShellExec('npm', ['init', '-y'], options);
  1490. // })
  1491. var g = {
  1492. 'client': () => {
  1493. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1494. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1495. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1496. stdio: ['pipe', process.stdout, process.stderr],
  1497. inherit: true,
  1498. shell: true,
  1499. cwd: path.dirname(__dirname),
  1500. env: env
  1501. })
  1502. },
  1503. 'modelr': () => {
  1504. var tasks = [
  1505. () => {
  1506. var p = nodeShellExec('"ember"', [
  1507. 'g'
  1508. , 'modelr'
  1509. , processedArgs._[2]], {
  1510. inherit: true, shell: true, env: process.env
  1511. }).then(() => {
  1512. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1513. return true;
  1514. }).catch((e) => { console.error(e) })
  1515. return p;
  1516. },
  1517. () => {
  1518. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1519. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1520. chromeprefs = JSON.parse(chromeprefs)
  1521. var previous = chromeprefs.download.default_directory;
  1522. var parentDir = path.dirname(__dirname);
  1523. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1524. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1525. // PB : TODO -- detect where chrome is installed.
  1526. // PB : TODO -- set the download dir to the place where files are needed.
  1527. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1528. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1529. , '--profile-directory="chess"'
  1530. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1531. inherit: true, shell: true
  1532. , env: process.env
  1533. }).then(() => {
  1534. chromeprefs.download.default_directory = previous;
  1535. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1536. return true;
  1537. }).catch((e) => { console.error(e) })
  1538. return p;
  1539. }
  1540. ,
  1541. () => {
  1542. console.log('Browser process should have closed here....')
  1543. return true;
  1544. }
  1545. ]
  1546. any(tasks)
  1547. }
  1548. }
  1549. g[processedArgs._[1]]();
  1550. }
  1551. }
  1552. var util = require('util');
  1553. var cliname = 'elxr';
  1554. var ver = '1.1';
  1555. var readme = `
  1556. Command syntax examples
  1557. elxr
  1558. Displays help. Same as elxr h
  1559. elxr i
  1560. Runs interactive propmts to help choose installation options.
  1561. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1562. General command syntax.
  1563. Eg: NODE_ENV=development elxr pull elixir
  1564. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1565. The specific cmd defines what the value is interpreted as.
  1566. There are several cmds that do not require an {{instancename}} parameter.
  1567. Eg: elxr remote remove origin
  1568. Git operations or passthrough external commands on all repository folders in you working directory.
  1569. Main objectives.
  1570. elxr cli is a wrapper around other shell commands and api based operations.
  1571. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1572. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1573. `;
  1574. var help = `
  1575. ${readme}
  1576. # list of commands... please refer dveloper documentation for ${cliname}
  1577. ${
  1578. // util.inspect(
  1579. [Object.keys(op)]
  1580. // )
  1581. }
  1582. `;
  1583. var elxr = {
  1584. help() {
  1585. return chalk.cyanBright(`
  1586. -------------------------------------------------------------------------------
  1587. *** BBH Elixir ***
  1588. -------------------------------------------------------------------------------
  1589. elxr ${ver}
  1590. A cli tool for chess
  1591. ${help}
  1592. -------------------------------------------------------------------------------
  1593. `)
  1594. }
  1595. , info() {
  1596. return chalk.cyanBright(`
  1597. -------------------------------------------------------------------------------
  1598. *** BBH Elixir ***
  1599. -------------------------------------------------------------------------------
  1600. elxr ${ver}
  1601. A cli tool for chess
  1602. -------------------------------------------------------------------------------
  1603. `)
  1604. }
  1605. , getpulltask(def){
  1606. // def can be an instance config
  1607. // Or an object with many repos and elevated repos
  1608. // Or a single repo ( Either Elevated or normal. )
  1609. // USAGE
  1610. // elxr pull elixir origin master
  1611. // elxr pull
  1612. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  1613. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  1614. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  1615. // The branch pipline should feed back to master
  1616. // master -> test -> stage -> release[nnnn] -> production
  1617. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  1618. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  1619. var __args = {
  1620. remotename : args.remotename|| processedArgs._[2]
  1621. , url : args.url || processedArgs._[3]
  1622. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  1623. }
  1624. // var commands = [
  1625. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  1626. // ,
  1627. // ]
  1628. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1629. // var pullCmd = [ gitbash
  1630. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1631. // , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  1632. def = def || {
  1633. repos : selectedinstance.repos,
  1634. elevated : selectedinstance.elevated
  1635. }
  1636. var elevatedpulltasks = null;
  1637. if(def.repo) {
  1638. // Single repo case.
  1639. if(def.repo.requiresElevation) {
  1640. elevatedpulltasks = function() {
  1641. return performPull(def.repo).then(() => {
  1642. return true;
  1643. }).catch((e) => {
  1644. console.error(e)
  1645. })
  1646. }
  1647. return
  1648. }
  1649. else {
  1650. var regularpulltasks = function(){
  1651. var pendingpulls = [];
  1652. pendingpulls.push(performPull(def.repo))
  1653. return Promise.all(pendingpulls).finally(Traq.finally)
  1654. }
  1655. }
  1656. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1657. else return getTaskWithoutElevation({ regularpulltasks})
  1658. }
  1659. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1660. console.dir(def)
  1661. var env = Object.assign({}, process.env); // Shallow clone it.
  1662. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1663. var useGitPull = processedArgs.useGitPull || false;
  1664. if(def.elevated || def.repos) {
  1665. if(def.elevated) def.requiresElevation = true;
  1666. else delete def.requiresElevation;
  1667. }
  1668. else {
  1669. if(def.requiresElevation) def.elevated = [def]
  1670. else def.repos = [def]
  1671. }
  1672. var regularpulltasks = function(){ return Promise.resolve(true) }
  1673. if(def.elevated){
  1674. elevatedpulltasks = function() {
  1675. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1676. return true;
  1677. }).catch((e) => {
  1678. console.error(e)
  1679. })
  1680. }
  1681. }
  1682. if(def.repos) {
  1683. var regularpulltasks = function(){
  1684. var pendingpulls = [];
  1685. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1686. return Promise.all(pendingpulls).finally(Traq.finally)
  1687. }
  1688. }
  1689. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1690. else return getTaskWithoutElevation({ regularpulltasks})
  1691. }
  1692. }
  1693. function preworkerconfig(){
  1694. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1695. gitRepos = selectedinstance.repos
  1696. // gitRepos = ['chess-server-lib'];
  1697. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1698. elevatedRunasRepos = selectedinstance.elevated
  1699. // Repos that should excluded from merge for releases...
  1700. exludeMergeRepos = selectedinstance.exludeMergeRepos
  1701. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1702. // mysql -u root -p db_name < drop_all_tables.sql
  1703. var mysql = '../xampp/mysql/bin/mysql'
  1704. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1705. }
  1706. // The main elxr cli process
  1707. function elxrworker() {
  1708. var subcommandlabels = {
  1709. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1710. }
  1711. var __runcmd = function (label) {
  1712. var distinquishedlabel = subcommandlabels[label] || label
  1713. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1714. }
  1715. // --runas
  1716. if (processedArgs.runas) {
  1717. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1718. return __runcmd('runas')
  1719. }
  1720. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1721. }
  1722. function acquireChoices(selectedinstance) {
  1723. var hasconfig = false;
  1724. console.warn(chalk.cyan(`
  1725. -------------------------------------------------------------------------------
  1726. Warning : Cannot locate your preferred configuration since it was not specified
  1727. You should fork the default chess configuration to customize and make it
  1728. your own instance with a named config as
  1729. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1730. And then run this tool as follows
  1731. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1732. OR
  1733. Run this tool with the following command to use a quick start default.
  1734. elxr --default
  1735. OR
  1736. Choose one of the options below to run interactively.
  1737. We will run your choice at the next prompt.
  1738. -------------------------------------------------------------------------------
  1739. `))
  1740. var prompt = cli.prompter;
  1741. return prompt.ask(`Choose an option :
  1742. d) Install the default chess instance.
  1743. => elxr i chess node_env=development --default
  1744. n) Create your custom new instance interactively
  1745. => elxr i {{instanceName}} node_env={{environment}}
  1746. i) Choose an instance and environment to install
  1747. => elxr i {{instanceName}} node_env={{environment}}
  1748. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1749. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1750. h) Help
  1751. q) Quit
  1752. Default <= d
  1753. : `).then((choice) => {
  1754. if (choice && choice === 'd' || !choice) {
  1755. processedArgs._[0] = 'i'
  1756. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1757. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1758. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1759. }
  1760. else if (choice === 'h') {
  1761. processedArgs._[0] = 'h'
  1762. fs.writeFileSync('run.done', 'noop help');
  1763. console.log(elxr.help()); process.exit()
  1764. }
  1765. else if (choice === 'n' || choice === 'i') {
  1766. var p1 = cli.prompter;
  1767. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1768. processedArgs._[0] = 'i'
  1769. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1770. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1771. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1772. if (choice === 'n') {
  1773. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1774. console.warn(
  1775. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1776. process.exit();
  1777. }
  1778. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1779. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1780. })
  1781. })
  1782. })
  1783. } else if (choice === 'c') {
  1784. var p1 = cli.prompter;
  1785. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1786. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1787. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1788. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1789. return p1.ask(`Enter cmd :
  1790. p) pull
  1791. Default <= p
  1792. : `).then(function (cmd) {
  1793. if (!cmd || cmd === 'p') {
  1794. processedArgs._[0] = 'pull'
  1795. }
  1796. else processedArgs._[0] = cmd
  1797. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1798. selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1799. })
  1800. })
  1801. })
  1802. })
  1803. } else {
  1804. 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.`));
  1805. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1806. fs.writeFileSync('run.done', 'noop quit');
  1807. process.exit()
  1808. }
  1809. })
  1810. }
  1811. var mergeObjByKey = function(arrOfObjs, keyName) {
  1812. var keyedDistinct = {}
  1813. var distinctArrOfObjs = []
  1814. arrOfObjs.forEach( o => {
  1815. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1816. })
  1817. Object.keys(keyedDistinct).forEach(key => {
  1818. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1819. })
  1820. return distinctArrOfObjs;
  1821. }
  1822. var cacheWriteInstanceConfig = function(chessinstances){
  1823. var instanceName = chessinstances['current_run'].instanceName;
  1824. var node_env = chessinstances['current_run'].node_env;
  1825. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1826. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1827. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1828. }
  1829. var acquireConfig = function (selected) {
  1830. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1831. return performPull(configrepo).then(() => {
  1832. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1833. selectedinstance = require(manifestpath)()
  1834. // Config from server always override merges into selection ecept for the current selection.
  1835. // PB : TODO -- utils.assign Array merges are non-distinct...
  1836. if(!selectedinstance.repos[0].repo) {
  1837. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1838. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  1839. }
  1840. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  1841. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1842. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  1843. }
  1844. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  1845. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  1846. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1847. cacheWriteInstanceConfig(chessinstances)
  1848. ENV.NODE_ENV = selectedinstance.node_env;
  1849. })
  1850. .catch((e) => {
  1851. console.error(e)
  1852. console.error('Config acquisition failed.')
  1853. })
  1854. }
  1855. var launchpath = path.normalize(process.cwd())
  1856. var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  1857. // The easisest would be to ask for a target directory and default to current dir....
  1858. var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  1859. var __default = {
  1860. // Default is public server only.
  1861. // All public repos are by default available.
  1862. reposervers: ['https://git.bbh.org.in']
  1863. , repos: [
  1864. { repo : 'setup' }
  1865. , { repo : 'elxr' }
  1866. , { repo : 'loopback-connector-mysql' }
  1867. , { repo : 'loopback-jsonapi-model-serializer' }
  1868. , { repo : 'loopback-component-jsonapi' }
  1869. , { repo : 'ember-service-worker' }
  1870. , { repo : 'ember-service-worker-asset-cache' }
  1871. , { repo : 'ember-service-worker-cache-fallback' }
  1872. , { repo : 'ember-service-worker-index' }
  1873. , { repo : 'ember-sw-client-route' }
  1874. ]
  1875. , elevated: []
  1876. , exludeMergeRepos: {}
  1877. , instanceName: 'chess'
  1878. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1879. , node_env: 'development'
  1880. }
  1881. var hasElxr = function(path, options, cb) {
  1882. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  1883. options = options || {};
  1884. var tasks = [
  1885. '/elxr' // Is there a subfolder named elxr
  1886. , '/elxr/.git' // which is self git repository
  1887. , '/elxr/.elxr' // and has .elxr subfolder
  1888. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  1889. ]
  1890. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  1891. var value = existsFolderSync(path + tpath);
  1892. return { value, done : acc && !value };
  1893. }).value }
  1894. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  1895. var value = existsFolderSync(path + tpath);
  1896. return { value, done : acc && !value };
  1897. }).value );
  1898. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  1899. var value = existsFolderSync(path + tpath);
  1900. return { value, done : acc && !value };
  1901. }).value);
  1902. }
  1903. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  1904. var detectfromroot = function(root){
  1905. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  1906. }
  1907. var detectinstances = function () {
  1908. console.log(`launchpath = ${launchpath}`)
  1909. console.log(`thisscriptdir = ${thisscriptdir}`)
  1910. // PB : TODO -- !Postpone this.
  1911. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  1912. // Note : Paths should already be normalized fefore this.
  1913. var root = instanceroot;
  1914. var detected = { root };
  1915. var instanceoptions = [clioverrides]
  1916. return hasElxr(launchpath).then( (elxrCliExists) => {
  1917. // We need a reference to the root director for elxr cli to be properly oriented.
  1918. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  1919. // We were run from the proper root with elxr cli in the subfolder.
  1920. instanceroot = root = launchpath;
  1921. instanceoptions.splice( 0, 0, detected = { root })
  1922. instanceoptions.splice( 0, 0, detectfromroot(root))
  1923. }
  1924. else {
  1925. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  1926. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  1927. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  1928. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  1929. instanceroot = root = launchpath;
  1930. instanceoptions.splice( 0, 0, detected = { root })
  1931. instanceoptions.splice( 0, 0, detectfromroot(root))
  1932. }
  1933. else if (launchpath === thisscriptdir) {
  1934. var parentHasElxr = hasElxrSync(launchpath + '/..')
  1935. // PB : TODO -- verify if we have .elxr folder in the parent...
  1936. if(!parentHasElxr) {
  1937. // ! thisscriptdir is not elxr.
  1938. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  1939. }
  1940. // Same directory doesn't mean we are being run from elxr sub directory.
  1941. // In standalone build script we may or not be in the same location.
  1942. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1943. // Unbuilt therefore we are in the elxr sub directory.
  1944. instanceroot = root = path.normalize(launchpath + '/..');
  1945. instanceoptions.splice( 0, 0, detected = { root });
  1946. instanceoptions.splice( 0, 0, detectfromroot(root));
  1947. }
  1948. else {
  1949. // Built version.
  1950. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  1951. if(parentHasElxr) {
  1952. // Built version was run from the full elxr subfolder. Should work
  1953. // PB : TODO -- but we should switch to the full version...
  1954. instanceroot = root = path.normalize(launchpath + '/..');
  1955. instanceoptions.splice( 0, 0, detected = { root })
  1956. instanceoptions.splice( 0, 0, detectfromroot(root))
  1957. }
  1958. else {
  1959. instanceroot = root = launchpath;
  1960. instanceoptions.splice( 0, 0, detected = { root })
  1961. instanceoptions.splice( 0, 0, detectfromroot(root))
  1962. // Assume current launchpath is a new instance and create.
  1963. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  1964. // if(clioverrides.instanceName) {
  1965. // if(clioverrides.node_env) {
  1966. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  1967. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  1968. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  1969. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  1970. // // eg : floder name can be elixir01 but instance name is elixr
  1971. // }
  1972. // else {
  1973. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  1974. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  1975. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  1976. // }
  1977. // }
  1978. // else {
  1979. // instanceroot = root = launchpath;
  1980. // if(clioverrides.node_env) {
  1981. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  1982. // instanceoptions.splice( 0, 0, detectfromroot(root))
  1983. // }
  1984. // else {
  1985. // // Nothing was specified... We only have one option from root.
  1986. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  1987. // }
  1988. // }
  1989. }
  1990. }
  1991. }
  1992. else {
  1993. if(elxrCliExists) {
  1994. instanceroot = root = launchpath;
  1995. instanceoptions.splice( 0, 0, detected = { root })
  1996. instanceoptions.splice( 0, 0, detectfromroot(root))
  1997. }
  1998. }
  1999. }
  2000. instanceroot = detected.root
  2001. __default.root = root;
  2002. clioverrides.root = clioverrides.root || root;
  2003. // Resolves empty array when No known instances detected.
  2004. return Promise.resolve(instanceoptions)
  2005. })
  2006. }
  2007. if(clioverrides.reconfirm) {
  2008. var reconfirm = { 'instanceName' : clioverrides['instanceName'] === 'chess' }
  2009. }
  2010. else { var reconfirm = {}; }
  2011. var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
  2012. return function(prompts, k, i, a){
  2013. // No local instances config found. We use a default initialized instance available in selectedinstance
  2014. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2015. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2016. if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
  2017. || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
  2018. || reconfirm[k]) {
  2019. prompts.push(async ()=>{
  2020. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2021. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2022. // If latest altered state is required we can reerence this directly.
  2023. // var asyncthis = Object.assign(this);
  2024. promptables[k].choices = choices[k]
  2025. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2026. return await target[k]
  2027. })
  2028. }
  2029. delete mustPrompt[k]
  2030. return prompts
  2031. }
  2032. }
  2033. var __interactive_prompts = function( target, choices ){
  2034. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2035. var interactionpoints = {
  2036. runchoice : {
  2037. label :
  2038. `Choose an option :
  2039. d) Install the default chess instance.
  2040. => elxr i chess node_env=development --default
  2041. n) Create your custom new instance interactively
  2042. => elxr i {{instanceName}} node_env={{environment}}
  2043. i) Choose an instance and environment to install
  2044. => elxr i {{instanceName}} node_env={{environment}}
  2045. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2046. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2047. h) Help
  2048. q) Quit
  2049. : `
  2050. , choices : []
  2051. , defaultchoice : 'c'
  2052. , interpret : function(choice){
  2053. var interpret_map = {
  2054. d : function(){
  2055. processedArgs._[0] = 'i'
  2056. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2057. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2058. target.reposerver = 'https://git.bbh.org.in'
  2059. }
  2060. , n : function() { processedArgs._[0] = 'i' }
  2061. , i : function() { processedArgs._[0] = 'i' }
  2062. , c : async function() {
  2063. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2064. label : `Enter cmd :
  2065. p) pull
  2066. Default <= p
  2067. : `
  2068. , defaultchoice : 'pull'
  2069. }
  2070. ));
  2071. var cmd = await target['cmd'];
  2072. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2073. else target['cmd'] = processedArgs._[0] = cmd
  2074. return cmd;
  2075. }
  2076. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2077. , q : function() { process.exit() }
  2078. }
  2079. var __interpreter = interpret_map['c']
  2080. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2081. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2082. return __interpreter.call(target)
  2083. }
  2084. }
  2085. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  2086. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
  2087. , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
  2088. , repouser : { label : `Enter User Id for ${target.reposerver} ( <= ${target.repouser || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  2089. }
  2090. var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices)
  2091. return Object.keys(interactionpoints).reduce(eachPrompt, [])
  2092. }
  2093. var downloadsdir = '../Downloads';
  2094. var prerequisites = [
  2095. {
  2096. shellcmd: 'git',
  2097. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2098. , installer: 'Git-2.31.0-64-bit.exe'
  2099. , installcmd: ['cmd', ['/c', 'start',
  2100. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2101. , '/VERYSILENT'
  2102. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2103. ]]
  2104. , preinstallsteps: function() {
  2105. var prompt = cli.prompter;
  2106. var steps = [
  2107. () => {
  2108. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2109. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2110. }
  2111. else return Promise.resolve(true)
  2112. }
  2113. ]
  2114. var prompts = [
  2115. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  2116. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  2117. ]
  2118. return any([any(steps), any(prompts)])
  2119. }
  2120. , installsteps: function () {
  2121. return any([this.installcmd].map(callsheltask))
  2122. }
  2123. , postinstallsteps: function(){
  2124. var prompt = cli.prompter;
  2125. var gitUser = 'guest';
  2126. var gitEmail = 'guest@bbh.org.in';
  2127. var prompts = [];
  2128. prompts.push(
  2129. ()=>{
  2130. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  2131. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  2132. }
  2133. )
  2134. prompts.push(
  2135. ()=>{
  2136. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  2137. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  2138. }
  2139. )
  2140. return any(prompts).then(()=>{
  2141. var steps = [
  2142. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2143. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2144. ]
  2145. return any(steps.map(callsheltask)).then(() => {
  2146. })
  2147. });
  2148. }
  2149. , install: function () {
  2150. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2151. }
  2152. , verifyAndInstall : function(){
  2153. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2154. if(exists) {
  2155. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  2156. return this.getUser(null, this.postinstallsteps.bind(this))
  2157. }
  2158. return this.install();
  2159. });
  2160. }
  2161. , getUser : function(repo, onNoResult){
  2162. onNoResult = onNoResult || function(){return false}
  2163. var globalOrLocal = '--global';
  2164. if(!repo) globalOrLocal = '--global';
  2165. else globalOrLocal = '--local'
  2166. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  2167. // not yet configured.
  2168. if(!result.success) return onNoResult()
  2169. else {
  2170. var users = result.messages[0].trim().split('\n');
  2171. if(users.length === 0 ||
  2172. users.length === 1 && users[0] === 'guest') {
  2173. return onNoResult()
  2174. }
  2175. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  2176. }
  2177. })
  2178. .catch((e)=>{
  2179. console.log(e)
  2180. return onNoResult()
  2181. })
  2182. }
  2183. }
  2184. ,
  2185. {
  2186. shellcmd: 'node',
  2187. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  2188. , installer: 'node-v14.16.0-x64.msi'
  2189. , installcmd: ['MSIEXEC.exe', ['/i'
  2190. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  2191. , 'ACCEPT=YES', '/passive']]
  2192. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  2193. }
  2194. ]
  2195. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  2196. function ensureDirectoryExistence(filePath) {
  2197. var dirname = path.dirname(filePath);
  2198. if (fs.existsSync(dirname)) {
  2199. return filePath;
  2200. }
  2201. ensureDirectoryExistence(dirname);
  2202. fs.mkdirSync(dirname);
  2203. return filePath;
  2204. }
  2205. var mainTasks = [];
  2206. function verifyAndInstallPrerequisites() {
  2207. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  2208. // PB : TODO include and build from files... using rollup..
  2209. var downloadbatch =
  2210. `::**************************************************************************
  2211. :Download_ <url> <File>
  2212. Powershell.exe ^
  2213. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2214. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2215. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2216. exit /b
  2217. ::**************************************************************************`
  2218. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  2219. var windowselevate =
  2220. `
  2221. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2222. <script language="vbscript">
  2223. document.title = "elxr control panel"
  2224. self.ResizeTo 200,600
  2225. Sub Window_Onload
  2226. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2227. End Sub
  2228. Set objShell = CreateObject("WScript.Shell")
  2229. Set objENV = objShell.Environment("Process")
  2230. dim NODE_ENV
  2231. NODE_ENV = objENV("NODE_ENV")
  2232. </script>
  2233. <script language="javascript">
  2234. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2235. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2236. // alert(windowselevate.commandLine)
  2237. var args = windowselevate.commandLine.split('"').slice(3);
  2238. // alert(args)
  2239. var processedArgs = { _ : [] }
  2240. var namedArgs = [];
  2241. for(var item in args){
  2242. if(args[item].charAt(0) === '-'){
  2243. namedArgs.push(args[item])
  2244. var split = args[item].split('=');
  2245. processedArgs[split[0].slice(2)] = split[1] || true;
  2246. }
  2247. else processedArgs._.push(args[item]);
  2248. }
  2249. // args = args.forEach(function(item){ })
  2250. // alert('processedArgs._ : ' + processedArgs._);
  2251. // alert(processedArgs.runas);
  2252. // PB : TODO -- Convert all the cli args back to string.
  2253. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2254. // alert(cargs)
  2255. var shell = new ActiveXObject('shell.application');
  2256. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2257. // shell.ShellExecute('where', 'node', '', '', 10);
  2258. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2259. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2260. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2261. window.onload = function() {
  2262. document.body.style.backgroundColor = 'black';
  2263. document.body.style.fontFamily = 'arial';
  2264. var log = document.createElement('div');
  2265. log.innerHTML='Please Wait';
  2266. function l(msg){ log.innerHTML+= msg; };
  2267. log.style.color = 'blue';
  2268. log.style.width = '95%';
  2269. log.id = 'log';
  2270. document.body.appendChild(log);
  2271. l('<Br/>Current config : ')
  2272. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2273. l('<Br/>cmd = ' + processedArgs._[0])
  2274. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2275. l('<Br/><Br/>')
  2276. var timer = function(){
  2277. l('.');
  2278. if(fso.FileExists("run.done")) close();
  2279. else window.setTimeout(timer, 1000);
  2280. };
  2281. window.setTimeout(timer, 3000);
  2282. };
  2283. </script>
  2284. </html>
  2285. `
  2286. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2287. var downloadtasks = [];
  2288. var installtasks = [];
  2289. prerequisites.forEach(preq => {
  2290. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2291. if (exists) console.log(`${preq.shellcmd} exists`)
  2292. else {
  2293. console.log(`${preq.shellcmd} is not installed`)
  2294. return preq.preinstallsteps.call(preq).then(() => {
  2295. installtasks.push(preq.install.bind(preq))
  2296. })
  2297. }
  2298. }))
  2299. })
  2300. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2301. }
  2302. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  2303. return {
  2304. get (){
  2305. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  2306. var asyncprop = Promise.resolve(propValue)
  2307. if(promptable.interpret){
  2308. asyncprop = promptable.interpret(propValue)
  2309. }
  2310. return asyncprop.then(
  2311. ()=>{
  2312. Object.defineProperty(this, propName, {
  2313. value: propValue,
  2314. writable: true,
  2315. configurable : true,
  2316. enumerable : true
  2317. });
  2318. return propValue
  2319. }
  2320. )
  2321. })
  2322. }
  2323. // , set (propValue){
  2324. // Object.defineProperty(this, propName, {
  2325. // value: propValue,
  2326. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  2327. // configurable : true,
  2328. // enumerable : true
  2329. // })
  2330. // return propValue;
  2331. // }
  2332. , configurable : true
  2333. , enumerable : true
  2334. }
  2335. }
  2336. function acquirelocalinstances(selected){
  2337. // utils.assign is used to cleanup duplicates...
  2338. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2339. return chessinstances
  2340. }
  2341. function findlocalinstances(chessinstances, instanceoptions){
  2342. // We can expect a .elxr at each level.
  2343. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  2344. earlyreduce( ( value, p, i, a )=>{
  2345. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  2346. if(existsSync( localinstancesPath )) {
  2347. try {
  2348. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  2349. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  2350. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  2351. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  2352. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  2353. return {
  2354. value : chessinstances[instanceName][instanceType]
  2355. , done : true
  2356. };
  2357. }
  2358. })
  2359. })
  2360. }
  2361. catch(e){
  2362. return { }
  2363. }
  2364. }
  2365. else return { }
  2366. }
  2367. )
  2368. }
  2369. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2370. var selectedinstance = null;
  2371. var chessinstances = { current_run : {} };
  2372. var promptkeys = {
  2373. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  2374. // 'instanceName' : true
  2375. // , 'node_env' : true
  2376. }
  2377. function createChessInsance( cfg ){
  2378. var inst = {};
  2379. var __new = Object.assign({}, __default, cfg)
  2380. inst[cfg.node_env] = __new; return inst;
  2381. }
  2382. acquireElevationState().then(() => {
  2383. var skipprerequisites = false;
  2384. function initinstances(selected_overrides) {
  2385. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectinstances.
  2386. var instanceName = selected_overrides.instanceName
  2387. || clioverrides.instanceName
  2388. // || processedArgs._[1]
  2389. || chessinstances.current_run.instanceName
  2390. var node_env = selected_overrides.node_env
  2391. || clioverrides.node_env
  2392. // || processedArgs.node_env
  2393. || chessinstances.current_run.node_env
  2394. var reposerver = selected_overrides.reposerver
  2395. || clioverrides.reposerver
  2396. // || processedArgs.node_env
  2397. || chessinstances.current_run.reposerver
  2398. if(!instanceName) {
  2399. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  2400. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2401. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2402. }
  2403. if(!node_env) {
  2404. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2405. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2406. }
  2407. if(!reposerver) {
  2408. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2409. }
  2410. chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
  2411. instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
  2412. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  2413. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  2414. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  2415. }
  2416. // Override sequence.
  2417. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2418. selectedinstance = utils.assign(
  2419. chessinstances[instanceName][node_env]
  2420. , clioverrides
  2421. , selected_overrides
  2422. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  2423. );
  2424. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  2425. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  2426. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  2427. // // Brand New.
  2428. // selectedinstance = Object.assign( __default, selectedinstance )
  2429. // }
  2430. if(!selectedinstance.repos[0].repo) {
  2431. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2432. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2433. }
  2434. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2435. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2436. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2437. }
  2438. // Config from server always override merges into selection except for the current selection.
  2439. // PB : TODO -- utils.assign Array merges are non-distinct...
  2440. chessinstances[instanceName][node_env] = selectedinstance;
  2441. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2442. cacheWriteInstanceConfig(chessinstances)
  2443. // PB : TODO -- We should probably write the new server config also...
  2444. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2445. return chessinstances
  2446. }
  2447. var noprerequisites = {
  2448. add : true, 'set-url' : true, 'repo-relocate' : true
  2449. , remote : true
  2450. }
  2451. var skipprereqs = {}
  2452. var maintask = () => {
  2453. // Default cmd to run !
  2454. processedArgs._[0] === processedArgs._[0] || 'pull';
  2455. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  2456. if(!noprerequisites[processedArgs._[0]]
  2457. && !skipprereqs[processedArgs._[0]]
  2458. ) {
  2459. return prerequisites.git.verifyAndInstall().then(()=>{
  2460. var e = { message : 'verifyAndInstall', success : true}
  2461. return acquireConfig(selectedinstance).catch((err) => {
  2462. e = err;
  2463. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  2464. console.error(err)
  2465. }).then(() => { preworkerconfig(); return elxrworker(true) })
  2466. // .finally(()=>{
  2467. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2468. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2469. // // return process.exit()
  2470. // })
  2471. })
  2472. }
  2473. else {
  2474. console.log('cmd has no preqs or has been configured to skip preqs')
  2475. preworkerconfig()
  2476. return elxrworker()
  2477. }
  2478. }
  2479. const retaincount = 2
  2480. var min = runtimestamp;
  2481. var collect = []
  2482. if(noprerequisites[processedArgs._[0]]
  2483. || skipprereqs[processedArgs._[0]]
  2484. ) {
  2485. return elxrworker()
  2486. }
  2487. var getchoices = function(detectedinstanceoptions, promptkeys){
  2488. var instances = []
  2489. var reposervers = [];
  2490. var instnaceNames = []
  2491. var instanceTypes = ['development', 'production'];
  2492. Object.keys( chessinstances).forEach(instanceName => {
  2493. if(instanceName === 'current_run') return;
  2494. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  2495. var instance = chessinstances[instanceName][node_env];
  2496. reposervers = reposervers.concat(instance.reposervers)
  2497. if(instance.reposerver) reposervers.push(instance.reposerver)
  2498. instances.push(instance)
  2499. instanceTypes.push(instance.node_env)
  2500. instnaceNames.push(instance.instanceName)
  2501. })
  2502. })
  2503. instances = instances.concat(detectedinstanceoptions)
  2504. if(selectedinstance['instanceName']) instnaceNames.push(selectedinstance['instanceName'])
  2505. if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName'])
  2506. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  2507. var choices = {
  2508. 'instanceName' : Array.from( new Set(instnaceNames) )
  2509. , 'reposerver' : Array.from( new Set(reposervers) )
  2510. , 'instanceType' : Array.from( new Set(instanceTypes) )
  2511. }
  2512. return choices;
  2513. }
  2514. return detectinstances().then((detectedinstanceoptions)=>{
  2515. detectedinstanceoptions.splice(0,0, __default)
  2516. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  2517. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2) )
  2518. // promptkeys = utils.assign(promptkeys, clioverrides)
  2519. try {
  2520. chessinstances = acquirelocalinstances(selectedinstance);
  2521. findlocalinstances(chessinstances, detectedinstanceoptions)
  2522. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  2523. var choices = getchoices(detectedinstanceoptions, promptkeys)
  2524. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2525. return initinstances(selectedinstance)
  2526. })
  2527. }
  2528. catch (e) {
  2529. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  2530. var choices = getchoices(detectedinstanceoptions, promptkeys)
  2531. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2532. return initinstances(selectedinstance)
  2533. })
  2534. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2535. // // Weve not been told what to do.
  2536. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  2537. // }
  2538. todo = todo.then(() => {
  2539. try {
  2540. chessinstances = acquirelocalinstances(selectedinstance)
  2541. findlocalinstances(chessinstances, detectedinstanceoptions)
  2542. detectedinstanceoptions.splice(0,0, __default)
  2543. initinstances(selectedinstance)
  2544. }
  2545. catch (e) {
  2546. console.error(e)
  2547. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2548. console.log('A config will be createed with the instance and environment chosen...')
  2549. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2550. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2551. // return selectedinstance = Object.assign(__default, selectedinstance);
  2552. // })
  2553. return selectedinstance
  2554. }
  2555. })
  2556. }
  2557. return todo
  2558. })
  2559. .then(()=>{
  2560. if(!__isElevated) {
  2561. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  2562. // collect garbage
  2563. return dirs( (dir)=>{
  2564. var matches = /run-(.*)/gm.exec(dir.name)
  2565. if(matches) {
  2566. if(+(matches[1]) < min) {
  2567. min = matches[1]
  2568. collect.splice( 0, 0, matches[1] )
  2569. }
  2570. else collect.push(matches[1])
  2571. }
  2572. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  2573. // delete garbage
  2574. if(collect.length > retaincount) {
  2575. var asyncs = [];
  2576. while((collect.length - asyncs.length) > retaincount) {
  2577. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  2578. }
  2579. return Promise.all(asyncs)
  2580. }
  2581. else return true
  2582. })
  2583. }
  2584. else return true;
  2585. })
  2586. .then(()=>{
  2587. // PB : TODO -- Keep only the last n runs...
  2588. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  2589. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  2590. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  2591. mainTasks.push(maintask)
  2592. return any(mainTasks);
  2593. })
  2594. })
  2595. // detect if alread installed -> Take no action.
  2596. // download if no installer avalable -> next()
  2597. // install
  2598. function chackandinstall(items) {
  2599. var tasks = []
  2600. items.forEach(item => {
  2601. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  2602. })
  2603. return Promise.all(tasks).then(existances => {
  2604. existances.forEach((exists, i) => {
  2605. if (!exists) {
  2606. return downloadandinstall([items[i]])
  2607. }
  2608. })
  2609. })
  2610. }
  2611. function downloadandinstall(items) {
  2612. var tasks = []
  2613. items.forEach(item => {
  2614. tasks.push(getTaskDownload(item))
  2615. })
  2616. return Promise.all(tasks)
  2617. }
  2618. // Sample instances config.
  2619. // var instances = {
  2620. // "elixir": {
  2621. // "production": {
  2622. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  2623. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  2624. // , "exludeMergeRepos": {
  2625. // "elixir-config-development": true, "elixir-config-test": true
  2626. // , "elixir-config-production": true, "elixir-data": true
  2627. // }
  2628. // , "instanceName": "elixir", "node_env": "production"
  2629. // }
  2630. // },
  2631. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  2632. // }
  2633. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...