All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
2 from concurrent.futures import Executor, ProcessPoolExecutor
3 from functools import partial
5 from multiprocessing import freeze_support
6 from typing import Set, Tuple
8 from aiohttp import web
13 # This is used internally by tests to shut down the server prematurely
14 _stop_signal = asyncio.Event()
16 VERSION_HEADER = "X-Protocol-Version"
17 LINE_LENGTH_HEADER = "X-Line-Length"
18 PYTHON_VARIANT_HEADER = "X-Python-Variant"
19 SKIP_STRING_NORMALIZATION_HEADER = "X-Skip-String-Normalization"
20 FAST_OR_SAFE_HEADER = "X-Fast-Or-Safe"
25 PYTHON_VARIANT_HEADER,
26 SKIP_STRING_NORMALIZATION_HEADER,
31 class InvalidVariantHeader(Exception):
35 @click.command(context_settings={"help_option_names": ["-h", "--help"]})
37 "--bind-host", type=str, help="Address to bind the server to.", default="localhost"
39 @click.option("--bind-port", type=int, help="Port to listen on", default=45484)
40 @click.version_option(version=black.__version__)
41 def main(bind_host: str, bind_port: int) -> None:
42 logging.basicConfig(level=logging.INFO)
44 ver = black.__version__
45 black.out(f"blackd version {ver} listening on {bind_host} port {bind_port}")
46 web.run_app(app, host=bind_host, port=bind_port, handle_signals=True, print=None)
49 def make_app() -> web.Application:
50 app = web.Application()
51 executor = ProcessPoolExecutor()
53 cors = aiohttp_cors.setup(app)
54 resource = cors.add(app.router.add_resource("/"))
56 resource.add_route("POST", partial(handle, executor=executor)),
58 "*": aiohttp_cors.ResourceOptions(
59 allow_headers=(*BLACK_HEADERS, "Content-Type"), expose_headers="*"
67 async def handle(request: web.Request, executor: Executor) -> web.Response:
69 if request.headers.get(VERSION_HEADER, "1") != "1":
71 status=501, text="This server only supports protocol version 1"
75 request.headers.get(LINE_LENGTH_HEADER, black.DEFAULT_LINE_LENGTH)
78 return web.Response(status=400, text="Invalid line length header value")
80 if PYTHON_VARIANT_HEADER in request.headers:
81 value = request.headers[PYTHON_VARIANT_HEADER]
83 pyi, versions = parse_python_variant_header(value)
84 except InvalidVariantHeader as e:
87 text=f"Invalid value for {PYTHON_VARIANT_HEADER}: {e.args[0]}",
93 skip_string_normalization = bool(
94 request.headers.get(SKIP_STRING_NORMALIZATION_HEADER, False)
97 if request.headers.get(FAST_OR_SAFE_HEADER, "safe") == "fast":
99 mode = black.FileMode(
100 target_versions=versions,
102 line_length=line_length,
103 string_normalization=not skip_string_normalization,
105 req_bytes = await request.content.read()
106 charset = request.charset if request.charset is not None else "utf8"
107 req_str = req_bytes.decode(charset)
108 loop = asyncio.get_event_loop()
109 formatted_str = await loop.run_in_executor(
110 executor, partial(black.format_file_contents, req_str, fast=fast, mode=mode)
113 content_type=request.content_type, charset=charset, text=formatted_str
115 except black.NothingChanged:
116 return web.Response(status=204)
117 except black.InvalidInput as e:
118 return web.Response(status=400, text=str(e))
119 except Exception as e:
120 logging.exception("Exception during handling a request")
121 return web.Response(status=500, text=str(e))
124 def parse_python_variant_header(value: str) -> Tuple[bool, Set[black.TargetVersion]]:
129 for version in value.split(","):
131 if version.startswith("cpy"):
132 version = version[len("cpy") :]
133 elif version.startswith("pypy"):
135 version = version[len("pypy") :]
136 major_str, *rest = version.split(".")
138 major = int(major_str)
139 if major not in (2, 3):
140 raise InvalidVariantHeader("major version must be 2 or 3")
143 if major == 2 and minor != 7:
144 raise InvalidVariantHeader(
145 "minor version must be 7 for Python 2"
148 # Default to lowest supported minor version.
149 minor = 7 if major == 2 else 3
150 version_str = f"{tag.upper()}{major}{minor}"
151 # If PyPY is the same as CPython in some version, use
152 # the corresponding CPython version.
153 if tag == "pypy" and not hasattr(black.TargetVersion, version_str):
154 version_str = f"CPY{major}{minor}"
155 if major == 3 and not hasattr(black.TargetVersion, version_str):
156 raise InvalidVariantHeader(f"3.{minor} is not supported")
157 versions.add(black.TargetVersion[version_str])
158 except (KeyError, ValueError):
159 raise InvalidVariantHeader("expected e.g. '3.7', 'pypy3.5'")
160 return False, versions
163 def patched_main() -> None:
169 if __name__ == "__main__":