Ejemplo n.º 1
0
def _get_ansi_code(color=None, style=None):
    """return ansi escape code corresponding to color and style

    :type color: str or None
    :param color:
      the color name (see `ANSI_COLORS` for available values)
      or the color number when 256 colors are available

    :type style: str or None
    :param style:
      style string (see `ANSI_COLORS` for available values). To get
      several style effects at the same time, use a coma as separator.

    :raise KeyError: if an unexistent color or style identifier is given

    :rtype: str
    :return: the built escape code
    """
    ansi_code = []
    if style:
        style_attrs = utils._splitstrip(style)
        for effect in style_attrs:
            ansi_code.append(ANSI_STYLES[effect])
    if color:
        if color.isdigit():
            ansi_code.extend(['38', '5'])
            ansi_code.append(color)
        else:
            ansi_code.append(ANSI_COLORS[color])
    if ansi_code:
        return ANSI_PREFIX + ';'.join(ansi_code) + ANSI_END
    return ''
Ejemplo n.º 2
0
    def __init__(
        self,
        output: Optional[TextIO] = None,
        color_mapping: Union[
            ColorMappingDict, Dict[str, Tuple[Optional[str], Optional[str]]], None
        ] = None,
    ) -> None:
        super().__init__(output)
        # pylint: disable-next=fixme
        # TODO: Remove DeprecationWarning and only accept ColorMappingDict as color_mapping parameter
        if color_mapping and not isinstance(
            list(color_mapping.values())[0], MessageStyle
        ):
            warnings.warn(
                "In pylint 3.0, the ColoreziedTextReporter will only accept ColorMappingDict as color_mapping parameter",
                DeprecationWarning,
            )
            temp_color_mapping: ColorMappingDict = {}
            for key, value in color_mapping.items():
                color = value[0]
                style_attrs = tuple(_splitstrip(value[1]))
                temp_color_mapping[key] = MessageStyle(color, style_attrs)
            color_mapping = temp_color_mapping
        else:
            color_mapping = cast(Optional[ColorMappingDict], color_mapping)
        self.color_mapping = color_mapping or ColorizedTextReporter.COLOR_MAPPING
        ansi_terms = ["xterm-16color", "xterm-256color"]
        if os.environ.get("TERM") not in ansi_terms:
            if sys.platform == "win32":
                # pylint: disable=import-error,import-outside-toplevel
                import colorama

                self.out = colorama.AnsiToWin32(self.out)
Ejemplo n.º 3
0
def _get_ansi_code(color=None, style=None):
    """return ansi escape code corresponding to color and style

    :type color: str or None
    :param color:
      the color name (see `ANSI_COLORS` for available values)
      or the color number when 256 colors are available

    :type style: str or None
    :param style:
      style string (see `ANSI_COLORS` for available values). To get
      several style effects at the same time, use a coma as separator.

    :raise KeyError: if an unexistent color or style identifier is given

    :rtype: str
    :return: the built escape code
    """
    ansi_code = []
    if style:
        style_attrs = utils._splitstrip(style)
        for effect in style_attrs:
            ansi_code.append(ANSI_STYLES[effect])
    if color:
        if color.isdigit():
            ansi_code.extend(["38", "5"])
            ansi_code.append(color)
        else:
            ansi_code.append(ANSI_COLORS[color])
    if ansi_code:
        return ANSI_PREFIX + ";".join(ansi_code) + ANSI_END
    return ""
Ejemplo n.º 4
0
 def config_from_file(self, config_file=None):
     """Will return `True` if plugins have been loaded. For pylint>=1.5. Else `False`."""
     self.read_config_file(config_file)
     if self.cfgfile_parser.has_option("MASTER", "load-plugins"):
         plugins = _splitstrip(self.cfgfile_parser.get("MASTER", "load-plugins"))
         self.load_plugin_modules(plugins)
     self.load_config_file()
     return True
Ejemplo n.º 5
0
    def config_from_file(self, config_file=None):
        """Will return `True` if plugins have been loaded. For pylint>=1.5. Else `False`."""
        if PYLINT_VERSION >= (1, 5):
            self.read_config_file(config_file)
            if self.cfgfile_parser.has_option('MASTER', 'load-plugins'):
                # pylint: disable=protected-access
                plugins = _splitstrip(
                    self.cfgfile_parser.get('MASTER', 'load-plugins'))
                self.load_plugin_modules(plugins)
            self.load_config_file()
            return True

        self.load_file_configuration(config_file)
        return False
