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.

преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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. var result = {}
  239. var shellresult = { shell : objShell, result : result }
  240. var WshRunning = 0
  241. var WshFinished = 1
  242. var WshFailed = 2
  243. while(oExec.Status === WshRunning){
  244. WScript.StdOut.write('.')
  245. WScript.Sleep(500)
  246. }
  247. var strOutput = ''
  248. switch(oExec.Status) {
  249. case WshFinished :
  250. strOutput = oExec.StdOut.ReadAll()
  251. result.success = true;
  252. result.code = 0
  253. break;
  254. case WshFailed :
  255. strOutput = oExec.StdErr.ReadAll()
  256. result.success = false;
  257. result.code = WshFailed
  258. break;
  259. default : strOutput = 'failed'
  260. break;
  261. }
  262. result.result = command + ' ' + cargs + ' exited with code ' + result.code
  263. result.messages = [strOutput]
  264. // WScript.Echo(oExec.Status)
  265. // WScript.Echo(oExec.ProcessID)
  266. // WScript.Echo(oExec.ExitCode)
  267. // console.log(objShell.StdOut.ReadAll)
  268. // console.log(objShell.StdErr.ReadAll)
  269. return shellresult;
  270. }
  271. var p = null;
  272. var pworker = function(resolve, reject){
  273. // console.dir(p)
  274. var pfx = selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date())
  275. // console.log('p.chain.length ================ ' + p.chain.length)
  276. options = options || {
  277. runFile : path.normalize( pfx + "out.txt")
  278. // runFile : null
  279. }
  280. var runFile = null;
  281. // var runFile = options.runFile
  282. // var runFile = selectedinstance.root + '\\' + stampedFilePfx(new Date()) + command + cargs + "out.txt";
  283. // console.log(runFile)
  284. var args = cargs.concat()
  285. // runFile ? (args.push(">"), args.push(runFile)) : cargs
  286. // console.log(command + ' ' + args.join(' '))
  287. // command = 'cmd'
  288. // args = ['/c', 'start',
  289. // '/WAIT', selectedinstance.root + '/Downloads' + '/' + 'Git-2.33.0.2-64-bit.exe'
  290. // , '/VERYSILENT'
  291. // // , '/MERGETASKS=!runcode' // This is required only for vscode...
  292. // ]
  293. var runbat = path.normalize(pfx + "run.bat")
  294. // console.log('runbat : ' + runbat)
  295. fs.writeFileSync(runbat, command + ' ' + args.join(' ') + ' \r\n' + 'echo done > ' + runFile )
  296. // fs.writeFileSync(runFile, 'started')
  297. // WScript.Quit()
  298. // elevatedshellexecute(runFile)
  299. // while(!existsSync(runbat)) { wait(function(){
  300. // console.log('awiting batch : ' + runbat)
  301. // // shellExec( 'start', ['/W', '/b', runbat])
  302. // // shellExec( 'cmd', ['/k', '/b', runbat])
  303. // shellExec( command, args)
  304. // // cmd /b /c
  305. // }, 500) }
  306. console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' ')))
  307. // var shellresult = shellExec( 'cmd', ['/c', runbat])
  308. var shellresult = shellExec( command, args)
  309. var wrapup = function(result) {
  310. // console.log('Wrapping up')
  311. try {
  312. resolve(result)
  313. }
  314. catch(e){
  315. // console.dir(e)
  316. if(e.message === 'Input past end of file') {
  317. // console.log('resolving'); console.dir(result)
  318. resolve(result)
  319. }
  320. else {
  321. reject(e)
  322. }
  323. }
  324. }
  325. if(runFile){
  326. var waitr = function(){
  327. WScript.StdOut.write('.')
  328. if(existsSync(runFile)) {
  329. var strOutput = fs.readFileSync(runFile)
  330. shellresult.result.messages = [strOutput]
  331. wrapup(shellresult.result)
  332. sfs.unlinkSync(runFile)
  333. }
  334. wait( waitr, 500)
  335. }
  336. // console.log(wait)
  337. wait( waitr, 500)
  338. }
  339. else {
  340. // console.log('There is no runfile.')
  341. // console.log(shellresult.strOutput)
  342. wrapup(shellresult.result)
  343. }
  344. }
  345. p = new Promise(pworker)
  346. // promises.push(p)
  347. // // Promise tThens don't get hooked up... we need to postpone promise starting until all the thens are registered...
  348. // wait(function(){
  349. // console.log('p.chain.length' + p.chain.length)
  350. // p.start() } , 5000) // Bind and setTImeout is not supported by JScript
  351. return p;
  352. }
  353. createPromiseClass(/*ovrrides*/)
  354. __main( selectedinstance )
  355. }
  356. function createPromiseClass(overrides) {
  357. function reject(e){
  358. var p = this;
  359. console.log('Promise Rejection : ' + p.fn)
  360. console.dir(e)
  361. // throw e;f
  362. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Rejection can only be called once')}
  363. var __i = 0;
  364. var __e = e;
  365. do {
  366. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) break;
  367. try {
  368. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  369. __i++;
  370. __e = null;
  371. }
  372. catch(e){ __i++; __e = e}
  373. } while(__e)
  374. do {
  375. try { for(var i = __i; i < p.chain.length; i++, __i = i) if(!p.chain[i].isCatch) { p.result = p.chain[i](p.result); } }
  376. catch(e){
  377. __i ++;
  378. do {
  379. try {
  380. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  381. __i ++;
  382. __e = null;
  383. }
  384. catch(e){ __i++; __e = e}
  385. } while(__e)
  386. }
  387. } while ( __i < p.chain.length )
  388. p.state = PromiseClass.REJECTED;
  389. }
  390. function resolve(result){
  391. var p = this;
  392. // console.log(result + ' resolve was called with chain length ' + p.chain.length )
  393. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Resolve can only be called once')}
  394. p.result = result;
  395. if(PromiseClass.resolve(p.result) === p.result) {
  396. // console.log( 'result is still a promise waiting for result and promisechain' )
  397. waitForResult(p.result, function(r){ p.processchain(r) })
  398. }
  399. else {
  400. // console.log( 'result is value waiting for promisechain' )
  401. // console.dir(result)
  402. return p.processchain(result)
  403. }
  404. };
  405. function processchain(r){
  406. var __i = 0;
  407. var i = __i;
  408. var __e = null;
  409. p = this;
  410. // console.log('processchain chain.length : ' + p.chain.length)
  411. function __processchain(r){
  412. function waitForThen(p){
  413. if(i < p.chain.length) {
  414. if(!p.chain[i].isCatch) {
  415. // console.log('chain idx : ' + i + ' Executing : then ' + p.result + ' ' + p.chain[i])
  416. try {
  417. p.result = p.chain[i](p.result)
  418. if(PromiseClass.resolve(p.result) === p.result) {
  419. // console.log('chain idx : ' + i + ' result is still a promise starting it ')
  420. // console.dir(p.result.chain)
  421. // console.log('p.result.start : ' + p.result.start + ' ------------------ ')
  422. p.result.start()
  423. // console.log(p.result.fn + ' ------------------ ')
  424. waitForResult(p.result, function(r){
  425. // console.log('we waited')
  426. // WScript.write('.')
  427. p.result = r; i++; __i = i;
  428. waitForThen(p)
  429. })
  430. }
  431. else {
  432. i++; __i = i;
  433. waitForThen(p)
  434. }
  435. }
  436. catch(e) {
  437. i++; __i = i;
  438. __e = e;
  439. console.log('failed on index ' + __i + p.chain[__i-1] )
  440. console.dir(e)
  441. waitForCatch(p);
  442. }
  443. }
  444. else {
  445. // console.log(i + ' Skipping catch : ' + p.result + ' ' + p.chain[i])
  446. i++; __i = i;
  447. waitForThen(p)
  448. }
  449. }
  450. else return p.state = PromiseClass.FULFILLED;
  451. }
  452. function waitForCatch(p) {
  453. if(i < p.chain.length) {
  454. if(p.chain[i].isCatch) {
  455. console.log('chain idx : ' + i + ' Executing : catch : ' + p.result + ' ' + p.chain[i])
  456. try {
  457. p.result = p.chain[i](__e);
  458. if(PromiseClass.resolve(p.result) === p.result) {
  459. p.result.start()
  460. waitForResult(p.result, function(r){
  461. p.result = r; i++; __i = i;
  462. })
  463. waitForThen(p)
  464. }
  465. else {
  466. p.result = r; i++; __i = i;
  467. waitForThen(p)
  468. }
  469. }
  470. catch(e){ i++; __i = i;; __e = e; waitForCatch(p) }
  471. }
  472. else {
  473. i++; __i = i;
  474. waitForCatch(p)
  475. }
  476. }
  477. else return p.state = PromiseClass.REJECTED
  478. }
  479. waitForThen(p);
  480. }
  481. __processchain(r)
  482. }
  483. var create = function(fn){
  484. var p = {
  485. then : function(thenfn){
  486. // console.log('Adding then')
  487. thenfn.isThen = true
  488. // if(Object.prototype.toString.call(p.chain) !== '[object Array]') console.dir(p.chain)
  489. p.chain.push(thenfn)
  490. return p;
  491. }
  492. , pcatch : function(catchfn) {
  493. catchfn.isCatch = true
  494. p.chain.push(catchfn)
  495. return p;
  496. }
  497. , start : function(){
  498. if(this.started) {
  499. console.error('Cannot start more than once...')
  500. return p
  501. };
  502. this.started = true;
  503. this.fn = fn;
  504. try { fn( function(r){
  505. // console.log('calling presolve in starter ')
  506. p.resolve(r) } , function(r){ p.reject(r) } ) }
  507. catch(e){
  508. // console.log('start catch : ' + e)
  509. // console.log('p.chain.length : ' + p.chain.length)
  510. // // console.dir(p)
  511. // console.dir(e)
  512. // console.log(fn)
  513. p.reject(e)
  514. }
  515. return p
  516. }
  517. , state : PromiseClass.PENDING
  518. , chain : []
  519. , reject : reject
  520. , resolve : resolve
  521. , processchain : processchain
  522. }
  523. p['catch'] = p['pcatch']
  524. p.chain.forEach = forEach;
  525. return p;
  526. }
  527. var PromiseClass = function(fn /*, donotstart */){
  528. var p = create(fn)
  529. // if(!donotstart) {
  530. // wait(function(){
  531. // console.log('p.chain.length' + p.chain.length)
  532. // p.start() } , 500) // Bind and setTImeout is not supported by JScript
  533. // }
  534. return p
  535. }
  536. PromiseClass.PENDING = 1
  537. PromiseClass.FULFILLED = 2
  538. PromiseClass.REJECTED = 3
  539. // PromiseClass.STARTED = 4
  540. PromiseClass.isSETTLED = function(p){ p.state === PromiseClass.FULFILLED || p.state === PromiseClass.REJECTED }
  541. PromiseClass.resolve = function(v){
  542. if(v && v.then) return v;
  543. var p = create(function(resolve, reject){
  544. resolve(v)
  545. });
  546. // console.log('p.chain in resolve. length ' + p.chain.length)
  547. // p.result = v;
  548. // wait(function(){ p.processchain(v) }, 0)
  549. return p;
  550. }
  551. function waitForResult(p, cb){
  552. if(!p) return cb(p)
  553. if(p.state !== PromiseClass.PENDING) cb(p.result)
  554. // console.log(p.state + ' Waiting for ..... ' + p.runFile)
  555. if(p.runFile && false) {
  556. while(!existsSync(p.runFile) && p.state === PromiseClass.PENDING) {
  557. console.log('Waiting for ResultFle'); wait(cb, 500)
  558. }
  559. cb(p.result)
  560. }
  561. else {
  562. // while(p.state === PromiseClass.PENDING) {
  563. // console.log('Waiting for Result')
  564. function waiter(){
  565. // console.log(p.result)
  566. if(p.state === PromiseClass.PENDING) wait(waiter, 500);
  567. else return cb(p.result)
  568. }
  569. wait(waiter, 500)
  570. // }
  571. }
  572. }
  573. PromiseClass.all = any; // Serialized...
  574. PromiseClass.__all = function(arr){
  575. arr.forEach = forEach;
  576. var resultPs = [];
  577. var results = [];
  578. console.log('All : ' + arr.length)
  579. var pAll = new PromiseClass(function(resolve, reject){
  580. console.log('All started : ' + pAll)
  581. // console.dir(pAll)
  582. arr.forEach(function(p){
  583. if(!p.then) { var pfn = p;
  584. p = new PromiseClass(function(resolve, reject){
  585. try{
  586. resolve(pfn())
  587. }
  588. catch(e){
  589. reject(e)
  590. }
  591. })
  592. p.start()
  593. }
  594. else {
  595. // !p.start ? p.start = function(){return p} : null
  596. // p.start()
  597. // .then( function(){ waitForResult(p, function(r){ results.push(r) }) })
  598. }
  599. resultPs.push(p)
  600. // waitForResult(p, function(r){ results.push(r) })
  601. })
  602. // PB : TODO -- This is the same as processchain!!!
  603. var allwaitr = function(){
  604. var allResolved = true
  605. console.log('resultPs : ' + resultPs.length)
  606. for(var rIdx =0; rIdx < resultPs.length; rIdx++ ){
  607. if(resultPs[rIdx]) {
  608. allResolved = false
  609. waitForResult(resultPs[rIdx], function(r){
  610. if(Promise.resolve(r) !== r) results[rIdx] = r; resultPs[rIdx] = null;
  611. })
  612. break;
  613. }
  614. }
  615. if(allResolved) {
  616. // console.log('All Reseloved')
  617. // console.dir(results)
  618. resolve(results)
  619. }
  620. else wait(allwaitr, 500)
  621. }
  622. wait(allwaitr, 500)
  623. })
  624. // pAll.chain = arr;
  625. return pAll
  626. }
  627. // PromiseClass.resolve = overrides.resolve;
  628. Promise = PromiseClass;
  629. return PromiseClass;
  630. }
  631. function __main( selectedinstance ){
  632. var downloadsdir = selectedinstance.root + '/Downloads';
  633. var callsheltask = function(args) { return function() { return nodeShellExec.apply(null, args) } }
  634. var gitUser = 'guest';
  635. var gitEmail = 'guest@bbh.org.in';
  636. var BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  637. function getVersion() { return BUILD_VERSION; }
  638. console.log(getVersion())
  639. function ensureDirectoryExistence(filePath) {
  640. var dirname = path.dirname(filePath);
  641. if (existsSyncFolder(dirname)) {
  642. return filePath;
  643. }
  644. ensureDirectoryExistence(dirname);
  645. fs.mkdirSync(dirname);
  646. return filePath;
  647. }
  648. var getTaskCheckExists = function(command, options) {
  649. options = options || {}
  650. return function() {
  651. var runFile = path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date()) + 'where' + command + "out.txt");
  652. var p = nodeShellExec.apply(null, ['cmd', ['/c', 'where', command], { runFile : runFile } ])
  653. p.runFile = runFile;
  654. var catchr = 'catch'
  655. // console.log(p['catch'])
  656. if(p['catch']) { catchr = 'catch' } else { catchr = 'pcatch';}
  657. if (options.ignorefailures) {
  658. return p.then(function(v) {
  659. // WScript.Echo('firstThen ' + v);
  660. return v })[catchr]( function(e) {
  661. console.error(e);
  662. // Ignore. Not a major error if where command fails !!!
  663. throw e;
  664. })
  665. }
  666. else return p.then(function() {
  667. // WScript.Echo('firstThen ddd');
  668. return v });
  669. }
  670. }
  671. function verifyAndInstallPrerequisites() {
  672. fs.writeFileSync(ensureDirectoryExistence(downloadsdir + '/readme.txt'), getVersion() + ' Your local downloads for this instance');
  673. var downloadbatch =
  674. "::************************************************************************** \r\n \
  675. :Download_ <url> <File> \r\n \
  676. Powershell.exe ^\r\n \
  677. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^\r\n \
  678. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^\r\n \
  679. (New-Object System.Net.WebClient).DownloadFile('%1','%2') \r\n \
  680. exit /b \r\n \
  681. ::**************************************************************************";
  682. ensureDirectoryExistence(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/readme.txt'))
  683. fs.writeFileSync(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat'), downloadbatch);
  684. var downloadtasks = [];
  685. var installtasks = [];
  686. prerequisites.forEach(function(preq) {
  687. var p = preq.exists().then(function(exists) {
  688. if (exists) console.log( preq.shellcmd + ' exists');
  689. else {
  690. console.log(exists)
  691. console.log(preq.shellcmd + ' is not installed');
  692. return preq.preinstallsteps().then(function(){
  693. // console.log(' task.install : ' + preq.install)
  694. installtasks.push( function(){ return preq.install() } );
  695. })
  696. }
  697. })
  698. // .then(function(res){ console.log( 'preinstallsteps ' + res)});
  699. downloadtasks.push( p )
  700. });
  701. // console.log('downloadtasks')
  702. // console.dir(downloadtasks[0])
  703. var p = Promise.all(downloadtasks).then(function(){
  704. // console.log('calling install tasks : ' + installtasks.length)
  705. return any(installtasks) })
  706. // console.log('Promise.all.chain : ' + p.chain)
  707. return p
  708. }
  709. // var choiceHandler = function(choices, choice) {
  710. // console.log('chosen : ' + choice)
  711. // var decision = choices['d'];
  712. // if (choice && choice === 'd' || !choice) {
  713. // decision = choices['d']
  714. // }
  715. // else if (isNaN((+choice))) {
  716. // decision = choice
  717. // }
  718. // else decision = choices[choice-1]
  719. // if(!decision) throw 'Invalid selection : ' + decision
  720. // return decision
  721. // }
  722. var prerequisites = [
  723. {
  724. shellcmd: 'git',
  725. url: 'https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe'
  726. , installer: 'Git-2.33.0.2-64-bit.exe'
  727. , installcmd: ['cmd', ['/c', 'start',
  728. '/WAIT', downloadsdir + '/' + 'Git-2.33.0.2-64-bit.exe'
  729. , '/VERYSILENT'
  730. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  731. ]]
  732. , preinstallsteps: function() {
  733. var self = this;
  734. console.log('Git preinstall steps')
  735. var steps = [];
  736. steps.push(
  737. function(){
  738. // console.log('cli prompt steps')
  739. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  740. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  741. }
  742. )
  743. steps.push(
  744. function(){
  745. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  746. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  747. }
  748. )
  749. steps.push(
  750. function(){
  751. if (!existsSync(downloadsdir + '/' + self.installer)) {
  752. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer])
  753. }
  754. else {
  755. console.log(self.installer + ' Already exits Download skipped.')
  756. return Promise.resolve(true)
  757. }
  758. }
  759. )
  760. return any(steps)
  761. // return any([any(steps), any(prompts)])
  762. }
  763. , installsteps: function () {
  764. var self = this;
  765. console.log('Git Installsteps called')
  766. var ifns = [self.installcmd]
  767. ifns.map = map;
  768. return any(ifns.map(callsheltask))['catch'](function(e){
  769. if(e.code === 1602) {
  770. console.warn("Installation was probably cancelled.")
  771. }
  772. else throw e
  773. })
  774. }
  775. , postinstallsteps: function(){
  776. // PB : TODO -- Detect failure or cancellation before attenpting postinstall steps...
  777. var steps = [];
  778. steps.push(
  779. function(){
  780. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  781. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  782. }
  783. )
  784. steps.push(
  785. function(){
  786. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  787. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  788. }
  789. )
  790. return any(steps).then(function(){
  791. var steps = [
  792. ['git', ['config', '--global', '--add', 'user.name', gitUser]]
  793. , ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
  794. ]
  795. steps.map = map;
  796. return any(steps.map(callsheltask)).then(function(){
  797. })
  798. });
  799. }
  800. , install: function () {
  801. var self = this;
  802. console.log('Git Install called')
  803. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() }, function(){ return self.postinstallsteps() } ])
  804. }
  805. , verifyAndInstall : function(){
  806. var self = this;
  807. return self.exists().then( function(exits) {
  808. if(exists) return self.getUser(null, function(){ return self.postinstallsteps() } )
  809. else return self.install();
  810. })
  811. }
  812. , exists : function(next){
  813. var self = this;
  814. return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
  815. // console.dir(exists)
  816. // console.log(exists + ' git exists')
  817. if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
  818. return true;
  819. }
  820. else return false
  821. })
  822. }
  823. , getUser : function(repo, onNoResult){
  824. onNoResult = onNoResult || function(){return false}
  825. var globalOrLocal = '--global';
  826. if(!repo) globalOrLocal = '--global';
  827. else globalOrLocal = '--local'
  828. var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]]
  829. fns.map = map;
  830. return any(fns.map(callsheltask)).then(function(result){
  831. // not yet configured.
  832. if(!result.success) return onNoResult()
  833. else {
  834. var users = result.messages[0].trim().split('\n');
  835. if(users.length === 0 ||
  836. users.length === 1 && users[0] === 'guest') {
  837. return onNoResult()
  838. }
  839. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  840. }
  841. })
  842. .pcatch(function(e){
  843. console.log(e)
  844. return onNoResult()
  845. })
  846. }
  847. }
  848. ,
  849. {
  850. shellcmd: 'node',
  851. url: 'https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi'
  852. , installer: 'node-v14.17.3-x64.msi'
  853. , installcmd: ['MSIEXEC.exe', ['/i'
  854. , path.normalize(downloadsdir + '/' + 'node-v14.17.3-x64.msi')
  855. , 'ACCEPT=YES', '/passive']]
  856. , install : function() {
  857. var self = this;
  858. var ifns = [self.installcmd]
  859. ifns.map = map;
  860. return any(ifns.map(callsheltask))['catch'](function(e){
  861. if(e.code === 1602) {
  862. console.warn("Installation was probably cancelled.")
  863. }
  864. else throw e
  865. })
  866. }
  867. , exists : function(next){
  868. var self = this;
  869. return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
  870. // console.log(self.shellcmd + ' ' + exists + ' node exists')
  871. if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
  872. return true
  873. }
  874. else {
  875. // console.log(self.shellcmd + ' ' + exists + ' node doesnt exist')
  876. return false
  877. }
  878. })
  879. }
  880. , preinstallsteps: function() {
  881. var self = this;
  882. console.log('Node preinstall steps')
  883. var steps = [];
  884. steps.push(
  885. function(){
  886. if (!existsSync(downloadsdir + '/' + self.installer)) {
  887. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  888. , { waitmsg : 'downloading node please wait' })
  889. }
  890. else {
  891. console.log(self.installer + ' Already exits Download skipped.')
  892. return Promise.resolve(true)
  893. }
  894. }
  895. )
  896. return any(steps)
  897. // return any([any(steps), any(prompts)])
  898. }
  899. }
  900. ]
  901. if(!prerequisites.forEach) prerequisites.forEach = forEach;
  902. // nodeShellExec(selectedinstance.root + '/.elxr/run-' + '1629889572461' + '/download.bat'
  903. // , ['https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.32.0.2-64-bit.exe'
  904. // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
  905. promises.push(verifyAndInstallPrerequisites())
  906. if(wsh) startPromises();
  907. }