Home | History | Annotate | Line # | Download | only in system
      1 # Copyright (C) Internet Systems Consortium, Inc. ("ISC")
      2 #
      3 # SPDX-License-Identifier: MPL-2.0
      4 #
      5 # This Source Code Form is subject to the terms of the Mozilla Public
      6 # License, v. 2.0.  If a copy of the MPL was not distributed with this
      7 # file, you can obtain one at https://mozilla.org/MPL/2.0/.
      8 #
      9 # See the COPYRIGHT file distributed with this work for additional
     10 # information regarding copyright ownership.
     11 
     12 # pylint: disable=unknown-option-value,re-compile-alias
     13 
     14 import re
     15 
     16 from astroid import nodes
     17 
     18 from pylint.checkers import BaseRawFileChecker
     19 from pylint.lint import PyLinter
     20 
     21 
     22 class ReCompileChecker(BaseRawFileChecker):
     23 
     24     name = "custom_raw"
     25     msgs = {
     26         "R9901": (
     27             "Replace re.compile() with Re() using `from re import compile as Re`",
     28             "re-compile-alias",
     29             (
     30                 "Use a Re() alias instead of re.compile() by importing the "
     31                 "re.compile() function as Re()"
     32             ),
     33         ),
     34     }
     35     options = ()
     36 
     37     def process_module(self, node: nodes.Module) -> None:
     38         pattern = re.compile(r"re\.compile\(")
     39         with node.stream() as stream:
     40             for lineno, line in enumerate(stream):
     41                 if pattern.search(line.decode("utf-8")):
     42                     self.add_message("re-compile-alias", line=lineno)
     43 
     44 
     45 def register(linter: PyLinter) -> None:
     46     linter.register_checker(ReCompileChecker(linter))
     47