cdl.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env node
  2. var cardinal = require('..')
  3. var path = require('path')
  4. var settings = require('../settings')
  5. var args = process.argv
  6. var theme = settings.resolveTheme()
  7. var opts = settings.getSettings()
  8. var highlighted
  9. opts = opts || {}
  10. opts.theme = theme
  11. // jsx is only turned on when highlighting non-json files
  12. opts.jsx = false
  13. function usage() {
  14. var msg = [
  15. 'Usage: cdl <filename.js> [options]'
  16. , ''
  17. , 'Options (~/.cardinalrc overrides):'
  18. , ' --nonum: turn off line printing'
  19. , ''
  20. , 'Unix Pipe Example: cat filename.js | grep console | cdl'
  21. , ''
  22. ].join('\n')
  23. console.log(msg)
  24. }
  25. function highlightFile() {
  26. try {
  27. // Enabling jsx for JSON breaks most likelely due to esprima AST generation
  28. // not working for JSON
  29. opts.jsx = path.extname(args[2]) !== '.json'
  30. highlighted = cardinal.highlightFileSync(args[2], opts)
  31. console.log(highlighted)
  32. } catch (e) {
  33. console.trace()
  34. console.error(e)
  35. }
  36. }
  37. (function runner() {
  38. // E.g., "cardinal myfile.js"
  39. if (args.length === 3) return highlightFile()
  40. var opt = args[3]
  41. // E.g., "cardinal myfile.js --nonum"
  42. if (opt && opt.indexOf('--') === 0) {
  43. if ((/^--(nonum|noline)/i).test(opt)) opts.linenos = false
  44. else {
  45. usage()
  46. return console.error('Unknown option: ', opt)
  47. }
  48. return highlightFile()
  49. }
  50. // UNIX pipes e.g., "cat myfile.js | grep console | cardinal
  51. var stdin = process.stdin
  52. var stdout = process.stdout
  53. // line numbers don't make sense when we are printing line by line
  54. opts.linenos = false
  55. stdin.setEncoding('utf-8')
  56. stdin.resume()
  57. stdin
  58. .on('data', function(chunk) {
  59. chunk.split('\n').forEach(function(line) {
  60. try {
  61. stdout.write(cardinal.highlight(line, opts) + '\n')
  62. } catch (e) {
  63. // line doesn't represent a valid js snippet and therefore cannot be parsed -> just print as is
  64. stdout.write(line + '\n')
  65. }
  66. })
  67. })
  68. })()