lib/i18n/tasks/scanners/base_scanner.rb in i18n-tasks-0.4.5 vs lib/i18n/tasks/scanners/base_scanner.rb in i18n-tasks-0.5.0

- old
+ new

@@ -8,11 +8,11 @@ include ::I18n::Tasks::Logging attr_reader :config, :key_filter, :record_src_loc def initialize(config = {}) - @config = config.dup.with_indifferent_access.tap do |conf| + @config = config.dup.with_indifferent_access.tap do |conf| conf[:paths] = %w(app/) if conf[:paths].blank? conf[:include] = Array(conf[:include]) if conf[:include].present? if conf.key?(:exclude) conf[:exclude] = Array(conf[:exclude]) else @@ -26,26 +26,27 @@ def key_filter=(value) @key_filter = value @key_filter_pattern = compile_key_pattern(value) if @key_filter end - # @return [Array] found key usages, absolutized and unique + # @return [Array] keys used in source, absolutized and unique def keys - @keys ||= (traverse_files { |path| scan_file(path) }.reduce(:+) || []).uniq(&:key) + @keys ||= (traverse_files { |path| scan_file(path) }.reduce(:+) || []).uniq(&:first) end - def keys_with_src_locations - with_src_locations do + # @return [Array<{key,usages}] + def keys_with_source_locations + recording_source_locations do keys = traverse_files { |path| - ::I18n::Tasks::KeyGroup.new(scan_file(path), src_path: path) + scan_file(path) }.reduce(:+) || [] - keys.group_by(&:key).map { |key, key_loc| - {key: key, usages: key_loc.map { |k| k[:src].merge(path: k[:src_path]) }} + keys.group_by(&:first).map { |key, key_loc| + [key, data: {source_locations: key_loc.map { |(k, attr)| attr[:data] }}] } end end - + def read_file(path) result = nil File.open(path, 'rb') { |f| result = f.read } result end @@ -84,11 +85,11 @@ yield ensure self.key_filter = filter_was end - def with_src_locations + def recording_source_locations was = @record_src_loc @record_src_loc = true yield ensure @record_src_loc = was @@ -98,19 +99,26 @@ def path_fnmatch_any?(path, globs) globs.any? { |glob| File.fnmatch(glob, path) } end - def src_location(text, src_pos) - return nil unless @record_src_loc + def src_location(path, text, src_pos) + src = {path: path} + if @record_src_loc + src.merge!(src_text_location(text, src_pos)) + end + src + end + + def src_text_location(text, src_pos) line_begin = text.rindex(/^/, src_pos - 1) line_end = text.index(/.(?=\n|$)/, src_pos) - {src: { + { pos: src_pos, line_num: text[0..src_pos].count("\n") + 1, line_pos: src_pos - line_begin + 1, line: text[line_begin..line_end] - }} + } end # remove the leading colon and unwrap quotes from the key match def strip_literal(literal) key = literal