forked from coala/coala-bears
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRuboCopBear.py
274 lines (262 loc) · 11.9 KB
/
RuboCopBear.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import json
import yaml
from coalib.bearlib import deprecate_settings
from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.GemRequirement import GemRequirement
from dependency_management.requirements.PipRequirement import PipRequirement
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
from coalib.results.Result import Result
@linter(executable='rubocop',
use_stdin=True)
class RuboCopBear:
"""
Check Ruby code for syntactic, formatting as well as semantic problems.
See <https://github.com/bbatsov/rubocop#cops> for more information.
"""
LANGUAGES = {'Ruby'}
REQUIREMENTS = {GemRequirement('rubocop'),
PipRequirement('pyyaml', '3.12')}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'[email protected]'}
LICENSE = 'AGPL-3.0'
ASCIINEMA_URL = 'https://asciinema.org/a/39241'
CAN_DETECT = {'Simplification'}
CAN_FIX = {'Syntax', 'Formatting'}
severity_map = {'error': RESULT_SEVERITY.MAJOR,
'warning': RESULT_SEVERITY.NORMAL,
'convention': RESULT_SEVERITY.INFO}
@staticmethod
def create_arguments(filename, file, config_file, rubocop_config: str=''):
# Need both stdin and filename. Explained in this comment:
# https://github.com/bbatsov/rubocop/pull/2146#issuecomment-131403694
args = (filename, '--stdin', '--format=json')
if rubocop_config:
args += ('--config', rubocop_config)
else:
args += ('--config', config_file)
return args
@staticmethod
@deprecate_settings(indent_size='tab_width',
method_length_count_comments='method_count_comments',
method_naming_convention='method_name_case',
variable_naming_convention='variable_name_case')
def generate_config(filename, file,
access_modifier_indentation: str='indent',
preferred_alias: str='prefer_alias',
align_hash_rocket_by: str='key',
align_colon_by: str='key',
inspect_last_argument_hash: str='always_inspect',
align_parameters: str='with_first_parameter',
class_check: str='is_a?',
comment_keywords: tuple=('TODO',
'FIXME',
'OPTIMIZE',
'HACK',
'REVIEW'),
min_if_unless_guard: int=1,
indent_size: int=2,
method_naming_convention: str='snake',
string_literals: str='single_quotes',
variable_naming_convention: str='snake',
max_class_length: int=100,
class_length_count_comments: bool=False,
max_module_length: int=100,
module_length_count_comments: bool=False,
cyclomatic_complexity: int=6,
max_line_length: int=79,
line_length_allow_here_doc: bool=True,
line_length_allow_uri: bool=True,
max_method_length: int=10,
method_length_count_comments: bool=False,
max_parameters: int=5,
count_keyword_args: bool=True,
ignore_unused_block_args_if_empty: bool=True,
allow_unused_block_keyword_arguments: bool=False,
ignore_unused_method_args_if_empty: bool=True,
allow_unused_method_keyword_args: bool=False):
"""
Not all settings added.
Notable settings missing: Rails settings.
:param access_modifier_indentation:
Indent private/protected/public as deep as method definitions
options:
``indent`` : Indent modifiers like class members.
``outdent`` : Indent modifiers one level less than
class members.
:param preferred_alias:
Which method to use for aliasing in ruby.
options : ``alias`` , ``alias_method``.
:param align_hash_rocket_by:
Alignment of entries using hash rocket as separator.
:param align_colon_by:
Alignment of entries using colon as separator.
:param inspect_last_argument_hash:
Select whether hashes that are the last argument in a method call
should be inspected.
options: ``always_inspect``, ``always_ignore``,
``ignore_implicit``, ``ignore_explicit``.
:param align_parameters:
Alignment of parameters in multi-line method calls.
options:
``with_first_parameter``: Aligns the following lines
along the same column as the
first parameter.
``with_fixed_indentation``: Aligns the following lines with one
level of indentation relative to
the start of the line with the
method call.
:param class_check:
How to check type of class.
options: ``is_a?``, ``kind_of?``.
:param comment_keywords:
Checks formatting of special comments based on keywords like
TODO, FIXME etc.
:param min_if_unless_guard:
The number of lines that are tolerable within an if/unless block,
more than these lines call for the usage of a guard clause.
:param indent_size:
Number of spaces per indentation level.
:param method_naming_convention:
Case of a method's name.
options: ``snake``, ``camel``.
:param string_literals:
Use ' or " as string literals.
options: ``single_quotes``, ``double_quotes``.
:param variable_naming_convention:
Case of a variable's name.
options: ``snake``, ``camel``.
:param max_class_length:
Max lines in a class.
:param class_length_count_comments:
Whether or not to count comments while calculating the class
length.
:param max_module_length:
Max lines in a module.
:param module_length_count_comments:
Whether or not to count comments while calculating
the module length.
:param cyclomatic_complexity:
Cyclomatic Complexity of the file.
:param max_line_length:
Max length of a line.
:param line_length_allow_here_doc:
Allow here-doc lines to be more than the max line length.
:param line_length_allow_uri:
To make it possible to copy or click on URIs in the code,
we allow ignore long lines containing a URI to be longer than max
line length.
:param max_method_length:
Max number of lines in a method.
:param method_length_count_comments:
Whether or not to count full line comments while calculating
method length.
:param max_parameters:
Max number of parameters in parameter list.
:param count_keyword_args:
Count keyword args while counting all arguments?
:param ignore_unused_block_args_if_empty:
Ignore unused block arguments if block is empty.
:param allow_unused_block_keyword_arguments:
Allow unused block keyword arguments.
:param ignore_unused_method_args_if_empty:
Allows unused method argument if method is empty.
:param allow_unused_method_keyword_args:
Allows unused keyword arguments in a method.
"""
naming_convention = {'camel': 'camelCase', 'snake': 'snake_case'}
options = {
'Style/AccessModifierIndentation': {
'EnforcedStyle': access_modifier_indentation
},
'Style/Alias': {
'EnforcedStyle': preferred_alias
},
'Style/AlignHash': {
'EnforcedHashRocketStyle': align_hash_rocket_by,
'EnforcedColonStyle': align_colon_by,
'EnforcedLastArgumentHashStyle': inspect_last_argument_hash
},
'Style/AlignParameters': {
'EnforcedStyle': align_parameters
},
'Style/ClassCheck': {
'EnforcedStyle': class_check
},
'Style/CommentAnnotation': {
'Keywords': comment_keywords
},
'Style/GuardClause': {
'MinBodyLength': min_if_unless_guard
},
'Style/IndentationWidth': {
'Width': indent_size
},
'Style/MethodName': {
'EnforcedStyle': naming_convention.get(
method_naming_convention,
method_naming_convention)
},
'Style/StringLiterals': {
'EnforcedStyle': string_literals
},
'Style/VariableName': {
'EnforcedStyle': naming_convention.get(
variable_naming_convention,
variable_naming_convention)
},
'Metrics/ClassLength': {
'Max': max_class_length,
'CountComments': class_length_count_comments
},
'Metrics/ModuleLength': {
'CountComments': module_length_count_comments,
'Max': max_module_length
},
'Metrics/CyclomaticComplexity': {
'Max': cyclomatic_complexity
},
'Metrics/LineLength': {
'Max': max_line_length,
'AllowHeredoc': line_length_allow_here_doc,
'AllowURI': line_length_allow_uri
},
'Metrics/MethodLength': {
'CountComments': method_length_count_comments,
'Max': max_method_length
},
'Metrics/ParameterLists': {
'Max': max_parameters,
'CountKeywordArgs': count_keyword_args
},
'Lint/UnusedBlockArgument': {
'IgnoreEmptyBlocks': ignore_unused_block_args_if_empty,
'AllowUnusedKeywordArguments':
allow_unused_block_keyword_arguments
},
'Lint/UnusedMethodArgument': {
'AllowUnusedKeywordArguments':
allow_unused_method_keyword_args,
'IgnoreEmptyMethods':
ignore_unused_method_args_if_empty
},
}
return yaml.dump(options, default_flow_style=False)
def process_output(self, output, filename, file):
output = json.loads(output)
assert len(output['files']) == 1
for result in output['files'][0]['offenses']:
# TODO: Add condition for auto-correct, when rubocop is updated.
# Relevant Issue: https://github.com/bbatsov/rubocop/issues/2932
yield Result.from_values(
origin='{class_name} ({rule})'.format(
class_name=self.__class__.__name__,
rule=result['cop_name']),
message=result['message'],
file=filename,
diffs=None,
severity=self.severity_map[result['severity']],
line=result['location']['line'],
column=result['location']['column'],
# Tested with linebreaks, it's secure.
end_column=result['location']['column'] +
result['location']['length'])