Last active
November 11, 2019 22:50
-
-
Save alebian/9a980f514001ae62b46d5469e5bb92c8 to your computer and use it in GitHub Desktop.
Rubocop's cop to check if gem has version declared in Gemfile
This file contains hidden or 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
require: | |
- ./lib/no_gem_version.rb |
This file contains hidden or 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
module RuboCop | |
module Cop | |
module Style | |
# Check that gems have version. | |
# | |
# Gems without versioning can cause a lot of truble when updated without notice | |
# | |
# @example | |
# # bad | |
# gem 'rubocop' | |
# | |
# # good | |
# gem 'rubocop', '~> 0.50' | |
class NoGemVersion < Cop | |
GEMFILE_FILE_NAME = 'Gemfile'.freeze | |
MSG = 'Gem `%<gem_name>s` does not have a version set.'.freeze | |
def_node_matcher :defining_dependency?, <<-PATTERN | |
(send _ :gem ...) | |
PATTERN | |
def initialize(config = nil, options = nil) | |
super(config, options) | |
@in_gemfile = false | |
end | |
def investigate(processed_source) | |
@in_gemfile = true if processed_source.buffer.name.split('/').last == GEMFILE_FILE_NAME | |
end | |
def on_send(node) | |
return unless @in_gemfile | |
if defining_dependency?(node) && !has_version?(node) | |
add_offense(node, :expression, format(MSG, gem_name: node.arguments[0].children[0])) | |
end | |
end | |
private | |
# node.node_parts => [nil, :gem, s(:str, "some_gem"), s(:str, "some_version")] | |
def has_version?(node) | |
node.node_parts.size >= 4 | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment