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 51KB

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