| 220 | for error in errors: |
| 221 | if not show_line_numbers: |
| 222 | lines.append(f"- {error.problem}") |
| 223 | else: |
| 224 | lines.append(f"- line {error.line_number} col {error.col_number}: {error.problem}") |
| 225 | return "\n".join(lines) |
| 226 | |
| 227 | |
| 228 | def flake8(file_path: str) -> str: |
| 229 | """Run flake8 on a given file and return the output as a string""" |
| 230 | if Path(file_path).suffix != ".py": |
| 231 | return "" |
| 232 | cmd = "flake8 --isolated --select=F821,F822,F831,E111,E112,E113,E999,E902 {file_path}" |
| 233 | out = subprocess.run( |
| 234 | cmd.format(file_path=file_path), shell=True, check=False, capture_output=True |
| 235 | ) |
| 236 | # Use errors="replace" so non-UTF-8 bytes (e.g. GBK-encoded paths on Windows) don't crash decoding. |
| 237 | return out.stdout.decode("utf-8", errors="replace") |
| 238 | |
| 239 | |
| 240 | class Filemap: |
| 241 | def show_filemap(self, file_contents: str, encoding: str = "utf8"): |
| 242 | import warnings |
| 243 | |
| 244 | from tree_sitter_languages import get_language, get_parser |
| 245 | |
| 246 | warnings.simplefilter("ignore", category=FutureWarning) |
| 247 | |
| 248 | parser = get_parser("python") |
| 249 | language = get_language("python") |
| 250 | |
| 251 | tree = parser.parse(bytes(file_contents.encode(encoding, errors="replace"))) |
| 252 | |
| 253 | # See https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries. |
| 254 | query = language.query(""" |
| 255 | (function_definition |
| 256 | body: (_) @body) |
| 257 | """) |
| 258 | |
| 259 | # TODO: consider special casing docstrings such that they are not elided. This |
| 260 | # could be accomplished by checking whether `body.text.decode('utf8')` starts |