Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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