Ejemplo n.º 6
0
    def test_generate_config_disable_symbolic_names(self):
        # Test that --generate-rcfile puts symbolic names in the --disable
        # option.

        out = StringIO()
        self._run_pylint(["--generate-rcfile", "--rcfile="], out=out)

        output = out.getvalue()
        # Get rid of the pesky messages that pylint emits if the
        # configuration file is not found.
        master = re.search(r"\[MASTER", output)
        out = StringIO(output[master.start():])
        parser = configparser.RawConfigParser()
        parser.readfp(out)
        messages = utils._splitstrip(parser.get('MESSAGES CONTROL', 'disable'))
        assert 'suppressed-message' in messages
Ejemplo n.º 7
0
    def test_generate_config_disable_symbolic_names(self):
        # Test that --generate-rcfile puts symbolic names in the --disable
        # option.

        out = StringIO()
        self._run_pylint(["--generate-rcfile", "--rcfile="], out=out)

        output = out.getvalue()
        # Get rid of the pesky messages that pylint emits if the
        # configuration file is not found.
        master = re.search(r"\[MASTER", output)
        out = StringIO(output[master.start():])
        parser = configparser.RawConfigParser()
        parser.read_file(out)
        messages = utils._splitstrip(parser.get("MESSAGES CONTROL", "disable"))
        assert "suppressed-message" in messages
Ejemplo n.º 8
0
	def _do_load(self):
		from pylint.config import PYLINTRC
		from pylint import utils
		
		self.load_defaults()
		try:
			self.load_default_plugins()
		except Exception:
			pass
		config_file = getattr(self, 'config_file', PYLINTRC)
		self.read_config_file(config_file)
		
		if self.cfgfile_parser.has_option('MASTER', 'load-plugins'):
			plugins = utils._splitstrip(self.cfgfile_parser.get('MASTER', 'load-plugins'))
			self.load_plugin_modules(plugins)
		
		self.load_config_file()
		print('SETUP!')
Ejemplo n.º 9
0
def _do_load(linter):
	"""
	Workaround if the patched pylint.lint doesn't exist (i.e No PyLinterMixIn class).
	:param linter:
	:return:
	"""
	from pylint import config
	from pylint.utils import _splitstrip
	linter.load_defaults()
	try:
		linter.load_default_plugins()
	except Exception:
		pass
	config_file = getattr(linter, 'config_file', config.PYLINTRC)
	linter.read_config_file(config_file)
	
	if linter.cfgfile_parser.has_option('MASTER', 'load-plugins'):
		plugins = _splitstrip(linter.cfgfile_parser.get('MASTER', 'load-plugins'))
		linter.load_plugin_modules(plugins)
	
	linter.load_config_file()
	print('External "_do_load" complete!', file = sys.stderr)
Ejemplo n.º 10
0
def colorize_ansi(
    msg: str,
    msg_style: Union[MessageStyle, str, None] = None,
    style: Optional[str] = None,
    **kwargs: Optional[str],
) -> str:
    """colorize message by wrapping it with ansi escape codes

    :param msg: the message string to colorize

    :param msg_style: the message style
        or color (for backwards compatibility): the color of the message style

    :param style: the message's style elements, this will be deprecated

    :param kwargs: used to accept `color` parameter while it is being deprecated

    :return: the ansi escaped string
    """
    # pylint: disable-next=fixme
    # TODO: Remove DeprecationWarning and only accept MessageStyle as parameter
    if not isinstance(msg_style, MessageStyle):
        warnings.warn(
            "In pylint 3.0, the colorize_ansi function of Text reporters will only accept a MessageStyle parameter",
            DeprecationWarning,
        )
        color = kwargs.get("color")
        style_attrs = tuple(_splitstrip(style))
        msg_style = MessageStyle(color or msg_style, style_attrs)
    # If both color and style are not defined, then leave the text as is
    if msg_style.color is None and len(msg_style.style) == 0:
        return msg
    escape_code = _get_ansi_code(msg_style)
    # If invalid (or unknown) color, don't wrap msg with ansi codes
    if escape_code:
        return f"{escape_code}{msg}{ANSI_RESET}"
    return msg
Ejemplo n.º 11
0
def _add_plugins(run: "Run", value: Optional[str]) -> None:
    """Add plugins to the list of loadable plugins."""
    assert value is not None
    run._plugins.extend(utils._splitstrip(value))
Ejemplo n.º 12
0
def _add_plugins(run: Run, value: str | None) -> None:
    """Add plugins to the list of loadable plugins."""
    assert value is not None
    run._plugins.extend(utils._splitstrip(value))