|
1 | 1 | import subprocess |
| 2 | +import sys |
| 3 | + |
| 4 | +import logging |
| 5 | +logger = logging.getLogger(__name__) |
| 6 | + |
| 7 | +try: import xml.etree.cElementTree as ET |
| 8 | +except ImportError: import xml.etree.ElementTree as ET |
| 9 | + |
| 10 | +try: from io import StringIO |
| 11 | +except ImportError: from cStringIO import StringIO |
| 12 | + |
2 | 13 | from pelican import signals |
3 | 14 | from pelican.readers import BaseReader |
4 | | -from pelican.utils import pelican_open |
| 15 | + |
| 16 | +from . import embed_metadata_filter |
| 17 | + |
| 18 | +def check_command(proc, cmd): |
| 19 | + """Roughly as subprocess.check_call does, wait for PROC and throw |
| 20 | + an exception if it didn't exit successfully. CMD should be the |
| 21 | + command passed to subprocess.Popen.""" |
| 22 | + status = proc.wait() |
| 23 | + if status: |
| 24 | + raise subprocess.CalledProcessError(status, cmd) |
| 25 | + |
| 26 | +def extract_metadata(text): |
| 27 | + """A filter script converts Pandoc's internal representation of the |
| 28 | + metadata into an HTML tree structure so that it will make it to |
| 29 | + the output, with strings properly formatted. Separate that |
| 30 | + tree from the HTML for the document itself, and decode it into |
| 31 | + Pelican's desired representation.""" |
| 32 | + |
| 33 | + def walk_dl(e): |
| 34 | + rv = {} |
| 35 | + key = None |
| 36 | + for child in e: |
| 37 | + if child.tag == "dt": |
| 38 | + assert key is None |
| 39 | + assert len(child) == 0 |
| 40 | + key = child.text |
| 41 | + else: |
| 42 | + assert child.tag == "dd" |
| 43 | + assert key is not None |
| 44 | + assert len(child) == 1 |
| 45 | + rv[key] = walk(child[0]) |
| 46 | + key = None |
| 47 | + return rv |
| 48 | + |
| 49 | + def walk_ul(e): |
| 50 | + rv = [] |
| 51 | + for child in e: |
| 52 | + assert child.tag == "li" |
| 53 | + assert len(child) == 1 |
| 54 | + rv.append(walk(child[0])) |
| 55 | + return rv |
| 56 | + |
| 57 | + def walk_value(e): |
| 58 | + assert e.get("class") == "metavalue" |
| 59 | + # Setting e.tag and e.tail to None temporarily seems to be the |
| 60 | + # least-hassle way to persuade ET.tostring to dump the *contents* |
| 61 | + # of e but not e itself. |
| 62 | + tag = e.tag |
| 63 | + tail = e.tail |
| 64 | + try: |
| 65 | + e.tag = None |
| 66 | + e.tail = None |
| 67 | + return (ET.tostring(e, encoding="utf-8", method="html") |
| 68 | + .decode("utf-8")) |
| 69 | + finally: |
| 70 | + e.tag = tag |
| 71 | + e.tail = tail |
| 72 | + |
| 73 | + def walk(e): |
| 74 | + if e.tag == "dl": |
| 75 | + return walk_dl(e) |
| 76 | + elif e.tag == "ul": |
| 77 | + return walk_ul(e) |
| 78 | + elif e.tag == "div" or e.tag == "span": |
| 79 | + return walk_value(e) |
| 80 | + else: |
| 81 | + logger.error("unexpected metadata structure: " + |
| 82 | + ET.tostring(e, encoding="utf-8", method="html") |
| 83 | + .decode("utf-8")) |
| 84 | + |
| 85 | + |
| 86 | + metadata, _, document = text.partition("<hr />") |
| 87 | + document = document.strip() |
| 88 | + |
| 89 | + # Remove namespaces from all metadata elements while parsing them. |
| 90 | + # This is necessary because Pandoc thinks you have to put an |
| 91 | + # xmlns= on every use of <math>, and that makes ET.tostring |
| 92 | + # generate tags like <ns0:math>, which an HTML (not XHTML) parser |
| 93 | + # will not understand. |
| 94 | + it = ET.iterparse(StringIO(metadata)) |
| 95 | + for _, el in it: |
| 96 | + if "}" in el.tag: |
| 97 | + el.tag = el.tag.split("}", 1)[1] |
| 98 | + |
| 99 | + assert it.root.tag == "dl" |
| 100 | + return document, walk(it.root) |
5 | 101 |
|
6 | 102 | class PandocReader(BaseReader): |
7 | 103 | enabled = True |
8 | | - file_extensions = ['md', 'markdown', 'mkd', 'mdown'] |
| 104 | + file_extensions = ["md", "markdown", "mkd", "mdown"] |
9 | 105 |
|
10 | | - def read(self, filename): |
11 | | - with pelican_open(filename) as fp: |
12 | | - text = list(fp.splitlines()) |
| 106 | + def memoize_settings(self): |
| 107 | + """Load settings and compute the various subprocess invocations we |
| 108 | + will be using.""" |
| 109 | + if hasattr(self, "pd_extensions"): return |
13 | 110 |
|
14 | | - metadata = {} |
15 | | - for i, line in enumerate(text): |
16 | | - kv = line.split(':', 1) |
17 | | - if len(kv) == 2: |
18 | | - name, value = kv[0].lower(), kv[1].strip() |
19 | | - metadata[name] = self.process_metadata(name, value) |
20 | | - else: |
21 | | - content = "\n".join(text[i:]) |
22 | | - break |
| 111 | + extra_args = self.settings.get("PANDOC_ARGS", []) |
| 112 | + |
| 113 | + pos_extensions = set() |
| 114 | + neg_extensions = set() |
| 115 | + for ext in self.settings.get("PANDOC_EXTENSIONS", []): |
| 116 | + if len(ext) >= 2: |
| 117 | + if ext[0] == "-": |
| 118 | + neg_extensions.add(ext[1:]) |
| 119 | + continue |
| 120 | + elif ext[0] == "+": |
| 121 | + pos_extensions.add(ext[1:]) |
| 122 | + continue |
| 123 | + logger.error("invalid PANDOC_EXTENSIONS item {!r}".format(ext)) |
| 124 | + |
| 125 | + # For compatibility with older versions of this plugin that |
| 126 | + # parsed vaguely MMD-style metadata blocks themselves, we |
| 127 | + # default to +mmd_title_block. Unfortunately, |
| 128 | + # +mmd_title_block causes Pandoc to mis-parse YAML and |
| 129 | + # possibly also native title blocks (see |
| 130 | + # https://github.com/jgm/pandoc/issues/2026). Therefore, |
| 131 | + # if there's nothing about title blocks in PANDOC_EXTENSIONS, |
| 132 | + # we also explicitly disable YAML and native title blocks. |
| 133 | + |
| 134 | + if ("mmd_title_block" not in pos_extensions and |
| 135 | + "mmd_title_block" not in neg_extensions and |
| 136 | + "pandoc_title_block" not in pos_extensions and |
| 137 | + "pandoc_title_block" not in neg_extensions and |
| 138 | + "yaml_metadata_block" not in pos_extensions and |
| 139 | + "yaml_metadata_block" not in neg_extensions): |
| 140 | + pos_extensions.add("mmd_title_block") |
| 141 | + neg_extensions.add("pandoc_title_block") |
| 142 | + neg_extensions.add("yaml_metadata_block") |
23 | 143 |
|
24 | | - extra_args = self.settings.get('PANDOC_ARGS', []) |
25 | | - extensions = self.settings.get('PANDOC_EXTENSIONS', '') |
26 | | - if isinstance(extensions, list): |
27 | | - extensions = ''.join(extensions) |
| 144 | + both_exts = pos_extensions & neg_extensions |
| 145 | + if both_exts: |
| 146 | + logger.error("Pandoc syntax extensions both enabled and disabled: " |
| 147 | + + " ".join(sorted(both_exts))) |
| 148 | + pos_extensions -= both_exts |
| 149 | + neg_extensions -= both_exts |
28 | 150 |
|
29 | | - pandoc_cmd = ["pandoc", "--from=markdown" + extensions, "--to=html5"] |
30 | | - pandoc_cmd.extend(extra_args) |
| 151 | + syntax = "markdown" |
| 152 | + if pos_extensions: |
| 153 | + syntax += "".join(sorted("+"+ext for ext in pos_extensions)) |
| 154 | + if neg_extensions: |
| 155 | + syntax += "".join(sorted("-"+ext for ext in neg_extensions)) |
31 | 156 |
|
32 | | - proc = subprocess.Popen(pandoc_cmd, |
33 | | - stdin = subprocess.PIPE, |
34 | | - stdout = subprocess.PIPE) |
| 157 | + pd_cmd_1 = ["pandoc", "-f", syntax, "-t", "json"] |
| 158 | + pd_cmd_2 = ["pandoc", "-f", "json", "-t", "html5"] |
| 159 | + # We don't know whether the extra_args are relevant to the reader or |
| 160 | + # writer, and it is harmless to supply them to both. |
| 161 | + pd_cmd_1.extend(extra_args) |
| 162 | + pd_cmd_2.extend(extra_args) |
35 | 163 |
|
36 | | - output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8') |
37 | | - status = proc.wait() |
38 | | - if status: |
39 | | - raise subprocess.CalledProcessError(status, pandoc_cmd) |
| 164 | + self.pd_cmd_1 = pd_cmd_1 |
| 165 | + self.pd_cmd_2 = pd_cmd_2 |
| 166 | + self.filt_cmd = [sys.executable, embed_metadata_filter.__file__] |
| 167 | + logger.debug("Reader command: " + " ".join(self.pd_cmd_1)) |
| 168 | + logger.debug("Writer command: " + " ".join(self.pd_cmd_2)) |
| 169 | + logger.debug("Filter command: " + " ".join(self.filt_cmd)) |
| 170 | + |
| 171 | + def read(self, filename): |
| 172 | + self.memoize_settings() |
| 173 | + |
| 174 | + # We do not use --filter because that requires the filter to |
| 175 | + # be directly executable. By constructing a pipeline by hand |
| 176 | + # we can use sys.executable and not worry about #! lines or |
| 177 | + # execute bits. |
| 178 | + PIPE = subprocess.PIPE |
| 179 | + fp = None |
| 180 | + p1 = None |
| 181 | + p2 = None |
| 182 | + p3 = None |
| 183 | + try: |
| 184 | + fp = open(filename, "rb") |
| 185 | + p1 = subprocess.Popen(self.pd_cmd_1, stdin=fp, stdout=PIPE) |
| 186 | + p2 = subprocess.Popen(self.filt_cmd, stdin=p1.stdout, stdout=PIPE) |
| 187 | + p3 = subprocess.Popen(self.pd_cmd_2, stdin=p2.stdout, stdout=PIPE) |
| 188 | + |
| 189 | + text = p3.stdout.read().decode("utf-8") |
| 190 | + |
| 191 | + finally: |
| 192 | + if fp is not None: fp.close() |
| 193 | + if p1 is not None: check_command(p1, self.pd_cmd_1) |
| 194 | + if p2 is not None: check_command(p2, self.filt_cmd) |
| 195 | + if p3 is not None: check_command(p3, self.pd_cmd_2) |
| 196 | + |
| 197 | + document, raw_metadata = extract_metadata(text) |
| 198 | + metadata = {} |
| 199 | + for k, v in raw_metadata.items(): |
| 200 | + k = k.lower() |
| 201 | + metadata[k] = self.process_metadata(k, v) |
40 | 202 |
|
41 | | - return output, metadata |
| 203 | + return document, metadata |
42 | 204 |
|
43 | 205 | def add_reader(readers): |
44 | 206 | for ext in PandocReader.file_extensions: |
|
0 commit comments