555
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
pirms 3 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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. function unique(arr) {
  770. var hash = {}, result = [];
  771. for ( var i = 0, l = arr.length; i < l; ++i ) {
  772. if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
  773. hash[ arr[i] ] = true;
  774. result.push(arr[i]);
  775. }
  776. }
  777. return result;
  778. }
  779. // var ENV = Object.assign({}, process.env); // Shallow clone it.
  780. var WshShell = WScript.CreateObject("WScript.Shell")
  781. var ENV = WshShell.Environment("Process")
  782. WScript.echo( ENV("Path") )
  783. function sysAddPathVar(path){
  784. // Object.assign({
  785. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  786. // }, options)
  787. // var newpath = ENV("Path").split(';');
  788. // newpath = Array.from(new Set(newpath.push(path))).join(';')
  789. var newpath = [];
  790. newpath.push(path)
  791. newpath = unique(newpath).join(';')
  792. // path.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  793. return any([nodeShellExec('setx', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  794. // , nodeShellExec('set', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  795. ] );
  796. }
  797. var prerequisites = [
  798. {
  799. shellcmd: 'git',
  800. url: 'https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe'
  801. , installer: 'Git-2.33.0.2-64-bit.exe'
  802. , installcmd: ['cmd', ['/c', 'start',
  803. '/WAIT', downloadsdir + '/' + 'Git-2.33.0.2-64-bit.exe'
  804. , '/VERYSILENT'
  805. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  806. ]]
  807. , preinstallsteps: function() {
  808. var self = this;
  809. console.log('Git preinstall steps')
  810. var steps = [];
  811. steps.push(
  812. function(){
  813. // console.log('cli prompt steps')
  814. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  815. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  816. }
  817. )
  818. steps.push(
  819. function(){
  820. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  821. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  822. }
  823. )
  824. steps.push(
  825. function(){
  826. if (!existsSync(downloadsdir + '/' + self.installer)) {
  827. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer])
  828. }
  829. else {
  830. console.log(self.installer + ' Already exits Download skipped.')
  831. return Promise.resolve(true)
  832. }
  833. }
  834. )
  835. return any(steps)
  836. // return any([any(steps), any(prompts)])
  837. }
  838. , installsteps: function () {
  839. var self = this;
  840. console.log('Git Installsteps called')
  841. var ifns = [self.installcmd]
  842. if(!ifns.map) ifns.map = map;
  843. return any(ifns.map(callsheltask))['catch'](function(e){
  844. if(e.code === 1602) {
  845. console.warn("Installation was probably cancelled.")
  846. }
  847. else throw e
  848. })
  849. }
  850. , postinstallsteps: function(){
  851. // PB : TODO -- Detect failure or cancellation before attenpting postinstall steps...
  852. var steps = [];
  853. steps.push(
  854. function(){
  855. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  856. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  857. }
  858. )
  859. steps.push(
  860. function(){
  861. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  862. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  863. }
  864. )
  865. return any(steps).then(function(){
  866. var steps = [
  867. ['git', ['config', '--global', '--add', 'user.name', gitUser]]
  868. , ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
  869. ]
  870. if(!steps.map) steps.map = map;
  871. return any(steps.map(callsheltask)).then(function(){
  872. })
  873. });
  874. }
  875. , install: function () {
  876. var self = this;
  877. console.log('Git Install called')
  878. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() }, function(){ return self.postinstallsteps() } ])
  879. }
  880. , verifyAndInstall : function(){
  881. var self = this;
  882. return self.exists().then( function(exits) {
  883. if(exists) return self.getUser(null, function(){ return self.postinstallsteps() } )
  884. else return self.install();
  885. })
  886. }
  887. , exists : exists
  888. , getUser : function(repo, onNoResult){
  889. onNoResult = onNoResult || function(){return false}
  890. var globalOrLocal = '--global';
  891. if(!repo) globalOrLocal = '--global';
  892. else globalOrLocal = '--local'
  893. var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]]
  894. if(!ifns.map) ifns.map = map;
  895. return any(fns.map(callsheltask)).then(function(result){
  896. // not yet configured.
  897. if(!result.success) return onNoResult()
  898. else {
  899. var users = result.messages[0].trim().split('\n');
  900. if(users.length === 0 ||
  901. users.length === 1 && users[0] === 'guest') {
  902. return onNoResult()
  903. }
  904. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  905. }
  906. })
  907. ['catch'](function(e){
  908. console.log(e)
  909. return onNoResult()
  910. })
  911. }
  912. }
  913. ,
  914. {
  915. shellcmd: 'node',
  916. url: 'https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi'
  917. , installer: 'node-v14.17.3-x64.msi'
  918. , installcmd: ['MSIEXEC.exe', ['/i'
  919. , path.normalize(downloadsdir + '/' + 'node-v14.17.3-x64.msi')
  920. , 'ACCEPT=YES', '/passive']]
  921. , install : function() {
  922. var self = this;
  923. var ifns = [self.installcmd]
  924. if(!ifns.map) ifns.map = map;
  925. return any(ifns.map(callsheltask))['catch'](function(e){
  926. if(e.code === 1602) {
  927. console.warn("Installation was probably cancelled.")
  928. }
  929. else throw e
  930. })
  931. }
  932. , exists : exists
  933. , preinstallsteps: function() {
  934. var self = this;
  935. console.log('Node preinstall steps')
  936. var steps = [];
  937. steps.push(
  938. function(){
  939. if (!existsSync(downloadsdir + '/' + self.installer)) {
  940. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  941. , { waitmsg : 'downloading node please wait' })
  942. }
  943. else {
  944. console.log(self.installer + ' Already exits Download skipped.')
  945. return Promise.resolve(true)
  946. }
  947. }
  948. )
  949. return any(steps)
  950. // return any([any(steps), any(prompts)])
  951. }
  952. }
  953. , {
  954. shellcmd: 'python2'
  955. , url: 'https://www.python.org/ftp/python/2.7.18/python-2.7.18.amd64.msi'
  956. , installer: 'python-2.7.18.amd64.msi'
  957. , installcmd: ['MSIEXEC.exe', ['/i'
  958. , path.normalize(downloadsdir + '/' + 'python-2.7.18.amd64.msi')
  959. , 'ACCEPT=YES', '/passive']]
  960. , preinstallsteps : function() { return Promise.resolve(true) }
  961. , install : function() {
  962. var self = this;
  963. var ifns = [self.installcmd]
  964. if(!ifns.map) ifns.map = map;
  965. console.log('Installing')
  966. return any(ifns.map(callsheltask))['catch'](function(e){
  967. if(e.code === 1602) {
  968. console.warn("Installation was probably cancelled.")
  969. }
  970. else throw e
  971. }).then(function(){
  972. return self.postinstallsteps()
  973. })
  974. }
  975. , postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
  976. , exists : exists
  977. }
  978. ,
  979. {
  980. shellcmd: 'elxr'
  981. , installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
  982. , preinstallsteps: function() {
  983. var self = this;
  984. console.log('Elxr preinstall steps')
  985. var steps = [];
  986. steps.push(
  987. function(){
  988. console.log('Elxr PreInstallsteps called')
  989. var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  990. if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  991. if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  992. // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  993. ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  994. }
  995. else {
  996. throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  997. }
  998. }
  999. else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1000. if(!ifns.map) ifns.map = map;
  1001. return any(ifns.map(callsheltask))['catch'](function(e){
  1002. if(e.code === 1602) {
  1003. console.warn("Installation was probably cancelled.")
  1004. }
  1005. else throw e
  1006. })
  1007. }
  1008. )
  1009. return any([any(steps)])
  1010. }
  1011. , installsteps: function () {
  1012. var self = this;
  1013. console.log('Elxr Installsteps called')
  1014. var ifns = [self.installcmd]
  1015. if(!ifns.map) ifns.map = map;
  1016. return any(ifns.map(callsheltask))['catch'](function(e){
  1017. if(e.code === 1602) {
  1018. console.warn("Installation was probably cancelled.")
  1019. }
  1020. else throw e
  1021. })
  1022. }
  1023. , install: function () {
  1024. var self = this;
  1025. console.log('Elxr Install called')
  1026. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() } ])
  1027. }
  1028. // , exists : function(){
  1029. // console.log('Elxr PreInstallsteps called')
  1030. // var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  1031. // if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1032. // if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1033. // // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1034. // ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1035. // }
  1036. // else {
  1037. // throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1038. // }
  1039. // }
  1040. // else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1041. // if(!ifns.map) ifns.map = map;
  1042. // return any(ifns.map(callsheltask))['catch'](function(e){
  1043. // if(e.code === 1602) {
  1044. // console.warn("Installation was probably cancelled.")
  1045. // }
  1046. // else throw e
  1047. // })
  1048. // }
  1049. , exists : exists
  1050. }
  1051. ]
  1052. if(!prerequisites.forEach) prerequisites.forEach = forEach;
  1053. // nodeShellExec(selectedinstance.root + '/.elxr/run-' + '1629889572461' + '/download.bat'
  1054. // , ['https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.32.0.2-64-bit.exe'
  1055. // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
  1056. promises.push(verifyAndInstallPrerequisites())
  1057. startPromises();
  1058. }