|
| 1 | +""" |
| 2 | +Generic shell utilities. |
| 3 | +""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from enum import IntEnum, auto |
| 10 | +from typing import TYPE_CHECKING, TextIO |
| 11 | + |
| 12 | +from packaging.requirements import Requirement |
| 13 | + |
| 14 | +from sync_pre_commit_lock import Printer |
| 15 | +from sync_pre_commit_lock.utils import url_diff |
| 16 | + |
| 17 | +if TYPE_CHECKING: |
| 18 | + from collections.abc import Callable, Sequence |
| 19 | + |
| 20 | + from sync_pre_commit_lock.pre_commit_config import PreCommitHook, PreCommitRepo |
| 21 | + |
| 22 | + |
| 23 | +def use_color() -> bool: |
| 24 | + """ |
| 25 | + Determine if we should use color in the terminal output. |
| 26 | + Follows the NO_COLOR and FORCE_COLOR conventions. |
| 27 | + See: |
| 28 | + - https://no-color.org/ |
| 29 | + - https://force-color.org/ |
| 30 | + """ |
| 31 | + no_color = os.getenv("NO_COLOR") is not None |
| 32 | + force_color = os.getenv("FORCE_COLOR") is not None |
| 33 | + return not no_color and (sys.stdout.isatty() or force_color) |
| 34 | + |
| 35 | + |
| 36 | +# Compute once |
| 37 | +USE_COLOR = use_color() |
| 38 | + |
| 39 | + |
| 40 | +def _color(escape: str) -> str: |
| 41 | + return escape if USE_COLOR else "" |
| 42 | + |
| 43 | + |
| 44 | +class Colors: |
| 45 | + """ |
| 46 | + ANSI color codes for terminal output |
| 47 | + """ |
| 48 | + |
| 49 | + BLUE = _color("\033[94m") |
| 50 | + GREEN = _color("\033[92m") |
| 51 | + YELLOW = _color("\033[93m") |
| 52 | + RED = _color("\033[91m") |
| 53 | + PURPLE = _color("\033[95m") |
| 54 | + CYAN = _color("\033[96m") |
| 55 | + BOLD = _color("\033[1m") |
| 56 | + UNDERLINE = _color("\033[4m") |
| 57 | + END = _color("\033[0m") |
| 58 | + |
| 59 | + |
| 60 | +class Verbosity(IntEnum): |
| 61 | + QUIET = auto() |
| 62 | + NORMAL = auto() |
| 63 | + DEBUG = auto() |
| 64 | + |
| 65 | + |
| 66 | +def style(*colors: str) -> Callable[[str], str]: |
| 67 | + prefix = "".join(colors) |
| 68 | + |
| 69 | + def helper(msg: str) -> str: |
| 70 | + return f"{prefix}{msg}{Colors.END}" |
| 71 | + |
| 72 | + return helper |
| 73 | + |
| 74 | + |
| 75 | +debug = style(Colors.PURPLE) |
| 76 | +cyan = style(Colors.CYAN) |
| 77 | +info = style(Colors.CYAN) |
| 78 | +bold = style(Colors.BOLD) |
| 79 | +success = style(Colors.GREEN, Colors.BOLD) |
| 80 | +warning = style(Colors.YELLOW) |
| 81 | +error = style(Colors.RED, Colors.BOLD) |
| 82 | + |
| 83 | + |
| 84 | +class ShellPrinter(Printer): |
| 85 | + success_list_token: str = f"{Colors.GREEN}✔{Colors.END}" |
| 86 | + |
| 87 | + """ |
| 88 | + A printer that outputs messages to the shell with color coding. |
| 89 | + """ |
| 90 | + |
| 91 | + def __init__(self, with_prefix: bool = True, verbosity: Verbosity = Verbosity.NORMAL) -> None: |
| 92 | + self.plugin_prefix = "[sync-pre-commit-lock]" if with_prefix else "" |
| 93 | + self.verbosity = verbosity |
| 94 | + |
| 95 | + def with_prefix(self, msg: str) -> str: |
| 96 | + if not self.plugin_prefix: |
| 97 | + return msg |
| 98 | + return "\n".join(f"{self.plugin_prefix} {line}" for line in msg.split("\n")) |
| 99 | + |
| 100 | + def print(self, msg: str, verbosity: Verbosity = Verbosity.NORMAL, out: TextIO | None = None) -> None: |
| 101 | + if self.verbosity >= verbosity: |
| 102 | + # Bind late due to https://github.com/pytest-dev/pytest/issues/5997 |
| 103 | + (out or sys.stdout).write(f"{msg}\n") |
| 104 | + |
| 105 | + def debug(self, msg: str) -> None: |
| 106 | + self.print(debug(self.with_prefix(msg)), Verbosity.DEBUG) |
| 107 | + |
| 108 | + def info(self, msg: str) -> None: |
| 109 | + self.print(info(self.with_prefix(msg))) |
| 110 | + |
| 111 | + def success(self, msg: str) -> None: |
| 112 | + self.print(success(self.with_prefix(msg))) |
| 113 | + |
| 114 | + def warning(self, msg: str) -> None: |
| 115 | + self.print(warning(self.with_prefix(msg))) |
| 116 | + |
| 117 | + def error(self, msg: str) -> None: |
| 118 | + self.print(error(self.with_prefix(msg)), Verbosity.QUIET, out=sys.stderr) |
| 119 | + |
| 120 | + def list_updated_packages(self, packages: dict[str, tuple[PreCommitRepo, PreCommitRepo]]) -> None: |
| 121 | + for package, (old, new) in packages.items(): |
| 122 | + for row in self._format_repo(package, old, new): |
| 123 | + line = " ".join(row).rstrip() |
| 124 | + if self.plugin_prefix: |
| 125 | + line = f"{info(self.plugin_prefix)} {line}" |
| 126 | + self.print(line) |
| 127 | + |
| 128 | + def _format_repo_url(self, old_repo_url: str, new_repo_url: str, package_name: str) -> str: |
| 129 | + url = url_diff( |
| 130 | + old_repo_url, |
| 131 | + new_repo_url, |
| 132 | + f"{cyan('{')}{Colors.RED}", |
| 133 | + f"{Colors.END}{cyan(' -> ')}{Colors.GREEN}", |
| 134 | + f"{Colors.END}{cyan('}')}", |
| 135 | + ) |
| 136 | + return url.replace(package_name, cyan(bold(package_name))) |
| 137 | + |
| 138 | + def _format_repo(self, package: str, old: PreCommitRepo, new: PreCommitRepo) -> Sequence[Sequence[str]]: |
| 139 | + new_version = new.rev != old.rev |
| 140 | + repo = ( |
| 141 | + self.success_list_token, |
| 142 | + self._format_repo_url(old.repo, new.repo, package), |
| 143 | + "\t", |
| 144 | + error(old.rev) if new_version else "", |
| 145 | + info("->") if new_version else "", |
| 146 | + success(new.rev) if new_version else "", |
| 147 | + ) |
| 148 | + nb_hooks = len(old.hooks) |
| 149 | + hooks = [ |
| 150 | + row |
| 151 | + for idx, (old_hook, new_hook) in enumerate(zip(old.hooks, new.hooks)) |
| 152 | + for row in self._format_hook(old_hook, new_hook, idx + 1 == nb_hooks) |
| 153 | + ] |
| 154 | + return [repo, *hooks] if hooks else [repo] |
| 155 | + |
| 156 | + def _format_hook(self, old: PreCommitHook, new: PreCommitHook, last: bool) -> Sequence[Sequence[str]]: |
| 157 | + if not len(old.additional_dependencies): |
| 158 | + return [] |
| 159 | + hook = ( |
| 160 | + f" {'└' if last else '├'} {cyan(bold(old.id))}", |
| 161 | + "", |
| 162 | + "", |
| 163 | + "", |
| 164 | + ) |
| 165 | + pairs = [ |
| 166 | + (old_dep, new_dep) |
| 167 | + for old_dep, new_dep in zip(old.additional_dependencies, new.additional_dependencies) |
| 168 | + if old_dep != new_dep |
| 169 | + ] |
| 170 | + |
| 171 | + dependencies = [ |
| 172 | + self._format_additional_dependency(old_dep, new_dep, " " if last else "│", idx + 1 == len(pairs)) |
| 173 | + for idx, (old_dep, new_dep) in enumerate(pairs) |
| 174 | + ] |
| 175 | + return (hook, *dependencies) |
| 176 | + |
| 177 | + def _format_additional_dependency(self, old: str, new: str, prefix: str, last: bool) -> Sequence[str]: |
| 178 | + old_req = Requirement(old) |
| 179 | + new_req = Requirement(new) |
| 180 | + return ( |
| 181 | + f" {prefix} {'└' if last else '├'} {cyan(bold(old_req.name))}", |
| 182 | + "\t", |
| 183 | + error(str(old_req.specifier).lstrip("==") or "*"), |
| 184 | + info("->"), |
| 185 | + success(str(new_req.specifier).lstrip("==")), |
| 186 | + ) |
0 commit comments