555
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.

i.win.js 50KB

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