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 54KB

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