Skip to content

Commit

Permalink
Merge pull request #7 from lennertvandevelde/fix-code-args-code-selec…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
devanshkv committed Apr 18, 2024
2 parents 22826fc + dd5889d commit fa86e89
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 41 deletions.
55 changes: 19 additions & 36 deletions argmark/argmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
import re
from typing import List

from inspect import cleandoc
from mdutils.mdutils import MdUtils


Expand All @@ -23,35 +23,10 @@ def inline_code(code: str) -> str:
return f"`{code}`"


def get_indent(line: str) -> int:
"""
Get the indent of the file.
Args:
line (str) : A string whose indent needs to be found
Returns:
int: Indent
"""
indent = 0
for c in line:
if c == " ":
indent += 1
elif c == "\t":
indent += 8
else:
# break on first word / non-white char
break
return indent


def gen_help(lines: List) -> None:
"""
Generate the help given the source code as list of lines
Generate lines of code containing the argument parser and pass it to md_help.
Args:
Expand All @@ -62,27 +37,35 @@ def gen_help(lines: List) -> None:
None
"""
indent = 0
lines_string = ""
lines_string += "import argparse"
lines_string += "\n"
lines_string += "import argmark"
lines_string += "\n"

parser_expr = re.compile(r"(\w+)\.parse_args\(")
for i, line in enumerate(lines):
if "ArgumentParser(" in line:
firstline = i
if ".parse_args(" in line:
parser = re.search(parser_expr, line)
if parser is not None:
lastline = i
parser = parser.group(1)
indent = get_indent(line)
break
lines = lines[:lastline]
lines.append("\n")
lines.append(" " * indent + "import argmark")
lines.append(" " * indent + f"argmark.md_help({parser})")
logging.debug("\n".join(lines))
exec("\n".join(lines), {"__name__": "__main__"})

lines = lines[firstline:lastline]

lines_string += cleandoc("\n".join(lines))
lines_string += "\n"
lines_string += f"argmark.md_help({parser})"
logging.debug(lines_string)
exec(lines_string, {"__name__": "__main__"})


def md_help(parser: _argparse.ArgumentParser) -> None:
"""
Generate a mardown file from the given argument parser.
Args:
parser: parser object
Expand Down
5 changes: 0 additions & 5 deletions tests/test_argmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@ def test_inline_code():
assert inline_code("f") == "`f`"


def test_get_indent():
assert get_indent(" foo") == 2
assert get_indent("\tfoo") == 8


def test_gen_help():
py_file = os.path.join(_install_dir, "sample_argparse.py")
md_file = "sample_argparse.md"
Expand Down

0 comments on commit fa86e89

Please sign in to comment.