Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 154KB

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