tis-cli前端项目快速搭建命令行工具
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.

430 lines
9.1 KiB

4 years ago
  1. import process from 'node:process';
  2. import readline from 'node:readline';
  3. import chalk from 'chalk';
  4. import cliCursor from 'cli-cursor';
  5. import cliSpinners from 'cli-spinners';
  6. import logSymbols from 'log-symbols';
  7. import stripAnsi from 'strip-ansi';
  8. import wcwidth from 'wcwidth';
  9. import isInteractive from 'is-interactive';
  10. import isUnicodeSupported from 'is-unicode-supported';
  11. import {BufferListStream} from 'bl';
  12. const TEXT = Symbol('text');
  13. const PREFIX_TEXT = Symbol('prefixText');
  14. const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code
  15. // TODO: Use class fields when ESLint 8 is out.
  16. class StdinDiscarder {
  17. constructor() {
  18. this.requests = 0;
  19. this.mutedStream = new BufferListStream();
  20. this.mutedStream.pipe(process.stdout);
  21. const self = this; // eslint-disable-line unicorn/no-this-assignment
  22. this.ourEmit = function (event, data, ...args) {
  23. const {stdin} = process;
  24. if (self.requests > 0 || stdin.emit === self.ourEmit) {
  25. if (event === 'keypress') { // Fixes readline behavior
  26. return;
  27. }
  28. if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
  29. process.emit('SIGINT');
  30. }
  31. Reflect.apply(self.oldEmit, this, [event, data, ...args]);
  32. } else {
  33. Reflect.apply(process.stdin.emit, this, [event, data, ...args]);
  34. }
  35. };
  36. }
  37. start() {
  38. this.requests++;
  39. if (this.requests === 1) {
  40. this.realStart();
  41. }
  42. }
  43. stop() {
  44. if (this.requests <= 0) {
  45. throw new Error('`stop` called more times than `start`');
  46. }
  47. this.requests--;
  48. if (this.requests === 0) {
  49. this.realStop();
  50. }
  51. }
  52. realStart() {
  53. // No known way to make it work reliably on Windows
  54. if (process.platform === 'win32') {
  55. return;
  56. }
  57. this.rl = readline.createInterface({
  58. input: process.stdin,
  59. output: this.mutedStream,
  60. });
  61. this.rl.on('SIGINT', () => {
  62. if (process.listenerCount('SIGINT') === 0) {
  63. process.emit('SIGINT');
  64. } else {
  65. this.rl.close();
  66. process.kill(process.pid, 'SIGINT');
  67. }
  68. });
  69. }
  70. realStop() {
  71. if (process.platform === 'win32') {
  72. return;
  73. }
  74. this.rl.close();
  75. this.rl = undefined;
  76. }
  77. }
  78. let stdinDiscarder;
  79. class Ora {
  80. constructor(options) {
  81. if (!stdinDiscarder) {
  82. stdinDiscarder = new StdinDiscarder();
  83. }
  84. if (typeof options === 'string') {
  85. options = {
  86. text: options,
  87. };
  88. }
  89. this.options = {
  90. text: '',
  91. color: 'cyan',
  92. stream: process.stderr,
  93. discardStdin: true,
  94. ...options,
  95. };
  96. this.spinner = this.options.spinner;
  97. this.color = this.options.color;
  98. this.hideCursor = this.options.hideCursor !== false;
  99. this.interval = this.options.interval || this.spinner.interval || 100;
  100. this.stream = this.options.stream;
  101. this.id = undefined;
  102. this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : isInteractive({stream: this.stream});
  103. this.isSilent = typeof this.options.isSilent === 'boolean' ? this.options.isSilent : false;
  104. // Set *after* `this.stream`
  105. this.text = this.options.text;
  106. this.prefixText = this.options.prefixText;
  107. this.linesToClear = 0;
  108. this.indent = this.options.indent;
  109. this.discardStdin = this.options.discardStdin;
  110. this.isDiscardingStdin = false;
  111. }
  112. get indent() {
  113. return this._indent;
  114. }
  115. set indent(indent = 0) {
  116. if (!(indent >= 0 && Number.isInteger(indent))) {
  117. throw new Error('The `indent` option must be an integer from 0 and up');
  118. }
  119. this._indent = indent;
  120. this.updateLineCount();
  121. }
  122. _updateInterval(interval) {
  123. if (interval !== undefined) {
  124. this.interval = interval;
  125. }
  126. }
  127. get spinner() {
  128. return this._spinner;
  129. }
  130. set spinner(spinner) {
  131. this.frameIndex = 0;
  132. if (typeof spinner === 'object') {
  133. if (spinner.frames === undefined) {
  134. throw new Error('The given spinner must have a `frames` property');
  135. }
  136. this._spinner = spinner;
  137. } else if (!isUnicodeSupported()) {
  138. this._spinner = cliSpinners.line;
  139. } else if (spinner === undefined) {
  140. // Set default spinner
  141. this._spinner = cliSpinners.dots;
  142. } else if (spinner !== 'default' && cliSpinners[spinner]) {
  143. this._spinner = cliSpinners[spinner];
  144. } else {
  145. throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);
  146. }
  147. this._updateInterval(this._spinner.interval);
  148. }
  149. get text() {
  150. return this[TEXT];
  151. }
  152. set text(value) {
  153. this[TEXT] = value;
  154. this.updateLineCount();
  155. }
  156. get prefixText() {
  157. return this[PREFIX_TEXT];
  158. }
  159. set prefixText(value) {
  160. this[PREFIX_TEXT] = value;
  161. this.updateLineCount();
  162. }
  163. get isSpinning() {
  164. return this.id !== undefined;
  165. }
  166. getFullPrefixText(prefixText = this[PREFIX_TEXT], postfix = ' ') {
  167. if (typeof prefixText === 'string') {
  168. return prefixText + postfix;
  169. }
  170. if (typeof prefixText === 'function') {
  171. return prefixText() + postfix;
  172. }
  173. return '';
  174. }
  175. updateLineCount() {
  176. const columns = this.stream.columns || 80;
  177. const fullPrefixText = this.getFullPrefixText(this.prefixText, '-');
  178. this.lineCount = 0;
  179. for (const line of stripAnsi(' '.repeat(this.indent) + fullPrefixText + '--' + this[TEXT]).split('\n')) {
  180. this.lineCount += Math.max(1, Math.ceil(wcwidth(line) / columns));
  181. }
  182. }
  183. get isEnabled() {
  184. return this._isEnabled && !this.isSilent;
  185. }
  186. set isEnabled(value) {
  187. if (typeof value !== 'boolean') {
  188. throw new TypeError('The `isEnabled` option must be a boolean');
  189. }
  190. this._isEnabled = value;
  191. }
  192. get isSilent() {
  193. return this._isSilent;
  194. }
  195. set isSilent(value) {
  196. if (typeof value !== 'boolean') {
  197. throw new TypeError('The `isSilent` option must be a boolean');
  198. }
  199. this._isSilent = value;
  200. }
  201. frame() {
  202. const {frames} = this.spinner;
  203. let frame = frames[this.frameIndex];
  204. if (this.color) {
  205. frame = chalk[this.color](frame);
  206. }
  207. this.frameIndex = ++this.frameIndex % frames.length;
  208. const fullPrefixText = (typeof this.prefixText === 'string' && this.prefixText !== '') ? this.prefixText + ' ' : '';
  209. const fullText = typeof this.text === 'string' ? ' ' + this.text : '';
  210. return fullPrefixText + frame + fullText;
  211. }
  212. clear() {
  213. if (!this.isEnabled || !this.stream.isTTY) {
  214. return this;
  215. }
  216. this.stream.cursorTo(0);
  217. for (let index = 0; index < this.linesToClear; index++) {
  218. if (index > 0) {
  219. this.stream.moveCursor(0, -1);
  220. }
  221. this.stream.clearLine(1);
  222. }
  223. if (this.indent || this.lastIndent !== this.indent) {
  224. this.stream.cursorTo(this.indent);
  225. }
  226. this.lastIndent = this.indent;
  227. this.linesToClear = 0;
  228. return this;
  229. }
  230. render() {
  231. if (this.isSilent) {
  232. return this;
  233. }
  234. this.clear();
  235. this.stream.write(this.frame());
  236. this.linesToClear = this.lineCount;
  237. return this;
  238. }
  239. start(text) {
  240. if (text) {
  241. this.text = text;
  242. }
  243. if (this.isSilent) {
  244. return this;
  245. }
  246. if (!this.isEnabled) {
  247. if (this.text) {
  248. this.stream.write(`- ${this.text}\n`);
  249. }
  250. return this;
  251. }
  252. if (this.isSpinning) {
  253. return this;
  254. }
  255. if (this.hideCursor) {
  256. cliCursor.hide(this.stream);
  257. }
  258. if (this.discardStdin && process.stdin.isTTY) {
  259. this.isDiscardingStdin = true;
  260. stdinDiscarder.start();
  261. }
  262. this.render();
  263. this.id = setInterval(this.render.bind(this), this.interval);
  264. return this;
  265. }
  266. stop() {
  267. if (!this.isEnabled) {
  268. return this;
  269. }
  270. clearInterval(this.id);
  271. this.id = undefined;
  272. this.frameIndex = 0;
  273. this.clear();
  274. if (this.hideCursor) {
  275. cliCursor.show(this.stream);
  276. }
  277. if (this.discardStdin && process.stdin.isTTY && this.isDiscardingStdin) {
  278. stdinDiscarder.stop();
  279. this.isDiscardingStdin = false;
  280. }
  281. return this;
  282. }
  283. succeed(text) {
  284. return this.stopAndPersist({symbol: logSymbols.success, text});
  285. }
  286. fail(text) {
  287. return this.stopAndPersist({symbol: logSymbols.error, text});
  288. }
  289. warn(text) {
  290. return this.stopAndPersist({symbol: logSymbols.warning, text});
  291. }
  292. info(text) {
  293. return this.stopAndPersist({symbol: logSymbols.info, text});
  294. }
  295. stopAndPersist(options = {}) {
  296. if (this.isSilent) {
  297. return this;
  298. }
  299. const prefixText = options.prefixText || this.prefixText;
  300. const text = options.text || this.text;
  301. const fullText = (typeof text === 'string') ? ' ' + text : '';
  302. this.stop();
  303. this.stream.write(`${this.getFullPrefixText(prefixText, ' ')}${options.symbol || ' '}${fullText}\n`);
  304. return this;
  305. }
  306. }
  307. export default function ora(options) {
  308. return new Ora(options);
  309. }
  310. export async function oraPromise(action, options) {
  311. const actionIsFunction = typeof action === 'function';
  312. // eslint-disable-next-line promise/prefer-await-to-then
  313. const actionIsPromise = typeof action.then === 'function';
  314. if (!actionIsFunction && !actionIsPromise) {
  315. throw new TypeError('Parameter `action` must be a Function or a Promise');
  316. }
  317. const {successText, failText} = typeof options === 'object'
  318. ? options
  319. : {successText: undefined, failText: undefined};
  320. const spinner = ora(options).start();
  321. try {
  322. const promise = actionIsFunction ? action(spinner) : action;
  323. const result = await promise;
  324. spinner.succeed(
  325. successText === undefined
  326. ? undefined
  327. : (typeof successText === 'string' ? successText : successText(result)),
  328. );
  329. return result;
  330. } catch (error) {
  331. spinner.fail(
  332. failText === undefined
  333. ? undefined
  334. : (typeof failText === 'string' ? failText : failText(error)),
  335. );
  336. throw error;
  337. }
  338. }