|
7 | 7 | import textwrap |
8 | 8 | from concurrent.futures import ProcessPoolExecutor |
9 | 9 | from dataclasses import dataclass |
10 | | -from typing import TYPE_CHECKING, Any |
| 10 | +from typing import TYPE_CHECKING, Any, Dict |
11 | 11 |
|
12 | 12 | import anyio |
13 | 13 | import anyio.to_process |
|
16 | 16 | from anyio import Path |
17 | 17 |
|
18 | 18 | if TYPE_CHECKING: |
19 | | - from collections.abc import AsyncGenerator |
| 19 | + from collections.abc import AsyncGenerator, Iterator |
20 | 20 |
|
21 | 21 | from .config import Config |
22 | 22 |
|
23 | 23 |
|
24 | 24 | def _hash_ast(source: str) -> str: |
25 | 25 | return hashlib.sha1( |
26 | | - ast.unparse(ast.parse(source, type_comments=True)).encode("utf-8") |
| 26 | + "".join(_stringify_ast(ast.parse(source, type_comments=True))).encode("utf-8") |
27 | 27 | ).hexdigest() |
28 | 28 |
|
29 | 29 |
|
| 30 | +def _normalize(lineend: str, value: str) -> str: |
| 31 | + # To normalize, we strip any leading and trailing space from |
| 32 | + # each line... |
| 33 | + stripped = [i.strip() for i in value.splitlines()] |
| 34 | + normalized = lineend.join(stripped) |
| 35 | + # ...and remove any blank lines at the beginning and end of |
| 36 | + # the whole string |
| 37 | + return normalized.strip() |
| 38 | + |
| 39 | + |
| 40 | +def _stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]: |
| 41 | + # this was taken from black |
| 42 | + # https://github.com/psf/black/blob/ddfecf06c13dd86205c851e340124e325ed82c5c/src/black/parsing.py#L143-L216 |
| 43 | + # and serves as a workaround for generating a hash of an AST, because ast.unparse |
| 44 | + # is not available until Python 3.9 |
| 45 | + """Simple visitor generating strings to compare ASTs by content.""" |
| 46 | + |
| 47 | + if ( |
| 48 | + isinstance(node, ast.Constant) |
| 49 | + and isinstance(node.value, str) |
| 50 | + and node.kind == "u" |
| 51 | + ): |
| 52 | + # It's a quirk of history that we strip the u prefix over here. We used to |
| 53 | + # rewrite the AST nodes for Python version compatibility and we never copied |
| 54 | + # over the kind |
| 55 | + node.kind = None |
| 56 | + |
| 57 | + yield f"{' ' * depth}{node.__class__.__name__}(" |
| 58 | + |
| 59 | + for field in sorted(node._fields): |
| 60 | + # TypeIgnore has only one field 'lineno' which breaks this comparison |
| 61 | + if isinstance(node, ast.TypeIgnore): |
| 62 | + break |
| 63 | + |
| 64 | + try: |
| 65 | + value = getattr(node, field) |
| 66 | + except AttributeError: |
| 67 | + continue |
| 68 | + |
| 69 | + yield f"{' ' * (depth+1)}{field}=" |
| 70 | + |
| 71 | + if isinstance(value, list): |
| 72 | + for item in value: |
| 73 | + # Ignore nested tuples within del statements, because we may insert |
| 74 | + # parentheses and they change the AST. |
| 75 | + if ( |
| 76 | + field == "targets" |
| 77 | + and isinstance(node, ast.Delete) |
| 78 | + and isinstance(item, ast.Tuple) |
| 79 | + ): |
| 80 | + for elt in item.elts: |
| 81 | + yield from _stringify_ast(elt, depth + 2) |
| 82 | + |
| 83 | + elif isinstance(item, ast.AST): |
| 84 | + yield from _stringify_ast(item, depth + 2) |
| 85 | + |
| 86 | + elif isinstance(value, ast.AST): |
| 87 | + yield from _stringify_ast(value, depth + 2) |
| 88 | + |
| 89 | + else: |
| 90 | + if ( |
| 91 | + isinstance(node, ast.Constant) |
| 92 | + and field == "value" |
| 93 | + and isinstance(value, str) |
| 94 | + ): |
| 95 | + # Constant strings may be indented across newlines, if they are |
| 96 | + # docstrings; fold spaces after newlines when comparing. Similarly, |
| 97 | + # trailing and leading space may be removed. |
| 98 | + normalized = _normalize("\n", value) |
| 99 | + elif field == "type_comment" and isinstance(value, str): |
| 100 | + # Trailing whitespace in type comments is removed. |
| 101 | + normalized = value.rstrip() |
| 102 | + else: |
| 103 | + normalized = value |
| 104 | + yield f"{' ' * (depth+2)}{normalized!r}, # {value.__class__.__name__}" |
| 105 | + |
| 106 | + yield f"{' ' * depth}) # /{node.__class__.__name__}" |
| 107 | + |
| 108 | + |
30 | 109 | @dataclass |
31 | 110 | class TransformationResult: |
32 | 111 | source: Path |
@@ -147,7 +226,7 @@ async def get_meta(self, file: File) -> FileMeta | None: |
147 | 226 | """ |
148 | 227 | if self._meta is None: |
149 | 228 | if meta_raw := await self.cache.get("meta.json"): |
150 | | - self._meta = msgspec.json.decode(meta_raw, type=dict[str, FileMeta]) |
| 229 | + self._meta = msgspec.json.decode(meta_raw, type=Dict[str, FileMeta]) |
151 | 230 | else: |
152 | 231 | self._meta = {} |
153 | 232 |
|
|
0 commit comments