cli.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. "use strict";
  2. var __importStar = (this && this.__importStar) || function (mod) {
  3. if (mod && mod.__esModule) return mod;
  4. var result = {};
  5. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  6. result["default"] = mod;
  7. return result;
  8. };
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. var fs = __importStar(require("mz/fs"));
  11. var path = __importStar(require("path"));
  12. var yargs = require("yargs");
  13. var index_1 = require("./index");
  14. var theme_1 = require("./theme");
  15. yargs
  16. .option('theme', {
  17. alias: 't',
  18. nargs: 1,
  19. description: 'Use a theme defined in a JSON file',
  20. })
  21. .usage(['', 'Usage: highlight [options] [file]', '', 'Outputs a file or STDIN input with syntax highlighting'].join('\n'))
  22. .option('language', {
  23. alias: 'l',
  24. nargs: 1,
  25. description: 'Set the langugage explicitely\nIf omitted will try to auto-detect',
  26. })
  27. .version()
  28. .help('help')
  29. .alias('help', 'h')
  30. .alias('version', 'v');
  31. var argv = yargs.argv;
  32. var file = argv._[0];
  33. var codePromise;
  34. if (!file && !process.stdin.isTTY) {
  35. // Input from STDIN
  36. process.stdin.setEncoding('utf8');
  37. var code_1 = '';
  38. process.stdin.on('readable', function () {
  39. var chunk = process.stdin.read();
  40. if (chunk !== null) {
  41. code_1 += chunk;
  42. }
  43. });
  44. codePromise = new Promise(function (resolve) {
  45. process.stdin.on('end', function () {
  46. var chunk = process.stdin.read();
  47. if (chunk !== null) {
  48. code_1 += chunk;
  49. }
  50. resolve(code_1);
  51. });
  52. });
  53. }
  54. else if (file) {
  55. // Read file
  56. codePromise = fs.readFile(file, 'utf-8');
  57. }
  58. else {
  59. yargs.showHelp();
  60. process.exit(1);
  61. throw new Error();
  62. }
  63. Promise.all([codePromise, argv.theme ? fs.readFile(argv.theme, 'utf8') : undefined])
  64. .then(function (_a) {
  65. var code = _a[0], theme = _a[1];
  66. var options = {
  67. ignoreIllegals: true,
  68. theme: (theme && theme_1.parse(theme)) || undefined,
  69. };
  70. if (file) {
  71. var ext = path.extname(file).substr(1);
  72. if (ext && index_1.supportsLanguage(ext)) {
  73. options.language = ext;
  74. }
  75. }
  76. options.language = argv.language;
  77. return new Promise(function (resolve, reject) {
  78. return process.stdout.write(index_1.highlight(code, options), function (err) { return (err ? reject(err) : resolve()); });
  79. });
  80. })
  81. .then(function () {
  82. process.exit(0);
  83. })
  84. .catch(function (err) {
  85. console.error(err);
  86. process.exit(1);
  87. });
  88. //# sourceMappingURL=cli.js.map