您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

cliverse.js 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // cliverse.js
  2. const util = require('util')
  3. const { spawn, spawnSync } = require('child_process');
  4. const fs = require('fs')
  5. function nodeShellExec() {
  6. var args = Array.from(arguments);
  7. if(args.length > 1){
  8. var opts = args[2] = args[2] || {}
  9. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  10. }
  11. else {
  12. var opts = {
  13. title : `${args[0]}`
  14. // , inherit: true, shell: true
  15. }
  16. }
  17. opts.stdin = 'pipe';
  18. // // const spawn = require('child_process').spawn;
  19. // const s = spawn(
  20. // 'C:\\Program Files\\Git\\bin\\sh.exe'
  21. // , ['notepad', 'index'], { cwd: __dirname });
  22. // var interval = null;
  23. // var t = setTimeout(function(){
  24. // interval = setInterval(function(){
  25. // console.log('Awaiting close : ' + child.spawnargs)
  26. // }, 1500)
  27. // // console.log('Awaiting close : ' + child.spawnargs)
  28. // }, 0)
  29. // child.on('close', (code) => {
  30. // console.error('Prematurely closed even before promise...')
  31. // })
  32. // D:\chess\instances\elixir_01\elxr/.elxr/run-1630002739610/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  33. // D:\\chess\\instances\\elixir_01\\elxr/.elxr/run-1630002923584/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  34. // console.dir(args[2])
  35. console.log('nodeshellexec ::: ')
  36. console.log(`${args[0]} ${args[1].join(' ') } ${args[args.length-1].cwd}`)
  37. const child = spawn(...args);
  38. var p = new Promise(function(resolve, reject){
  39. // console.log(...args)
  40. if(!opts.detached) {
  41. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  42. var success = true;
  43. if(opts.stdio !== 'ignore') {
  44. child.stdout.setEncoding('utf8');
  45. child.stderr.setEncoding('utf8');
  46. child.stdout.on('data', (chunk) => {
  47. chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */
  48. process.stdout.write( chunk )
  49. });
  50. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */
  51. console.error('Error exit not handled.')
  52. console.error(util.inspect(chunk))
  53. });
  54. child.stderr.on('data', (chunk) => {
  55. if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
  56. messages.push(chunk);
  57. // process.stdout.write( chunk )
  58. // console.error('stderr e: ' + chunk)
  59. });
  60. }
  61. child.on('close', (code) => {
  62. // console.log('Proper close was fired')
  63. var logEntry = { code, success }
  64. if(+code !== 0 || opts.haserrors) {
  65. success = false; logEntry = { messages, result: `${opts.title} exited with code ${code}`, success, code }
  66. };
  67. if(opts.stdio !== 'ignore') {
  68. logEntry = { result: `${opts.title} exited with code ${code}`, messages, code }
  69. logEntry.success = success;
  70. if(opts.evaluateResult) logEntry = opts.evaluateResult(success, logEntry);
  71. if(opts.runas){
  72. // success ? logEntry.success = true : null;
  73. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  74. }
  75. else {
  76. // console.log( messages.join('') )
  77. // process.stdout.write( JSON.stringify(logEntry) )
  78. }
  79. }
  80. else if(opts.evaluateResult) {
  81. try { logEntry = opts.evaluateResult(false, logEntry); }
  82. catch(e){ reject(e) }
  83. }
  84. // clearInterval(interval)
  85. if(code !== 0 || opts.haserrors) {
  86. args[2].benign || args[2].ignorefailures ? (logEntry.benign = true, logEntry.ignorefailures = true) : null
  87. return reject(logEntry)
  88. }
  89. resolve(logEntry)
  90. });
  91. }
  92. else {
  93. child.unref()
  94. // clearInterval(interval)
  95. resolve(true);
  96. }
  97. });
  98. p.process = child;
  99. return p;
  100. }
  101. console.log('----------------------')
  102. // console.dir(c)
  103. console.log('----------------------')
  104. // process.exit()
  105. var prompt = function(choices, label, defaultchoice, selectedchoice){
  106. // prompt accepts either an array or an object as choices.
  107. var choices = choices || [];
  108. defaultchoice = defaultchoice || choices[0] || selectedchoice || choices[Object.keys(choices)[0]]
  109. var ci = 0;
  110. return this.prompter.ask(
  111. `${label} \n` + Object.keys(choices).map(
  112. choice => {
  113. ++ci; var choice_label = isNaN(+choice) ? `${ci}) (${choice})` : ci + ')';
  114. return ` ${choice_label} ${choices[choice]} `
  115. }).join('\n')
  116. + `\n d) default ( <= ${ defaultchoice || choices[0]} ) : `
  117. + `\n selected ( <= ${ selectedchoice || defaultchoice || choices[0]} ) : `
  118. ).then(choice => {
  119. // propName = promptable.interpret(propValue)
  120. if(!choice && selectedchoice) return selectedchoice;
  121. if(!choice) return defaultchoice || choices[0];
  122. if(choice && isNaN(+choice)) {
  123. if(choice === 'd') return defaultchoice || choices[0];
  124. try {
  125. return JSON.parse(choice);
  126. }
  127. catch(e) {
  128. // console.error(e)
  129. return choice // Treat it as a string if it is not parsable
  130. }
  131. }
  132. return choices[(+choice) - 1];
  133. })
  134. }
  135. const readline = require("readline");
  136. var cli = {
  137. nodeShellExec
  138. , get prompter() {
  139. var prompt_interface = {
  140. ask : function(q){
  141. // Needs to be serialized. Parallel asks are not possible.
  142. const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
  143. return new Promise((resolve, reject)=>{
  144. clii.question(q, (answer)=>{
  145. console.log(answer)
  146. try {
  147. clii.close();
  148. console.log("readline.createInterface closed");
  149. resolve(answer)
  150. }
  151. catch(e) {
  152. reject(e)
  153. }
  154. })
  155. })
  156. }
  157. }
  158. return prompt_interface
  159. }
  160. , prompt
  161. , createTask(task, str){
  162. var tasks = {
  163. getTaskCheckExists : (str)=>{
  164. return (command, options) => {
  165. options = options || {}
  166. return () => {
  167. var p = nodeShellExec.apply(null, [str, [command]])
  168. if (options.ignorefailures) {
  169. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  170. return false;
  171. })
  172. }
  173. else return p.then(() => { return true });
  174. }
  175. }
  176. }
  177. }
  178. return tasks[task](str)
  179. }
  180. }
  181. module.exports = cli