Debian Codegraph @

markdown/__main__.py

raw
1 # Python Markdown
2
3 # A Python implementation of John Gruber's Markdown.
4
5 # Documentation: https://python-markdown.github.io/
6 # GitHub: https://github.com/Python-Markdown/markdown/
7 # PyPI: https://pypi.org/project/Markdown/
8
9 # Started by Manfred Stienstra (http://www.dwerg.net/).
10 # Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
11 # Currently maintained by Waylan Limberg (https://github.com/waylan),
12 # Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
13
14 # Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
15 # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
16 # Copyright 2004 Manfred Stienstra (the original version)
17
18 # License: BSD (see LICENSE.md for details).
19
20 from __future__ import annotations
21
22 import sys
23 import optparse
24 import warnings
25 import markdown
26 try:
27 # We use `unsafe_load` because users may need to pass in actual Python
28 # objects. As this is only available from the CLI, the user has much
29 # worse problems if an attacker can use this as an attach vector.
30 from yaml import unsafe_load as yaml_load
31 except ImportError: # pragma: no cover
32 try:
33 # Fall back to PyYAML <5.1
34 from yaml import load as yaml_load
35 except ImportError:
36 # Fall back to JSON
37 from json import load as yaml_load
38
39 import logging
40 from logging import DEBUG, WARNING, CRITICAL
41
42 logger = logging.getLogger('MARKDOWN')
43
44
45 def parse_options(args=None, values=None):
46 """
47 Define and parse `optparse` options for command-line usage.
48 """
49 usage = """%prog [options] [INPUTFILE]
50 (STDIN is assumed if no INPUTFILE is given)"""
51 desc = "A Python implementation of John Gruber's Markdown. " \
52 "https://python-markdown.github.io/"
53 ver = "%%prog %s" % markdown.__version__
54 epilog = "WARNING: The Python-Markdown library does NOT sanitize its HTML output. If " \
55 "you are processing Markdown input from an untrusted source, it is your " \
56 "responsibility to ensure that it is properly sanitized. For more " \
57 "information see <https://python-markdown.github.io/sanitization/>."
58
59 parser = optparse.OptionParser(usage=usage, description=desc, version=ver, epilog=epilog)
60 parser.add_option("-f", "--file", dest="filename", default=None,
61 help="Write output to OUTPUT_FILE. Defaults to STDOUT.",
62 metavar="OUTPUT_FILE")
63 parser.add_option("-e", "--encoding", dest="encoding",
64 help="Encoding for input and output files.",)
65 parser.add_option("-o", "--output_format", dest="output_format",
66 default='xhtml', metavar="OUTPUT_FORMAT",
67 help="Use output format 'xhtml' (default) or 'html'.")
68 parser.add_option("-n", "--no_lazy_ol", dest="lazy_ol",
69 action='store_false', default=True,
70 help="Observe number of first item of ordered lists.")
71 parser.add_option("-x", "--extension", action="append", dest="extensions",
72 help="Load extension EXTENSION.", metavar="EXTENSION")
73 parser.add_option("-c", "--extension_configs",
74 dest="configfile", default=None,
75 help="Read extension configurations from CONFIG_FILE. "
76 "CONFIG_FILE must be of JSON or YAML format. YAML "
77 "format requires that a python YAML library be "
78 "installed. The parsed JSON or YAML must result in a "
79 "python dictionary which would be accepted by the "
80 "'extension_configs' keyword on the markdown.Markdown "
81 "class. The extensions must also be loaded with the "
82 "`--extension` option.",
83 metavar="CONFIG_FILE")
84 parser.add_option("-q", "--quiet", default=CRITICAL,
85 action="store_const", const=CRITICAL+10, dest="verbose",
86 help="Suppress all warnings.")
87 parser.add_option("-v", "--verbose",
88 action="store_const", const=WARNING, dest="verbose",
89 help="Print all warnings.")
90 parser.add_option("--noisy",
91 action="store_const", const=DEBUG, dest="verbose",
92 help="Print debug messages.")
93
94 (options, args) = parser.parse_args(args, values)
95
96 if len(args) == 0:
97 input_file = None
98 else:
99 input_file = args[0]
100
101 if not options.extensions:
102 options.extensions = []
103
104 extension_configs = {}
105 if options.configfile:
106 with open(
107 options.configfile, mode="r", encoding=options.encoding
108 ) as fp:
109 try:
110 extension_configs = yaml_load(fp)
111 except Exception as e:
112 message = "Failed parsing extension config file: %s" % \
113 options.configfile
114 e.args = (message,) + e.args[1:]
115 raise
116
117 opts = {
118 'input': input_file,
119 'output': options.filename,
120 'extensions': options.extensions,
121 'extension_configs': extension_configs,
122 'encoding': options.encoding,
123 'output_format': options.output_format,
124 'lazy_ol': options.lazy_ol
125 }
126
127 return opts, options.verbose
128
129
130 def run(): # pragma: no cover
131 """Run Markdown from the command line."""
132
133 # Parse options and adjust logging level if necessary
134 options, logging_level = parse_options()
135 if not options:
136 sys.exit(2)
137 logger.setLevel(logging_level)
138 console_handler = logging.StreamHandler()
139 logger.addHandler(console_handler)
140 if logging_level <= WARNING:
141 # Ensure deprecation warnings get displayed
142 warnings.filterwarnings('default')
143 logging.captureWarnings(True)
144 warn_logger = logging.getLogger('py.warnings')
145 warn_logger.addHandler(console_handler)
146
147 # Run
148 markdown.markdownFromFile(**options)
149
150
151 if __name__ == '__main__': # pragma: no cover
152 # Support running module as a command line command.
153 # python -m markdown [options] [args]
154 run()