Debian Codegraph @

third_party/python/markdown_it_py/markdown_it/cli/parse.py

raw
1 #!/usr/bin/env python
2 """
3 CLI interface to markdown-it-py
4
5 Parse one or more markdown files, convert each to HTML, and print to stdout.
6 """
7 from __future__ import annotations
8
9 import argparse
10 from collections.abc import Iterable, Sequence
11 import sys
12
13 from markdown_it import __version__
14 from markdown_it.main import MarkdownIt
15
16 version_str = "markdown-it-py [version {}]".format(__version__)
17
18
19 def main(args: Sequence[str] | None = None) -> int:
20 namespace = parse_args(args)
21 if namespace.filenames:
22 convert(namespace.filenames)
23 else:
24 interactive()
25 return 0
26
27
28 def convert(filenames: Iterable[str]) -> None:
29 for filename in filenames:
30 convert_file(filename)
31
32
33 def convert_file(filename: str) -> None:
34 """
35 Parse a Markdown file and dump the output to stdout.
36 """
37 try:
38 with open(filename, "r", encoding="utf8", errors="ignore") as fin:
39 rendered = MarkdownIt().render(fin.read())
40 print(rendered, end="")
41 except OSError:
42 sys.stderr.write(f'Cannot open file "{filename}".\n')
43 sys.exit(1)
44
45
46 def interactive() -> None:
47 """
48 Parse user input, dump to stdout, rinse and repeat.
49 Python REPL style.
50 """
51 print_heading()
52 contents = []
53 more = False
54 while True:
55 try:
56 prompt, more = ("... ", True) if more else (">>> ", True)
57 contents.append(input(prompt) + "\n")
58 except EOFError:
59 print("\n" + MarkdownIt().render("\n".join(contents)), end="")
60 more = False
61 contents = []
62 except KeyboardInterrupt:
63 print("\nExiting.")
64 break
65
66
67 def parse_args(args: Sequence[str] | None) -> argparse.Namespace:
68 """Parse input CLI arguments."""
69 parser = argparse.ArgumentParser(
70 description="Parse one or more markdown files, "
71 "convert each to HTML, and print to stdout",
72 # NOTE: Remember to update README.md w/ the output of `markdown-it -h`
73 epilog=(
74 f"""
75 Interactive:
76
77 $ markdown-it
78 markdown-it-py [version {__version__}] (interactive)
79 Type Ctrl-D to complete input, or Ctrl-C to exit.
80 >>> # Example
81 ... > markdown *input*
82 ...
83 <h1>Example</h1>
84 <blockquote>
85 <p>markdown <em>input</em></p>
86 </blockquote>
87
88 Batch:
89
90 $ markdown-it README.md README.footer.md > index.html
91 """
92 ),
93 formatter_class=argparse.RawDescriptionHelpFormatter,
94 )
95 parser.add_argument("-v", "--version", action="version", version=version_str)
96 parser.add_argument(
97 "filenames", nargs="*", help="specify an optional list of files to convert"
98 )
99 return parser.parse_args(args)
100
101
102 def print_heading() -> None:
103 print("{} (interactive)".format(version_str))
104 print("Type Ctrl-D to complete input, or Ctrl-C to exit.")
105
106
107 if __name__ == "__main__":
108 exit_code = main(sys.argv[1:])
109 sys.exit(exit_code)