Skip to content

Instantly share code, notes, and snippets.

@zealot128
Created September 24, 2019 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zealot128/e6ec1767a40a6c3d85d7f171f4d88293 to your computer and use it in GitHub Desktop.
Save zealot128/e6ec1767a40a6c3d85d7f171f4d88293 to your computer and use it in GitHub Desktop.
Vue-i18n + ruby i18n-tasks unused scanner
require 'i18n/tasks/scanners/file_scanner'
# finds v-t="" and $t/$tc usages and prefixed that usages with the given prefix, e.g.
# so i18n-tasks unused / i18n-tasks missing will work and scan vue files correctly
# LIMITATIONS:
# - no advanced v-t="{ ... }" syntax supported
# - of course, no dynamic loading of $t(some_data_property) does not work
class VueI18nScanner < I18n::Tasks::Scanners::FileScanner
include I18n::Tasks::Scanners::OccurrenceFromPosition
KEY_IN_QUOTES = /(?<in>["'])(?<key>[\w\.]+)(?<in>["'])/.freeze
WRAPPED_KEY_IN_QUOTES = /(?<out>["'])#{KEY_IN_QUOTES}(?<out>["'])/.freeze
# @return [Array<[absolute key, Results::Occurrence]>]
def scan_file(path)
text = read_file(path)
# single file component translation used
return [] if text.include?('<i18n')
out = []
# v-t="'key'" v-t='"key"'
text.to_enum(:scan, /v-t=#{WRAPPED_KEY_IN_QUOTES}/).each do |_|
key = Regexp.last_match[:key]
occurrence = occurrence_from_position(
path, text, Regexp.last_match.offset(:key).first
)
out << [key, occurrence]
end
text.to_enum(:scan, /\$tc?\(#{KEY_IN_QUOTES}/).each do |_|
key = Regexp.last_match[:key]
occurrence = occurrence_from_position(
path, text, Regexp.last_match.offset(:key).first
)
out << [key, occurrence]
end
out
end
end
I18n::Tasks.add_scanner 'VueI18nScanner', only: %w(*.vue *.js)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment