Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code validity check #27

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions naucse_render/markdown.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging
import traceback
from textwrap import dedent
import re

Expand Down Expand Up @@ -147,6 +149,13 @@ def image(self, src, title, text):
return super().image(self._convert_url(src), title, text)


def check_python_code_validity(code: str, execute=False):
compiled = compile(code, "fake-file", "exec")

if execute:
exec(compiled)


class Markdown(mistune.Markdown):
def output_admonition(self):
name = self.token['name']
Expand All @@ -158,6 +167,19 @@ def output_admonition(self):
body += self.tok()
return self.renderer.admonition(name, body)

def output_code(self):
text = self.token['text']
lang = self.token['lang']

if lang.lower() == "python":
try:
check_python_code_validity(text, execute=True)
except BaseException:
logging.warning(f"Code {text} raises an error when compiled/executed: "
f"{traceback.format_exc()}")

return self.renderer.block_code(text, lang)

def output_deflist_term(self):
items = [['term', self.renderer.placeholder()]]
while True:
Expand Down