|
| 1 | +import argparse |
| 2 | +import bisect |
| 3 | +import re |
| 4 | +import sys |
| 5 | +import textwrap |
| 6 | +from typing import NoReturn, Optional, cast |
| 7 | + |
| 8 | +import libcst as cst |
| 9 | +from libcst._position import CodeRange |
| 10 | +import libcst.matchers as m |
| 11 | +import libcst.metadata as metadata |
| 12 | + |
| 13 | + |
| 14 | +class CommentFinder(cst.CSTVisitor): |
| 15 | + METADATA_DEPENDENCIES = (metadata.PositionProvider,) |
| 16 | + |
| 17 | + def __init__(self) -> None: |
| 18 | + self.ignored_linenos: set[int] = set() |
| 19 | + |
| 20 | + def visit_Comment(self, node: cst.Comment) -> None: |
| 21 | + if re.search(r"\bdict-ignore\b", node.value): |
| 22 | + position: Optional[CodeRange] = self.get_metadata(metadata.PositionProvider, node) # type: ignore |
| 23 | + if position: |
| 24 | + for lineno in range(position.start.line, position.end.line + 1): |
| 25 | + self.ignored_linenos.add(lineno) |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def get_ignored_lines(cls, wrapper: cst.MetadataWrapper) -> frozenset[int]: |
| 29 | + comment_finder = cls() |
| 30 | + wrapper.visit(comment_finder) |
| 31 | + return frozenset(comment_finder.ignored_linenos) |
| 32 | + |
| 33 | + |
| 34 | +class DictChecker(cst.CSTTransformer): |
| 35 | + METADATA_DEPENDENCIES = (metadata.PositionProvider,) |
| 36 | + |
| 37 | + def __init__(self, fix: bool) -> None: |
| 38 | + self.fix = fix |
| 39 | + self.ignored_linenos: tuple[int, ...] = () |
| 40 | + |
| 41 | + def setup(self, filename: str) -> None: |
| 42 | + with open(filename) as f: |
| 43 | + self.lines = f.readlines() |
| 44 | + self.num_changes = 0 |
| 45 | + self.filename = filename |
| 46 | + |
| 47 | + def is_ignored(self, position: Optional[CodeRange]) -> bool: |
| 48 | + if position is None: |
| 49 | + return False |
| 50 | + next_idx = bisect.bisect_left(self.ignored_linenos, position.start.line) |
| 51 | + return ( |
| 52 | + next_idx < len(self.ignored_linenos) |
| 53 | + and self.ignored_linenos[next_idx] <= position.end.line |
| 54 | + ) |
| 55 | + |
| 56 | + def leave_Dict(self, original_node: cst.Dict, updated_node: cst.Dict) -> cst.BaseExpression: |
| 57 | + position: Optional[CodeRange] = self.get_metadata(metadata.PositionProvider, original_node) # type: ignore |
| 58 | + if self.is_ignored(position): |
| 59 | + return updated_node |
| 60 | + existing_elements: list[cst.DictElement] = [ |
| 61 | + element # type: ignore |
| 62 | + for element in updated_node.elements |
| 63 | + if m.matches(element, m.DictElement()) |
| 64 | + ] |
| 65 | + if existing_elements and all( |
| 66 | + self.is_compatible_element(element) for element in existing_elements |
| 67 | + ): |
| 68 | + self.num_changes += 1 |
| 69 | + if self.fix: |
| 70 | + return cst.Call( |
| 71 | + cst.Name("dict"), |
| 72 | + args=[ |
| 73 | + cst.Arg( |
| 74 | + keyword=cst.Name(cast(cst.SimpleString, element.key).raw_value), |
| 75 | + value=element.value, |
| 76 | + equal=cst.AssignEqual( |
| 77 | + whitespace_before=cst.SimpleWhitespace(""), |
| 78 | + whitespace_after=cst.SimpleWhitespace(""), |
| 79 | + ), |
| 80 | + comma=element.comma, |
| 81 | + ) |
| 82 | + if isinstance(element, cst.DictElement) |
| 83 | + else cst.Arg( |
| 84 | + value=element.value, |
| 85 | + star="**", |
| 86 | + comma=element.comma, |
| 87 | + whitespace_after_star=cast( |
| 88 | + cst.StarredDictElement, element |
| 89 | + ).whitespace_before_value, |
| 90 | + ) |
| 91 | + for element in updated_node.elements |
| 92 | + ], |
| 93 | + ) |
| 94 | + else: |
| 95 | + print( |
| 96 | + f"{self.filename}:{self.format_range(position)} {self.format_code(original_node)}" |
| 97 | + ) |
| 98 | + return updated_node |
| 99 | + |
| 100 | + def format_range(self, range: Optional[CodeRange]) -> str: |
| 101 | + if range is None: |
| 102 | + return "" |
| 103 | + return f"{range.start.line}:{range.start.column + 1}:" |
| 104 | + |
| 105 | + def format_code(self, node: cst.CSTNode) -> str: |
| 106 | + source_code = self.module.code_for_node(node) |
| 107 | + first_line, *lines = source_code.split("\n", maxsplit=1) |
| 108 | + if lines: |
| 109 | + [line] = lines |
| 110 | + return f"{first_line}\n{textwrap.dedent(line)}" |
| 111 | + else: |
| 112 | + return first_line |
| 113 | + |
| 114 | + @classmethod |
| 115 | + def is_compatible_element(cls, element: cst.DictElement) -> bool: |
| 116 | + return ( |
| 117 | + m.matches(element.key, m.SimpleString()) |
| 118 | + and cast(cst.SimpleString, element.key).raw_value.isidentifier() |
| 119 | + ) |
| 120 | + |
| 121 | + def check_files(self, filenames: str) -> bool: |
| 122 | + """Return whether the check fails for any file.""" |
| 123 | + failed = False |
| 124 | + for filename in filenames: |
| 125 | + self.filename = filename |
| 126 | + if self.check_file(filename): |
| 127 | + failed = True |
| 128 | + |
| 129 | + return failed |
| 130 | + |
| 131 | + def check_file(self, filename: str) -> bool: |
| 132 | + """Return whether the check fails.""" |
| 133 | + self.setup(filename) |
| 134 | + try: |
| 135 | + self.module = cst.parse_module("".join(self.lines)) |
| 136 | + except (SyntaxError, ValueError): |
| 137 | + return True |
| 138 | + else: |
| 139 | + wrapper = cst.MetadataWrapper(self.module) |
| 140 | + self.ignored_linenos = tuple(sorted(CommentFinder.get_ignored_lines(wrapper))) |
| 141 | + updated_module = wrapper.visit(self) |
| 142 | + if self.num_changes and self.fix: |
| 143 | + error = "error" if self.num_changes == 1 else "errors" |
| 144 | + print(f"Fixed {self.num_changes} {error} in '{filename}'.") |
| 145 | + with open(filename, "w") as f: |
| 146 | + f.write(updated_module.code) |
| 147 | + return self.num_changes > 0 |
| 148 | + |
| 149 | + |
| 150 | +def parse_args() -> argparse.Namespace: |
| 151 | + parser = argparse.ArgumentParser() |
| 152 | + parser.add_argument("files", nargs="+", metavar="FILES") |
| 153 | + parser.add_argument("--fix", action="store_true", help="Modify files in place.") |
| 154 | + return parser.parse_args() |
| 155 | + |
| 156 | + |
| 157 | +def main(args: argparse.Namespace) -> int: |
| 158 | + filenames = args.files |
| 159 | + fix = args.fix |
| 160 | + |
| 161 | + checker = DictChecker(fix) |
| 162 | + if checker.check_files(filenames): |
| 163 | + return 1 |
| 164 | + return 0 |
| 165 | + |
| 166 | + |
| 167 | +def main_cli() -> NoReturn: |
| 168 | + args = parse_args() |
| 169 | + sys.exit(main(args)) |
| 170 | + |
| 171 | + |
| 172 | +if __name__ == "__main__": |
| 173 | + main_cli() |
0 commit comments