2020-04-27 18:09:41 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module RuboCop
|
|
|
|
module Cop
|
|
|
|
module Gitlab
|
2022-09-14 15:12:56 +00:00
|
|
|
class Json < RuboCop::Cop::Base
|
|
|
|
extend RuboCop::Cop::AutoCorrector
|
|
|
|
|
2021-01-26 18:09:30 +00:00
|
|
|
MSG = <<~EOL
|
2022-10-20 12:10:43 +00:00
|
|
|
Prefer `Gitlab::Json` over calling `JSON` or `to_json` directly. See https://docs.gitlab.com/ee/development/json.html
|
2020-04-27 18:09:41 +00:00
|
|
|
EOL
|
|
|
|
|
2022-10-24 12:11:34 +00:00
|
|
|
AVAILABLE_METHODS = %i[parse parse! load decode dump generate encode pretty_generate].to_set.freeze
|
|
|
|
|
2020-04-27 18:09:41 +00:00
|
|
|
def_node_matcher :json_node?, <<~PATTERN
|
2022-10-20 12:10:43 +00:00
|
|
|
(send (const {nil? | (const nil? :ActiveSupport)} :JSON) $_ $...)
|
|
|
|
PATTERN
|
|
|
|
|
|
|
|
def_node_matcher :to_json_call?, <<~PATTERN
|
|
|
|
(send $_ :to_json)
|
2020-04-27 18:09:41 +00:00
|
|
|
PATTERN
|
|
|
|
|
|
|
|
def on_send(node)
|
2022-10-20 12:10:43 +00:00
|
|
|
method_name, arg_source = match_node(node)
|
|
|
|
return unless method_name
|
2020-04-27 18:09:41 +00:00
|
|
|
|
2022-09-14 15:12:56 +00:00
|
|
|
add_offense(node) do |corrector|
|
2022-10-20 12:10:43 +00:00
|
|
|
replacement = "Gitlab::Json.#{method_name}(#{arg_source})"
|
2020-04-27 18:09:41 +00:00
|
|
|
|
|
|
|
corrector.replace(node.source_range, replacement)
|
|
|
|
end
|
|
|
|
end
|
2022-10-20 12:10:43 +00:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def match_node(node)
|
|
|
|
method_name, arg_nodes = json_node?(node)
|
|
|
|
|
|
|
|
# Only match if the method is implemented by Gitlab::Json
|
2022-10-24 12:11:34 +00:00
|
|
|
if method_name && AVAILABLE_METHODS.include?(method_name)
|
2022-10-20 12:10:43 +00:00
|
|
|
return [method_name, arg_nodes.map(&:source).join(', ')]
|
|
|
|
end
|
|
|
|
|
|
|
|
receiver = to_json_call?(node)
|
2022-10-24 12:11:34 +00:00
|
|
|
return [:dump, receiver.source] if receiver
|
2022-10-20 12:10:43 +00:00
|
|
|
|
|
|
|
nil
|
|
|
|
end
|
2020-04-27 18:09:41 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|