MCPcopy
hub / github.com/microsoft/autogen / check_code_blocks

Function check_code_blocks

python/check_md_code_blocks.py:38–75  ·  view source on GitHub ↗

Check Python code blocks in a Markdown file for syntax errors.

(markdown_file_paths: List[str])

Source from the content-addressed store, hash-verified

36 return code_blocks
37
38def check_code_blocks(markdown_file_paths: List[str]) -> None:
39 """Check Python code blocks in a Markdown file for syntax errors."""
40 files_with_errors = []
41
42 for markdown_file_path in markdown_file_paths:
43 code_blocks = extract_python_code_blocks(markdown_file_path)
44 had_errors = False
45 for code_block, line_no in code_blocks:
46 markdown_file_path_with_line_no = f"{markdown_file_path}:{line_no}"
47 logger.info("Checking a code block in %s...", markdown_file_path_with_line_no)
48
49 # Skip blocks that don't import autogen_agentchat, autogen_core, or autogen_ext
50 if all(all(import_code not in code_block for import_code in [f"import {module}", f"from {module}"]) for module in ["autogen_agentchat", "autogen_core", "autogen_ext"]):
51 logger.info(" " + darkgreen("OK[ignored]"))
52 continue
53
54 with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as temp_file:
55 temp_file.write(code_block.encode("utf-8"))
56 temp_file.flush()
57
58 # Run pyright on the temporary file using subprocess.run
59 import subprocess
60
61 result = subprocess.run(["pyright", temp_file.name], capture_output=True, text=True)
62 if result.returncode != 0:
63 logger.info(" " + darkred("FAIL"))
64 highlighted_code = highlight(code_block, PythonLexer(), TerminalFormatter()) # type: ignore
65 output = f"{faint('========================================================')}\n{red('Error')}: Pyright found issues in {teal(markdown_file_path_with_line_no)}:\n{faint('--------------------------------------------------------')}\n{highlighted_code}\n{faint('--------------------------------------------------------')}\n\n{teal('pyright output:')}\n{red(result.stdout)}{faint('========================================================')}\n"
66 logger.info(output)
67 had_errors = True
68 else:
69 logger.info(" " + darkgreen("OK"))
70
71 if had_errors:
72 files_with_errors.append(markdown_file_path)
73
74 if files_with_errors:
75 raise RuntimeError("Syntax errors found in the following files:\n" + "\n".join(files_with_errors))
76
77if __name__ == "__main__":
78 parser = argparse.ArgumentParser(description="Check code blocks in Markdown files for syntax errors.")

Callers 1

Calls 5

infoMethod · 0.80
joinMethod · 0.80
flushMethod · 0.45
runMethod · 0.45

Tested by

no test coverage detected