mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-14 06:34:44 +00:00
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
This commit is contained in:
parent
72ad6dc953
commit
f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions
|
|
@ -1,33 +1,39 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import errno
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from logging import Filter
|
||||
from typing import IO, Any, ClassVar, Iterator, List, Optional, TextIO, Type
|
||||
from typing import Any
|
||||
from typing import ClassVar
|
||||
from typing import IO
|
||||
from typing import Iterator
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
from typing import TextIO
|
||||
from typing import Type
|
||||
|
||||
from pip._vendor.rich.console import (
|
||||
Console,
|
||||
ConsoleOptions,
|
||||
ConsoleRenderable,
|
||||
RenderResult,
|
||||
)
|
||||
from pip._internal.exceptions import DiagnosticPipError
|
||||
from pip._internal.utils._log import getLogger
|
||||
from pip._internal.utils._log import VERBOSE
|
||||
from pip._internal.utils.compat import WINDOWS
|
||||
from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX
|
||||
from pip._internal.utils.misc import ensure_dir
|
||||
from pip._vendor.rich.console import Console
|
||||
from pip._vendor.rich.console import ConsoleOptions
|
||||
from pip._vendor.rich.console import ConsoleRenderable
|
||||
from pip._vendor.rich.console import RenderResult
|
||||
from pip._vendor.rich.highlighter import NullHighlighter
|
||||
from pip._vendor.rich.logging import RichHandler
|
||||
from pip._vendor.rich.segment import Segment
|
||||
from pip._vendor.rich.style import Style
|
||||
|
||||
from pip._internal.exceptions import DiagnosticPipError
|
||||
from pip._internal.utils._log import VERBOSE, getLogger
|
||||
from pip._internal.utils.compat import WINDOWS
|
||||
from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX
|
||||
from pip._internal.utils.misc import ensure_dir
|
||||
|
||||
_log_state = threading.local()
|
||||
subprocess_logger = getLogger("pip.subprocessor")
|
||||
subprocess_logger = getLogger('pip.subprocessor')
|
||||
|
||||
|
||||
class BrokenStdoutLoggingError(Exception):
|
||||
|
|
@ -36,7 +42,7 @@ class BrokenStdoutLoggingError(Exception):
|
|||
"""
|
||||
|
||||
|
||||
def _is_broken_pipe_error(exc_class: Type[BaseException], exc: BaseException) -> bool:
|
||||
def _is_broken_pipe_error(exc_class: type[BaseException], exc: BaseException) -> bool:
|
||||
if exc_class is BrokenPipeError:
|
||||
return True
|
||||
|
||||
|
|
@ -65,11 +71,11 @@ def indent_log(num: int = 2) -> Iterator[None]:
|
|||
|
||||
|
||||
def get_indentation() -> int:
|
||||
return getattr(_log_state, "indentation", 0)
|
||||
return getattr(_log_state, 'indentation', 0)
|
||||
|
||||
|
||||
class IndentingFormatter(logging.Formatter):
|
||||
default_time_format = "%Y-%m-%dT%H:%M:%S"
|
||||
default_time_format = '%Y-%m-%dT%H:%M:%S'
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
|
@ -92,15 +98,15 @@ class IndentingFormatter(logging.Formatter):
|
|||
prefix to add to each line).
|
||||
"""
|
||||
if levelno < logging.WARNING:
|
||||
return ""
|
||||
return ''
|
||||
if formatted.startswith(DEPRECATION_MSG_PREFIX):
|
||||
# Then the message already has a prefix. We don't want it to
|
||||
# look like "WARNING: DEPRECATION: ...."
|
||||
return ""
|
||||
return ''
|
||||
if levelno < logging.ERROR:
|
||||
return "WARNING: "
|
||||
return 'WARNING: '
|
||||
|
||||
return "ERROR: "
|
||||
return 'ERROR: '
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
"""
|
||||
|
|
@ -111,11 +117,11 @@ class IndentingFormatter(logging.Formatter):
|
|||
message_start = self.get_message_start(formatted, record.levelno)
|
||||
formatted = message_start + formatted
|
||||
|
||||
prefix = ""
|
||||
prefix = ''
|
||||
if self.add_timestamp:
|
||||
prefix = f"{self.formatTime(record)} "
|
||||
prefix += " " * get_indentation()
|
||||
formatted = "".join([prefix + line for line in formatted.splitlines(True)])
|
||||
prefix = f'{self.formatTime(record)} '
|
||||
prefix += ' ' * get_indentation()
|
||||
formatted = ''.join([prefix + line for line in formatted.splitlines(True)])
|
||||
return formatted
|
||||
|
||||
|
||||
|
|
@ -125,20 +131,20 @@ class IndentedRenderable:
|
|||
indent: int
|
||||
|
||||
def __rich_console__(
|
||||
self, console: Console, options: ConsoleOptions
|
||||
self, console: Console, options: ConsoleOptions,
|
||||
) -> RenderResult:
|
||||
segments = console.render(self.renderable, options)
|
||||
lines = Segment.split_lines(segments)
|
||||
for line in lines:
|
||||
yield Segment(" " * self.indent)
|
||||
yield Segment(' ' * self.indent)
|
||||
yield from line
|
||||
yield Segment("\n")
|
||||
yield Segment('\n')
|
||||
|
||||
|
||||
class RichPipStreamHandler(RichHandler):
|
||||
KEYWORDS: ClassVar[Optional[List[str]]] = []
|
||||
KEYWORDS: ClassVar[list[str] | None] = []
|
||||
|
||||
def __init__(self, stream: Optional[TextIO], no_color: bool) -> None:
|
||||
def __init__(self, stream: TextIO | None, no_color: bool) -> None:
|
||||
super().__init__(
|
||||
console=Console(file=stream, no_color=no_color, soft_wrap=True),
|
||||
show_time=False,
|
||||
|
|
@ -149,27 +155,27 @@ class RichPipStreamHandler(RichHandler):
|
|||
|
||||
# Our custom override on Rich's logger, to make things work as we need them to.
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
style: Optional[Style] = None
|
||||
style: Style | None = None
|
||||
|
||||
# If we are given a diagnostic error to present, present it with indentation.
|
||||
if record.msg == "[present-diagnostic] %s" and len(record.args) == 1:
|
||||
if record.msg == '[present-diagnostic] %s' and len(record.args) == 1:
|
||||
diagnostic_error: DiagnosticPipError = record.args[0] # type: ignore[index]
|
||||
assert isinstance(diagnostic_error, DiagnosticPipError)
|
||||
|
||||
renderable: ConsoleRenderable = IndentedRenderable(
|
||||
diagnostic_error, indent=get_indentation()
|
||||
diagnostic_error, indent=get_indentation(),
|
||||
)
|
||||
else:
|
||||
message = self.format(record)
|
||||
renderable = self.render_message(record, message)
|
||||
if record.levelno is not None:
|
||||
if record.levelno >= logging.ERROR:
|
||||
style = Style(color="red")
|
||||
style = Style(color='red')
|
||||
elif record.levelno >= logging.WARNING:
|
||||
style = Style(color="yellow")
|
||||
style = Style(color='yellow')
|
||||
|
||||
try:
|
||||
self.console.print(renderable, overflow="ignore", crop=False, style=style)
|
||||
self.console.print(renderable, overflow='ignore', crop=False, style=style)
|
||||
except Exception:
|
||||
self.handleError(record)
|
||||
|
||||
|
|
@ -182,10 +188,10 @@ class RichPipStreamHandler(RichHandler):
|
|||
# exception so we can handle it in main() instead of logging the
|
||||
# broken pipe error and continuing.
|
||||
if (
|
||||
exc_class
|
||||
and exc
|
||||
and self.console.file is sys.stdout
|
||||
and _is_broken_pipe_error(exc_class, exc)
|
||||
exc_class and
|
||||
exc and
|
||||
self.console.file is sys.stdout and
|
||||
_is_broken_pipe_error(exc_class, exc)
|
||||
):
|
||||
raise BrokenStdoutLoggingError()
|
||||
|
||||
|
|
@ -218,7 +224,7 @@ class ExcludeLoggerFilter(Filter):
|
|||
return not super().filter(record)
|
||||
|
||||
|
||||
def setup_logging(verbosity: int, no_color: bool, user_log_file: Optional[str]) -> int:
|
||||
def setup_logging(verbosity: int, no_color: bool, user_log_file: str | None) -> int:
|
||||
"""Configures and sets up all of the logging
|
||||
|
||||
Returns the requested logging level, as its integer value.
|
||||
|
|
@ -245,99 +251,99 @@ def setup_logging(verbosity: int, no_color: bool, user_log_file: Optional[str])
|
|||
include_user_log = user_log_file is not None
|
||||
if include_user_log:
|
||||
additional_log_file = user_log_file
|
||||
root_level = "DEBUG"
|
||||
root_level = 'DEBUG'
|
||||
else:
|
||||
additional_log_file = "/dev/null"
|
||||
additional_log_file = '/dev/null'
|
||||
root_level = level
|
||||
|
||||
# Disable any logging besides WARNING unless we have DEBUG level logging
|
||||
# enabled for vendored libraries.
|
||||
vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"
|
||||
vendored_log_level = 'WARNING' if level in ['INFO', 'ERROR'] else 'DEBUG'
|
||||
|
||||
# Shorthands for clarity
|
||||
log_streams = {
|
||||
"stdout": "ext://sys.stdout",
|
||||
"stderr": "ext://sys.stderr",
|
||||
'stdout': 'ext://sys.stdout',
|
||||
'stderr': 'ext://sys.stderr',
|
||||
}
|
||||
handler_classes = {
|
||||
"stream": "pip._internal.utils.logging.RichPipStreamHandler",
|
||||
"file": "pip._internal.utils.logging.BetterRotatingFileHandler",
|
||||
'stream': 'pip._internal.utils.logging.RichPipStreamHandler',
|
||||
'file': 'pip._internal.utils.logging.BetterRotatingFileHandler',
|
||||
}
|
||||
handlers = ["console", "console_errors", "console_subprocess"] + (
|
||||
["user_log"] if include_user_log else []
|
||||
handlers = ['console', 'console_errors', 'console_subprocess'] + (
|
||||
['user_log'] if include_user_log else []
|
||||
)
|
||||
|
||||
logging.config.dictConfig(
|
||||
{
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"filters": {
|
||||
"exclude_warnings": {
|
||||
"()": "pip._internal.utils.logging.MaxLevelFilter",
|
||||
"level": logging.WARNING,
|
||||
'version': 1,
|
||||
'disable_existing_loggers': False,
|
||||
'filters': {
|
||||
'exclude_warnings': {
|
||||
'()': 'pip._internal.utils.logging.MaxLevelFilter',
|
||||
'level': logging.WARNING,
|
||||
},
|
||||
"restrict_to_subprocess": {
|
||||
"()": "logging.Filter",
|
||||
"name": subprocess_logger.name,
|
||||
'restrict_to_subprocess': {
|
||||
'()': 'logging.Filter',
|
||||
'name': subprocess_logger.name,
|
||||
},
|
||||
"exclude_subprocess": {
|
||||
"()": "pip._internal.utils.logging.ExcludeLoggerFilter",
|
||||
"name": subprocess_logger.name,
|
||||
'exclude_subprocess': {
|
||||
'()': 'pip._internal.utils.logging.ExcludeLoggerFilter',
|
||||
'name': subprocess_logger.name,
|
||||
},
|
||||
},
|
||||
"formatters": {
|
||||
"indent": {
|
||||
"()": IndentingFormatter,
|
||||
"format": "%(message)s",
|
||||
'formatters': {
|
||||
'indent': {
|
||||
'()': IndentingFormatter,
|
||||
'format': '%(message)s',
|
||||
},
|
||||
"indent_with_timestamp": {
|
||||
"()": IndentingFormatter,
|
||||
"format": "%(message)s",
|
||||
"add_timestamp": True,
|
||||
'indent_with_timestamp': {
|
||||
'()': IndentingFormatter,
|
||||
'format': '%(message)s',
|
||||
'add_timestamp': True,
|
||||
},
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"level": level,
|
||||
"class": handler_classes["stream"],
|
||||
"no_color": no_color,
|
||||
"stream": log_streams["stdout"],
|
||||
"filters": ["exclude_subprocess", "exclude_warnings"],
|
||||
"formatter": "indent",
|
||||
'handlers': {
|
||||
'console': {
|
||||
'level': level,
|
||||
'class': handler_classes['stream'],
|
||||
'no_color': no_color,
|
||||
'stream': log_streams['stdout'],
|
||||
'filters': ['exclude_subprocess', 'exclude_warnings'],
|
||||
'formatter': 'indent',
|
||||
},
|
||||
"console_errors": {
|
||||
"level": "WARNING",
|
||||
"class": handler_classes["stream"],
|
||||
"no_color": no_color,
|
||||
"stream": log_streams["stderr"],
|
||||
"filters": ["exclude_subprocess"],
|
||||
"formatter": "indent",
|
||||
'console_errors': {
|
||||
'level': 'WARNING',
|
||||
'class': handler_classes['stream'],
|
||||
'no_color': no_color,
|
||||
'stream': log_streams['stderr'],
|
||||
'filters': ['exclude_subprocess'],
|
||||
'formatter': 'indent',
|
||||
},
|
||||
# A handler responsible for logging to the console messages
|
||||
# from the "subprocessor" logger.
|
||||
"console_subprocess": {
|
||||
"level": level,
|
||||
"class": handler_classes["stream"],
|
||||
"stream": log_streams["stderr"],
|
||||
"no_color": no_color,
|
||||
"filters": ["restrict_to_subprocess"],
|
||||
"formatter": "indent",
|
||||
'console_subprocess': {
|
||||
'level': level,
|
||||
'class': handler_classes['stream'],
|
||||
'stream': log_streams['stderr'],
|
||||
'no_color': no_color,
|
||||
'filters': ['restrict_to_subprocess'],
|
||||
'formatter': 'indent',
|
||||
},
|
||||
"user_log": {
|
||||
"level": "DEBUG",
|
||||
"class": handler_classes["file"],
|
||||
"filename": additional_log_file,
|
||||
"encoding": "utf-8",
|
||||
"delay": True,
|
||||
"formatter": "indent_with_timestamp",
|
||||
'user_log': {
|
||||
'level': 'DEBUG',
|
||||
'class': handler_classes['file'],
|
||||
'filename': additional_log_file,
|
||||
'encoding': 'utf-8',
|
||||
'delay': True,
|
||||
'formatter': 'indent_with_timestamp',
|
||||
},
|
||||
},
|
||||
"root": {
|
||||
"level": root_level,
|
||||
"handlers": handlers,
|
||||
'root': {
|
||||
'level': root_level,
|
||||
'handlers': handlers,
|
||||
},
|
||||
"loggers": {"pip._vendor": {"level": vendored_log_level}},
|
||||
}
|
||||
'loggers': {'pip._vendor': {'level': vendored_log_level}},
|
||||
},
|
||||
)
|
||||
|
||||
return level_number
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue