blob: ed994ffd0b07cc8bc6bdb8c3bbc932fa28ecf910 [file] [log] [blame]
Danny Hermes97791812016-11-01 12:43:01 -07001# Copyright 2016 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""This script runs Pylint on the specified source.
16
17Before running Pylint, it generates a Pylint configuration on
18the fly based on programmatic defaults.
19"""
20
21from __future__ import print_function
22
23import collections
24import copy
25import io
26import os
27import subprocess
28import sys
29
30import six
31
32
33_SCRIPTS_DIR = os.path.abspath(os.path.dirname(__file__))
34PRODUCTION_RC = os.path.join(_SCRIPTS_DIR, 'pylintrc')
35TEST_RC = os.path.join(_SCRIPTS_DIR, 'pylintrc.test')
36
37_PRODUCTION_RC_ADDITIONS = {
38 'MESSAGES CONTROL': {
39 'disable': [
40 'I',
41 'import-error',
42 'no-member',
43 'protected-access',
44 'redefined-variable-type',
45 'similarities',
46 ],
47 },
48}
49_PRODUCTION_RC_REPLACEMENTS = {
50 'MASTER': {
51 'ignore': ['CVS', '.git', '.cache', '.tox', '.nox'],
52 'load-plugins': 'pylint.extensions.check_docs',
53 },
54 'REPORTS': {
55 'reports': 'no',
56 },
57 'BASIC': {
58 'method-rgx': '[a-z_][a-z0-9_]{2,40}$',
59 'function-rgx': '[a-z_][a-z0-9_]{2,40}$',
60 },
61 'TYPECHECK': {
62 'ignored-modules': ['six', 'google.protobuf'],
63 },
64 'DESIGN': {
65 'min-public-methods': '0',
66 'max-args': '10',
67 'max-attributes': '15',
68 },
69}
70_TEST_RC_ADDITIONS = copy.deepcopy(_PRODUCTION_RC_ADDITIONS)
71_TEST_RC_ADDITIONS['MESSAGES CONTROL']['disable'].extend([
72 'missing-docstring',
73 'no-self-use',
74 'redefined-outer-name',
75 'unused-argument',
76])
77_TEST_RC_REPLACEMENTS = copy.deepcopy(_PRODUCTION_RC_REPLACEMENTS)
78_TEST_RC_REPLACEMENTS.setdefault('BASIC', {})
79_TEST_RC_REPLACEMENTS['BASIC'].update({
80 'good-names': ['i', 'j', 'k', 'ex', 'Run', '_', 'fh'],
81 'method-rgx': '[a-z_][a-z0-9_]{2,80}$',
82 'function-rgx': '[a-z_][a-z0-9_]{2,80}$',
83})
84IGNORED_FILES = ()
85
86_ERROR_TEMPLATE = 'Pylint failed on {} with status {:d}.'
87_LINT_FILESET_MSG = (
88 'Keyword arguments rc_filename and description are both '
89 'required. No other keyword arguments are allowed.')
90
91
92def get_default_config():
93 """Get the default Pylint configuration.
94
95 .. note::
96
97 The output of this function varies based on the current version of
98 Pylint installed.
99
100 Returns:
101 str: The default Pylint configuration.
102 """
103 # Swallow STDERR if it says
104 # "No config file found, using default configuration"
105 result = subprocess.check_output(['pylint', '--generate-rcfile'],
106 stderr=subprocess.PIPE)
107 # On Python 3, this returns bytes (from STDOUT), so we
108 # convert to a string.
109 return result.decode('utf-8')
110
111
112def read_config(contents):
113 """Reads pylintrc config into native ConfigParser object.
114
115 Args:
116 contents (str): The contents of the file containing the INI config.
117
118 Returns
119 ConfigParser.ConfigParser: The parsed configuration.
120 """
121 file_obj = io.StringIO(contents)
122 config = six.moves.configparser.ConfigParser()
123 config.readfp(file_obj)
124 return config
125
126
127def _transform_opt(opt_val):
128 """Transform a config option value to a string.
129
130 If already a string, do nothing. If an iterable, then
131 combine into a string by joining on ",".
132
133 Args:
134 opt_val (Union[str, list]): A config option's value.
135
136 Returns:
137 str: The option value converted to a string.
138 """
139 if isinstance(opt_val, (list, tuple)):
140 return ','.join(opt_val)
141 else:
142 return opt_val
143
144
145def lint_fileset(*dirnames, **kwargs):
146 """Lints a group of files using a given rcfile.
147
148 Keyword arguments are
149
150 * ``rc_filename`` (``str``): The name of the Pylint config RC file.
151 * ``description`` (``str``): A description of the files and configuration
152 currently being run.
153
154 Args:
155 dirnames (tuple): Directories to run Pylint in.
156 kwargs: The keyword arguments. The only keyword arguments
157 are ``rc_filename`` and ``description`` and both
158 are required.
159
160 Raises:
161 KeyError: If the wrong keyword arguments are used.
162 """
163 try:
164 rc_filename = kwargs['rc_filename']
165 description = kwargs['description']
166 if len(kwargs) != 2:
167 raise KeyError
168 except KeyError:
169 raise KeyError(_LINT_FILESET_MSG)
170
171 pylint_shell_command = ['pylint', '--rcfile', rc_filename]
172 pylint_shell_command.extend(dirnames)
173 status_code = subprocess.call(pylint_shell_command)
174 if status_code != 0:
175 error_message = _ERROR_TEMPLATE.format(description, status_code)
176 print(error_message, file=sys.stderr)
177 sys.exit(status_code)
178
179
180def make_rc(base_cfg, target_filename,
181 additions=None, replacements=None):
182 """Combines a base rc and additions into single file.
183
184 Args:
185 base_cfg (ConfigParser.ConfigParser): The configuration we are
186 merging into.
187 target_filename (str): The filename where the new configuration
188 will be saved.
189 additions (dict): (Optional) The values added to the configuration.
190 replacements (dict): (Optional) The wholesale replacements for
191 the new configuration.
192
193 Raises:
194 KeyError: if one of the additions or replacements does not
195 already exist in the current config.
196 """
197 # Set-up the mutable default values.
198 if additions is None:
199 additions = {}
200 if replacements is None:
201 replacements = {}
202
203 # Create fresh config, which must extend the base one.
204 new_cfg = six.moves.configparser.ConfigParser()
205 # pylint: disable=protected-access
206 new_cfg._sections = copy.deepcopy(base_cfg._sections)
207 new_sections = new_cfg._sections
208 # pylint: enable=protected-access
209
210 for section, opts in additions.items():
211 curr_section = new_sections.setdefault(
212 section, collections.OrderedDict())
213 for opt, opt_val in opts.items():
214 curr_val = curr_section.get(opt)
215 if curr_val is None:
216 raise KeyError('Expected to be adding to existing option.')
217 curr_val = curr_val.rstrip(',')
218 opt_val = _transform_opt(opt_val)
219 curr_section[opt] = '%s, %s' % (curr_val, opt_val)
220
221 for section, opts in replacements.items():
222 curr_section = new_sections.setdefault(
223 section, collections.OrderedDict())
224 for opt, opt_val in opts.items():
225 curr_val = curr_section.get(opt)
226 if curr_val is None:
227 raise KeyError('Expected to be replacing existing option.')
228 opt_val = _transform_opt(opt_val)
229 curr_section[opt] = '%s' % (opt_val,)
230
231 with open(target_filename, 'w') as file_obj:
232 new_cfg.write(file_obj)
233
234
235def main():
236 """Script entry point. Lints both sets of files."""
237 default_config = read_config(get_default_config())
238 make_rc(default_config, PRODUCTION_RC,
239 additions=_PRODUCTION_RC_ADDITIONS,
240 replacements=_PRODUCTION_RC_REPLACEMENTS)
241 make_rc(default_config, TEST_RC,
242 additions=_TEST_RC_ADDITIONS,
243 replacements=_TEST_RC_REPLACEMENTS)
244 lint_fileset('google', rc_filename=PRODUCTION_RC,
245 description='Library')
246 lint_fileset('tests', 'system_tests', rc_filename=TEST_RC,
247 description='Test')
248
249
250if __name__ == '__main__':
251 main()