OLD | NEW |
(Empty) | |
| 1 # Copyright 2012 Google Inc. |
| 2 # |
| 3 # http://www.logilab.fr/ -- mailto:contact@logilab.fr |
| 4 # This program is free software; you can redistribute it and/or modify it under |
| 5 # the terms of the GNU General Public License as published by the Free Software |
| 6 # Foundation; either version 2 of the License, or (at your option) any later |
| 7 # version. |
| 8 # |
| 9 # This program is distributed in the hope that it will be useful, but WITHOUT |
| 10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 11 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details |
| 12 # |
| 13 # You should have received a copy of the GNU General Public License along with |
| 14 # this program; if not, write to the Free Software Foundation, Inc., |
| 15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 16 """Checkers for various standard library functions.""" |
| 17 |
| 18 import re |
| 19 import sys |
| 20 |
| 21 import astroid |
| 22 |
| 23 from pylint.interfaces import IAstroidChecker |
| 24 from pylint.checkers import BaseChecker |
| 25 from pylint.checkers import utils |
| 26 |
| 27 _VALID_OPEN_MODE_REGEX = re.compile(r'^(r?U|[rwa]\+?b?)$') |
| 28 |
| 29 if sys.version_info >= (3, 0): |
| 30 OPEN_MODULE = '_io' |
| 31 else: |
| 32 OPEN_MODULE = '__builtin__' |
| 33 |
| 34 class OpenModeChecker(BaseChecker): |
| 35 __implements__ = (IAstroidChecker,) |
| 36 name = 'open_mode' |
| 37 |
| 38 msgs = { |
| 39 'W1501': ('"%s" is not a valid mode for open.', |
| 40 'bad-open-mode', |
| 41 'Python supports: r, w, a modes with b, +, and U options. ' |
| 42 'See http://docs.python.org/2/library/functions.html#open'), |
| 43 } |
| 44 |
| 45 @utils.check_messages('bad-open-mode') |
| 46 def visit_callfunc(self, node): |
| 47 """Visit a CallFunc node.""" |
| 48 if hasattr(node, 'func'): |
| 49 infer = utils.safe_infer(node.func) |
| 50 if infer and infer.root().name == OPEN_MODULE: |
| 51 if getattr(node.func, 'name', None) in ('open', 'file'): |
| 52 self._check_open_mode(node) |
| 53 |
| 54 def _check_open_mode(self, node): |
| 55 """Check that the mode argument of an open or file call is valid.""" |
| 56 try: |
| 57 mode_arg = utils.get_argument_from_call(node, position=1, keyword='m
ode') |
| 58 if mode_arg: |
| 59 mode_arg = utils.safe_infer(mode_arg) |
| 60 if (isinstance(mode_arg, astroid.Const) |
| 61 and not _VALID_OPEN_MODE_REGEX.match(mode_arg.value)): |
| 62 self.add_message('bad-open-mode', node=node, |
| 63 args=(mode_arg.value)) |
| 64 except (utils.NoSuchArgumentError, TypeError): |
| 65 pass |
| 66 |
| 67 def register(linter): |
| 68 """required method to auto register this checker """ |
| 69 linter.register_checker(OpenModeChecker(linter)) |
| 70 |
OLD | NEW |