You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

i.win.js 57KB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  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: 'sqlexpress',
  1206. url: 'https://go.microsoft.com/fwlink/?linkid=866658'
  1207. , installer: 'SQL2019-SSEI-Expr.exe'
  1208. , installcmd: ['cmd', ['/c', 'start',
  1209. '/WAIT', downloadsdir + '/' + 'SQL2019-SSEI-Expr.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('Node preinstall steps')
  1218. var steps = [];
  1219. steps.push(
  1220. function(){
  1221. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1222. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1223. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1224. }
  1225. else {
  1226. console.log(self.installer + ' Already exits Download skipped.')
  1227. return Promise.resolve(true)
  1228. }
  1229. }
  1230. )
  1231. return any(steps)
  1232. // return any([any(steps), any(prompts)])
  1233. }
  1234. }
  1235. , {
  1236. shellcmd: 'Ssms2019.exe',
  1237. url: 'https://aka.ms/ssmsfullsetup'
  1238. , installer: 'SSMS-Setup-ENU.exe'
  1239. , installcmd: ['cmd', ['/c', 'start',
  1240. '/WAIT', downloadsdir + '/' + 'SSMS-Setup-ENU.exe'
  1241. , '/Quiet'
  1242. //, 'SSMSInstallRoot=%systemdrive%\\Program Files (x86)\\Microsoft SQL Server\\140\\Tools\\Binn\\ManagementStudio'
  1243. ]]
  1244. , install : install
  1245. , exists : exists
  1246. , preinstallsteps: function() {
  1247. var self = this;
  1248. console.log('smss 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: 'Ssms.exe',
  1269. url: 'https://go.microsoft.com/fwlink/?linkid=2043154&clcid=0x409'
  1270. , installer: 'SSMS-Setup-ENU.exe'
  1271. , installcmd: ['cmd', ['/c', 'start',
  1272. '/WAIT', downloadsdir + '/' + 'SSMS-Setup-ENU.exe'
  1273. , '/Quiet'
  1274. //, 'SSMSInstallRoot=%systemdrive%\\Program Files (x86)\\Microsoft SQL Server\\140\\Tools\\Binn\\ManagementStudio'
  1275. ]]
  1276. , install : install
  1277. , exists : exists
  1278. , preinstallsteps: function() {
  1279. var self = this;
  1280. console.log('smss preinstall steps')
  1281. var steps = [];
  1282. steps.push(
  1283. function(){
  1284. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1285. console.log(self.url)
  1286. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', ['"' + self.url + '"', downloadsdir + '/' + self.installer]
  1287. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1288. }
  1289. else {
  1290. console.log(self.installer + ' Already exits Download skipped.')
  1291. return Promise.resolve(true)
  1292. }
  1293. }
  1294. )
  1295. return any(steps)
  1296. // return any([any(steps), any(prompts)])
  1297. }
  1298. }
  1299. , {
  1300. shellcmd: 'mysql',
  1301. 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'
  1302. , installer: 'mysql-installer-community-8.0.30.0.msi'
  1303. , installcmd: ['MSIEXEC.exe', ['/i'
  1304. , path.normalize(downloadsdir + '/' + 'mysql-installer-community-8.0.30.0.msi')
  1305. //, 'ACCEPT=YES', '/passive'
  1306. ]]
  1307. , install : install
  1308. , exists : exists
  1309. , preinstallsteps: function() {
  1310. var self = this;
  1311. console.log('mysql preinstall steps')
  1312. var steps = [];
  1313. steps.push(
  1314. function(){
  1315. if (!existsSync(downloadsdir + '/' + self.installer)) {
  1316. console.log(self.url)
  1317. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  1318. , { waitmsg : 'downloading '+ self.shellcmd +' please wait' })
  1319. }
  1320. else {
  1321. console.log(self.installer + ' Already exits Download skipped.')
  1322. return Promise.resolve(true)
  1323. }
  1324. }
  1325. )
  1326. return any(steps)
  1327. // return any([any(steps), any(prompts)])
  1328. }
  1329. }
  1330. , {
  1331. shellcmd: 'elxr'
  1332. , forceinstall : true
  1333. , installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
  1334. , preinstallsteps: function() {
  1335. var self = this;
  1336. console.log('Elxr preinstall steps')
  1337. var steps = [];
  1338. steps.push(
  1339. )
  1340. return any([any(steps)])
  1341. }
  1342. , installsteps: function () {
  1343. var self = this;
  1344. console.log('Elxr Installsteps called')
  1345. var installIfNotExists = function(){
  1346. console.log('Elxr PreInstallsteps called')
  1347. var steps = [];
  1348. var chessRepo = 'https://git.bbh.org.in'
  1349. steps.push(
  1350. function(){
  1351. // console.log('cli prompt steps')
  1352. var choices = { 0 : 'http://git.bbh', 1 : 'https://git.bbh.org.in' }
  1353. return cli.prompt(choices, 'git repository : ', chessRepo).then(function(choice){ chessRepo = choice } )
  1354. }
  1355. )
  1356. return any(steps).then(function(chessRepo){
  1357. var ifns = [
  1358. ['git', ['clone', chessRepo + '/chess/elxr'] ]
  1359. ]
  1360. if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1361. if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1362. // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1363. ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1364. }
  1365. else {
  1366. throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1367. }
  1368. }
  1369. else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1370. ifns.push(['npm', ['i'], { cwd : '.\\elxr' } ])
  1371. if(!ifns.map) ifns.map = map;
  1372. return any(ifns.map(callsheltask))['catch'](function(e){
  1373. if(e.code === 1602) {
  1374. console.warn("Installation was probably cancelled.")
  1375. }
  1376. else throw e
  1377. })
  1378. })
  1379. }
  1380. var ifns = [ self.installcmd ]
  1381. if(!ifns.map) ifns.map = map;
  1382. return installIfNotExists().then(function(){
  1383. return any(ifns.map(callsheltask))['catch'](function(e){
  1384. if(e.code === 1602) {
  1385. console.warn("Installation was probably cancelled.")
  1386. }
  1387. else throw e
  1388. })
  1389. })
  1390. }
  1391. , install: function () {
  1392. var self = this;
  1393. console.log('Elxr Install called')
  1394. return any([ self.preinstallsteps, function(){ return self.installsteps() }
  1395. , nodeShellExec('start', ['""', '"C:\\Program Files\\Git\\bin\\sh.exe"', '-c', '"node ' + (selectedinstance.root + '\\elxr\\index.js').replace(/\\/g, '/') + ' i elixir"'])
  1396. // , nodeShellExec('node', [selectedinstance.root + 'elxr\\index.js'])
  1397. ])
  1398. }
  1399. // , exists : function(){
  1400. // console.log('Elxr PreInstallsteps called')
  1401. // var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  1402. // if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1403. // if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1404. // // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1405. // ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1406. // }
  1407. // else {
  1408. // throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1409. // }
  1410. // }
  1411. // else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1412. // if(!ifns.map) ifns.map = map;
  1413. // return any(ifns.map(callsheltask))['catch'](function(e){
  1414. // if(e.code === 1602) {
  1415. // console.warn("Installation was probably cancelled.")
  1416. // }
  1417. // else throw e
  1418. // })
  1419. // }
  1420. , exists : exists
  1421. }
  1422. ]
  1423. if(!prerequisites.forEach) prerequisites.forEach = forEach;
  1424. // nodeShellExec(selectedinstance.root + '/.elxr/run-' + '1629889572461' + '/download.bat'
  1425. // , ['https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.32.0.2-64-bit.exe'
  1426. // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
  1427. promises.push(verifyAndInstallPrerequisites())
  1428. startPromises();
  1429. }