555
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

i.win.js 40KB

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