-
Notifications
You must be signed in to change notification settings - Fork 266
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
PrismParser: Contextual parsing for Rails
- Loading branch information
1 parent
9852a3f
commit ac7c37e
Showing
8 changed files
with
1,331 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
# frozen_string_literal: true | ||
|
||
require_relative 'file_scanner' | ||
require_relative 'ruby_ast_scanner' | ||
|
||
module I18n::Tasks::Scanners | ||
class PrismScanner < FileScanner | ||
def initialize(**args) | ||
unless RAILS_VISITOR || RUBY_VISITOR | ||
warn( | ||
'Please make sure `prism` is available to use this feature. Fallback to Ruby AST Scanner.' | ||
) | ||
end | ||
|
||
@visitor_class = | ||
args.dig(:config, :rails_visitor) ? RAILS_VISITOR : RUBY_VISITOR | ||
|
||
@fallback = RubyAstScanner.new(**args) | ||
super | ||
end | ||
|
||
protected | ||
|
||
# Extract all occurrences of translate calls from the file at the given path. | ||
# | ||
# @return [Array<[key, Results::KeyOccurrence]>] each occurrence found in the file | ||
def scan_file(path) | ||
return @fallback.send(:scan_file, path) if @visitor_class.nil? | ||
|
||
process_prism_parse_result( | ||
path, | ||
PARSER.parse_file(path).value, | ||
PARSER.parse_file_comments(path) | ||
) | ||
rescue Exception => e # rubocop:disable Lint/RescueException | ||
raise( | ||
::I18n::Tasks::CommandError.new( | ||
e, | ||
"Error scanning #{path}: #{e.message}" | ||
) | ||
) | ||
end | ||
|
||
def process_prism_parse_result(path, parsed, comments = nil) | ||
return @fallback.send(:scan_file, path) if RUBY_VISITOR.skip_prism_comment?(comments) | ||
|
||
visitor = @visitor_class.new(comments: comments) | ||
nodes = parsed.accept(visitor) | ||
|
||
nodes | ||
.filter_map do |node| | ||
next node.occurrences(path) if node.is_a?(I18n::Tasks::Scanners::PrismScanners::TranslationNode) | ||
next unless node.respond_to?(:translation_nodes) | ||
|
||
node.translation_nodes.flat_map { |n| n.occurrences(path) } | ||
end | ||
.flatten(1) | ||
end | ||
|
||
begin | ||
require 'prism' | ||
require_relative 'prism_scanners/rails_visitor' | ||
require_relative 'prism_scanners/visitor' | ||
PARSER = Prism | ||
RUBY_VISITOR = I18n::Tasks::Scanners::PrismScanners::Visitor | ||
RAILS_VISITOR = I18n::Tasks::Scanners::PrismScanners::RailsVisitor | ||
rescue LoadError | ||
PARSER = nil | ||
VISITOR = nil | ||
end | ||
end | ||
end |
Oops, something went wrong.