cardinal-highlight-diff-spike.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*jshint asi:true */
  2. 'use strict';
  3. var fs = require('fs')
  4. , path = require('path')
  5. , utl = require('../utl')
  6. , highlighter = require('..')
  7. , colors = require('ansicolors')
  8. , diffFile = path.join(__dirname, 'fixtures', 'git-diff.txt')
  9. , diff = fs.readFileSync(diffFile, 'utf-8')
  10. // @@ is not a valid js token, so when we see it, we can be sure that we are dealing with a git or svn diff
  11. var diffRegex = /^@@[^@]+@@$/m;
  12. var diffIndRegex = /^(@@[^@]+@@)(.*)$/;
  13. var addRemRegex = /^[+\-]/;
  14. var lines = diff.split('\n');
  15. function isDiff(lines) {
  16. return !!lines
  17. .filter(function (line) {
  18. return diffRegex.test(line);
  19. })
  20. .length;
  21. }
  22. var diff = isDiff(lines);
  23. function tryHighlight(code) {
  24. // TODO: need to remove symbols added to get valid code
  25. // this should be done by getting the splits instead of the actual code from the highlighter
  26. // now we can remove first / last one after highlighting completed
  27. function tryAppending(appended, tryNext) {
  28. try {
  29. return highlighter.highlight(code + appended);
  30. } catch (e) {
  31. return tryNext(code);
  32. }
  33. }
  34. function tryRemoveLeadingComma(tryNext) {
  35. var success;
  36. try {
  37. success = highlighter.highlight(code.replace(/^( +),(.+)$/, '$1 $2'));
  38. return success;
  39. } catch (e) {
  40. return tryNext(code);
  41. }
  42. }
  43. function tryPlain() {
  44. try {
  45. return highlighter.highlight(code);
  46. } catch (e) {
  47. return tryCloseMustache();
  48. }
  49. }
  50. function tryCloseMustache() { return tryAppending('}', tryCloseParen); }
  51. function tryCloseParen() { return tryAppending('\\)', tryCloseMustacheParen); }
  52. function tryCloseMustacheParen() { return tryAppending('})', tryRemovingCommas);}
  53. function tryRemovingCommas() { return tryRemoveLeadingComma(giveUp); }
  54. function giveUp() { return code; }
  55. return tryPlain();
  56. }
  57. function highlightDiffInd(line, matches) {
  58. var highlighted = colors.brightBlue(matches[1])
  59. , code = matches[2];
  60. return code ? highlighted + tryHighlight(code) : highlighted;
  61. }
  62. function colorsAddRemove(c) {
  63. return addRemRegex.test(c) ? colors.yellow(c) : c;
  64. }
  65. function highlightDiff(line) {
  66. var diffIndMatches = diffIndRegex.exec(line);
  67. return diffIndMatches
  68. ? highlightDiffInd(line, diffIndMatches)
  69. : colorsAddRemove(line[0]) + tryHighlight(line.slice(1));
  70. }
  71. var highlightFn = diff ? highlightDiff : tryHighlight;
  72. var highlightedLines = lines.map(highlightFn);
  73. console.log(highlightedLines.join('\n'));