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

i.win.js 54KB

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年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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. WScript = function(){}
  38. WScript.Echo = function(m){
  39. console.log('Invalid Wscript')
  40. throw "Failed in Node Run."
  41. }
  42. var wait = function(ms, cb) {any
  43. return new __Promise(function(resolve){ setTimeout(resolve, ms) } ).then(function(){ cb() });
  44. }
  45. var fs = require('fs')
  46. var existsSync = require('fs').existsSync;
  47. var existsSyncFolder = existsSync
  48. var path = require('path');
  49. console.log('before cliverse')
  50. var cli = require('./cliverse')
  51. var nodeShellExec = cli.nodeShellExec;
  52. console.log('before bbhverse')
  53. var utils = require('bbhverse');
  54. var any = utils.any;
  55. var wait = setTimeout
  56. // --------------------------------------------
  57. // PB : TODO -- This should be parent dir if elxr is already installed.
  58. var selectedinstance = { root : path.resolve(".") }
  59. __main(selectedinstance)
  60. }
  61. catch(e) {
  62. WScript.Echo('detected wsh')
  63. scripthostName = 'wsh'
  64. WScript.Echo(WScript.FullName)
  65. // WScript.Echo('--' + WScript.Arguments(0) + '--')
  66. // WScript.Echo('------------ALL-----------')
  67. // var argEnumerator = new Enumerator(WScript.Arguments)
  68. // for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
  69. // WScript.Echo('-arg-' + argEnumerator.item() + '-arg-')
  70. // }
  71. // // Unnamed
  72. // WScript.Echo('------------UNNAMED-----------')
  73. // argEnumerator = new Enumerator(WScript.Arguments.Unnamed)
  74. // for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
  75. // WScript.Echo('-arg-' + argEnumerator.item() + '-arg-') // Value
  76. // }
  77. // // Named
  78. // WScript.Echo('------------NAMED-----------')
  79. // argEnumerator = new Enumerator(WScript.Arguments.Named)
  80. // for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
  81. // // WScript.Echo('-arg-' + argEnumerator.item(argEnumerator) + '-arg-') // Key
  82. // WScript.Echo('-key-' + argEnumerator.item() + '-key-') // Key
  83. // WScript.Echo('-val=' + WScript.Arguments.Named(argEnumerator.item()) + '=val-') // Value
  84. // }
  85. // cscript elxr/i.win.js /all:true
  86. var all = WScript.Arguments.Named('all');
  87. trim = function(str) { return str.replace(/^\s+|\s+$/g, ''); };
  88. var fs = new ActiveXObject('Scripting.FileSystemObject');
  89. var WshShell = WScript.CreateObject("WScript.Shell")
  90. var ENV = WshShell.Environment("Process")
  91. var sfn = WScript.ScriptFullName
  92. // WScript.Echo(sfn)
  93. var cd = fs.GetAbsolutePathName(".")
  94. var cfn = cd + '\\i.win.js'
  95. // WScript.Echo(cfn)
  96. var waslaunchedwithenv = trim(ENV.Item('LAUNCHEDWITHENV'));
  97. // for(e=new Enumerator(ENV); !e.atEnd(); e.moveNext()) WScript.echo(e.item(e));
  98. if(waslaunchedwithenv !== "YES"){
  99. var a = fs.CreateTextFile("launchwithenv.bat", true)
  100. a.WriteLine("@echo off")
  101. a.WriteLine("echo %PATH%")
  102. var gitpath = "C:\\Program Files\\Git\\cmd"
  103. var nodepath = "C:\\Program Files\\nodejs\\"
  104. var codepath = "C:\\Users\\Pradeep\\AppData\\Local\\Programs\\Microsoft VS Code\\bin"
  105. a.WriteLine("set PATH=%PATH%;" + gitpath )
  106. a.WriteLine("set PATH=%PATH%;" + nodepath )
  107. a.WriteLine("set PATH=%PATH%;" + codepath )
  108. // a.WriteLine("set LAUNCHEDWITHENV=YES" )
  109. var runningInExlr = function() {
  110. var __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  111. if(fs.FileExists('./' + __ALIAS__STAMP__)) return true
  112. }
  113. if(cfn === sfn && runningInExlr()) {
  114. a.WriteLine("cd ..");
  115. a.WriteLine("SET LAUNCHEDWITHENV=YES && cscript "+cfn+" /all:true") // PB : TODO -- Retain all script args...
  116. }
  117. else {
  118. a.WriteLine("SET LAUNCHEDWITHENV=YES && cscript "+sfn+" /all:true")
  119. }
  120. // a.WriteLine("powershell.exe ^")
  121. // a.WriteLine("[Environment]::GetEnvironmentVariable('Path')" )
  122. a.Close()
  123. WshShell.run("cmd /k launchwithenv.bat")
  124. WScript.Quit()
  125. // WshShell.run("powershell -noexit [Environment]::GetEnvironmentVariable(\"\"Path\"\"\) ")
  126. // WshShell.run("powershell -noexit [Environment]::SetEnvironmentVariable(\"\"Path\"\", $env:Path + \"\";C:\\tttt\"\", \"\"Machine\"\"\) ")
  127. }
  128. console = {
  129. log : function(m) { WScript.Echo(m)}
  130. , error : function(m) {WScript.Echo(m) }
  131. , dir : function(o) {
  132. for(var i in o){ console.log(i + ' : ' + o[i])}
  133. }
  134. }
  135. // if(!String.prototype.trim) String.prototype.trim = function(){
  136. // return this.replace(/^\s+|\s+$/g, '');
  137. // };
  138. // var ovrrides = {
  139. // resolve : function(v){
  140. // if(v && v.then) return v;
  141. // var p = new Promise(function(resolve, reject){ resolve(v) });
  142. // return p;
  143. // }
  144. // };
  145. // // --------------------------------------------
  146. // // Cscript
  147. var wsh = true;
  148. function isWin(){ return true; }
  149. // If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then
  150. var clii = {
  151. question : function(q, answercb){
  152. WScript.Echo(q)
  153. // console.log('WScript.StdIn : ' + WScript.StdIn.ReadLine() + ' ==== ')
  154. var answer = WScript.StdIn.ReadLine()
  155. answercb(answer)
  156. }
  157. }
  158. var prompter = {
  159. ask : function(q){
  160. // Needs to be serialized. Parallel asks are not possible.
  161. // const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
  162. return new Promise(function(resolve, reject){
  163. clii.question(q, function(answer){
  164. // clii.close();
  165. // console.log("resolve is being called");
  166. resolve(answer)
  167. })
  168. })
  169. }
  170. }
  171. var cli = {
  172. prompt : function(choices, label, defaultchoice){
  173. var options = [];
  174. choices.forEach = forEach
  175. choices.forEach(function(choice){ options.push( ((+choice) + 1) + ' ' + choices[choice] )})
  176. return prompter.ask( label + ' \\n ' + options.join('\n') + '\n default ( <= ' + (defaultchoice || choices[0]) + ' ) : '
  177. ).then( function(choice){
  178. if(!choice) return defaultchoice || choices[0];
  179. if(choice && isNaN(+choice)) return choice;
  180. return choices[(+choice) - 1];
  181. })
  182. }
  183. }
  184. var any = function(iterable, continueOnFailure) {
  185. // var cancelsignal = Symbol()
  186. if(!iterable.reduce) iterable.reduce = reduce
  187. // console.log('iterable.reduce ' + iterable.reduce)
  188. var cancelsignal = "cancelme{mangledrunid}"
  189. return iterable.reduce(
  190. function(p, tasq, i ,a) {
  191. // console.dir(a)
  192. // console.log('Entered')
  193. var handleError = function(err, pVal){
  194. if(err !== cancelsignal) {
  195. // Cancel only once on first failure.
  196. console.warn('Possible failure for task with result : ' )
  197. console.log('Failed : ' + err.message + ' ')
  198. console.dir(pVal)
  199. console.dir(p)
  200. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  201. console.error('Error : ' + err.stack)
  202. console.error(a[i-1])
  203. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  204. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  205. else return pVal;
  206. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  207. }
  208. }
  209. if(Promise.resolve(p) === p ) {
  210. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  211. console.dir(' p.then is ' + p.then)
  212. return p.then( function(pVal){
  213. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  214. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  215. // Failures are known for promises on reject.
  216. // In future if we support direct sync function execution with a result examination for failure
  217. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  218. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  219. // Truthy values are failures if obj has error=true.
  220. if(pVal && pVal.error) handleError(pVal, pVal)
  221. var trycall = function(tasq){
  222. try {
  223. var result = tasq() // PB : TODO -- Handle scope for call
  224. if(tasq.resultHandler) return tasq.resultHandler(result)
  225. // else (Promise.resolve(result) === result ) ? result.start() : null
  226. return result
  227. } catch (error) {
  228. console.error(error);
  229. console.error('Error : ' + error ? error.stack : 'No stack')
  230. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  231. }
  232. }
  233. var handleNext = function(){
  234. // console.log('Task finished with result : ')
  235. // console.dir(pVal)
  236. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  237. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  238. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  239. return (Promise.resolve(tasq) === tasq ) ? tasq /*.start()*/ : trycall(tasq) ;
  240. }
  241. if(Promise.resolve(pVal) === pVal) {
  242. // Passed in function retured a promise. We still need to wait for it.
  243. pVal.then(function(pVal){ return handleNext(); })
  244. }
  245. else return handleNext()
  246. })['catch'](function(error) {
  247. if(error !== cancelsignal) {
  248. console.log('E3 : i = ' + i);
  249. if(error.result) console.error(error.result)
  250. console.error('Error : ' + (error.message || error.messages))
  251. console.error('Error : ' + error.stack)
  252. tasq ? console.log("tasq : " + tasq.toString()) : null;
  253. console.log('debugData 3-------------------------');
  254. // handleError()
  255. throw error
  256. }
  257. else throw cancelsignal;
  258. })
  259. }
  260. else if(!p) {
  261. handleError({ error : true, message : 'Failed without result' }, pVal)
  262. console.log("Bypass remaining on prior failure");
  263. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  264. }
  265. else return p; // A truthy value
  266. }
  267. , Promise.resolve(true)
  268. );
  269. }
  270. // __Promise = ovrrides
  271. function forEach(eachFn){
  272. for(var i=0; i<this.length; i++) eachFn(this[i])
  273. }
  274. function reduce(reducnFn, iv){
  275. var acc = iv
  276. for(var i=0; i<this.length; i++) {acc = reducnFn(acc, this[i], i, this) }
  277. return acc;
  278. }
  279. function map(eachFn){
  280. var mapped = []
  281. for(var i=0; i<this.length; i++) mapped.push(eachFn(this[i]))
  282. return mapped
  283. }
  284. var wait = function(cb, ms) { WScript.Sleep(ms); cb() }
  285. var fso = new ActiveXObject('Scripting.FileSystemObject');
  286. var existsSync = function(filepath){ return fso.FileExists(filepath) }
  287. var fs = {
  288. writeFileSync : function(filepath, text) {
  289. // console.log(filepath)
  290. var fh = fso.CreateTextFile(filepath, true);
  291. fh.WriteLine(text);
  292. fh.Close();
  293. }
  294. , mkdirSync : function(path) {
  295. fso.CreateFolder(path)
  296. }
  297. , readFileSync : function(filepath){
  298. var objFileToRead = fso.OpenTextFile(filepath,1)
  299. var strFileText = objFileToRead.ReadAll()
  300. objFileToRead.Close()
  301. return strFileText
  302. }
  303. , unlinkSync : function(filepath){ fso.DeleteFile(filepath) }
  304. }
  305. var path = {
  306. resolve : function(path){ return fso.GetAbsolutePathName(path) }
  307. , dirname : function(filepath) {
  308. var normalized = this.normalize(filepath)
  309. var li = normalized.lastIndexOf("\\")
  310. if( li > -1) {
  311. return normalized.substring(0, li)
  312. }
  313. }
  314. , normalize : function(path){
  315. return path.replace(/\//g,'\\');
  316. }
  317. }
  318. // Detect or specify install directory.
  319. var selectedinstance = { root : path.resolve(".") }
  320. var existsSyncFolder = function(path){
  321. return fso.FolderExists(path)
  322. }
  323. var shell = new ActiveXObject('shell.application');
  324. promises.forEach = forEach
  325. function startPromises(){
  326. promises.forEach(function(p){
  327. // console.log(p.chain)
  328. p.start();
  329. // promises.splice(0,1)
  330. })
  331. }
  332. function batchshellescape(str) {
  333. return str.replace('=', '^=')
  334. }
  335. function nodeShellExec(command, cargs, options){
  336. // for(var arg=0; arg < cargs.length; arg++) {
  337. // // cargs[arg] = '"' + batchshellescape(cargs[arg]) +'"';
  338. // cargs[arg] = '"' + cargs[arg] +'"';
  339. // }
  340. var elevatedshellexecute = function(cmd, argstr){
  341. shell.ShellExecute(cmd, argstr , "", "", 1);
  342. }
  343. var shellExec = function(cmd, argstr){
  344. var objShell = WScript.createobject("wscript.shell")
  345. // console.log(argstr.join( ' '))
  346. console.log(cmd + ' ' + argstr.join(' '))
  347. var oExec = objShell.Exec(cmd + ' ' + argstr.join(' '))
  348. var result = {}
  349. var shellresult = { shell : objShell, result : result }
  350. var WshRunning = 0
  351. var WshFinished = 1
  352. var WshFailed = 2
  353. while(oExec.Status === WshRunning){
  354. WScript.StdOut.write('s.')
  355. WScript.Sleep(500)
  356. }
  357. var strOutput = '\n'
  358. switch(oExec.Status) {
  359. case WshFinished :
  360. strOutput = oExec.StdOut.ReadAll()
  361. result.success = true;
  362. result.code = 0
  363. break;
  364. case WshFailed :
  365. strOutput = oExec.StdErr.ReadAll()
  366. result.success = false;
  367. result.code = WshFailed
  368. break;
  369. default : strOutput = 'failed'
  370. break;
  371. }
  372. result.result = command + ' ' + cargs + ' exited with code ' + result.code
  373. result.messages = [strOutput]
  374. // console.log(strOutput)
  375. // WScript.Echo(oExec.Status)
  376. // WScript.Echo(oExec.ProcessID)
  377. // WScript.Echo(oExec.ExitCode)
  378. // console.log(objShell.StdOut.ReadAll)
  379. // console.log(objShell.StdErr.ReadAll)
  380. // objShell = WScript.createobject("wscript.shell")
  381. objShell = null;
  382. return shellresult;
  383. }
  384. var p = null;
  385. var pworker = function(resolve, reject){
  386. // console.dir(p)
  387. var pfx = selectedinstance.root + '\\.elxr\\run-' + runtimestamp + '\\' + stampedFilePfx(new Date())
  388. // console.log('p.chain.length ================ ' + p.chain.length)
  389. options = options || {
  390. runFile : path.normalize( pfx + "out.txt")
  391. // runFile : null
  392. }
  393. var runFile = null;
  394. var runFile = options.runFile || pfx + command + cargs + "out.txt";
  395. // console.log(runFile)
  396. var args = cargs.concat()
  397. // runFile ? (args.push(">"), args.push(runFile)) : cargs
  398. // console.log(command + ' ' + args.join(' '))
  399. // command = 'cmd'
  400. // args = ['/c', 'start',
  401. // '/WAIT', selectedinstance.root + '/Downloads' + '/' + 'Git-2.33.0.2-64-bit.exe'
  402. // , '/VERYSILENT'
  403. // // , '/MERGETASKS=!runcode' // This is required only for vscode...
  404. // ]
  405. var runbat = path.normalize(pfx + "run.bat")
  406. // console.log('runbat : ' + runbat)
  407. fs.writeFileSync(runbat,
  408. '@echo off \r\n' +
  409. (options.cwd ? 'cd ' + options.cwd + ' \r\n' : '') +
  410. // ' cmd /k notepad.exe \r\n' +
  411. command + ' ' + args.join(' ') + ' \r\n' +
  412. 'cmd /c echo done >> ' + runFile + ' \r\n' +
  413. 'echo done'
  414. )
  415. // fs.writeFileSync(runFile, 'started')
  416. // WScript.Quit()
  417. // elevatedshellexecute(runFile)
  418. // while(!existsSync(runbat)) { wait(function(){
  419. // console.log('awiting batch : ' + runbat)
  420. // // shellExec( 'start', ['/W', '/b', runbat])
  421. // // shellExec( 'cmd', ['/k', '/b', runbat])
  422. // shellExec( command, args)
  423. // // cmd /b /c
  424. // }, 500) }
  425. console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' ')))
  426. var shellresult = shellExec( 'cmd', [ '/c', runbat])
  427. // var shellresult = shellExec( 'cmd', ['/c', runbat])
  428. // var shellresult = shellExec( command, args)
  429. var wrapup = function(result) {
  430. // console.log('Wrapping up')
  431. try {
  432. // console.log('resolving.....................');
  433. // console.log('--------------P' + result.messages.join(' ').trim() +'P--------------')
  434. // if(result.messages.join().trim()) resolve(result)
  435. // else reject(result)
  436. resolve(result)
  437. }
  438. catch(e){
  439. // console.dir(e)
  440. if(e.message === 'Input past end of file') {
  441. // console.log('---------------------------------------')
  442. // console.dir(result)
  443. resolve(result)
  444. }
  445. else {
  446. // console.dir(e)
  447. reject(e)
  448. }
  449. }
  450. }
  451. // if(runFile){
  452. // var waitr = function(){
  453. // WScript.StdOut.write('w.')
  454. // if(existsSync(runFile)) {
  455. // var strOutput = fs.readFileSync(runFile)
  456. // shellresult.result.messages = [strOutput]
  457. // wrapup(shellresult.result)
  458. // fs.unlinkSync(runFile)
  459. // }
  460. // // console.dir(shellresult.result)
  461. // wait( waitr, 500)
  462. // }
  463. // // console.log(wait)
  464. // wait( waitr, 500)
  465. // }
  466. // else {
  467. // console.log('There is no runfile.')
  468. console.log(shellresult.strOutput)
  469. wrapup(shellresult.result)
  470. // }
  471. }
  472. p = new Promise(pworker)
  473. // promises.push(p)
  474. // // Promise tThens don't get hooked up... we need to postpone promise starting until all the thens are registered...
  475. // wait(function(){
  476. // console.log('p.chain.length' + p.chain.length)
  477. // p.start() } , 5000) // Bind and setTImeout is not supported by JScript
  478. return p;
  479. }
  480. createPromiseClass(/*ovrrides*/)
  481. __main( selectedinstance )
  482. function createPromiseClass(overrides) {
  483. function reject(e){
  484. var p = this;
  485. console.log('Promise Rejection : ' + p.fn)
  486. console.dir(e)
  487. // throw e;f
  488. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Rejection can only be called once')}
  489. var __i = 0;
  490. var __e = e;
  491. do {
  492. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) break;
  493. try {
  494. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  495. __i++;
  496. __e = null;
  497. }
  498. catch(e){ __i++; __e = e}
  499. } while(__e)
  500. do {
  501. try { for(var i = __i; i < p.chain.length; i++, __i = i) if(!p.chain[i].isCatch) { p.result = p.chain[i](p.result); } }
  502. catch(e){
  503. __i ++;
  504. do {
  505. try {
  506. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  507. __i ++;
  508. __e = null;
  509. }
  510. catch(e){ __i++; __e = e}
  511. } while(__e)
  512. }
  513. } while ( __i < p.chain.length )
  514. p.state = PromiseClass.REJECTED;
  515. }
  516. function resolve(result){
  517. var p = this;
  518. // console.log(result + ' resolve was called with chain length ' + p.chain.length )
  519. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Resolve can only be called once')}
  520. p.result = result;
  521. if(PromiseClass.resolve(p.result) === p.result) {
  522. // console.log( 'result is still a promise waiting for result and promisechain' )
  523. waitForResult(p.result, function(r){ p.processchain(r) })
  524. }
  525. else {
  526. // console.log( 'result is value waiting for promisechain' )
  527. // console.dir(result)
  528. return p.processchain(result)
  529. }
  530. };
  531. function processchain(r){
  532. var __i = 0;
  533. var i = __i;
  534. var __e = null;
  535. p = this;
  536. // console.log('processchain chain.length : ' + p.chain.length)
  537. function __processchain(r){
  538. function waitForThen(p){
  539. if(i < p.chain.length) {
  540. if(!p.chain[i].isCatch) {
  541. // console.log('chain idx : ' + i + ' Executing : then ' + p.result + ' ' + p.chain[i])
  542. try {
  543. p.result = p.chain[i](p.result)
  544. if(PromiseClass.resolve(p.result) === p.result) {
  545. // console.log('chain idx : ' + i + ' result is still a promise starting it ')
  546. // console.dir(p.result.chain)
  547. // console.log('p.result.start : ' + p.result.start + ' ------------------ ')
  548. p.result.start()
  549. // console.log(p.result.fn + ' ------------------ ')
  550. waitForResult(p.result, function(r){
  551. // console.log('we waited')
  552. // WScript.write('.')
  553. p.result = r; i++; __i = i;
  554. waitForThen(p)
  555. })
  556. }
  557. else {
  558. i++; __i = i;
  559. waitForThen(p)
  560. }
  561. }
  562. catch(e) {
  563. i++; __i = i;
  564. __e = e;
  565. console.log('failed on index ' + __i + p.chain[__i-1] )
  566. console.dir(e)
  567. waitForCatch(p);
  568. }
  569. }
  570. else {
  571. // console.log(i + ' Skipping catch : ' + p.result + ' ' + p.chain[i])
  572. i++; __i = i;
  573. waitForThen(p)
  574. }
  575. }
  576. else return p.state = PromiseClass.FULFILLED;
  577. }
  578. function waitForCatch(p) {
  579. if(i < p.chain.length) {
  580. if(p.chain[i].isCatch) {
  581. console.log('chain idx : ' + i + ' Executing : catch : ' + p.result + ' ' + p.chain[i])
  582. try {
  583. p.result = p.chain[i](__e);
  584. if(PromiseClass.resolve(p.result) === p.result) {
  585. p.result.start()
  586. waitForResult(p.result, function(r){
  587. p.result = r; i++; __i = i;
  588. })
  589. waitForThen(p)
  590. }
  591. else {
  592. p.result = r; i++; __i = i;
  593. waitForThen(p)
  594. }
  595. }
  596. catch(e){ i++; __i = i;; __e = e; waitForCatch(p) }
  597. }
  598. else {
  599. i++; __i = i;
  600. waitForCatch(p)
  601. }
  602. }
  603. else return p.state = PromiseClass.REJECTED
  604. }
  605. waitForThen(p);
  606. }
  607. __processchain(r)
  608. }
  609. var create = function(fn){
  610. var p = {
  611. then : function(thenfn){
  612. // console.log('Adding then')
  613. thenfn.isThen = true
  614. // if(Object.prototype.toString.call(p.chain) !== '[object Array]') console.dir(p.chain)
  615. p.chain.push(thenfn)
  616. return p;
  617. }
  618. , 'catch' : function(catchfn) {
  619. catchfn.isCatch = true
  620. p.chain.push(catchfn)
  621. return p;
  622. }
  623. , start : function(){
  624. if(this.started) {
  625. console.error('Cannot start more than once...')
  626. return p
  627. };
  628. this.started = true;
  629. this.fn = fn;
  630. try { fn( function(r){
  631. // console.log('calling presolve in starter ')
  632. p.resolve(r) } , function(r){ p.reject(r) } ) }
  633. catch(e){
  634. // console.log('start catch : ' + e)
  635. // console.log('p.chain.length : ' + p.chain.length)
  636. // // console.dir(p)
  637. // console.dir(e)
  638. // console.log(fn)
  639. p.reject(e)
  640. }
  641. return p
  642. }
  643. , state : PromiseClass.PENDING
  644. , chain : []
  645. , reject : reject
  646. , resolve : resolve
  647. , processchain : processchain
  648. }
  649. p.chain.forEach = forEach;
  650. return p;
  651. }
  652. var PromiseClass = function(fn /*, donotstart */){
  653. var p = create(fn)
  654. // if(!donotstart) {
  655. // wait(function(){
  656. // console.log('p.chain.length' + p.chain.length)
  657. // p.start() } , 500) // Bind and setTImeout is not supported by JScript
  658. // }
  659. return p
  660. }
  661. PromiseClass.PENDING = 1
  662. PromiseClass.FULFILLED = 2
  663. PromiseClass.REJECTED = 3
  664. // PromiseClass.STARTED = 4
  665. PromiseClass.isSETTLED = function(p){ p.state === PromiseClass.FULFILLED || p.state === PromiseClass.REJECTED }
  666. PromiseClass.resolve = function(v){
  667. if(v && v.then) return v;
  668. var p = create(function(resolve, reject){
  669. resolve(v)
  670. });
  671. // console.log('p.chain in resolve. length ' + p.chain.length)
  672. // p.result = v;
  673. // wait(function(){ p.processchain(v) }, 0)
  674. return p;
  675. }
  676. function waitForResult(p, cb){
  677. if(!p) return cb(p)
  678. if(p.state !== PromiseClass.PENDING) cb(p.result)
  679. // console.log(p.state + ' Waiting for ..... ' + p.runFile)
  680. if(p.runFile && false) {
  681. while(!existsSync(p.runFile) && p.state === PromiseClass.PENDING) {
  682. console.log('Waiting for ResultFle'); wait(cb, 500)
  683. }
  684. cb(p.result)
  685. }
  686. else {
  687. // while(p.state === PromiseClass.PENDING) {
  688. // console.log('Waiting for Result')
  689. function waiter(){
  690. // console.log(p.result)
  691. if(p.state === PromiseClass.PENDING) wait(waiter, 500);
  692. else return cb(p.result)
  693. }
  694. wait(waiter, 500)
  695. // }
  696. }
  697. }
  698. PromiseClass.all = any; // Serialized...
  699. PromiseClass.__all = function(arr){
  700. arr.forEach = forEach;
  701. var resultPs = [];
  702. var results = [];
  703. console.log('All : ' + arr.length)
  704. var pAll = new PromiseClass(function(resolve, reject){
  705. console.log('All started : ' + pAll)
  706. // console.dir(pAll)
  707. arr.forEach(function(p){
  708. if(!p.then) { var pfn = p;
  709. p = new PromiseClass(function(resolve, reject){
  710. try{
  711. resolve(pfn())
  712. }
  713. catch(e){
  714. reject(e)
  715. }
  716. })
  717. p.start()
  718. }
  719. else {
  720. // !p.start ? p.start = function(){return p} : null
  721. // p.start()
  722. // .then( function(){ waitForResult(p, function(r){ results.push(r) }) })
  723. }
  724. resultPs.push(p)
  725. // waitForResult(p, function(r){ results.push(r) })
  726. })
  727. // PB : TODO -- This is the same as processchain!!!
  728. var allwaitr = function(){
  729. var allResolved = true
  730. console.log('resultPs : ' + resultPs.length)
  731. for(var rIdx =0; rIdx < resultPs.length; rIdx++ ){
  732. if(resultPs[rIdx]) {
  733. allResolved = false
  734. waitForResult(resultPs[rIdx], function(r){
  735. if(Promise.resolve(r) !== r) results[rIdx] = r; resultPs[rIdx] = null;
  736. })
  737. break;
  738. }
  739. }
  740. if(allResolved) {
  741. // console.log('All Reseloved')
  742. // console.dir(results)
  743. resolve(results)
  744. }
  745. else wait(allwaitr, 500)
  746. }
  747. wait(allwaitr, 500)
  748. })
  749. // pAll.chain = arr;
  750. return pAll
  751. }
  752. // PromiseClass.resolve = overrides.resolve;
  753. Promise = PromiseClass;
  754. return PromiseClass;
  755. }
  756. }
  757. function __main( selectedinstance ){
  758. var downloadsdir = selectedinstance.root + '/Downloads';
  759. var callsheltask = function(args) {
  760. // console.log('callsheltask : ' + args)
  761. return function() {
  762. return nodeShellExec.apply(null, args) } }
  763. var gitUser = 'guest';
  764. var gitEmail = 'guest@bbh.org.in';
  765. var BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  766. function getVersion() { return BUILD_VERSION; }
  767. console.log(getVersion())
  768. function ensureDirectoryExistence(filePath) {
  769. var dirname = path.dirname(filePath);
  770. if (existsSyncFolder(dirname)) {
  771. return filePath;
  772. }
  773. ensureDirectoryExistence(dirname);
  774. fs.mkdirSync(dirname);
  775. return filePath;
  776. }
  777. var getTaskCheckExists = function(command, options) {
  778. options = options || {}
  779. return function() {
  780. var runFile = path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date()) + 'where' + command + "out.txt");
  781. var p = nodeShellExec.apply(null, ['cmd', ['/c', 'where', command], { runFile : runFile } ])
  782. p.runFile = runFile;
  783. if (options.ignorefailures) {
  784. return p.then(function(v) {
  785. // WScript.Echo('firstThen ' + v);
  786. return v })['catch']( function(e) {
  787. console.error(e);
  788. // Ignore. Not a major error if where command fails !!!
  789. throw e;
  790. })
  791. }
  792. else return p.then(function() {
  793. // WScript.Echo('firstThen ddd');
  794. return v });
  795. }
  796. }
  797. function verifyAndInstallPrerequisites() {
  798. fs.writeFileSync(ensureDirectoryExistence(downloadsdir + '/readme.txt'), getVersion() + ' Your local downloads for this instance');
  799. var downloadbatch =
  800. "::************************************************************************** \r\n \
  801. :Download_ <url> <File> \r\n \
  802. Powershell.exe ^\r\n \
  803. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^\r\n \
  804. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^\r\n \
  805. (New-Object System.Net.WebClient).DownloadFile('%1','%2') \r\n \
  806. exit /b \r\n \
  807. ::**************************************************************************";
  808. ensureDirectoryExistence(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/readme.txt'))
  809. fs.writeFileSync(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat'), downloadbatch);
  810. var downloadtasks = [];
  811. var installtasks = [];
  812. prerequisites.forEach(function(preq) {
  813. WScript.Echo(all)
  814. if(!all && preq.optional) return
  815. var p = preq.exists().then(function(exists) {
  816. if (exists) console.log( preq.shellcmd + ' exists');
  817. else {
  818. console.log(exists)
  819. console.log(preq.shellcmd + ' is not installed');
  820. return preq.preinstallsteps().then(function(){
  821. // console.log(' task.install : ' + preq.install)
  822. installtasks.push( function(){ return preq.install() } );
  823. })
  824. }
  825. })
  826. // .then(function(res){ console.log( 'preinstallsteps ' + res)});
  827. downloadtasks.push( p )
  828. });
  829. // console.log('downloadtasks')
  830. // console.dir(downloadtasks[0])
  831. var p = Promise.all(downloadtasks).then(function(){
  832. // console.log('calling install tasks : ' + installtasks.length)
  833. return any(installtasks) })
  834. // console.log('Promise.all.chain : ' + p.chain)
  835. return p
  836. }
  837. // var choiceHandler = function(choices, choice) {
  838. // console.log('chosen : ' + choice)
  839. // var decision = choices['d'];
  840. // if (choice && choice === 'd' || !choice) {
  841. // decision = choices['d']
  842. // }
  843. // else if (isNaN((+choice))) {
  844. // decision = choice
  845. // }
  846. // else decision = choices[choice-1]
  847. // if(!decision) throw 'Invalid selection : ' + decision
  848. // return decision
  849. // }
  850. // prereq definition helpers. We can't do proper inheritance in cscript. So fallback to global functions.
  851. function exists(next){
  852. var self = this;
  853. console.log('checking existence of ' + self.shellcmd)
  854. return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
  855. // console.log('-------------exists=======================')
  856. // console.dir(exists)
  857. // console.log(exists + ' ' + self.shellcmd + ' exists')
  858. if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
  859. return true;
  860. }
  861. else return false
  862. })['catch'](function(e){
  863. // console.log('-------------exists catch=======================')
  864. console.dir(e)
  865. return false;
  866. })
  867. }
  868. function unique(arr) {
  869. var hash = {}, result = [];
  870. for ( var i = 0, l = arr.length; i < l; ++i ) {
  871. if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
  872. hash[ arr[i] ] = true;
  873. result.push(arr[i]);
  874. }
  875. }
  876. return result;
  877. }
  878. // var ENV = Object.assign({}, process.env); // Shallow clone it.
  879. // WScript.echo( ENV("Path") )
  880. function sysAddPathVar(path){
  881. return true; // PB : TODO -- Not yet enabled. Remove sys path from path before saving.
  882. // Object.assign({
  883. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  884. // }, options)
  885. // var newpath = ENV("Path").split(';');
  886. // newpath = Array.from(new Set(newpath.push(path))).join(';')
  887. var newpath = [];
  888. newpath.push(path)
  889. newpath = unique(newpath).join(';')
  890. // path.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  891. return any([nodeShellExec('setx', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  892. // , nodeShellExec('set', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  893. ] );
  894. }
  895. var getCmdString = function(args){ return args[0] + ' ' + args[1].join(' ') }
  896. var getgitshelltask = function(args, onEachError) { return function(){
  897. console.log('----------getgitshelltask--------------called')
  898. return nodeShellExec( "cmd", ['/c', getCmdString(args)], args[2])
  899. // .catch( onEachError || function(e){ console.error(e) })
  900. }
  901. }
  902. var prerequisites = [
  903. {
  904. shellcmd: 'git',
  905. url: 'https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe'
  906. , installer: 'Git-2.33.0.2-64-bit.exe'
  907. , installcmd: ['cmd', ['/c', 'start',
  908. '/WAIT', downloadsdir + '/' + 'Git-2.33.0.2-64-bit.exe'
  909. , '/VERYSILENT'
  910. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  911. ]]
  912. , preinstallsteps: function() {
  913. var self = this;
  914. console.log('Git preinstall steps')
  915. var steps = [];
  916. // steps.push(
  917. // function(){
  918. // // console.log('cli prompt steps')
  919. // var choices = { 0 : 'guest', 1 : 'chessdemo' }
  920. // return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  921. // }
  922. // )
  923. // steps.push(
  924. // function(){
  925. // var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  926. // return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  927. // }
  928. // )
  929. steps.push(
  930. function(){
  931. if (!existsSync(downloadsdir + '/' + self.installer)) {
  932. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer])
  933. }
  934. else {
  935. console.log(self.installer + ' Already exits Download skipped.')
  936. return Promise.resolve(true)
  937. }
  938. }
  939. )
  940. return any(steps)
  941. // return any([any(steps), any(prompts)])
  942. }
  943. , installsteps: function () {
  944. var self = this;
  945. console.log('Git Installsteps called')
  946. var ifns = [self.installcmd]
  947. if(!ifns.map) ifns.map = map;
  948. return any(ifns.map(callsheltask))['catch'](function(e){
  949. if(e.code === 1602) {
  950. console.warn("Installation was probably cancelled.")
  951. }
  952. else throw e
  953. })
  954. }
  955. , postinstallsteps: function(){
  956. // PB : TODO -- Detect failure or cancellation before attenpting postinstall steps...
  957. var steps = [];
  958. steps.push(
  959. function(){
  960. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  961. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  962. }
  963. )
  964. steps.push(
  965. function(){
  966. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  967. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  968. }
  969. )
  970. return any(steps).then(function(){
  971. var steps = [
  972. ['git', ['config', '--global', '--add', 'user.name', gitUser]]
  973. , ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
  974. ]
  975. if(!steps.map) steps.map = map;
  976. return any(steps.map(callsheltask)).then(function(){
  977. })
  978. });
  979. }
  980. , install: function () {
  981. var self = this;
  982. console.log('Git Install called')
  983. var createTasq = function(args, shellT, onEachError) {
  984. var tasq = shellT ? shellT(args) : ( function(){
  985. console.log('sdsfdsdf ' + args)
  986. return any([nodeShellExec.apply(null, args)])
  987. // .catch( onEachError || function(e){ console.error(e) } )
  988. })
  989. tasq.toString = function(){ return JSON.stringify(args)}
  990. return tasq;
  991. }
  992. var execserial = function(tasklist, task, shellT, onEachError){
  993. var exec = function(taskArgs){
  994. console.log('execcing ' + task)
  995. var thistask = task.concat();
  996. thistask[1] = thistask[1].concat()
  997. thistask[1].push.apply(thistask[1], taskArgs)
  998. return createTasq(thistask, shellT)
  999. }
  1000. tasklist.map = map
  1001. console.log('execlist ' + tasklist.map(exec))
  1002. return any(tasklist.map(exec))
  1003. }
  1004. function resetgitconfig(){
  1005. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  1006. // Git Credential storage...
  1007. // git config --global credential.helper 'store --file ~/.gitcredentials'
  1008. // git credential-store --file ~/.gitcredentials store
  1009. // // notepad C:/Program Files/Git/etc/gitconfig
  1010. // git config --global --unset credential
  1011. // git config --edit --system
  1012. // git config --global credential.helper "store --file ~/gitcredentials"
  1013. // git credential fill
  1014. // git credential-store --file ~/git.store store
  1015. // Find system git config
  1016. // git config --global --edit
  1017. // git config --list --show-origin
  1018. // git config --list --show-origin --show-scope
  1019. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  1020. // Recipie
  1021. // git config --global --unset credentials.helper
  1022. // cd /path/to/my/repo
  1023. // git config --unset credential.helper
  1024. // git config credential.helper 'store --file ~/.git_repo_credentials'
  1025. // git config credential.*.username my_user_name
  1026. // git config credential.https://gitlab.com.username my_user_name
  1027. // git credential fill
  1028. // git config --global credential.modalprompt false // doesnst work.
  1029. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  1030. var options = {
  1031. inherit: true, shell: true //, env: process.env
  1032. , cwd: selectedinstance.root
  1033. // , runas: processedArgs.runas
  1034. }
  1035. var task = ['git', ['config'], options]
  1036. var tasklist = [
  1037. // ['--global', '--unset credentials.helper']
  1038. // ['--unset', 'credentials.helper']
  1039. // ,
  1040. // ['credential.helper', `'store --file git_repo_credentials'`]
  1041. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  1042. , ['--global', '--replace-all', 'user.name', 'pb']
  1043. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  1044. // , ['--list']
  1045. // , ['credential', 'fill']
  1046. ]
  1047. var onEachError = function(e) { console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n') }
  1048. var shellT = function(args) {
  1049. return getgitshelltask(args, onEachError)
  1050. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  1051. }
  1052. execserial(tasklist, task, shellT, onEachError )
  1053. }
  1054. return any([ /*self.preinstallsteps,*/
  1055. function(){ return self.installsteps() }
  1056. , function() { resetgitconfig() }
  1057. , function(){ return self.postinstallsteps() }
  1058. ])
  1059. }
  1060. , verifyAndInstall : function(){
  1061. var self = this;
  1062. return self.exists().then( function(exits) {
  1063. if(exists) return self.getUser(null, function(){ return self.postinstallsteps() } )
  1064. else return self.install();
  1065. })
  1066. }
  1067. , exists : exists
  1068. , getUser : function(repo, onNoResult){
  1069. onNoResult = onNoResult || function(){return false}
  1070. var globalOrLocal = '--global';
  1071. if(!repo) globalOrLocal = '--global';
  1072. else globalOrLocal = '--local'
  1073. var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]]
  1074. if(!ifns.map) ifns.map = map;
  1075. return any(fns.map(callsheltask)).then(function(result){
  1076. // not yet configured.
  1077. if(!result.success) return onNoResult()
  1078. else {
  1079. var users = result.messages[0].trim().split('\n');
  1080. if(users.length === 0 ||
  1081. users.length === 1 && users[0] === 'guest') {
  1082. return onNoResult()
  1083. }
  1084. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1085. }
  1086. })
  1087. ['catch'](function(e){
  1088. console.log(e)
  1089. return onNoResult()
  1090. })
  1091. }
  1092. }
  1093. ,
  1094. {
  1095. shellcmd: 'node',
  1096. url: 'https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi'
  1097. , installer: 'node-v14.17.3-x64.msi'
  1098. , installcmd: ['MSIEXEC.exe', ['/i'
  1099. , path.normalize(downloadsdir + '/' + 'node-v14.17.3-x64.msi')
  1100. , 'ACCEPT=YES', '/passive']]
  1101. , install : function() {
  1102. var self = this;
  1103. var ifns = [self.installcmd]
  1104. if(!ifns.map) ifns.map = map;
  1105. return any(ifns.map(callsheltask))['catch'](function(e){
  1106. if(e.code === 1602) {
  1107. console.warn("Installation was probably cancelled.")
  1108. }
  1109. else throw e
  1110. })
  1111. }
  1112. , exists : exists
  1113. , preinstallsteps: function() {
  1114. var self = this;
  1115. console.log('Node preinstall steps')
  1116. var steps = [];
  1117. steps.push(
  1118. function(){
  1119. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1120. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1121. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1122. }
  1123. else {
  1124. console.log(self.installer + ' Already exits Download skipped.')
  1125. return Promise.resolve(true)
  1126. }
  1127. }
  1128. )
  1129. return any(steps)
  1130. // return any([any(steps), any(prompts)])
  1131. }
  1132. }
  1133. , {
  1134. shellcmd: 'python'
  1135. , optional : true
  1136. , url: 'https://www.python.org/ftp/python/2.7.18/python-2.7.18.amd64.msi'
  1137. , installer: 'python-2.7.18.amd64.msi'
  1138. , installcmd: ['MSIEXEC.exe', ['/i'
  1139. , path.normalize(downloadsdir + '/' + 'python-2.7.18.amd64.msi')
  1140. , 'ACCEPT=YES', '/passive']]
  1141. , preinstallsteps: function() {
  1142. var self = this;
  1143. console.log(self.shellcmd + ' preinstall steps')
  1144. var steps = [];
  1145. steps.push(
  1146. function(){
  1147. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1148. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  1149. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1150. }
  1151. else {
  1152. console.log(self.installer + ' Already exits Download skipped.')
  1153. return Promise.resolve(true)
  1154. }
  1155. }
  1156. )
  1157. return any(steps)
  1158. // return any([any(steps), any(prompts)])
  1159. }
  1160. , install : function() {
  1161. var self = this;
  1162. var ifns = [self.installcmd]
  1163. if(!ifns.map) ifns.map = map;
  1164. console.log('Installing')
  1165. return any(ifns.map(callsheltask))['catch'](function(e){
  1166. if(e.code === 1602) {
  1167. console.warn("Installation was probably cancelled.")
  1168. }
  1169. else throw e
  1170. }).then(function(){
  1171. return self.postinstallsteps()
  1172. })
  1173. }
  1174. , postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
  1175. , exists : exists
  1176. }
  1177. , {
  1178. shellcmd: 'code'
  1179. , optional : true
  1180. , url: 'https://code.visualstudio.com/sha/download?build=stable&os=win32-x64-user'
  1181. , installer: 'VSCodeUserSetup-x64-1.65.2.exe'
  1182. , installcmd: ['cmd /c', ['start /WAIT ' + downloadsdir + '/' + 'VSCodeUserSetup-x64-1.65.2.exe /VERYSILENT'
  1183. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1184. ]]
  1185. , preinstallsteps: function() {
  1186. var self = this;
  1187. console.log(self.shellcmd + ' preinstall steps')
  1188. var steps = [];
  1189. steps.push(
  1190. function(){
  1191. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1192. console.log(self.url)
  1193. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1194. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1195. }
  1196. else {
  1197. console.log(self.installer + ' Already exits Download skipped.')
  1198. return Promise.resolve(true)
  1199. }
  1200. }
  1201. )
  1202. return any(steps)
  1203. // return any([any(steps), any(prompts)])
  1204. }
  1205. , install : function() {
  1206. var self = this;
  1207. var ifns = [self.installcmd]
  1208. if(!ifns.map) ifns.map = map;
  1209. console.log('Installing')
  1210. return any(ifns.map(callsheltask))['catch'](function(e){
  1211. if(e.code === 1602) {
  1212. console.warn("Installation was probably cancelled.")
  1213. }
  1214. else throw e
  1215. }).then(function(){
  1216. return self.postinstallsteps()
  1217. })
  1218. }
  1219. , postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
  1220. , exists : exists
  1221. }
  1222. , {
  1223. shellcmd: 'mysql',
  1224. url: 'https://dev.mysql.com/get/Downloads/MySQLInstaller/mysql-installer-community-8.0.30.0.msi' //'https://dev.mysql.com/get/Downloads/MySQLInstaller/mysql-installer-community-8.0.29.0.msi'
  1225. , installer: 'mysql-installer-community-8.0.30.0.msi'
  1226. , installcmd: ['MSIEXEC.exe', ['/i'
  1227. , path.normalize(downloadsdir + '/' + 'mysql-installer-community-8.0.30.0.msi')
  1228. //, 'ACCEPT=YES', '/passive'
  1229. ]]
  1230. , install : function() {
  1231. var self = this;
  1232. var ifns = [self.installcmd]
  1233. if(!ifns.map) ifns.map = map;
  1234. return any(ifns.map(callsheltask))['catch'](function(e){
  1235. if(e.code === 1602) {
  1236. console.warn("Installation was probably cancelled.")
  1237. }
  1238. else throw e
  1239. })
  1240. }
  1241. , exists : exists
  1242. , preinstallsteps: function() {
  1243. var self = this;
  1244. console.log('mysql preinstall steps')
  1245. var steps = [];
  1246. steps.push(
  1247. function(){
  1248. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1249. console.log(self.url)
  1250. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  1251. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1252. }
  1253. else {
  1254. console.log(self.installer + ' Already exits Download skipped.')
  1255. return Promise.resolve(true)
  1256. }
  1257. }
  1258. )
  1259. return any(steps)
  1260. // return any([any(steps), any(prompts)])
  1261. }
  1262. }
  1263. , {
  1264. shellcmd: 'elxr'
  1265. , installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
  1266. , preinstallsteps: function() {
  1267. var self = this;
  1268. console.log('Elxr preinstall steps')
  1269. var steps = [];
  1270. steps.push(
  1271. )
  1272. return any([any(steps)])
  1273. }
  1274. , installsteps: function () {
  1275. var self = this;
  1276. console.log('Elxr Installsteps called')
  1277. var installIfNotExists = function(){
  1278. console.log('Elxr PreInstallsteps called')
  1279. var ifns = [ ['git', ['clone', 'http://git.bbh.org.in/chess/elxr'] ] ]
  1280. if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1281. if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1282. // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1283. ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1284. }
  1285. else {
  1286. throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1287. }
  1288. }
  1289. else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1290. if(!ifns.map) ifns.map = map;
  1291. return any(ifns.map(callsheltask))['catch'](function(e){
  1292. if(e.code === 1602) {
  1293. console.warn("Installation was probably cancelled.")
  1294. }
  1295. else throw e
  1296. })
  1297. }
  1298. var ifns = [ self.installcmd ]
  1299. if(!ifns.map) ifns.map = map;
  1300. return installIfNotExists().then(function(){
  1301. return any(ifns.map(callsheltask))['catch'](function(e){
  1302. if(e.code === 1602) {
  1303. console.warn("Installation was probably cancelled.")
  1304. }
  1305. else throw e
  1306. })
  1307. })
  1308. }
  1309. , install: function () {
  1310. var self = this;
  1311. console.log('Elxr Install called')
  1312. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() }
  1313. , nodeShellExec('node', [selectedinstance.root + '\\elxr\\index.js', 'init'])
  1314. // , nodeShellExec('node', [selectedinstance.root + 'elxr\\index.js'])
  1315. ])
  1316. }
  1317. // , exists : function(){
  1318. // console.log('Elxr PreInstallsteps called')
  1319. // var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  1320. // if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1321. // if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1322. // // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1323. // ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1324. // }
  1325. // else {
  1326. // throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1327. // }
  1328. // }
  1329. // else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1330. // if(!ifns.map) ifns.map = map;
  1331. // return any(ifns.map(callsheltask))['catch'](function(e){
  1332. // if(e.code === 1602) {
  1333. // console.warn("Installation was probably cancelled.")
  1334. // }
  1335. // else throw e
  1336. // })
  1337. // }
  1338. , exists : exists
  1339. }
  1340. ]
  1341. if(!prerequisites.forEach) prerequisites.forEach = forEach;
  1342. // nodeShellExec(selectedinstance.root + '/.elxr/run-' + '1629889572461' + '/download.bat'
  1343. // , ['https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.32.0.2-64-bit.exe'
  1344. // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
  1345. promises.push(verifyAndInstallPrerequisites())
  1346. startPromises();
  1347. }