Swallow warnings when performing AST checks (#4189)

Fixes #4188
This commit is contained in:
Shantanu 2024-01-28 07:05:56 -08:00 committed by GitHub
parent 0b4364b7e3
commit d919746fae
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 6 deletions

View File

@ -34,6 +34,9 @@
<!-- Changes to Black's terminal output and error messages --> <!-- Changes to Black's terminal output and error messages -->
- Black will swallow any `SyntaxWarning`s or `DeprecationWarning`s produced by the `ast`
module when performing equivalence checks (#4189)
### _Blackd_ ### _Blackd_
<!-- Changes to blackd --> <!-- Changes to blackd -->

View File

@ -4,6 +4,7 @@
import ast import ast
import sys import sys
import warnings
from typing import Iterable, Iterator, List, Set, Tuple from typing import Iterable, Iterator, List, Set, Tuple
from black.mode import VERSION_TO_FEATURES, Feature, TargetVersion, supports_feature from black.mode import VERSION_TO_FEATURES, Feature, TargetVersion, supports_feature
@ -109,10 +110,13 @@ def lib2to3_unparse(node: Node) -> str:
return code return code
def parse_single_version( def _parse_single_version(
src: str, version: Tuple[int, int], *, type_comments: bool src: str, version: Tuple[int, int], *, type_comments: bool
) -> ast.AST: ) -> ast.AST:
filename = "<unknown>" filename = "<unknown>"
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
warnings.simplefilter("ignore", DeprecationWarning)
return ast.parse( return ast.parse(
src, filename, feature_version=version, type_comments=type_comments src, filename, feature_version=version, type_comments=type_comments
) )
@ -125,7 +129,7 @@ def parse_ast(src: str) -> ast.AST:
first_error = "" first_error = ""
for version in sorted(versions, reverse=True): for version in sorted(versions, reverse=True):
try: try:
return parse_single_version(src, version, type_comments=True) return _parse_single_version(src, version, type_comments=True)
except SyntaxError as e: except SyntaxError as e:
if not first_error: if not first_error:
first_error = str(e) first_error = str(e)
@ -133,7 +137,7 @@ def parse_ast(src: str) -> ast.AST:
# Try to parse without type comments # Try to parse without type comments
for version in sorted(versions, reverse=True): for version in sorted(versions, reverse=True):
try: try:
return parse_single_version(src, version, type_comments=False) return _parse_single_version(src, version, type_comments=False)
except SyntaxError: except SyntaxError:
pass pass