cdl 1.7 KB

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