-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
commented_keyword.rb
92 lines (81 loc) · 2.51 KB
/
commented_keyword.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for comments put on the same line as some keywords.
# These keywords are: `class`, `module`, `def`, `begin`, `end`.
#
# Note that some comments
# (`:nodoc:`, `:yields:`, `rubocop:disable` and `rubocop:todo`)
# are allowed.
#
# Auto-correction removes comments from `end` keyword and keeps comments
# for `class`, `module`, `def` and `begin` above the keyword.
#
# @example
# # bad
# if condition
# statement
# end # end if
#
# # bad
# class X # comment
# statement
# end
#
# # bad
# def x; end # comment
#
# # good
# if condition
# statement
# end
#
# # good
# class X # :nodoc:
# y
# end
class CommentedKeyword < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not place comments on the same line as the ' \
'`%<keyword>s` keyword.'
KEYWORDS = %w[begin class def end module].freeze
KEYWORD_REGEXES = KEYWORDS.map { |w| /^\s*#{w}\s/ }.freeze
ALLOWED_COMMENTS = %w[
:nodoc:
:yields:
rubocop:disable
rubocop:todo
].freeze
ALLOWED_COMMENT_REGEXES = ALLOWED_COMMENTS.map { |c| /#\s*#{c}/ }.freeze
def on_new_investigation
processed_source.comments.each do |comment|
next unless (match = line(comment).match(/(?<keyword>\S+).*#/)) && offensive?(comment)
register_offense(comment, match[:keyword])
end
end
private
def register_offense(comment, matched_keyword)
add_offense(comment, message: format(MSG, keyword: matched_keyword)) do |corrector|
range = range_with_surrounding_space(range: comment.loc.expression, newlines: false)
corrector.remove(range)
unless matched_keyword == 'end'
corrector.insert_before(
range.source_buffer.line_range(comment.loc.line), "#{comment.text}\n"
)
end
end
end
def offensive?(comment)
line = line(comment)
KEYWORD_REGEXES.any? { |r| r.match?(line) } &&
ALLOWED_COMMENT_REGEXES.none? { |r| r.match?(line) }
end
def line(comment)
comment.location.expression.source_line
end
end
end
end
end