Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. var __Promise = {};
  2. // if(!String.prototype.trim) String.prototype.trim = function(){
  3. // return this.replace(/^\s+|\s+$/g, '');
  4. // };
  5. // var ovrrides = {
  6. // resolve : function(v){
  7. // if(v && v.then) return v;
  8. // var p = new Promise(function(resolve, reject){ resolve(v) });
  9. // return p;
  10. // }
  11. // };
  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. var promises = [];
  22. function startPromises(){
  23. promises.forEach(function(p){
  24. // console.log(p.chain)
  25. p();
  26. // promises.splice(0,1)
  27. })
  28. }
  29. function isWin(){ return /^win/.test(process.platform) }
  30. try{
  31. __Promise = Promise
  32. var __require = require
  33. var map = Array.map
  34. // --------------------------------------------
  35. // Node Exists. Lets launch ourselves in Node itself
  36. // var wait = function(ms, cb) {any
  37. // return new __Promise(function(resolve){ setTimeout(resolve, ms) } ).then(function(){ cb() });
  38. // }
  39. // var fs = require('fs')
  40. // var { existsSync } = require('fs');
  41. // var existsSyncFolder = existsSync
  42. // var path = require('path');
  43. // var cli = require('./cliverse')
  44. // var nodeShellExec = cli.nodeShellExec;
  45. // var utils = require('bbhverse');
  46. // var any = utils.any;
  47. // var wait = setTimeout
  48. // --------------------------------------------
  49. var selectedinstance = { root : path.resolve(".") }
  50. __main(selectedinstance)
  51. }
  52. // catch(e){}
  53. catch(e){
  54. // // --------------------------------------------
  55. // // Cscript
  56. var wsh = true;
  57. function isWin(){ return true; }
  58. // If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then
  59. var clii = {
  60. question : function(q, answercb){
  61. WScript.Echo(q)
  62. // console.log('WScript.StdIn : ' + WScript.StdIn.ReadLine() + ' ==== ')
  63. var answer = WScript.StdIn.ReadLine()
  64. answercb(answer)
  65. }
  66. }
  67. var prompter = {
  68. ask : function(q){
  69. // Needs to be serialized. Parallel asks are not possible.
  70. // const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
  71. return new Promise(function(resolve, reject){
  72. clii.question(q, function(answer){
  73. // clii.close();
  74. // console.log("resolve is being called");
  75. resolve(answer)
  76. })
  77. })
  78. }
  79. }
  80. var cli = {
  81. prompt : function(choices, label, defaultchoice){
  82. var options = [];
  83. choices.forEach = forEach
  84. choices.forEach(function(choice){ options.push( ((+choice) + 1) + ' ' + choices[choice] )})
  85. return prompter.ask( label + ' \\n ' + options.join('\n') + '\n default ( <= ' + (defaultchoice || choices[0]) + ' ) : '
  86. ).then( function(choice){
  87. if(!choice) return defaultchoice || choices[0];
  88. if(choice && isNaN(+choice)) return choice;
  89. return choices[(+choice) - 1];
  90. })
  91. }
  92. }
  93. var any = function(iterable, continueOnFailure) {
  94. // var cancelsignal = Symbol()
  95. if(!iterable.reduce) iterable.reduce = reduce
  96. // console.log('iterable.reduce ' + iterable.reduce)
  97. var cancelsignal = "cancelme{mangledrunid}"
  98. return iterable.reduce(
  99. function(p, tasq, i ,a) {
  100. // console.dir(a)
  101. // console.log('Entered')
  102. var handleError = function(err, pVal){
  103. if(err !== cancelsignal) {
  104. // Cancel only once on first failure.
  105. console.warn('Possible failure for task with result : ' )
  106. console.log('Failed : ' + err.message + ' ')
  107. console.dir(pVal)
  108. console.dir(p)
  109. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  110. console.error('Error : ' + err.stack)
  111. console.error(a[i-1])
  112. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  113. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  114. else return pVal;
  115. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  116. }
  117. }
  118. if(Promise.resolve(p) === p ) {
  119. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  120. console.dir(' p.then is ' + p.then)
  121. return p.then( function(pVal){
  122. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  123. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  124. // Failures are known for promises on reject.
  125. // In future if we support direct sync function execution with a result examination for failure
  126. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  127. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  128. // Truthy values are failures if obj has error=true.
  129. if(pVal && pVal.error) handleError(pVal, pVal)
  130. var trycall = function(tasq){
  131. try {
  132. var result = tasq() // PB : TODO -- Handle scope for call
  133. if(tasq.resultHandler) return tasq.resultHandler(result)
  134. // else (Promise.resolve(result) === result ) ? result.start() : null
  135. return result
  136. } catch (error) {
  137. console.error(error);
  138. console.error('Error : ' + error ? error.stack : 'No stack')
  139. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  140. }
  141. }
  142. var handleNext = function(){
  143. // console.log('Task finished with result : ')
  144. // console.dir(pVal)
  145. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  146. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  147. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  148. return (Promise.resolve(tasq) === tasq ) ? tasq /*.start()*/ : trycall(tasq) ;
  149. }
  150. if(Promise.resolve(pVal) === pVal) {
  151. // Passed in function retured a promise. We still need to wait for it.
  152. pVal.then(function(pVal){ return handleNext(); })
  153. }
  154. else return handleNext()
  155. })['catch'](function(error) {
  156. if(error !== cancelsignal) {
  157. console.log('E3 : i = ' + i);
  158. if(error.result) console.error(error.result)
  159. console.error('Error : ' + (error.message || error.messages))
  160. console.error('Error : ' + error.stack)
  161. tasq ? console.log("tasq : " + tasq.toString()) : null;
  162. console.log('debugData 3-------------------------');
  163. // handleError()
  164. throw error
  165. }
  166. else throw cancelsignal;
  167. })
  168. }
  169. else if(!p) {
  170. handleError({ error : true, message : 'Failed without result' }, pVal)
  171. console.log("Bypass remaining on prior failure");
  172. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  173. }
  174. else return p; // A truthy value
  175. }
  176. , Promise.resolve(true)
  177. );
  178. }
  179. var console = { log : function(m) {WScript.Echo(m)}, error : function(m) {WScript.Echo(m) }
  180. , dir : function(o) {
  181. for(var i in o){ console.log(i + ' : ' + o[i])}
  182. }
  183. }
  184. // __Promise = ovrrides
  185. function forEach(eachFn){
  186. for(var i=0; i<this.length; i++) eachFn(this[i])
  187. }
  188. function reduce(reducnFn, iv){
  189. var acc = iv
  190. for(var i=0; i<this.length; i++) {acc = reducnFn(acc, this[i], i, this) }
  191. return acc;
  192. }
  193. function map(eachFn){
  194. var mapped = []
  195. for(var i=0; i<this.length; i++) mapped.push(eachFn(this[i]))
  196. return mapped
  197. }
  198. var wait = function(cb, ms) { WScript.Sleep(ms); cb() }
  199. var fso = new ActiveXObject('Scripting.FileSystemObject');
  200. var existsSync = function(filepath){ return fso.FileExists(filepath) }
  201. var fs = {
  202. writeFileSync : function(filepath, text) {
  203. // console.log(filepath)
  204. var fh = fso.CreateTextFile(filepath, true);
  205. fh.WriteLine(text);
  206. fh.Close();
  207. }
  208. , mkdirSync : function(path) {
  209. fso.CreateFolder(path)
  210. }
  211. , readFileSync : function(filepath){
  212. var objFileToRead = fso.OpenTextFile(filepath,1)
  213. var strFileText = objFileToRead.ReadAll()
  214. objFileToRead.Close()
  215. return strFileText
  216. }
  217. , unlinkSync : function(filepath){ fso.DeleteFile(filepath) }
  218. }
  219. var path = {
  220. resolve : function(path){ return fso.GetAbsolutePathName(path) }
  221. , dirname : function(filepath) {
  222. var normalized = this.normalize(filepath)
  223. var li = normalized.lastIndexOf("\\")
  224. if( li > -1) {
  225. return normalized.substring(0, li)
  226. }
  227. }
  228. , normalize : function(path){
  229. return path.replace(/\//g,'\\');
  230. }
  231. }
  232. // Detect or specify install directory.
  233. var selectedinstance = { root : path.resolve(".") }
  234. var existsSyncFolder = function(path){
  235. return fso.FolderExists(path)
  236. }
  237. var shell = new ActiveXObject('shell.application');
  238. promises.forEach = forEach
  239. function startPromises(){
  240. promises.forEach(function(p){
  241. // console.log(p.chain)
  242. p.start();
  243. // promises.splice(0,1)
  244. })
  245. }
  246. function nodeShellExec(command, cargs, options){
  247. var elevatedshellexecute = function(cmd, argstr){
  248. shell.ShellExecute(cmd, argstr , "", "", 1);
  249. }
  250. var shellExec = function(cmd, argstr){
  251. var objShell = WScript.createobject("wscript.shell")
  252. // console.log(argstr.join( ' '))
  253. var oExec = objShell.Exec(cmd + ' ' + argstr.join(' '))
  254. var result = {}
  255. var shellresult = { shell : objShell, result : result }
  256. var WshRunning = 0
  257. var WshFinished = 1
  258. var WshFailed = 2
  259. while(oExec.Status === WshRunning){
  260. WScript.StdOut.write('s.')
  261. WScript.Sleep(500)
  262. }
  263. var strOutput = '\n'
  264. switch(oExec.Status) {
  265. case WshFinished :
  266. strOutput = oExec.StdOut.ReadAll()
  267. result.success = true;
  268. result.code = 0
  269. break;
  270. case WshFailed :
  271. strOutput = oExec.StdErr.ReadAll()
  272. result.success = false;
  273. result.code = WshFailed
  274. break;
  275. default : strOutput = 'failed'
  276. break;
  277. }
  278. result.result = command + ' ' + cargs + ' exited with code ' + result.code
  279. result.messages = [strOutput]
  280. // console.log(strOutput)
  281. // WScript.Echo(oExec.Status)
  282. // WScript.Echo(oExec.ProcessID)
  283. // WScript.Echo(oExec.ExitCode)
  284. // console.log(objShell.StdOut.ReadAll)
  285. // console.log(objShell.StdErr.ReadAll)
  286. // objShell = WScript.createobject("wscript.shell")
  287. objShell = null;
  288. return shellresult;
  289. }
  290. var p = null;
  291. var pworker = function(resolve, reject){
  292. // console.dir(p)
  293. var pfx = selectedinstance.root + '\\.elxr\\run-' + runtimestamp + '\\' + stampedFilePfx(new Date())
  294. // console.log('p.chain.length ================ ' + p.chain.length)
  295. options = options || {
  296. runFile : path.normalize( pfx + "out.txt")
  297. // runFile : null
  298. }
  299. var runFile = null;
  300. var runFile = options.runFile || pfx + command + cargs + "out.txt";
  301. // console.log(runFile)
  302. var args = cargs.concat()
  303. // runFile ? (args.push(">"), args.push(runFile)) : cargs
  304. // console.log(command + ' ' + args.join(' '))
  305. // command = 'cmd'
  306. // args = ['/c', 'start',
  307. // '/WAIT', selectedinstance.root + '/Downloads' + '/' + 'Git-2.33.0.2-64-bit.exe'
  308. // , '/VERYSILENT'
  309. // // , '/MERGETASKS=!runcode' // This is required only for vscode...
  310. // ]
  311. var runbat = path.normalize(pfx + "run.bat")
  312. // console.log('runbat : ' + runbat)
  313. fs.writeFileSync(runbat,
  314. '@echo off \r\n' +
  315. (options.cwd ? 'cd ' + options.cwd + ' \r\n' : '') +
  316. // ' cmd /k notepad.exe \r\n' +
  317. command + ' ' + args.join(' ') + ' \r\n' +
  318. 'cmd /c echo done >> ' + runFile + ' \r\n' +
  319. 'echo done'
  320. )
  321. // fs.writeFileSync(runFile, 'started')
  322. // WScript.Quit()
  323. // elevatedshellexecute(runFile)
  324. // while(!existsSync(runbat)) { wait(function(){
  325. // console.log('awiting batch : ' + runbat)
  326. // // shellExec( 'start', ['/W', '/b', runbat])
  327. // // shellExec( 'cmd', ['/k', '/b', runbat])
  328. // shellExec( command, args)
  329. // // cmd /b /c
  330. // }, 500) }
  331. console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' ')))
  332. var shellresult = shellExec( 'cmd', [ '/c', runbat])
  333. // var shellresult = shellExec( 'cmd', ['/c', runbat])
  334. // var shellresult = shellExec( command, args)
  335. var wrapup = function(result) {
  336. // console.log('Wrapping up')
  337. try {
  338. // console.log('resolving.....................');
  339. // console.log('--------------P' + result.messages.join(' ').trim() +'P--------------')
  340. // if(result.messages.join().trim()) resolve(result)
  341. // else reject(result)
  342. resolve(result)
  343. }
  344. catch(e){
  345. // console.dir(e)
  346. if(e.message === 'Input past end of file') {
  347. // console.log('---------------------------------------')
  348. // console.dir(result)
  349. resolve(result)
  350. }
  351. else {
  352. // console.dir(e)
  353. reject(e)
  354. }
  355. }
  356. }
  357. // if(runFile){
  358. // var waitr = function(){
  359. // WScript.StdOut.write('w.')
  360. // if(existsSync(runFile)) {
  361. // var strOutput = fs.readFileSync(runFile)
  362. // shellresult.result.messages = [strOutput]
  363. // wrapup(shellresult.result)
  364. // fs.unlinkSync(runFile)
  365. // }
  366. // // console.dir(shellresult.result)
  367. // wait( waitr, 500)
  368. // }
  369. // // console.log(wait)
  370. // wait( waitr, 500)
  371. // }
  372. // else {
  373. // console.log('There is no runfile.')
  374. // console.log(shellresult.strOutput)
  375. wrapup(shellresult.result)
  376. // }
  377. }
  378. p = new Promise(pworker)
  379. // promises.push(p)
  380. // // Promise tThens don't get hooked up... we need to postpone promise starting until all the thens are registered...
  381. // wait(function(){
  382. // console.log('p.chain.length' + p.chain.length)
  383. // p.start() } , 5000) // Bind and setTImeout is not supported by JScript
  384. return p;
  385. }
  386. createPromiseClass(/*ovrrides*/)
  387. __main( selectedinstance )
  388. }
  389. function createPromiseClass(overrides) {
  390. function reject(e){
  391. var p = this;
  392. console.log('Promise Rejection : ' + p.fn)
  393. console.dir(e)
  394. // throw e;f
  395. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Rejection can only be called once')}
  396. var __i = 0;
  397. var __e = e;
  398. do {
  399. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) break;
  400. try {
  401. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  402. __i++;
  403. __e = null;
  404. }
  405. catch(e){ __i++; __e = e}
  406. } while(__e)
  407. do {
  408. try { for(var i = __i; i < p.chain.length; i++, __i = i) if(!p.chain[i].isCatch) { p.result = p.chain[i](p.result); } }
  409. catch(e){
  410. __i ++;
  411. do {
  412. try {
  413. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  414. __i ++;
  415. __e = null;
  416. }
  417. catch(e){ __i++; __e = e}
  418. } while(__e)
  419. }
  420. } while ( __i < p.chain.length )
  421. p.state = PromiseClass.REJECTED;
  422. }
  423. function resolve(result){
  424. var p = this;
  425. // console.log(result + ' resolve was called with chain length ' + p.chain.length )
  426. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Resolve can only be called once')}
  427. p.result = result;
  428. if(PromiseClass.resolve(p.result) === p.result) {
  429. // console.log( 'result is still a promise waiting for result and promisechain' )
  430. waitForResult(p.result, function(r){ p.processchain(r) })
  431. }
  432. else {
  433. // console.log( 'result is value waiting for promisechain' )
  434. // console.dir(result)
  435. return p.processchain(result)
  436. }
  437. };
  438. function processchain(r){
  439. var __i = 0;
  440. var i = __i;
  441. var __e = null;
  442. p = this;
  443. // console.log('processchain chain.length : ' + p.chain.length)
  444. function __processchain(r){
  445. function waitForThen(p){
  446. if(i < p.chain.length) {
  447. if(!p.chain[i].isCatch) {
  448. // console.log('chain idx : ' + i + ' Executing : then ' + p.result + ' ' + p.chain[i])
  449. try {
  450. p.result = p.chain[i](p.result)
  451. if(PromiseClass.resolve(p.result) === p.result) {
  452. // console.log('chain idx : ' + i + ' result is still a promise starting it ')
  453. // console.dir(p.result.chain)
  454. // console.log('p.result.start : ' + p.result.start + ' ------------------ ')
  455. p.result.start()
  456. // console.log(p.result.fn + ' ------------------ ')
  457. waitForResult(p.result, function(r){
  458. // console.log('we waited')
  459. // WScript.write('.')
  460. p.result = r; i++; __i = i;
  461. waitForThen(p)
  462. })
  463. }
  464. else {
  465. i++; __i = i;
  466. waitForThen(p)
  467. }
  468. }
  469. catch(e) {
  470. i++; __i = i;
  471. __e = e;
  472. console.log('failed on index ' + __i + p.chain[__i-1] )
  473. console.dir(e)
  474. waitForCatch(p);
  475. }
  476. }
  477. else {
  478. // console.log(i + ' Skipping catch : ' + p.result + ' ' + p.chain[i])
  479. i++; __i = i;
  480. waitForThen(p)
  481. }
  482. }
  483. else return p.state = PromiseClass.FULFILLED;
  484. }
  485. function waitForCatch(p) {
  486. if(i < p.chain.length) {
  487. if(p.chain[i].isCatch) {
  488. console.log('chain idx : ' + i + ' Executing : catch : ' + p.result + ' ' + p.chain[i])
  489. try {
  490. p.result = p.chain[i](__e);
  491. if(PromiseClass.resolve(p.result) === p.result) {
  492. p.result.start()
  493. waitForResult(p.result, function(r){
  494. p.result = r; i++; __i = i;
  495. })
  496. waitForThen(p)
  497. }
  498. else {
  499. p.result = r; i++; __i = i;
  500. waitForThen(p)
  501. }
  502. }
  503. catch(e){ i++; __i = i;; __e = e; waitForCatch(p) }
  504. }
  505. else {
  506. i++; __i = i;
  507. waitForCatch(p)
  508. }
  509. }
  510. else return p.state = PromiseClass.REJECTED
  511. }
  512. waitForThen(p);
  513. }
  514. __processchain(r)
  515. }
  516. var create = function(fn){
  517. var p = {
  518. then : function(thenfn){
  519. // console.log('Adding then')
  520. thenfn.isThen = true
  521. // if(Object.prototype.toString.call(p.chain) !== '[object Array]') console.dir(p.chain)
  522. p.chain.push(thenfn)
  523. return p;
  524. }
  525. , 'catch' : function(catchfn) {
  526. catchfn.isCatch = true
  527. p.chain.push(catchfn)
  528. return p;
  529. }
  530. , start : function(){
  531. if(this.started) {
  532. console.error('Cannot start more than once...')
  533. return p
  534. };
  535. this.started = true;
  536. this.fn = fn;
  537. try { fn( function(r){
  538. // console.log('calling presolve in starter ')
  539. p.resolve(r) } , function(r){ p.reject(r) } ) }
  540. catch(e){
  541. // console.log('start catch : ' + e)
  542. // console.log('p.chain.length : ' + p.chain.length)
  543. // // console.dir(p)
  544. // console.dir(e)
  545. // console.log(fn)
  546. p.reject(e)
  547. }
  548. return p
  549. }
  550. , state : PromiseClass.PENDING
  551. , chain : []
  552. , reject : reject
  553. , resolve : resolve
  554. , processchain : processchain
  555. }
  556. p.chain.forEach = forEach;
  557. return p;
  558. }
  559. var PromiseClass = function(fn /*, donotstart */){
  560. var p = create(fn)
  561. // if(!donotstart) {
  562. // wait(function(){
  563. // console.log('p.chain.length' + p.chain.length)
  564. // p.start() } , 500) // Bind and setTImeout is not supported by JScript
  565. // }
  566. return p
  567. }
  568. PromiseClass.PENDING = 1
  569. PromiseClass.FULFILLED = 2
  570. PromiseClass.REJECTED = 3
  571. // PromiseClass.STARTED = 4
  572. PromiseClass.isSETTLED = function(p){ p.state === PromiseClass.FULFILLED || p.state === PromiseClass.REJECTED }
  573. PromiseClass.resolve = function(v){
  574. if(v && v.then) return v;
  575. var p = create(function(resolve, reject){
  576. resolve(v)
  577. });
  578. // console.log('p.chain in resolve. length ' + p.chain.length)
  579. // p.result = v;
  580. // wait(function(){ p.processchain(v) }, 0)
  581. return p;
  582. }
  583. function waitForResult(p, cb){
  584. if(!p) return cb(p)
  585. if(p.state !== PromiseClass.PENDING) cb(p.result)
  586. // console.log(p.state + ' Waiting for ..... ' + p.runFile)
  587. if(p.runFile && false) {
  588. while(!existsSync(p.runFile) && p.state === PromiseClass.PENDING) {
  589. console.log('Waiting for ResultFle'); wait(cb, 500)
  590. }
  591. cb(p.result)
  592. }
  593. else {
  594. // while(p.state === PromiseClass.PENDING) {
  595. // console.log('Waiting for Result')
  596. function waiter(){
  597. // console.log(p.result)
  598. if(p.state === PromiseClass.PENDING) wait(waiter, 500);
  599. else return cb(p.result)
  600. }
  601. wait(waiter, 500)
  602. // }
  603. }
  604. }
  605. PromiseClass.all = any; // Serialized...
  606. PromiseClass.__all = function(arr){
  607. arr.forEach = forEach;
  608. var resultPs = [];
  609. var results = [];
  610. console.log('All : ' + arr.length)
  611. var pAll = new PromiseClass(function(resolve, reject){
  612. console.log('All started : ' + pAll)
  613. // console.dir(pAll)
  614. arr.forEach(function(p){
  615. if(!p.then) { var pfn = p;
  616. p = new PromiseClass(function(resolve, reject){
  617. try{
  618. resolve(pfn())
  619. }
  620. catch(e){
  621. reject(e)
  622. }
  623. })
  624. p.start()
  625. }
  626. else {
  627. // !p.start ? p.start = function(){return p} : null
  628. // p.start()
  629. // .then( function(){ waitForResult(p, function(r){ results.push(r) }) })
  630. }
  631. resultPs.push(p)
  632. // waitForResult(p, function(r){ results.push(r) })
  633. })
  634. // PB : TODO -- This is the same as processchain!!!
  635. var allwaitr = function(){
  636. var allResolved = true
  637. console.log('resultPs : ' + resultPs.length)
  638. for(var rIdx =0; rIdx < resultPs.length; rIdx++ ){
  639. if(resultPs[rIdx]) {
  640. allResolved = false
  641. waitForResult(resultPs[rIdx], function(r){
  642. if(Promise.resolve(r) !== r) results[rIdx] = r; resultPs[rIdx] = null;
  643. })
  644. break;
  645. }
  646. }
  647. if(allResolved) {
  648. // console.log('All Reseloved')
  649. // console.dir(results)
  650. resolve(results)
  651. }
  652. else wait(allwaitr, 500)
  653. }
  654. wait(allwaitr, 500)
  655. })
  656. // pAll.chain = arr;
  657. return pAll
  658. }
  659. // PromiseClass.resolve = overrides.resolve;
  660. Promise = PromiseClass;
  661. return PromiseClass;
  662. }
  663. function __main( selectedinstance ){
  664. var downloadsdir = selectedinstance.root + '/Downloads';
  665. var callsheltask = function(args) { return function() { return nodeShellExec.apply(null, args) } }
  666. var gitUser = 'guest';
  667. var gitEmail = 'guest@bbh.org.in';
  668. var BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  669. function getVersion() { return BUILD_VERSION; }
  670. console.log(getVersion())
  671. function ensureDirectoryExistence(filePath) {
  672. var dirname = path.dirname(filePath);
  673. if (existsSyncFolder(dirname)) {
  674. return filePath;
  675. }
  676. ensureDirectoryExistence(dirname);
  677. fs.mkdirSync(dirname);
  678. return filePath;
  679. }
  680. var getTaskCheckExists = function(command, options) {
  681. options = options || {}
  682. return function() {
  683. var runFile = path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date()) + 'where' + command + "out.txt");
  684. var p = nodeShellExec.apply(null, ['cmd', ['/c', 'where', command], { runFile : runFile } ])
  685. p.runFile = runFile;
  686. if (options.ignorefailures) {
  687. return p.then(function(v) {
  688. // WScript.Echo('firstThen ' + v);
  689. return v })['catch']( function(e) {
  690. console.error(e);
  691. // Ignore. Not a major error if where command fails !!!
  692. throw e;
  693. })
  694. }
  695. else return p.then(function() {
  696. // WScript.Echo('firstThen ddd');
  697. return v });
  698. }
  699. }
  700. function verifyAndInstallPrerequisites() {
  701. fs.writeFileSync(ensureDirectoryExistence(downloadsdir + '/readme.txt'), getVersion() + ' Your local downloads for this instance');
  702. var downloadbatch =
  703. "::************************************************************************** \r\n \
  704. :Download_ <url> <File> \r\n \
  705. Powershell.exe ^\r\n \
  706. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^\r\n \
  707. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^\r\n \
  708. (New-Object System.Net.WebClient).DownloadFile('%1','%2') \r\n \
  709. exit /b \r\n \
  710. ::**************************************************************************";
  711. ensureDirectoryExistence(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/readme.txt'))
  712. fs.writeFileSync(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat'), downloadbatch);
  713. var downloadtasks = [];
  714. var installtasks = [];
  715. prerequisites.forEach(function(preq) {
  716. var p = preq.exists().then(function(exists) {
  717. if (exists) console.log( preq.shellcmd + ' exists');
  718. else {
  719. console.log(exists)
  720. console.log(preq.shellcmd + ' is not installed');
  721. return preq.preinstallsteps().then(function(){
  722. // console.log(' task.install : ' + preq.install)
  723. installtasks.push( function(){ return preq.install() } );
  724. })
  725. }
  726. })
  727. // .then(function(res){ console.log( 'preinstallsteps ' + res)});
  728. downloadtasks.push( p )
  729. });
  730. // console.log('downloadtasks')
  731. // console.dir(downloadtasks[0])
  732. var p = Promise.all(downloadtasks).then(function(){
  733. // console.log('calling install tasks : ' + installtasks.length)
  734. return any(installtasks) })
  735. // console.log('Promise.all.chain : ' + p.chain)
  736. return p
  737. }
  738. // var choiceHandler = function(choices, choice) {
  739. // console.log('chosen : ' + choice)
  740. // var decision = choices['d'];
  741. // if (choice && choice === 'd' || !choice) {
  742. // decision = choices['d']
  743. // }
  744. // else if (isNaN((+choice))) {
  745. // decision = choice
  746. // }
  747. // else decision = choices[choice-1]
  748. // if(!decision) throw 'Invalid selection : ' + decision
  749. // return decision
  750. // }
  751. // prereq definition helpers. We can't do proper inheritance in cscript. So fallback to global functions.
  752. function exists(next){
  753. var self = this;
  754. console.log('checking existence of ' + self.shellcmd)
  755. return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
  756. // console.log('-------------exists=======================')
  757. // console.dir(exists)
  758. // console.log(exists + ' ' + self.shellcmd + ' exists')
  759. if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
  760. return true;
  761. }
  762. else return false
  763. })['catch'](function(e){
  764. // console.log('-------------exists catch=======================')
  765. console.dir(e)
  766. return false;
  767. })
  768. }
  769. var prerequisites = [
  770. {
  771. shellcmd: 'git',
  772. url: 'https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe'
  773. , installer: 'Git-2.33.0.2-64-bit.exe'
  774. , installcmd: ['cmd', ['/c', 'start',
  775. '/WAIT', downloadsdir + '/' + 'Git-2.33.0.2-64-bit.exe'
  776. , '/VERYSILENT'
  777. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  778. ]]
  779. , preinstallsteps: function() {
  780. var self = this;
  781. console.log('Git preinstall steps')
  782. var steps = [];
  783. steps.push(
  784. function(){
  785. // console.log('cli prompt steps')
  786. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  787. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  788. }
  789. )
  790. steps.push(
  791. function(){
  792. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  793. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  794. }
  795. )
  796. steps.push(
  797. function(){
  798. if (!existsSync(downloadsdir + '/' + self.installer)) {
  799. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer])
  800. }
  801. else {
  802. console.log(self.installer + ' Already exits Download skipped.')
  803. return Promise.resolve(true)
  804. }
  805. }
  806. )
  807. return any(steps)
  808. // return any([any(steps), any(prompts)])
  809. }
  810. , installsteps: function () {
  811. var self = this;
  812. console.log('Git Installsteps called')
  813. var ifns = [self.installcmd]
  814. if(!ifns.map) ifns.map = map;
  815. return any(ifns.map(callsheltask))['catch'](function(e){
  816. if(e.code === 1602) {
  817. console.warn("Installation was probably cancelled.")
  818. }
  819. else throw e
  820. })
  821. }
  822. , postinstallsteps: function(){
  823. // PB : TODO -- Detect failure or cancellation before attenpting postinstall steps...
  824. var steps = [];
  825. steps.push(
  826. function(){
  827. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  828. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  829. }
  830. )
  831. steps.push(
  832. function(){
  833. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  834. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  835. }
  836. )
  837. return any(steps).then(function(){
  838. var steps = [
  839. ['git', ['config', '--global', '--add', 'user.name', gitUser]]
  840. , ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
  841. ]
  842. if(!steps.map) steps.map = map;
  843. return any(steps.map(callsheltask)).then(function(){
  844. })
  845. });
  846. }
  847. , install: function () {
  848. var self = this;
  849. console.log('Git Install called')
  850. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() }, function(){ return self.postinstallsteps() } ])
  851. }
  852. , verifyAndInstall : function(){
  853. var self = this;
  854. return self.exists().then( function(exits) {
  855. if(exists) return self.getUser(null, function(){ return self.postinstallsteps() } )
  856. else return self.install();
  857. })
  858. }
  859. , exists : exists
  860. , getUser : function(repo, onNoResult){
  861. onNoResult = onNoResult || function(){return false}
  862. var globalOrLocal = '--global';
  863. if(!repo) globalOrLocal = '--global';
  864. else globalOrLocal = '--local'
  865. var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]]
  866. if(!ifns.map) ifns.map = map;
  867. return any(fns.map(callsheltask)).then(function(result){
  868. // not yet configured.
  869. if(!result.success) return onNoResult()
  870. else {
  871. var users = result.messages[0].trim().split('\n');
  872. if(users.length === 0 ||
  873. users.length === 1 && users[0] === 'guest') {
  874. return onNoResult()
  875. }
  876. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  877. }
  878. })
  879. ['catch'](function(e){
  880. console.log(e)
  881. return onNoResult()
  882. })
  883. }
  884. }
  885. ,
  886. {
  887. shellcmd: 'node',
  888. url: 'https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi'
  889. , installer: 'node-v14.17.3-x64.msi'
  890. , installcmd: ['MSIEXEC.exe', ['/i'
  891. , path.normalize(downloadsdir + '/' + 'node-v14.17.3-x64.msi')
  892. , 'ACCEPT=YES', '/passive']]
  893. , install : function() {
  894. var self = this;
  895. var ifns = [self.installcmd]
  896. if(!ifns.map) ifns.map = map;
  897. return any(ifns.map(callsheltask))['catch'](function(e){
  898. if(e.code === 1602) {
  899. console.warn("Installation was probably cancelled.")
  900. }
  901. else throw e
  902. })
  903. }
  904. , exists : exists
  905. , preinstallsteps: function() {
  906. var self = this;
  907. console.log('Node preinstall steps')
  908. var steps = [];
  909. steps.push(
  910. function(){
  911. if (!existsSync(downloadsdir + '/' + self.installer)) {
  912. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  913. , { waitmsg : 'downloading node please wait' })
  914. }
  915. else {
  916. console.log(self.installer + ' Already exits Download skipped.')
  917. return Promise.resolve(true)
  918. }
  919. }
  920. )
  921. return any(steps)
  922. // return any([any(steps), any(prompts)])
  923. }
  924. }
  925. ,
  926. {
  927. shellcmd: 'elxr'
  928. , installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
  929. , preinstallsteps: function() {
  930. var self = this;
  931. console.log('Elxr preinstall steps')
  932. var steps = [];
  933. steps.push(
  934. function(){
  935. console.log('Elxr PreInstallsteps called')
  936. var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  937. if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  938. if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  939. // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  940. ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  941. }
  942. else {
  943. throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  944. }
  945. }
  946. else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  947. if(!ifns.map) ifns.map = map;
  948. return any(ifns.map(callsheltask))['catch'](function(e){
  949. if(e.code === 1602) {
  950. console.warn("Installation was probably cancelled.")
  951. }
  952. else throw e
  953. })
  954. }
  955. )
  956. return any([any(steps)])
  957. }
  958. , installsteps: function () {
  959. var self = this;
  960. console.log('Elxr Installsteps called')
  961. var ifns = [self.installcmd]
  962. if(!ifns.map) ifns.map = map;
  963. return any(ifns.map(callsheltask))['catch'](function(e){
  964. if(e.code === 1602) {
  965. console.warn("Installation was probably cancelled.")
  966. }
  967. else throw e
  968. })
  969. }
  970. , install: function () {
  971. var self = this;
  972. console.log('Elxr Install called')
  973. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() } ])
  974. }
  975. // , exists : function(){
  976. // console.log('Elxr PreInstallsteps called')
  977. // var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  978. // if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  979. // if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  980. // // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  981. // ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  982. // }
  983. // else {
  984. // throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  985. // }
  986. // }
  987. // else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  988. // if(!ifns.map) ifns.map = map;
  989. // return any(ifns.map(callsheltask))['catch'](function(e){
  990. // if(e.code === 1602) {
  991. // console.warn("Installation was probably cancelled.")
  992. // }
  993. // else throw e
  994. // })
  995. // }
  996. , exists : exists
  997. }
  998. ]
  999. if(!prerequisites.forEach) prerequisites.forEach = forEach;
  1000. // nodeShellExec(selectedinstance.root + '/.elxr/run-' + '1629889572461' + '/download.bat'
  1001. // , ['https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.32.0.2-64-bit.exe'
  1002. // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
  1003. promises.push(verifyAndInstallPrerequisites())
  1004. startPromises();
  1005. }