detect_translatable_string.coffee 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. module.exports = class DetectTranslatableString
  2. # coffeelint: disable=detect_translatable_string
  3. rule:
  4. name: 'detect_translatable_string'
  5. level: 'ignore'
  6. message: 'The following string looks like it should be marked as translatable via __(...)'
  7. description: '''
  8. '''
  9. constructor: ->
  10. @callTokens = []
  11. tokens: ['STRING', 'CALL_START', 'CALL_END']
  12. lintToken: (token, tokenApi) ->
  13. [type, tokenValue] = token
  14. if type in ['CALL_START', 'CALL_END']
  15. @trackCall token, tokenApi
  16. return
  17. return false if @isInIgnoredMethod()
  18. return @lintString(token, tokenApi)
  19. lintString: (token, tokenApi) ->
  20. [type, tokenValue] = token
  21. # Remove quotes.
  22. string = tokenValue[1..-2]
  23. # Ignore strings with less than two words.
  24. return false if string.split(' ').length < 2
  25. # Ignore strings that are being used as exception; unlike Ruby exceptions, these should not reach the user.
  26. return false if tokenApi.peek(-3)[1] == 'throw'
  27. return false if tokenApi.peek(-2)[1] == 'throw'
  28. return false if tokenApi.peek(-1)[1] == 'throw'
  29. # Ignore strings that are being used for comparison
  30. return false if tokenApi.peek(-1)[1] == '=='
  31. # String interpolation is handled via concatenation, ignore such strings.
  32. return false if tokenApi.peek(1)[1] == '+'
  33. return false if tokenApi.peek(2)[1] == '+'
  34. BLOCKLIST = [
  35. # Only look at strings starting with upper case letters
  36. /^[^A-Z]/,
  37. # # Ignore strings starting with three upper case letters like SELECT, POST etc.
  38. # /^[A-Z]{3}/,
  39. ]
  40. return false if BLOCKLIST.some (entry) ->
  41. #console.log([string, entry, string.match(entry), token, tokenApi.peek(-1), tokenApi.peek(1)])
  42. string.match(entry)
  43. # console.log(tokenApi.peek(-3))
  44. # console.log(tokenApi.peek(-2))
  45. # console.log(tokenApi.peek(-1))
  46. # console.log(token)
  47. return { context: "Found: #{token[1]}" }
  48. ignoredMethods: {
  49. '__': true,
  50. 'log': true,
  51. 'T': true,
  52. 'controllerBind': true,
  53. 'debug': true, # App.Log.debug
  54. 'error': true, # App.Log.error
  55. 'set': true, # App.Config.set
  56. 'translateInline': true,
  57. 'translateContent': true,
  58. 'translatePlain': true,
  59. }
  60. isInIgnoredMethod: ->
  61. #console.log(@callTokens)
  62. for t in @callTokens
  63. return true if t.isIgnoredMethod
  64. return false
  65. trackCall: (token, tokenApi) ->
  66. if token[0] is 'CALL_START'
  67. p = tokenApi.peek(-1)
  68. token.isIgnoredMethod = p and @ignoredMethods[p[1]]
  69. @callTokens.push(token)
  70. else
  71. @callTokens.pop()
  72. return null