Commit e225b5c1 authored by Robert May's avatar Robert May

Add JSON wrapper cop

parent 2d2ce63d
......@@ -211,6 +211,13 @@ Gitlab/HTTParty:
- 'spec/**/*'
- 'ee/spec/**/*'
Gitlab/Json:
Enabled: false
Exclude:
- 'db/**/*'
- 'qa/**/*'
- 'scripts/**/*'
GitlabSecurity/PublicSend:
Enabled: true
Exclude:
......
# frozen_string_literal: true
module RuboCop
module Cop
module Gitlab
class Json < RuboCop::Cop::Cop
MSG_SEND = <<~EOL.freeze
Avoid calling `JSON` directly. Instead, use the `Gitlab::Json`
wrapper. This allows us to alter the JSON parser being used.
EOL
def_node_matcher :json_node?, <<~PATTERN
(send (const nil? :JSON)...)
PATTERN
def on_send(node)
add_offense(node, location: :expression, message: MSG_SEND) if json_node?(node)
end
def autocorrect(node)
autocorrect_json_node(node)
end
def autocorrect_json_node(node)
_, method_name, *arg_nodes = *node
replacement = "Gitlab::Json.#{method_name}(#{arg_nodes.map(&:source).join(', ')})"
lambda do |corrector|
corrector.replace(node.source_range, replacement)
end
end
end
end
end
end
# frozen_string_literal: true
require 'spec_helper'
require 'rubocop'
require 'rubocop/rspec/support'
require_relative '../../../../rubocop/cop/gitlab/json'
describe RuboCop::Cop::Gitlab::Json do
include CopHelper
subject(:cop) { described_class.new }
shared_examples('registering call offense') do |options|
let(:offending_lines) { options[:offending_lines] }
it 'registers an offense when the class calls JSON' do
inspect_source(source)
aggregate_failures do
expect(cop.offenses.size).to eq(offending_lines.size)
expect(cop.offenses.map(&:line)).to eq(offending_lines)
end
end
end
context 'when JSON is called' do
it_behaves_like 'registering call offense', offending_lines: [3] do
let(:source) do
<<~RUBY
class Foo
def bar
JSON.parse('{ "foo": "bar" }')
end
end
RUBY
end
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment