1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
import sys
import argparse
from .renderers.rst import RSTRenderer
from .renderers.markdown import MarkdownRenderer
from . import (
create_markdown,
__version__ as version
)
def _md(args):
if args.plugin:
plugins = args.plugin
else:
# default plugins
plugins = ['strikethrough', 'footnotes', 'table', 'speedup']
if args.renderer == 'rst':
renderer = RSTRenderer()
elif args.renderer == 'markdown':
renderer = MarkdownRenderer()
else:
renderer = args.renderer
return create_markdown(
escape=args.escape,
hard_wrap=args.hardwrap,
renderer=renderer,
plugins=plugins,
)
def _output(text, args):
if args.output:
with open(args.output, 'w') as f:
f.write(text)
else:
print(text)
CMD_HELP = '''Mistune, a sane and fast python markdown parser.
Here are some use cases of the command line tool:
$ python -m mistune -m "Hi **Markdown**"
<p>Hi <strong>Markdown</strong></p>
$ python -m mistune -f README.md
<p>...
$ cat README.md | python -m mistune
<p>...
'''
def cli():
parser = argparse.ArgumentParser(
prog='python -m mistune',
description=CMD_HELP,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'-m', '--message',
help='the markdown message to convert',
)
parser.add_argument(
'-f', '--file',
help='the markdown file to convert',
)
parser.add_argument(
'-p', '--plugin',
metavar='NAME',
action='extend',
nargs='+',
help='specifiy a plugin to use',
)
parser.add_argument(
'--escape',
action='store_true',
help='turn on escape option',
)
parser.add_argument(
'--hardwrap',
action='store_true',
help='turn on hardwrap option',
)
parser.add_argument(
'-o', '--output',
help='write the rendered result into file',
)
parser.add_argument(
'-r', '--renderer',
default='html',
help='specify the output renderer',
)
parser.add_argument('--version', action='version', version='mistune ' + version)
args = parser.parse_args()
message = args.message
if not message and not args.file:
message = read_stdin()
if message:
md = _md(args)
text = md(message)
_output(text, args)
elif args.file:
md = _md(args)
text = md.read(args.file)[0]
_output(text, args)
else:
print('You MUST specify a message or file')
return sys.exit(1)
def read_stdin():
is_stdin_pipe = not sys.stdin.isatty()
if is_stdin_pipe:
return sys.stdin.read()
else:
return None
if __name__ == '__main__':
cli()
|