cli.js 2.3 KB

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