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

пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  1. var scripthostName = 'node'
  2. var __Promise = {};
  3. var promises = [];
  4. function startPromises(){
  5. promises.forEach(function(p){
  6. // console.log(p.chain)
  7. p ? p() : null;
  8. // promises.splice(0,1)
  9. })
  10. }
  11. function isWin(){ return /^win/.test(process.platform) }
  12. var stampedFilePfx = function(date) {
  13. return date.getFullYear() +
  14. ('0' + (date.getMonth() + 1)).slice(-2) +
  15. ('0' + date.getDate()).slice(-2) +
  16. ('0' + date.getHours()).slice(-2) +
  17. ('0' + date.getMinutes()).slice(-2) +
  18. ('0' + date.getSeconds()).slice(-2);
  19. }
  20. var runtimestamp = (new Date()).getTime();
  21. try {
  22. console.log("detected node")
  23. // var WScript = console || WScript // Dummy
  24. // console.Echo = console.log
  25. __Promise = Promise
  26. var __require = require
  27. var map = Array.map
  28. function startPromises(){
  29. promises.forEach(function(p){
  30. // console.log(p.chain)
  31. p ? Promise.resolve(p) === p ? p : p() : null;
  32. // promises.splice(0,1)
  33. })
  34. }
  35. // --------------------------------------------
  36. // Node Exists. Lets launch ourselves in Node itself
  37. WScript = function(){}
  38. WScript.Echo = function(m){
  39. console.log('Invalid Wscript')
  40. throw "Failed in Node Run."
  41. }
  42. var wait = function(ms, cb) {any
  43. return new __Promise(function(resolve){ setTimeout(resolve, ms) } ).then(function(){ cb() });
  44. }
  45. var fs = require('fs')
  46. var existsSync = require('fs').existsSync;
  47. var existsSyncFolder = existsSync
  48. var path = require('path');
  49. console.log('before cliverse')
  50. var cli = require('./cliverse')
  51. var nodeShellExec = cli.nodeShellExec;
  52. console.log('before bbhverse')
  53. var utils = require('bbhverse');
  54. var any = utils.any;
  55. var wait = setTimeout
  56. // --------------------------------------------
  57. // PB : TODO -- This should be parent dir if elxr is already installed.
  58. var selectedinstance = { root : path.resolve(".") }
  59. __main(selectedinstance)
  60. }
  61. catch(e) {
  62. WScript.Echo('detected wsh')
  63. scripthostName = 'wsh'
  64. WScript.Echo(WScript.FullName)
  65. // WScript.Echo('--' + WScript.Arguments(0) + '--')
  66. // WScript.Echo('------------ALL-----------')
  67. // var argEnumerator = new Enumerator(WScript.Arguments)
  68. // for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
  69. // WScript.Echo('-arg-' + argEnumerator.item() + '-arg-')
  70. // }
  71. // // Unnamed
  72. // WScript.Echo('------------UNNAMED-----------')
  73. // argEnumerator = new Enumerator(WScript.Arguments.Unnamed)
  74. // for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
  75. // WScript.Echo('-arg-' + argEnumerator.item() + '-arg-') // Value
  76. // }
  77. // // Named
  78. // WScript.Echo('------------NAMED-----------')
  79. // argEnumerator = new Enumerator(WScript.Arguments.Named)
  80. // for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
  81. // // WScript.Echo('-arg-' + argEnumerator.item(argEnumerator) + '-arg-') // Key
  82. // WScript.Echo('-key-' + argEnumerator.item() + '-key-') // Key
  83. // WScript.Echo('-val=' + WScript.Arguments.Named(argEnumerator.item()) + '=val-') // Value
  84. // }
  85. // cscript elxr/i.win.js /all:true
  86. var all = WScript.Arguments.Named('all');
  87. trim = function(str) { return str.replace(/^\s+|\s+$/g, ''); };
  88. var fs = new ActiveXObject('Scripting.FileSystemObject');
  89. var WshShell = WScript.CreateObject("WScript.Shell")
  90. var ENV = WshShell.Environment("Process")
  91. var sfn = WScript.ScriptFullName
  92. // WScript.Echo(sfn)
  93. var cd = fs.GetAbsolutePathName(".")
  94. var cfn = cd + '\\i.win.js'
  95. // WScript.Echo(cfn)
  96. var waslaunchedwithenv = trim(ENV.Item('LAUNCHEDWITHENV'));
  97. // for(e=new Enumerator(ENV); !e.atEnd(); e.moveNext()) WScript.echo(e.item(e));
  98. if(waslaunchedwithenv !== "YES"){
  99. var a = fs.CreateTextFile("launchwithenv.bat", true)
  100. a.WriteLine("@echo off")
  101. a.WriteLine("echo %PATH%")
  102. var gitpath = "C:\\Program Files\\Git\\cmd"
  103. var nodepath = "C:\\Program Files\\nodejs\\"
  104. var codepath = "C:\\Users\\Pradeep\\AppData\\Local\\Programs\\Microsoft VS Code\\bin"
  105. var python2path = "C:\\Python27" // Python installer doesnt write to PATH!!!
  106. a.WriteLine("set PATH=%PATH%;" + gitpath )
  107. a.WriteLine("set PATH=%PATH%;" + nodepath )
  108. a.WriteLine("set PATH=%PATH%;" + codepath )
  109. a.WriteLine("set PATH=%PATH%;" + python2path )
  110. // a.WriteLine("set LAUNCHEDWITHENV=YES" )
  111. var __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  112. var currentIsExlr = function() {
  113. if(fs.FileExists('./' + __ALIAS__STAMP__)) return true
  114. }
  115. var runningInExlr = currentIsExlr()
  116. if(cfn === sfn && runningInExlr) {
  117. a.WriteLine("cd ..");
  118. a.WriteLine("SET LAUNCHEDWITHENV=YES && cscript "+cfn+" /all:true") // PB : TODO -- Retain all script args...
  119. }
  120. else {
  121. var guesselxr = fs.FileExists(cd + './elxr/' + __ALIAS__STAMP__)
  122. if(guesselxr) {
  123. a.WriteLine("SET LAUNCHEDWITHENV=YES && cscript "+cd + './elxr/' + 'i.win.js' +" /all:true")
  124. }
  125. else a.WriteLine("SET LAUNCHEDWITHENV=YES && cscript "+sfn+" /all:true")
  126. }
  127. // a.WriteLine("powershell.exe ^")
  128. // a.WriteLine("[Environment]::GetEnvironmentVariable('Path')" )
  129. a.Close()
  130. WshShell.run("cmd /k launchwithenv.bat")
  131. WScript.Quit()
  132. // WshShell.run("powershell -noexit [Environment]::GetEnvironmentVariable(\"\"Path\"\"\) ")
  133. // WshShell.run("powershell -noexit [Environment]::SetEnvironmentVariable(\"\"Path\"\", $env:Path + \"\";C:\\tttt\"\", \"\"Machine\"\"\) ")
  134. }
  135. console = {
  136. log : function(m) { WScript.Echo(m)}
  137. , error : function(m) {WScript.Echo(m) }
  138. , dir : function(o) {
  139. for(var i in o){ console.log(i + ' : ' + o[i])}
  140. }
  141. }
  142. // if(!String.prototype.trim) String.prototype.trim = function(){
  143. // return this.replace(/^\s+|\s+$/g, '');
  144. // };
  145. // var ovrrides = {
  146. // resolve : function(v){
  147. // if(v && v.then) return v;
  148. // var p = new Promise(function(resolve, reject){ resolve(v) });
  149. // return p;
  150. // }
  151. // };
  152. // // --------------------------------------------
  153. // // Cscript
  154. var wsh = true;
  155. function isWin(){ return true; }
  156. // If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then
  157. var clii = {
  158. question : function(q, answercb){
  159. WScript.Echo(q)
  160. // console.log('WScript.StdIn : ' + WScript.StdIn.ReadLine() + ' ==== ')
  161. var answer = WScript.StdIn.ReadLine()
  162. answercb(answer)
  163. }
  164. }
  165. var prompter = {
  166. ask : function(q){
  167. // Needs to be serialized. Parallel asks are not possible.
  168. // const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
  169. return new Promise(function(resolve, reject){
  170. clii.question(q, function(answer){
  171. // clii.close();
  172. // console.log("resolve is being called");
  173. resolve(answer)
  174. })
  175. })
  176. }
  177. }
  178. var cli = {
  179. prompt : function(choices, label, defaultchoice){
  180. var options = [];
  181. choices.forEach = forEach
  182. choices.forEach(function(choice){ options.push( ((+choice) + 1) + ' ' + choices[choice] )})
  183. return prompter.ask( label + ' \\n ' + options.join('\n') + '\n default ( <= ' + (defaultchoice || choices[0]) + ' ) : '
  184. ).then( function(choice){
  185. if(!choice) return defaultchoice || choices[0];
  186. if(choice && isNaN(+choice)) return choice;
  187. return choices[(+choice) - 1];
  188. })
  189. }
  190. }
  191. var any = function(iterable, continueOnFailure) {
  192. // var cancelsignal = Symbol()
  193. if(!iterable.reduce) iterable.reduce = reduce
  194. // console.log('iterable.reduce ' + iterable.reduce)
  195. var cancelsignal = "cancelme{mangledrunid}"
  196. return iterable.reduce(
  197. function(p, tasq, i ,a) {
  198. // console.dir(a)
  199. // console.log('Entered')
  200. var handleError = function(err, pVal){
  201. if(err !== cancelsignal) {
  202. // Cancel only once on first failure.
  203. console.warn('Possible failure for task with result : ' )
  204. console.log('Failed : ' + err.message + ' ')
  205. console.dir(pVal)
  206. console.dir(p)
  207. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  208. console.error('Error : ' + err.stack)
  209. console.error(a[i-1])
  210. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  211. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  212. else return pVal;
  213. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  214. }
  215. }
  216. if(Promise.resolve(p) === p ) {
  217. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  218. console.dir(' p.then is ' + p.then)
  219. return p.then( function(pVal){
  220. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  221. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  222. // Failures are known for promises on reject.
  223. // In future if we support direct sync function execution with a result examination for failure
  224. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  225. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  226. // Truthy values are failures if obj has error=true.
  227. if(pVal && pVal.error) handleError(pVal, pVal)
  228. var trycall = function(tasq){
  229. try {
  230. var result = tasq() // PB : TODO -- Handle scope for call
  231. if(tasq.resultHandler) return tasq.resultHandler(result)
  232. // else (Promise.resolve(result) === result ) ? result.start() : null
  233. return result
  234. } catch (error) {
  235. console.error(error);
  236. console.error('Error : ' + error ? error.stack : 'No stack')
  237. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  238. }
  239. }
  240. var handleNext = function(){
  241. // console.log('Task finished with result : ')
  242. // console.dir(pVal)
  243. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  244. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  245. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  246. return (Promise.resolve(tasq) === tasq ) ? tasq /*.start()*/ : trycall(tasq) ;
  247. }
  248. if(Promise.resolve(pVal) === pVal) {
  249. // Passed in function retured a promise. We still need to wait for it.
  250. pVal.then(function(pVal){ return handleNext(); })
  251. }
  252. else return handleNext()
  253. })['catch'](function(error) {
  254. if(error !== cancelsignal) {
  255. console.log('E3 : i = ' + i);
  256. if(error.result) console.error(error.result)
  257. console.error('Error : ' + (error.message || error.messages))
  258. console.error('Error : ' + error.stack)
  259. tasq ? console.log("tasq : " + tasq.toString()) : null;
  260. console.log('debugData 3-------------------------');
  261. // handleError()
  262. throw error
  263. }
  264. else throw cancelsignal;
  265. })
  266. }
  267. else if(!p) {
  268. handleError({ error : true, message : 'Failed without result' }, pVal)
  269. console.log("Bypass remaining on prior failure");
  270. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  271. }
  272. else return p; // A truthy value
  273. }
  274. , Promise.resolve(true)
  275. );
  276. }
  277. // __Promise = ovrrides
  278. function forEach(eachFn){
  279. for(var i=0; i<this.length; i++) eachFn(this[i])
  280. }
  281. function reduce(reducnFn, iv){
  282. var acc = iv
  283. for(var i=0; i<this.length; i++) {acc = reducnFn(acc, this[i], i, this) }
  284. return acc;
  285. }
  286. function map(eachFn){
  287. var mapped = []
  288. for(var i=0; i<this.length; i++) mapped.push(eachFn(this[i]))
  289. return mapped
  290. }
  291. var wait = function(cb, ms) { WScript.Sleep(ms); cb() }
  292. var fso = new ActiveXObject('Scripting.FileSystemObject');
  293. var existsSync = function(filepath){ return fso.FileExists(filepath) }
  294. var fs = {
  295. writeFileSync : function(filepath, text) {
  296. // console.log(filepath)
  297. var fh = fso.CreateTextFile(filepath, true);
  298. fh.WriteLine(text);
  299. fh.Close();
  300. }
  301. , mkdirSync : function(path) {
  302. fso.CreateFolder(path)
  303. }
  304. , readFileSync : function(filepath){
  305. var objFileToRead = fso.OpenTextFile(filepath,1)
  306. var strFileText = objFileToRead.ReadAll()
  307. objFileToRead.Close()
  308. return strFileText
  309. }
  310. , unlinkSync : function(filepath){ fso.DeleteFile(filepath) }
  311. }
  312. var path = {
  313. resolve : function(path){ return fso.GetAbsolutePathName(path) }
  314. , dirname : function(filepath) {
  315. var normalized = this.normalize(filepath)
  316. var li = normalized.lastIndexOf("\\")
  317. if( li > -1) {
  318. return normalized.substring(0, li)
  319. }
  320. }
  321. , normalize : function(path){
  322. return path.replace(/\//g,'\\');
  323. }
  324. }
  325. // Detect or specify install directory.
  326. var selectedinstance = { root : path.resolve(".") }
  327. var existsSyncFolder = function(path){
  328. return fso.FolderExists(path)
  329. }
  330. var shell = new ActiveXObject('shell.application');
  331. promises.forEach = forEach
  332. function startPromises(){
  333. promises.forEach(function(p){
  334. // console.log(p.chain)
  335. p.start();
  336. // promises.splice(0,1)
  337. })
  338. }
  339. function batchshellescape(str) {
  340. return str.replace('=', '^=')
  341. }
  342. function nodeShellExec(command, cargs, options){
  343. // for(var arg=0; arg < cargs.length; arg++) {
  344. // // cargs[arg] = '"' + batchshellescape(cargs[arg]) +'"';
  345. // cargs[arg] = '"' + cargs[arg] +'"';
  346. // }
  347. var elevatedshellexecute = function(cmd, argstr){
  348. shell.ShellExecute(cmd, argstr , "", "", 1);
  349. }
  350. var shellExec = function(cmd, argstr){
  351. var objShell = WScript.createobject("wscript.shell")
  352. // console.log(argstr.join( ' '))
  353. console.log(cmd + ' ' + argstr.join(' '))
  354. var oExec = objShell.Exec(cmd + ' ' + argstr.join(' '))
  355. var result = {}
  356. var shellresult = { shell : objShell, result : result }
  357. var WshRunning = 0
  358. var WshFinished = 1
  359. var WshFailed = 2
  360. while(oExec.Status === WshRunning){
  361. WScript.StdOut.write('s.')
  362. WScript.Sleep(500)
  363. }
  364. var strOutput = '\n'
  365. switch(oExec.Status) {
  366. case WshFinished :
  367. strOutput = oExec.StdOut.ReadAll()
  368. result.success = true;
  369. result.code = 0
  370. break;
  371. case WshFailed :
  372. strOutput = oExec.StdErr.ReadAll()
  373. result.success = false;
  374. result.code = WshFailed
  375. break;
  376. default : strOutput = 'failed'
  377. break;
  378. }
  379. result.result = command + ' ' + cargs + ' exited with code ' + result.code
  380. result.messages = [strOutput]
  381. // console.log(strOutput)
  382. // WScript.Echo(oExec.Status)
  383. // WScript.Echo(oExec.ProcessID)
  384. // WScript.Echo(oExec.ExitCode)
  385. // console.log(objShell.StdOut.ReadAll)
  386. // console.log(objShell.StdErr.ReadAll)
  387. // objShell = WScript.createobject("wscript.shell")
  388. objShell = null;
  389. return shellresult;
  390. }
  391. var p = null;
  392. var pworker = function(resolve, reject){
  393. // console.dir(p)
  394. var pfx = selectedinstance.root + '\\.elxr\\run-' + runtimestamp + '\\' + stampedFilePfx(new Date())
  395. // console.log('p.chain.length ================ ' + p.chain.length)
  396. options = options || {
  397. runFile : path.normalize( pfx + "out.txt")
  398. // runFile : null
  399. }
  400. var runFile = null;
  401. var runFile = options.runFile || pfx + command + cargs + "out.txt";
  402. // console.log(runFile)
  403. var args = cargs.concat()
  404. // runFile ? (args.push(">"), args.push(runFile)) : cargs
  405. // console.log(command + ' ' + args.join(' '))
  406. // command = 'cmd'
  407. // args = ['/c', 'start',
  408. // '/WAIT', selectedinstance.root + '/Downloads' + '/' + 'Git-2.33.0.2-64-bit.exe'
  409. // , '/VERYSILENT'
  410. // // , '/MERGETASKS=!runcode' // This is required only for vscode...
  411. // ]
  412. var runbat = path.normalize(pfx + "run.bat")
  413. // console.log('runbat : ' + runbat)
  414. fs.writeFileSync(runbat,
  415. '@echo off \r\n' +
  416. (options.cwd ? 'cd ' + options.cwd + ' \r\n' : '') +
  417. // ' cmd /k notepad.exe \r\n' +
  418. command + ' ' + args.join(' ') + ' \r\n' +
  419. 'cmd /c echo done >> ' + runFile + ' \r\n' +
  420. 'echo done'
  421. )
  422. // fs.writeFileSync(runFile, 'started')
  423. // WScript.Quit()
  424. // elevatedshellexecute(runFile)
  425. // while(!existsSync(runbat)) { wait(function(){
  426. // console.log('awiting batch : ' + runbat)
  427. // // shellExec( 'start', ['/W', '/b', runbat])
  428. // // shellExec( 'cmd', ['/k', '/b', runbat])
  429. // shellExec( command, args)
  430. // // cmd /b /c
  431. // }, 500) }
  432. console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' ')))
  433. var shellresult = shellExec( 'cmd', [ '/c', runbat])
  434. // var shellresult = shellExec( 'cmd', ['/c', runbat])
  435. // var shellresult = shellExec( command, args)
  436. var wrapup = function(result) {
  437. // console.log('Wrapping up')
  438. try {
  439. // console.log('resolving.....................');
  440. // console.log('--------------P' + result.messages.join(' ').trim() +'P--------------')
  441. // if(result.messages.join().trim()) resolve(result)
  442. // else reject(result)
  443. resolve(result)
  444. }
  445. catch(e){
  446. // console.dir(e)
  447. if(e.message === 'Input past end of file') {
  448. // console.log('---------------------------------------')
  449. // console.dir(result)
  450. resolve(result)
  451. }
  452. else {
  453. // console.dir(e)
  454. reject(e)
  455. }
  456. }
  457. }
  458. // if(runFile){
  459. // var waitr = function(){
  460. // WScript.StdOut.write('w.')
  461. // if(existsSync(runFile)) {
  462. // var strOutput = fs.readFileSync(runFile)
  463. // shellresult.result.messages = [strOutput]
  464. // wrapup(shellresult.result)
  465. // fs.unlinkSync(runFile)
  466. // }
  467. // // console.dir(shellresult.result)
  468. // wait( waitr, 500)
  469. // }
  470. // // console.log(wait)
  471. // wait( waitr, 500)
  472. // }
  473. // else {
  474. // console.log('There is no runfile.')
  475. console.log(shellresult.strOutput)
  476. wrapup(shellresult.result)
  477. // }
  478. }
  479. p = new Promise(pworker)
  480. // promises.push(p)
  481. // // Promise tThens don't get hooked up... we need to postpone promise starting until all the thens are registered...
  482. // wait(function(){
  483. // console.log('p.chain.length' + p.chain.length)
  484. // p.start() } , 5000) // Bind and setTImeout is not supported by JScript
  485. return p;
  486. }
  487. createPromiseClass(/*ovrrides*/)
  488. __main( selectedinstance )
  489. function createPromiseClass(overrides) {
  490. function reject(e){
  491. var p = this;
  492. console.log('Promise Rejection : ' + p.fn)
  493. console.dir(e)
  494. // throw e;f
  495. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Rejection can only be called once')}
  496. var __i = 0;
  497. var __e = e;
  498. do {
  499. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) break;
  500. try {
  501. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  502. __i++;
  503. __e = null;
  504. }
  505. catch(e){ __i++; __e = e}
  506. } while(__e)
  507. do {
  508. try { for(var i = __i; i < p.chain.length; i++, __i = i) if(!p.chain[i].isCatch) { p.result = p.chain[i](p.result); } }
  509. catch(e){
  510. __i ++;
  511. do {
  512. try {
  513. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  514. __i ++;
  515. __e = null;
  516. }
  517. catch(e){ __i++; __e = e}
  518. } while(__e)
  519. }
  520. } while ( __i < p.chain.length )
  521. p.state = PromiseClass.REJECTED;
  522. }
  523. function resolve(result){
  524. var p = this;
  525. // console.log(result + ' resolve was called with chain length ' + p.chain.length )
  526. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Resolve can only be called once')}
  527. p.result = result;
  528. if(PromiseClass.resolve(p.result) === p.result) {
  529. // console.log( 'result is still a promise waiting for result and promisechain' )
  530. waitForResult(p.result, function(r){ p.processchain(r) })
  531. }
  532. else {
  533. // console.log( 'result is value waiting for promisechain' )
  534. // console.dir(result)
  535. return p.processchain(result)
  536. }
  537. };
  538. function processchain(r){
  539. var __i = 0;
  540. var i = __i;
  541. var __e = null;
  542. p = this;
  543. // console.log('processchain chain.length : ' + p.chain.length)
  544. function __processchain(r){
  545. function waitForThen(p){
  546. if(i < p.chain.length) {
  547. if(!p.chain[i].isCatch) {
  548. // console.log('chain idx : ' + i + ' Executing : then ' + p.result + ' ' + p.chain[i])
  549. try {
  550. p.result = p.chain[i](p.result)
  551. if(PromiseClass.resolve(p.result) === p.result) {
  552. // console.log('chain idx : ' + i + ' result is still a promise starting it ')
  553. // console.dir(p.result.chain)
  554. // console.log('p.result.start : ' + p.result.start + ' ------------------ ')
  555. p.result.start()
  556. // console.log(p.result.fn + ' ------------------ ')
  557. waitForResult(p.result, function(r){
  558. // console.log('we waited')
  559. // WScript.write('.')
  560. p.result = r; i++; __i = i;
  561. waitForThen(p)
  562. })
  563. }
  564. else {
  565. i++; __i = i;
  566. waitForThen(p)
  567. }
  568. }
  569. catch(e) {
  570. i++; __i = i;
  571. __e = e;
  572. console.log('failed on index ' + __i + p.chain[__i-1] )
  573. console.dir(e)
  574. waitForCatch(p);
  575. }
  576. }
  577. else {
  578. // console.log(i + ' Skipping catch : ' + p.result + ' ' + p.chain[i])
  579. i++; __i = i;
  580. waitForThen(p)
  581. }
  582. }
  583. else return p.state = PromiseClass.FULFILLED;
  584. }
  585. function waitForCatch(p) {
  586. if(i < p.chain.length) {
  587. if(p.chain[i].isCatch) {
  588. console.log('chain idx : ' + i + ' Executing : catch : ' + p.result + ' ' + p.chain[i])
  589. try {
  590. p.result = p.chain[i](__e);
  591. if(PromiseClass.resolve(p.result) === p.result) {
  592. p.result.start()
  593. waitForResult(p.result, function(r){
  594. p.result = r; i++; __i = i;
  595. })
  596. waitForThen(p)
  597. }
  598. else {
  599. p.result = r; i++; __i = i;
  600. waitForThen(p)
  601. }
  602. }
  603. catch(e){ i++; __i = i;; __e = e; waitForCatch(p) }
  604. }
  605. else {
  606. i++; __i = i;
  607. waitForCatch(p)
  608. }
  609. }
  610. else return p.state = PromiseClass.REJECTED
  611. }
  612. waitForThen(p);
  613. }
  614. __processchain(r)
  615. }
  616. var create = function(fn){
  617. var p = {
  618. then : function(thenfn){
  619. // console.log('Adding then')
  620. thenfn.isThen = true
  621. // if(Object.prototype.toString.call(p.chain) !== '[object Array]') console.dir(p.chain)
  622. p.chain.push(thenfn)
  623. return p;
  624. }
  625. , 'catch' : function(catchfn) {
  626. catchfn.isCatch = true
  627. p.chain.push(catchfn)
  628. return p;
  629. }
  630. , start : function(){
  631. if(this.started) {
  632. console.error('Cannot start more than once...')
  633. return p
  634. };
  635. this.started = true;
  636. this.fn = fn;
  637. try { fn( function(r){
  638. // console.log('calling presolve in starter ')
  639. p.resolve(r) } , function(r){ p.reject(r) } ) }
  640. catch(e){
  641. // console.log('start catch : ' + e)
  642. // console.log('p.chain.length : ' + p.chain.length)
  643. // // console.dir(p)
  644. // console.dir(e)
  645. // console.log(fn)
  646. p.reject(e)
  647. }
  648. return p
  649. }
  650. , state : PromiseClass.PENDING
  651. , chain : []
  652. , reject : reject
  653. , resolve : resolve
  654. , processchain : processchain
  655. }
  656. p.chain.forEach = forEach;
  657. return p;
  658. }
  659. var PromiseClass = function(fn /*, donotstart */){
  660. var p = create(fn)
  661. // if(!donotstart) {
  662. // wait(function(){
  663. // console.log('p.chain.length' + p.chain.length)
  664. // p.start() } , 500) // Bind and setTImeout is not supported by JScript
  665. // }
  666. return p
  667. }
  668. PromiseClass.PENDING = 1
  669. PromiseClass.FULFILLED = 2
  670. PromiseClass.REJECTED = 3
  671. // PromiseClass.STARTED = 4
  672. PromiseClass.isSETTLED = function(p){ p.state === PromiseClass.FULFILLED || p.state === PromiseClass.REJECTED }
  673. PromiseClass.resolve = function(v){
  674. if(v && v.then) return v;
  675. var p = create(function(resolve, reject){
  676. resolve(v)
  677. });
  678. // console.log('p.chain in resolve. length ' + p.chain.length)
  679. // p.result = v;
  680. // wait(function(){ p.processchain(v) }, 0)
  681. return p;
  682. }
  683. function waitForResult(p, cb){
  684. if(!p) return cb(p)
  685. if(p.state !== PromiseClass.PENDING) cb(p.result)
  686. // console.log(p.state + ' Waiting for ..... ' + p.runFile)
  687. if(p.runFile && false) {
  688. while(!existsSync(p.runFile) && p.state === PromiseClass.PENDING) {
  689. console.log('Waiting for ResultFle'); wait(cb, 500)
  690. }
  691. cb(p.result)
  692. }
  693. else {
  694. // while(p.state === PromiseClass.PENDING) {
  695. // console.log('Waiting for Result')
  696. function waiter(){
  697. // console.log(p.result)
  698. if(p.state === PromiseClass.PENDING) wait(waiter, 500);
  699. else return cb(p.result)
  700. }
  701. wait(waiter, 500)
  702. // }
  703. }
  704. }
  705. PromiseClass.all = any; // Serialized...
  706. PromiseClass.__all = function(arr){
  707. arr.forEach = forEach;
  708. var resultPs = [];
  709. var results = [];
  710. console.log('All : ' + arr.length)
  711. var pAll = new PromiseClass(function(resolve, reject){
  712. console.log('All started : ' + pAll)
  713. // console.dir(pAll)
  714. arr.forEach(function(p){
  715. if(!p.then) { var pfn = p;
  716. p = new PromiseClass(function(resolve, reject){
  717. try{
  718. resolve(pfn())
  719. }
  720. catch(e){
  721. reject(e)
  722. }
  723. })
  724. p.start()
  725. }
  726. else {
  727. // !p.start ? p.start = function(){return p} : null
  728. // p.start()
  729. // .then( function(){ waitForResult(p, function(r){ results.push(r) }) })
  730. }
  731. resultPs.push(p)
  732. // waitForResult(p, function(r){ results.push(r) })
  733. })
  734. // PB : TODO -- This is the same as processchain!!!
  735. var allwaitr = function(){
  736. var allResolved = true
  737. console.log('resultPs : ' + resultPs.length)
  738. for(var rIdx =0; rIdx < resultPs.length; rIdx++ ){
  739. if(resultPs[rIdx]) {
  740. allResolved = false
  741. waitForResult(resultPs[rIdx], function(r){
  742. if(Promise.resolve(r) !== r) results[rIdx] = r; resultPs[rIdx] = null;
  743. })
  744. break;
  745. }
  746. }
  747. if(allResolved) {
  748. // console.log('All Reseloved')
  749. // console.dir(results)
  750. resolve(results)
  751. }
  752. else wait(allwaitr, 500)
  753. }
  754. wait(allwaitr, 500)
  755. })
  756. // pAll.chain = arr;
  757. return pAll
  758. }
  759. // PromiseClass.resolve = overrides.resolve;
  760. Promise = PromiseClass;
  761. return PromiseClass;
  762. }
  763. }
  764. function __main( selectedinstance ){
  765. var downloadsdir = selectedinstance.root + '/Downloads';
  766. var callsheltask = function(args) {
  767. // console.log('callsheltask : ' + args)
  768. return function() { return nodeShellExec.apply(null, args) } }
  769. var gitUser = 'guest';
  770. var gitEmail = 'guest@bbh.org.in';
  771. var BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  772. function getVersion() { return BUILD_VERSION; }
  773. console.log(getVersion())
  774. function ensureDirectoryExistence(filePath) {
  775. var dirname = path.dirname(filePath);
  776. if (existsSyncFolder(dirname)) {
  777. return filePath;
  778. }
  779. ensureDirectoryExistence(dirname);
  780. fs.mkdirSync(dirname);
  781. return filePath;
  782. }
  783. var getTaskCheckExists = function(command, options) {
  784. options = options || {}
  785. return function() {
  786. var runFile = path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date()) + 'where' + command + "out.txt");
  787. var p = nodeShellExec.apply(null, ['cmd', ['/c', 'where', command], { runFile : runFile } ])
  788. p.runFile = runFile;
  789. if (options.ignorefailures) {
  790. return p.then(function(v) {
  791. // WScript.Echo('firstThen ' + v);
  792. return v })['catch']( function(e) {
  793. console.error(e);
  794. // Ignore. Not a major error if where command fails !!!
  795. throw e;
  796. })
  797. }
  798. else return p.then(function() {
  799. // WScript.Echo('firstThen ddd');
  800. return v });
  801. }
  802. }
  803. function verifyAndInstallPrerequisites() {
  804. fs.writeFileSync(ensureDirectoryExistence(downloadsdir + '/readme.txt'), getVersion() + ' Your local downloads for this instance');
  805. var downloadbatch =
  806. "::************************************************************************** \r\n \
  807. :Download_ <url> <File> \r\n \
  808. Powershell.exe ^\r\n \
  809. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^\r\n \
  810. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^\r\n \
  811. (New-Object System.Net.WebClient).DownloadFile('%1','%2') \r\n \
  812. exit /b \r\n \
  813. ::**************************************************************************";
  814. ensureDirectoryExistence(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/readme.txt'))
  815. fs.writeFileSync(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat'), downloadbatch);
  816. var downloadtasks = [];
  817. var installtasks = [];
  818. prerequisites.forEach(function(preq) {
  819. WScript.Echo(all)
  820. if(!all && preq.optional) return
  821. var p = preq.exists().then(function(exists) {
  822. if (exists && !preq.forceinstall) console.log( preq.shellcmd + ' exists');
  823. else {
  824. console.log(exists)
  825. console.log(preq.shellcmd + ' is not installed');
  826. return preq.preinstallsteps().then(function(){
  827. // console.log(' task.install : ' + preq.install)
  828. installtasks.push( function(){ return preq.install() } );
  829. })
  830. }
  831. })
  832. // .then(function(res){ console.log( 'preinstallsteps ' + res)});
  833. downloadtasks.push( p )
  834. });
  835. // console.log('downloadtasks')
  836. // console.dir(downloadtasks[0])
  837. var p = Promise.all(downloadtasks).then(function(){
  838. // console.log('calling install tasks : ' + installtasks.length)
  839. return any(installtasks) })
  840. // console.log('Promise.all.chain : ' + p.chain)
  841. return p
  842. }
  843. // var choiceHandler = function(choices, choice) {
  844. // console.log('chosen : ' + choice)
  845. // var decision = choices['d'];
  846. // if (choice && choice === 'd' || !choice) {
  847. // decision = choices['d']
  848. // }
  849. // else if (isNaN((+choice))) {
  850. // decision = choice
  851. // }
  852. // else decision = choices[choice-1]
  853. // if(!decision) throw 'Invalid selection : ' + decision
  854. // return decision
  855. // }
  856. // prereq definition helpers. We can't do proper inheritance in cscript. So fallback to global functions.
  857. function exists(next){
  858. var self = this;
  859. console.log('checking existence of ' + self.shellcmd)
  860. return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
  861. // console.log('-------------exists=======================')
  862. // console.dir(exists)
  863. // console.log(exists + ' ' + self.shellcmd + ' exists')
  864. if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
  865. return true;
  866. }
  867. else return false
  868. })['catch'](function(e){
  869. // console.log('-------------exists catch=======================')
  870. console.dir(e)
  871. return false;
  872. })
  873. }
  874. function install() {
  875. var self = this;
  876. var ifns = [self.installcmd]
  877. if(!ifns.map) ifns.map = map;
  878. console.log('Installing')
  879. return any(ifns.map(callsheltask))['catch'](function(e){
  880. if(e.code === 1602) {
  881. console.warn("Installation was probably cancelled.")
  882. }
  883. else throw e
  884. }).then(function(){
  885. return self.postinstallsteps && self.postinstallsteps()
  886. })
  887. }
  888. function unique(arr) {
  889. var hash = {}, result = [];
  890. for ( var i = 0, l = arr.length; i < l; ++i ) {
  891. if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
  892. hash[ arr[i] ] = true;
  893. result.push(arr[i]);
  894. }
  895. }
  896. return result;
  897. }
  898. // var ENV = Object.assign({}, process.env); // Shallow clone it.
  899. // WScript.echo( ENV("Path") )
  900. function sysAddPathVar(path){
  901. return true; // PB : TODO -- Not yet enabled. Remove sys path from path before saving.
  902. // Object.assign({
  903. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  904. // }, options)
  905. // var newpath = ENV("Path").split(';');
  906. // newpath = Array.from(new Set(newpath.push(path))).join(';')
  907. var newpath = [];
  908. newpath.push(path)
  909. newpath = unique(newpath).join(';')
  910. // path.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  911. return any([nodeShellExec('setx', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  912. // , nodeShellExec('set', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  913. ] );
  914. }
  915. var getCmdString = function(args){ return args[0] + ' ' + args[1].join(' ') }
  916. var getgitshelltask = function(args, onEachError) { return function(){
  917. console.log('----------getgitshelltask--------------called')
  918. return nodeShellExec( "cmd", ['/c', getCmdString(args)], args[2])
  919. // .catch( onEachError || function(e){ console.error(e) })
  920. }
  921. }
  922. var prerequisites = [
  923. {
  924. shellcmd: 'git',
  925. url: 'https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe'
  926. , installer: 'Git-2.33.0.2-64-bit.exe'
  927. , installcmd: ['cmd', ['/c', 'start',
  928. '/WAIT', downloadsdir + '/' + 'Git-2.33.0.2-64-bit.exe'
  929. , '/VERYSILENT'
  930. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  931. ]]
  932. , preinstallsteps: function() {
  933. var self = this;
  934. console.log('Git preinstall steps')
  935. var steps = [];
  936. // steps.push(
  937. // function(){
  938. // // console.log('cli prompt steps')
  939. // var choices = { 0 : 'guest', 1 : 'chessdemo' }
  940. // return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  941. // }
  942. // )
  943. // steps.push(
  944. // function(){
  945. // var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  946. // return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  947. // }
  948. // )
  949. steps.push(
  950. function(){
  951. if (!existsSync(downloadsdir + '/' + self.installer)) {
  952. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer])
  953. }
  954. else {
  955. console.log(self.installer + ' Already exits Download skipped.')
  956. return Promise.resolve(true)
  957. }
  958. }
  959. )
  960. return any(steps)
  961. // return any([any(steps), any(prompts)])
  962. }
  963. , installsteps: function () {
  964. var self = this;
  965. console.log('Git Installsteps called')
  966. var ifns = [self.installcmd]
  967. if(!ifns.map) ifns.map = map;
  968. return any(ifns.map(callsheltask))['catch'](function(e){
  969. if(e.code === 1602) {
  970. console.warn("Installation was probably cancelled.")
  971. }
  972. else throw e
  973. })
  974. }
  975. , postinstallsteps: function(){
  976. // PB : TODO -- Detect failure or cancellation before attenpting postinstall steps...
  977. var steps = [];
  978. steps.push(
  979. function(){
  980. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  981. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  982. }
  983. )
  984. steps.push(
  985. function(){
  986. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  987. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  988. }
  989. )
  990. return any(steps).then(function(){
  991. var steps = [
  992. ['git', ['config', '--global', '--add', 'user.name', gitUser]]
  993. , ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
  994. ]
  995. if(!steps.map) steps.map = map;
  996. return any(steps.map(callsheltask)).then(function(){
  997. })
  998. });
  999. }
  1000. , install: function () {
  1001. var self = this;
  1002. console.log('Git Install called')
  1003. var createTasq = function(args, shellT, onEachError) {
  1004. var tasq = shellT ? shellT(args) : ( function(){
  1005. console.log('sdsfdsdf ' + args)
  1006. return any([nodeShellExec.apply(null, args)])
  1007. // .catch( onEachError || function(e){ console.error(e) } )
  1008. })
  1009. tasq.toString = function(){ return JSON.stringify(args)}
  1010. return tasq;
  1011. }
  1012. var execserial = function(tasklist, task, shellT, onEachError){
  1013. var exec = function(taskArgs){
  1014. console.log('execcing ' + task)
  1015. var thistask = task.concat();
  1016. thistask[1] = thistask[1].concat()
  1017. thistask[1].push.apply(thistask[1], taskArgs)
  1018. return createTasq(thistask, shellT)
  1019. }
  1020. tasklist.map = map
  1021. console.log('execlist ' + tasklist.map(exec))
  1022. return any(tasklist.map(exec))
  1023. }
  1024. function resetgitconfig(){
  1025. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  1026. // Git Credential storage...
  1027. // git config --global credential.helper 'store --file ~/.gitcredentials'
  1028. // git credential-store --file ~/.gitcredentials store
  1029. // // notepad C:/Program Files/Git/etc/gitconfig
  1030. // git config --global --unset credential
  1031. // git config --edit --system
  1032. // git config --global credential.helper "store --file ~/gitcredentials"
  1033. // git credential fill
  1034. // git credential-store --file ~/git.store store
  1035. // Find system git config
  1036. // git config --global --edit
  1037. // git config --list --show-origin
  1038. // git config --list --show-origin --show-scope
  1039. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  1040. // Recipie
  1041. // git config --global --unset credentials.helper
  1042. // cd /path/to/my/repo
  1043. // git config --unset credential.helper
  1044. // git config credential.helper 'store --file ~/.git_repo_credentials'
  1045. // git config credential.*.username my_user_name
  1046. // git config credential.https://gitlab.com.username my_user_name
  1047. // git credential fill
  1048. // git config --global credential.modalprompt false // doesnst work.
  1049. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  1050. var options = {
  1051. inherit: true, shell: true //, env: process.env
  1052. , cwd: selectedinstance.root
  1053. // , runas: processedArgs.runas
  1054. }
  1055. var task = ['git', ['config'], options]
  1056. var tasklist = [
  1057. // ['--global', '--unset credentials.helper']
  1058. // ['--unset', 'credentials.helper']
  1059. // ,
  1060. // ['credential.helper', `'store --file git_repo_credentials'`]
  1061. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  1062. , ['--global', '--replace-all', 'user.name', 'pb']
  1063. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  1064. // , ['--list']
  1065. // , ['credential', 'fill']
  1066. ]
  1067. var onEachError = function(e) { console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n') }
  1068. var shellT = function(args) {
  1069. return getgitshelltask(args, onEachError)
  1070. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  1071. }
  1072. execserial(tasklist, task, shellT, onEachError )
  1073. }
  1074. return any([ /*self.preinstallsteps,*/
  1075. function(){ return self.installsteps() }
  1076. , function() { resetgitconfig() }
  1077. , function(){ return self.postinstallsteps() }
  1078. ])
  1079. }
  1080. , verifyAndInstall : function(){
  1081. var self = this;
  1082. return self.exists().then( function(exits) {
  1083. if(exists) return self.getUser(null, function(){ return self.postinstallsteps() } )
  1084. else return self.install();
  1085. })
  1086. }
  1087. , exists : exists
  1088. , getUser : function(repo, onNoResult){
  1089. onNoResult = onNoResult || function(){return false}
  1090. var globalOrLocal = '--global';
  1091. if(!repo) globalOrLocal = '--global';
  1092. else globalOrLocal = '--local'
  1093. var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]]
  1094. if(!ifns.map) ifns.map = map;
  1095. return any(fns.map(callsheltask)).then(function(result){
  1096. // not yet configured.
  1097. if(!result.success) return onNoResult()
  1098. else {
  1099. var users = result.messages[0].trim().split('\n');
  1100. if(users.length === 0 ||
  1101. users.length === 1 && users[0] === 'guest') {
  1102. return onNoResult()
  1103. }
  1104. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1105. }
  1106. })
  1107. ['catch'](function(e){
  1108. console.log(e)
  1109. return onNoResult()
  1110. })
  1111. }
  1112. }
  1113. ,
  1114. {
  1115. shellcmd: 'node',
  1116. url: 'https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi'
  1117. , installer: 'node-v14.17.3-x64.msi'
  1118. , installcmd: ['MSIEXEC.exe', ['/i'
  1119. , path.normalize(downloadsdir + '/' + 'node-v14.17.3-x64.msi')
  1120. , 'ACCEPT=YES', '/passive']]
  1121. , install : install
  1122. , exists : exists
  1123. , preinstallsteps: function() {
  1124. var self = this;
  1125. console.log('Node preinstall steps')
  1126. var steps = [];
  1127. steps.push(
  1128. function(){
  1129. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1130. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1131. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1132. }
  1133. else {
  1134. console.log(self.installer + ' Already exits Download skipped.')
  1135. return Promise.resolve(true)
  1136. }
  1137. }
  1138. )
  1139. return any(steps)
  1140. // return any([any(steps), any(prompts)])
  1141. }
  1142. }
  1143. , {
  1144. shellcmd: 'python'
  1145. , optional : true
  1146. , url: 'https://www.python.org/ftp/python/2.7.18/python-2.7.18.amd64.msi'
  1147. , installer: 'python-2.7.18.amd64.msi'
  1148. , installcmd: ['MSIEXEC.exe', ['/i'
  1149. , path.normalize(downloadsdir + '/' + 'python-2.7.18.amd64.msi')
  1150. , 'ACCEPT=YES', '/passive']]
  1151. , preinstallsteps: function() {
  1152. var self = this;
  1153. console.log(self.shellcmd + ' preinstall steps')
  1154. var steps = [];
  1155. steps.push(
  1156. function(){
  1157. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1158. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  1159. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1160. }
  1161. else {
  1162. console.log(self.installer + ' Already exits Download skipped.')
  1163. return Promise.resolve(true)
  1164. }
  1165. }
  1166. )
  1167. return any(steps)
  1168. // return any([any(steps), any(prompts)])
  1169. }
  1170. , install : install
  1171. , postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
  1172. , exists : exists
  1173. }
  1174. , {
  1175. shellcmd: 'code'
  1176. , optional : true
  1177. , url: 'https://code.visualstudio.com/sha/download?build=stable&os=win32-x64-user'
  1178. , installer: 'VSCodeUserSetup-x64-1.65.2.exe'
  1179. , installcmd: ['cmd /c', ['start /WAIT ' + downloadsdir + '/' + 'VSCodeUserSetup-x64-1.65.2.exe /VERYSILENT'
  1180. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1181. ]]
  1182. , preinstallsteps: function() {
  1183. var self = this;
  1184. console.log(self.shellcmd + ' preinstall steps')
  1185. var steps = [];
  1186. steps.push(
  1187. function(){
  1188. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1189. console.log(self.url)
  1190. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1191. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1192. }
  1193. else {
  1194. console.log(self.installer + ' Already exits Download skipped.')
  1195. return Promise.resolve(true)
  1196. }
  1197. }
  1198. )
  1199. return any(steps)
  1200. // return any([any(steps), any(prompts)])
  1201. }
  1202. , install : install
  1203. , postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
  1204. , exists : exists
  1205. }
  1206. , {
  1207. shellcmd: 'sqlexpress',
  1208. url: 'https://go.microsoft.com/fwlink/?linkid=866658'
  1209. , installer: 'SQL2019-SSEI-Expr.exe'
  1210. , installcmd: ['cmd', ['/c', 'start',
  1211. '/WAIT', downloadsdir + '/' + 'SQL2019-SSEI-Expr.exe'
  1212. , ''
  1213. //, 'SSMSInstallRoot=%systemdrive%\\Program Files (x86)\\Microsoft SQL Server\\140\\Tools\\Binn\\ManagementStudio'
  1214. ]]
  1215. , install : install
  1216. , exists : exists
  1217. , preinstallsteps: function() {
  1218. var self = this;
  1219. console.log('Node preinstall steps')
  1220. var steps = [];
  1221. steps.push(
  1222. function(){
  1223. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1224. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1225. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1226. }
  1227. else {
  1228. console.log(self.installer + ' Already exits Download skipped.')
  1229. return Promise.resolve(true)
  1230. }
  1231. }
  1232. )
  1233. return any(steps)
  1234. // return any([any(steps), any(prompts)])
  1235. }
  1236. }
  1237. , {
  1238. // "C:\Program Files (x86)\Microsoft SQL Server Management Studio 18\Common7\IDE\Ssms.exe"
  1239. // SQL Management studio 2018
  1240. shellcmd: 'C:\\Program Files (x86)\\Microsoft SQL Server Management Studio 18\\Common7\\IDE\\Ssms.exe\\Ssms.exe',
  1241. url: 'https://aka.ms/ssmsfullsetup'
  1242. , installer: 'SSMS-Setup-ENU.exe'
  1243. , installcmd: ['cmd', ['/c', 'start',
  1244. '/WAIT', downloadsdir + '/' + 'SSMS-Setup-ENU.exe'
  1245. , '/IAcceptSQLServerLicenseTerms'
  1246. //, 'SSMSInstallRoot=%systemdrive%\\Program Files (x86)\\Microsoft SQL Server\\140\\Tools\\Binn\\ManagementStudio'
  1247. ]]
  1248. , install : install
  1249. , exists : exists
  1250. , preinstallsteps: function() {
  1251. var self = this;
  1252. console.log('smss preinstall steps')
  1253. var steps = [];
  1254. steps.push(
  1255. function(){
  1256. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1257. console.log(self.url)
  1258. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1259. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1260. }
  1261. else {
  1262. console.log(self.installer + ' Already exits Download skipped.')
  1263. return Promise.resolve(true)
  1264. }
  1265. }
  1266. )
  1267. return any(steps)
  1268. // return any([any(steps), any(prompts)])
  1269. }
  1270. }
  1271. , {
  1272. shellcmd: 'Ssms.exe', // SQL Mgmt Studo 2017
  1273. url: 'https://go.microsoft.com/fwlink/?linkid=2043154&clcid=0x409'
  1274. , installer: 'SSMS-Setup-ENU-2017.exe'
  1275. , installcmd: ['cmd', ['/c', 'start',
  1276. '/WAIT', downloadsdir + '/' + 'SSMS-Setup-ENU.exe'
  1277. , '/Quiet'
  1278. //, 'SSMSInstallRoot=%systemdrive%\\Program Files (x86)\\Microsoft SQL Server\\140\\Tools\\Binn\\ManagementStudio'
  1279. ]]
  1280. , install : install
  1281. , exists : exists
  1282. , preinstallsteps: function() {
  1283. var self = this;
  1284. console.log('smss preinstall steps')
  1285. var steps = [];
  1286. steps.push(
  1287. function(){
  1288. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1289. console.log(self.url)
  1290. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1291. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1292. }
  1293. else {
  1294. console.log(self.installer + ' Already exits Download skipped.')
  1295. return Promise.resolve(true)
  1296. }
  1297. }
  1298. )
  1299. return any(steps)
  1300. // return any([any(steps), any(prompts)])
  1301. }
  1302. }
  1303. , {
  1304. shellcmd: 'mysql',
  1305. url: 'https://dev.mysql.com/get/Downloads/MySQLInstaller/mysql-installer-community-8.0.30.0.msi' //'https://dev.mysql.com/get/Downloads/MySQLInstaller/mysql-installer-community-8.0.29.0.msi'
  1306. , installer: 'mysql-installer-community-8.0.30.0.msi'
  1307. , installcmd: ['MSIEXEC.exe', ['/i'
  1308. , path.normalize(downloadsdir + '/' + 'mysql-installer-community-8.0.30.0.msi')
  1309. //, 'ACCEPT=YES', '/passive'
  1310. ]]
  1311. , install : install
  1312. , exists : exists
  1313. , preinstallsteps: function() {
  1314. var self = this;
  1315. console.log('mysql preinstall steps')
  1316. var steps = [];
  1317. steps.push(
  1318. function(){
  1319. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1320. console.log(self.url)
  1321. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  1322. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1323. }
  1324. else {
  1325. console.log(self.installer + ' Already exits Download skipped.')
  1326. return Promise.resolve(true)
  1327. }
  1328. }
  1329. )
  1330. return any(steps)
  1331. // return any([any(steps), any(prompts)])
  1332. }
  1333. }
  1334. , {
  1335. shellcmd: 'elxr'
  1336. , forceinstall : true
  1337. , installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
  1338. , preinstallsteps: function() {
  1339. var self = this;
  1340. console.log('Elxr preinstall steps')
  1341. var steps = [];
  1342. steps.push(
  1343. )
  1344. return any([any(steps)])
  1345. }
  1346. , installsteps: function () {
  1347. var self = this;
  1348. console.log('Elxr Installsteps called')
  1349. var installIfNotExists = function(){
  1350. console.log('Elxr PreInstallsteps called')
  1351. var steps = [];
  1352. var chessRepo = 'https://git.bbh.org.in'
  1353. steps.push(
  1354. function(){
  1355. // console.log('cli prompt steps')
  1356. var choices = { 0 : 'http://git.bbh', 1 : 'https://git.bbh.org.in' }
  1357. return cli.prompt(choices, 'git repository : ', chessRepo).then(function(choice){ chessRepo = choice } )
  1358. }
  1359. )
  1360. return any(steps).then(function(){
  1361. var ifns = [
  1362. ['git', ['clone', chessRepo + '/chess/elxr'] ]
  1363. ]
  1364. if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1365. if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1366. // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1367. ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1368. }
  1369. else {
  1370. throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1371. }
  1372. }
  1373. else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1374. ifns.push(['npm', ['i'], { cwd : '.\\elxr' } ])
  1375. if(!ifns.map) ifns.map = map;
  1376. return any(ifns.map(callsheltask))['catch'](function(e){
  1377. if(e.code === 1602) {
  1378. console.warn("Installation was probably cancelled.")
  1379. }
  1380. else throw e
  1381. })
  1382. })
  1383. }
  1384. var ifns = [ self.installcmd ]
  1385. if(!ifns.map) ifns.map = map;
  1386. return installIfNotExists().then(function(){
  1387. return any(ifns.map(callsheltask))['catch'](function(e){
  1388. if(e.code === 1602) {
  1389. console.warn("Installation was probably cancelled.")
  1390. }
  1391. else throw e
  1392. })
  1393. })
  1394. }
  1395. , install: function () {
  1396. var self = this;
  1397. console.log('Elxr Install called')
  1398. return any([ self.preinstallsteps, function(){ return self.installsteps() }
  1399. , nodeShellExec('start', ['""', '"C:\\Program Files\\Git\\bin\\sh.exe"', '-c', '"node ' + (selectedinstance.root + '\\elxr\\index.js').replace(/\\/g, '/') + ' i elixir"'])
  1400. // , nodeShellExec('node', [selectedinstance.root + 'elxr\\index.js'])
  1401. ])
  1402. // return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() }
  1403. // , nodeShellExec('node', [selectedinstance.root + '\\elxr\\index.js', 'init'])
  1404. // // , nodeShellExec('node', [selectedinstance.root + 'elxr\\index.js'])
  1405. // ])
  1406. }
  1407. // , exists : function(){
  1408. // console.log('Elxr PreInstallsteps called')
  1409. // var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  1410. // if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1411. // if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1412. // // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1413. // ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1414. // }
  1415. // else {
  1416. // throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1417. // }
  1418. // }
  1419. // else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1420. // if(!ifns.map) ifns.map = map;
  1421. // return any(ifns.map(callsheltask))['catch'](function(e){
  1422. // if(e.code === 1602) {
  1423. // console.warn("Installation was probably cancelled.")
  1424. // }
  1425. // else throw e
  1426. // })
  1427. // }
  1428. , exists : exists
  1429. }
  1430. ]
  1431. if(!prerequisites.forEach) prerequisites.forEach = forEach;
  1432. // nodeShellExec(selectedinstance.root + '/.elxr/run-' + '1629889572461' + '/download.bat'
  1433. // , ['https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.32.0.2-64-bit.exe'
  1434. // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
  1435. promises.push(verifyAndInstallPrerequisites())
  1436. startPromises();
  1437. }