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

i.win.js 55KB

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