redeyed-function-config-skipping-tokens.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict'
  2. var test = require('tape')
  3. var redeyed = require('..')
  4. test('given i skip 2 more tokens after each semicolon', function(t) {
  5. var calls = 0
  6. var opts = {
  7. Punctuator: {
  8. ';': function identity(s, info) {
  9. // tell it to skip past second to last token that is 2 ahead of the current one
  10. calls++
  11. var skipToken = info.tokens[info.tokenIndex + 2]
  12. return skipToken ? { replacement: s, skipPastToken: skipToken } : s
  13. }
  14. }
  15. }
  16. ;[ { code: ';;;', expectedCalls: 1 }
  17. , { code: ';;;;', expectedCalls: 2 }
  18. , { code: '; ; ; ;', expectedCalls: 2 }
  19. , { code: ';;; ;;; ;;; ;', expectedCalls: 4 }
  20. , { code: ';;; ;;; ;;; ;;; ;', expectedCalls: 5 }
  21. , { code: ';;; ;;; ;;; ;;; ;;;', expectedCalls: 5 }
  22. , { code: ';;; ;;; ;;; ;;; ;;; ;', expectedCalls: 6 }
  23. ].forEach(function(x) {
  24. calls = 0
  25. redeyed(x.code, opts)
  26. t.equals(calls, x.expectedCalls, 'calls ' + x.expectedCalls + ' times for ' + x.code)
  27. })
  28. t.end()
  29. })
  30. test('replace log', function(t) {
  31. var opts = {
  32. Identifier: {
  33. console: function replaceLog(s, info) {
  34. var code = info.code
  35. var idx = info.tokenIndex
  36. var tokens = info.tokens
  37. var kind = tokens[idx + 2].value
  38. var firstArgTkn = tokens[idx + 4]
  39. var argIdx = idx + 3
  40. var open
  41. var tkn
  42. open = 1
  43. while (open) {
  44. tkn = tokens[++argIdx]
  45. if (tkn.value === '(') open++
  46. if (tkn.value === ')') open--
  47. }
  48. var argsIncludingClosingParen = code.slice(firstArgTkn.range[0], tkn.range[1])
  49. var result = 'log.' + kind + '("main-logger", ' + argsIncludingClosingParen
  50. return { replacement: result, skipPastToken: tkn }
  51. }
  52. }
  53. }
  54. var origCode = [
  55. 'console.info("info ", 1);'
  56. , 'console.warn("warn ", 3);'
  57. , 'console.error("error ", new Error("oh my!"));'
  58. ].join('\n')
  59. var expectedCode = [
  60. 'log.info("main-logger", "info ", 1));'
  61. , 'log.warn("main-logger", "warn ", 3));'
  62. , 'log.error("main-logger", "error ", new Error("oh my!")));'
  63. ].join('\n')
  64. var code = redeyed(origCode, opts).code
  65. t.equals(code, expectedCode, 'transforms all log statements')
  66. t.end()
  67. })