| 1 |
import asyncio |
| 2 |
import logging |
| 3 |
import os |
| 4 |
from concurrent.futures import Executor, ProcessPoolExecutor |
| 5 |
from datetime import datetime, timezone |
| 6 |
from functools import cache, partial |
| 7 |
from multiprocessing import freeze_support |
| 8 |
|
| 9 |
try: |
| 10 |
from aiohttp import web |
| 11 |
from multidict import MultiMapping |
| 12 |
|
| 13 |
from .middlewares import cors |
| 14 |
except ImportError as ie: |
| 15 |
raise ImportError( |
| 16 |
f"aiohttp dependency is not installed: {ie}. " |
| 17 |
+ "Please re-install black with the '[d]' extra install " |
| 18 |
+ "to obtain aiohttp_cors: `pip install black[d]`" |
| 19 |
) from None |
| 20 |
|
| 21 |
import click |
| 22 |
|
| 23 |
import black |
| 24 |
from _black_version import version as __version__ |
| 25 |
from black.concurrency import maybe_use_uvloop |
| 26 |
|
| 27 |
# This is used internally by tests to shut down the server prematurely |
| 28 |
_stop_signal = asyncio.Event() |
| 29 |
|
| 30 |
# Request headers |
| 31 |
PROTOCOL_VERSION_HEADER = "X-Protocol-Version" |
| 32 |
LINE_LENGTH_HEADER = "X-Line-Length" |
| 33 |
PYTHON_VARIANT_HEADER = "X-Python-Variant" |
| 34 |
SKIP_SOURCE_FIRST_LINE = "X-Skip-Source-First-Line" |
| 35 |
SKIP_STRING_NORMALIZATION_HEADER = "X-Skip-String-Normalization" |
| 36 |
SKIP_MAGIC_TRAILING_COMMA = "X-Skip-Magic-Trailing-Comma" |
| 37 |
PREVIEW = "X-Preview" |
| 38 |
UNSTABLE = "X-Unstable" |
| 39 |
ENABLE_UNSTABLE_FEATURE = "X-Enable-Unstable-Feature" |
| 40 |
FAST_OR_SAFE_HEADER = "X-Fast-Or-Safe" |
| 41 |
DIFF_HEADER = "X-Diff" |
| 42 |
|
| 43 |
BLACK_HEADERS = [ |
| 44 |
PROTOCOL_VERSION_HEADER, |
| 45 |
LINE_LENGTH_HEADER, |
| 46 |
PYTHON_VARIANT_HEADER, |
| 47 |
SKIP_SOURCE_FIRST_LINE, |
| 48 |
SKIP_STRING_NORMALIZATION_HEADER, |
| 49 |
SKIP_MAGIC_TRAILING_COMMA, |
| 50 |
PREVIEW, |
| 51 |
UNSTABLE, |
| 52 |
ENABLE_UNSTABLE_FEATURE, |
| 53 |
FAST_OR_SAFE_HEADER, |
| 54 |
DIFF_HEADER, |
| 55 |
] |
| 56 |
|
| 57 |
# Response headers |
| 58 |
BLACK_VERSION_HEADER = "X-Black-Version" |
| 59 |
DEFAULT_MAX_BODY_SIZE = 5 * 1024 * 1024 |
| 60 |
DEFAULT_WORKERS = os.cpu_count() or 1 |
| 61 |
|
| 62 |
|
| 63 |
class HeaderError(Exception): |
| 64 |
pass |
| 65 |
|
| 66 |
|
| 67 |
class InvalidVariantHeader(Exception): |
| 68 |
pass |
| 69 |
|
| 70 |
|
| 71 |
@click.command(context_settings={"help_option_names": ["-h", "--help"]}) |
| 72 |
@click.option( |
| 73 |
"--bind-host", |
| 74 |
type=str, |
| 75 |
help="Address to bind the server to.", |
| 76 |
default="localhost", |
| 77 |
show_default=True, |
| 78 |
) |
| 79 |
@click.option( |
| 80 |
"--bind-port", type=int, help="Port to listen on", default=45484, show_default=True |
| 81 |
) |
| 82 |
@click.option( |
| 83 |
"--cors-allow-origin", |
| 84 |
"cors_allow_origins", |
| 85 |
multiple=True, |
| 86 |
help="Origin allowed to access blackd over CORS. Can be passed multiple times.", |
| 87 |
) |
| 88 |
@click.option( |
| 89 |
"--max-body-size", |
| 90 |
type=click.IntRange(min=1), |
| 91 |
default=DEFAULT_MAX_BODY_SIZE, |
| 92 |
show_default=True, |
| 93 |
help="Maximum request body size in bytes.", |
| 94 |
) |
| 95 |
@click.version_option(version=black.__version__) |
| 96 |
def main( |
| 97 |
bind_host: str, |
| 98 |
bind_port: int, |
| 99 |
cors_allow_origins: tuple[str, ...], |
| 100 |
max_body_size: int, |
| 101 |
) -> None: |
| 102 |
logging.basicConfig(level=logging.INFO) |
| 103 |
app = make_app(cors_allow_origins=cors_allow_origins, max_body_size=max_body_size) |
| 104 |
ver = black.__version__ |
| 105 |
black.out(f"blackd version {ver} listening on {bind_host} port {bind_port}") |
| 106 |
loop = maybe_use_uvloop() |
| 107 |
try: |
| 108 |
web.run_app( |
| 109 |
app, |
| 110 |
host=bind_host, |
| 111 |
port=bind_port, |
| 112 |
handle_signals=True, |
| 113 |
print=None, |
| 114 |
loop=loop, |
| 115 |
) |
| 116 |
finally: |
| 117 |
if not loop.is_closed(): |
| 118 |
loop.close() |
| 119 |
|
| 120 |
|
| 121 |
@cache |
| 122 |
def executor() -> Executor: |
| 123 |
return ProcessPoolExecutor(max_workers=DEFAULT_WORKERS) |
| 124 |
|
| 125 |
|
| 126 |
def make_app( |
| 127 |
*, |
| 128 |
cors_allow_origins: tuple[str, ...] = (), |
| 129 |
max_body_size: int = DEFAULT_MAX_BODY_SIZE, |
| 130 |
) -> web.Application: |
| 131 |
app = web.Application( |
| 132 |
client_max_size=max_body_size, |
| 133 |
middlewares=[ |
| 134 |
cors( |
| 135 |
allow_headers=(*BLACK_HEADERS, "Content-Type"), |
| 136 |
allow_origins=frozenset(cors_allow_origins), |
| 137 |
expose_headers=(BLACK_VERSION_HEADER,), |
| 138 |
) |
| 139 |
], |
| 140 |
) |
| 141 |
app.add_routes([ |
| 142 |
web.post( |
| 143 |
"/", |
| 144 |
partial( |
| 145 |
handle, |
| 146 |
executor=executor(), |
| 147 |
executor_semaphore=asyncio.BoundedSemaphore(DEFAULT_WORKERS), |
| 148 |
), |
| 149 |
) |
| 150 |
]) |
| 151 |
return app |
| 152 |
|
| 153 |
|
| 154 |
async def handle( |
| 155 |
request: web.Request, |
| 156 |
executor: Executor, |
| 157 |
executor_semaphore: asyncio.BoundedSemaphore, |
| 158 |
) -> web.Response: |
| 159 |
headers = {BLACK_VERSION_HEADER: __version__} |
| 160 |
try: |
| 161 |
if request.headers.get(PROTOCOL_VERSION_HEADER, "1") != "1": |
| 162 |
return web.Response( |
| 163 |
status=501, text="This server only supports protocol version 1" |
| 164 |
) |
| 165 |
|
| 166 |
fast = False |
| 167 |
if request.headers.get(FAST_OR_SAFE_HEADER, "safe") == "fast": |
| 168 |
fast = True |
| 169 |
try: |
| 170 |
mode = parse_mode(request.headers) |
| 171 |
except HeaderError as e: |
| 172 |
return web.Response(status=400, text=e.args[0]) |
| 173 |
req_bytes = await request.read() |
| 174 |
charset = request.charset if request.charset is not None else "utf8" |
| 175 |
req_str = req_bytes.decode(charset) |
| 176 |
then = datetime.now(timezone.utc) |
| 177 |
|
| 178 |
header = "" |
| 179 |
if mode.skip_source_first_line: |
| 180 |
first_newline_position: int = req_str.find("\n") + 1 |
| 181 |
header = req_str[:first_newline_position] |
| 182 |
req_str = req_str[first_newline_position:] |
| 183 |
|
| 184 |
only_diff = bool(request.headers.get(DIFF_HEADER, False)) |
| 185 |
formatted_str = await format_code( |
| 186 |
req_str=req_str, |
| 187 |
fast=fast, |
| 188 |
mode=mode, |
| 189 |
then=then, |
| 190 |
only_diff=only_diff, |
| 191 |
executor=executor, |
| 192 |
executor_semaphore=executor_semaphore, |
| 193 |
) |
| 194 |
|
| 195 |
# Put the source first line back |
| 196 |
req_str = header + req_str |
| 197 |
formatted_str = header + formatted_str |
| 198 |
|
| 199 |
return web.Response( |
| 200 |
content_type=request.content_type, |
| 201 |
charset=charset, |
| 202 |
headers=headers, |
| 203 |
text=formatted_str, |
| 204 |
) |
| 205 |
except black.NothingChanged: |
| 206 |
return web.Response(status=204, headers=headers) |
| 207 |
except black.InvalidInput as e: |
| 208 |
return web.Response(status=400, headers=headers, text=str(e)) |
| 209 |
except black.SourceASTParseError as e: |
| 210 |
return web.Response(status=400, headers=headers, text=str(e)) |
| 211 |
except web.HTTPException: |
| 212 |
raise |
| 213 |
except Exception as e: |
| 214 |
logging.exception("Exception during handling a request") |
| 215 |
return web.Response(status=500, headers=headers, text=str(e)) |
| 216 |
|
| 217 |
|
| 218 |
async def format_code( |
| 219 |
*, |
| 220 |
req_str: str, |
| 221 |
fast: bool, |
| 222 |
mode: black.FileMode, |
| 223 |
then: datetime, |
| 224 |
only_diff: bool, |
| 225 |
executor: Executor, |
| 226 |
executor_semaphore: asyncio.BoundedSemaphore, |
| 227 |
) -> str: |
| 228 |
async with executor_semaphore: |
| 229 |
loop = asyncio.get_event_loop() |
| 230 |
formatted_str = await loop.run_in_executor( |
| 231 |
executor, partial(black.format_file_contents, req_str, fast=fast, mode=mode) |
| 232 |
) |
| 233 |
|
| 234 |
if not only_diff: |
| 235 |
return formatted_str |
| 236 |
|
| 237 |
now = datetime.now(timezone.utc) |
| 238 |
src_name = f"In\t{then}" |
| 239 |
dst_name = f"Out\t{now}" |
| 240 |
return await loop.run_in_executor( |
| 241 |
executor, |
| 242 |
partial(black.diff, req_str, formatted_str, src_name, dst_name), |
| 243 |
) |
| 244 |
|
| 245 |
|
| 246 |
def parse_mode(headers: MultiMapping[str]) -> black.Mode: |
| 247 |
try: |
| 248 |
line_length = int(headers.get(LINE_LENGTH_HEADER, black.DEFAULT_LINE_LENGTH)) |
| 249 |
except ValueError: |
| 250 |
raise HeaderError("Invalid line length header value") from None |
| 251 |
|
| 252 |
if PYTHON_VARIANT_HEADER in headers: |
| 253 |
value = headers[PYTHON_VARIANT_HEADER] |
| 254 |
try: |
| 255 |
pyi, versions = parse_python_variant_header(value) |
| 256 |
except InvalidVariantHeader as e: |
| 257 |
raise HeaderError( |
| 258 |
f"Invalid value for {PYTHON_VARIANT_HEADER}: {e.args[0]}", |
| 259 |
) from None |
| 260 |
else: |
| 261 |
pyi = False |
| 262 |
versions = set() |
| 263 |
|
| 264 |
skip_string_normalization = bool( |
| 265 |
headers.get(SKIP_STRING_NORMALIZATION_HEADER, False) |
| 266 |
) |
| 267 |
skip_magic_trailing_comma = bool(headers.get(SKIP_MAGIC_TRAILING_COMMA, False)) |
| 268 |
skip_source_first_line = bool(headers.get(SKIP_SOURCE_FIRST_LINE, False)) |
| 269 |
|
| 270 |
preview = bool(headers.get(PREVIEW, False)) |
| 271 |
unstable = bool(headers.get(UNSTABLE, False)) |
| 272 |
enable_features: set[black.Preview] = set() |
| 273 |
enable_unstable_features = headers.get(ENABLE_UNSTABLE_FEATURE, "").split(",") |
| 274 |
for piece in enable_unstable_features: |
| 275 |
piece = piece.strip() |
| 276 |
if piece: |
| 277 |
try: |
| 278 |
enable_features.add(black.Preview[piece]) |
| 279 |
except KeyError: |
| 280 |
raise HeaderError( |
| 281 |
f"Invalid value for {ENABLE_UNSTABLE_FEATURE}: {piece}", |
| 282 |
) from None |
| 283 |
|
| 284 |
return black.FileMode( |
| 285 |
target_versions=versions, |
| 286 |
is_pyi=pyi, |
| 287 |
line_length=line_length, |
| 288 |
skip_source_first_line=skip_source_first_line, |
| 289 |
string_normalization=not skip_string_normalization, |
| 290 |
magic_trailing_comma=not skip_magic_trailing_comma, |
| 291 |
preview=preview, |
| 292 |
unstable=unstable, |
| 293 |
enabled_features=enable_features, |
| 294 |
) |
| 295 |
|
| 296 |
|
| 297 |
def parse_python_variant_header(value: str) -> tuple[bool, set[black.TargetVersion]]: |
| 298 |
if value == "pyi": |
| 299 |
return True, set() |
| 300 |
else: |
| 301 |
versions = set() |
| 302 |
for version in value.split(","): |
| 303 |
if version.startswith("py"): |
| 304 |
version = version[len("py") :] |
| 305 |
if "." in version: |
| 306 |
major_str, *rest = version.split(".") |
| 307 |
else: |
| 308 |
major_str = version[0] |
| 309 |
rest = [version[1:]] if len(version) > 1 else [] |
| 310 |
try: |
| 311 |
major = int(major_str) |
| 312 |
if major not in (2, 3): |
| 313 |
raise InvalidVariantHeader("major version must be 2 or 3") |
| 314 |
if len(rest) > 0: |
| 315 |
minor = int(rest[0]) |
| 316 |
if major == 2: |
| 317 |
raise InvalidVariantHeader("Python 2 is not supported") |
| 318 |
else: |
| 319 |
# Default to lowest supported minor version. |
| 320 |
minor = 7 if major == 2 else 3 |
| 321 |
version_str = f"PY{major}{minor}" |
| 322 |
if major == 3 and not hasattr(black.TargetVersion, version_str): |
| 323 |
raise InvalidVariantHeader(f"3.{minor} is not supported") |
| 324 |
versions.add(black.TargetVersion[version_str]) |
| 325 |
except (KeyError, ValueError): |
| 326 |
raise InvalidVariantHeader("expected e.g. '3.7', 'py3.5'") from None |
| 327 |
return False, versions |
| 328 |
|
| 329 |
|
| 330 |
def patched_main() -> None: |
| 331 |
freeze_support() |
| 332 |
main() |
| 333 |
|
| 334 |
|
| 335 |
if __name__ == "__main__": |
| 336 |
patched_main() |