Exemple #1
0
def test_get_line_color_none():
    style = PygmentsSyntaxTheme("default")
    style._background_style = Style(bgcolor=None)
    syntax = Syntax(
        CODE,
        lexer_name="python",
        line_numbers=True,
        line_range=(2, 10),
        theme=style,
        code_width=60,
        word_wrap=True,
        background_color="red",
    )
    assert syntax._get_line_numbers_color() == Color.default()
Exemple #2
0
def test_get_style_for_token():
    # from pygments.style import Style as PygmentsStyle
    # pygments_style = PygmentsStyle()
    from pygments.style import Token

    style = PygmentsSyntaxTheme("default")
    style_dict = {Token.Text: Style(color=None)}
    style._style_cache = style_dict
    syntax = Syntax(
        CODE,
        lexer_name="python",
        line_numbers=True,
        line_range=(2, 10),
        theme=style,
        code_width=60,
        word_wrap=True,
        background_color="red",
    )
    assert syntax._get_line_numbers_color() == Color.default()
Exemple #3
0
def test_pygments_syntax_theme():
    style = PygmentsSyntaxTheme("default")
    assert style.get_style_for_token("abc") == Style.parse("none")
Exemple #4
0
def test_pygments_syntax_theme_non_str():
    from pygments.style import Style as PygmentsStyle

    style = PygmentsSyntaxTheme(PygmentsStyle())
    assert style.get_background_style().bgcolor == Color.parse("#ffffff")
Exemple #5
0
def init_logging(level: int, location: pathlib.Path,
                 cli_flags: argparse.Namespace) -> None:
    root_logger = logging.getLogger()

    base_logger = logging.getLogger("red")
    base_logger.setLevel(level)
    dpy_logger = logging.getLogger("discord")
    dpy_logger.setLevel(logging.WARNING)
    warnings_logger = logging.getLogger("py.warnings")
    warnings_logger.setLevel(logging.WARNING)

    rich_console = rich.get_console()
    rich.reconfigure(tab_size=4)
    rich_console.push_theme(
        Theme({
            "log.time":
            Style(dim=True),
            "logging.level.warning":
            Style(color="yellow"),
            "logging.level.critical":
            Style(color="white", bgcolor="red"),
            "repr.number":
            Style(color="cyan"),
            "repr.url":
            Style(underline=True, italic=True, bold=False, color="cyan"),
        }))
    rich_console.file = sys.stdout
    # This is terrible solution, but it's the best we can do if we want the paths in tracebacks
    # to be visible. Rich uses `pygments.string` style  which is fine, but it also uses
    # this highlighter which dims most of the path and therefore makes it unreadable on Mac.
    PathHighlighter.highlights = []

    enable_rich_logging = False

    if isatty(0) and cli_flags.rich_logging is None:
        # Check if the bot thinks it has a active terminal.
        enable_rich_logging = True
    elif cli_flags.rich_logging is True:
        enable_rich_logging = True

    file_formatter = logging.Formatter(
        "[{asctime}] [{levelname}] {name}: {message}",
        datefmt="%Y-%m-%d %H:%M:%S",
        style="{")
    if enable_rich_logging is True:
        rich_formatter = logging.Formatter("{message}",
                                           datefmt="[%X]",
                                           style="{")

        stdout_handler = RedRichHandler(
            rich_tracebacks=True,
            show_path=False,
            highlighter=NullHighlighter(),
            tracebacks_extra_lines=cli_flags.rich_traceback_extra_lines,
            tracebacks_show_locals=cli_flags.rich_traceback_show_locals,
            tracebacks_theme=(PygmentsSyntaxTheme(FixedMonokaiStyle)
                              if rich_console.color_system == "truecolor" else
                              ANSISyntaxTheme(SYNTAX_THEME)),
        )
        stdout_handler.setFormatter(rich_formatter)
    else:
        stdout_handler = logging.StreamHandler(sys.stdout)
        stdout_handler.setFormatter(file_formatter)

    root_logger.addHandler(stdout_handler)
    logging.captureWarnings(True)

    if not location.exists():
        location.mkdir(parents=True, exist_ok=True)
    # Rotate latest logs to previous logs
    previous_logs: List[pathlib.Path] = []
    latest_logs: List[Tuple[pathlib.Path, str]] = []
    for path in location.iterdir():
        match = re.match(r"latest(?P<part>-part\d+)?\.log", path.name)
        if match:
            part = match.groupdict(default="")["part"]
            latest_logs.append((path, part))
        match = re.match(r"previous(?:-part\d+)?.log", path.name)
        if match:
            previous_logs.append(path)
    # Delete all previous.log files
    for path in previous_logs:
        path.unlink()
    # Rename latest.log files to previous.log
    for path, part in latest_logs:
        path.replace(location / f"previous{part}.log")

    latest_fhandler = RotatingFileHandler(
        stem="latest",
        directory=location,
        maxBytes=1_000_000,  # About 1MB per logfile
        backupCount=MAX_OLD_LOGS,
        encoding="utf-8",
    )
    all_fhandler = RotatingFileHandler(
        stem="red",
        directory=location,
        maxBytes=1_000_000,
        backupCount=MAX_OLD_LOGS,
        encoding="utf-8",
    )

    for fhandler in (latest_fhandler, all_fhandler):
        fhandler.setFormatter(file_formatter)
        root_logger.addHandler(fhandler)