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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
|
"""
Panflute filter to allow file includes
"""
import os
import json
import glob
import re
import itertools
from pathlib import Path
import panflute as pf
import lxml.etree as xml
from natsort import natsorted
from urllib.parse import urlparse
from .format_heuristics import formatFromPath
from .config import parseConfig, parseOptions, TEMP_FILE, Env
# Global variables
INCLUDE_INVALID = 0
INCLUDE_FILE = 1
INCLUDE_HEADER = 2
# Regex patterns
RE_IS_INCLUDE_HEADER = r"(\\?(!|\$))include-header"
RE_IS_INCLUDE_LINE = r"^(\\?(!|\$))include(-header)?"
RE_INCLUDE_PATTERN = r"^(\\?(!|\$))include(-header)?(\`(?P<args>[^\`]+(, ?[^\`]+)*)\`)? ((?P<fname>[^\`\'\"]+)|([\`\'\"])(?P<fnamealt>.+)\9)$"
# Inherited options
options = None
# parse env config
Env.parse()
def extract_info(rawString):
global options
includeType = INCLUDE_INVALID
config = {}
filename = None
# wildcards '*' are escaped which needs to be undone because of path globing
# convert_text has a tendency to produce multiline text which can not be matched correctly
# Also here we should unescape underscores from markdown_strict.
rawString = rawString.replace('\\*', '*').replace('\n', ' ').replace('\\_', '_')
if re.match(RE_IS_INCLUDE_HEADER, rawString):
includeType = INCLUDE_HEADER
else:
includeType = INCLUDE_FILE
matches = re.match(RE_INCLUDE_PATTERN, rawString)
if not matches:
# Pattern was not able to extract args and file glob... Hence, abort
raise ValueError(f"Unable to extract info from include line {rawString}")
groups = matches.groupdict()
# Get filename from Regex capture group
filename = groups.get('fname', None)
if not filename:
filename = groups.get('fnamealt', None)
# Get args from RegEx capture group
if 'args' in groups and groups['args']:
config = parseConfig(groups['args'])
if not filename:
raise ValueError(f"Unable to extract info from include line {rawString}")
return includeType, filename, config
def is_include_line(elem, raw=False):
# Revert to Markdown for regex matching
if not raw:
rawString = pf.convert_text(
elem,
input_format='panflute',
output_format='markdown_strict',
standalone=True,
pandoc_path=Env.PandocBin
)
else:
rawString = elem
includeType = INCLUDE_INVALID
config = {}
name = None
if re.match(RE_IS_INCLUDE_LINE, rawString):
includeType, name, config = extract_info(rawString)
return includeType, name, config
def is_code_include(elem):
includeType, name, config = is_include_line(elem.text, raw=True)
if includeType == INCLUDE_HEADER:
pf.debug("[WARN] Invalid !include-header in code blocks")
includeType = INCLUDE_INVALID
return includeType, name, config
# Skip whitespaces until newline
def skipWhitespaces(content):
whiteSpaceReg = re.compile(r"[^\s]|\n")
m = whiteSpaceReg.search(content)
if m == None:
return None
pos = m.span()[0]
if content[pos] == "\n":
pos += 1
return pos
def removeLeadingWhitespaces(s, num):
regex = re.compile(r"[^\s]")
m = regex.search(s)
if m == None:
return
pos = m.span()[0]
if num < 0:
return s[pos:]
else:
return s[min(pos, num):]
def dedent(content: str, num):
lines = content.split("\n")
return list(map(lambda s: removeLeadingWhitespaces(s, num), lines))
def findFile(filename: str):
resource_paths = options['include-resources'].split(':')
files = glob.glob(filename, recursive=True)
if len(files) == 0 and resource_paths:
for resource_path in resource_paths:
if os.path.isabs(resource_path):
files += glob.glob(os.path.normpath(os.path.join(resource_path, filename)), recursive=True)
else:
files += glob.glob(os.path.normpath(os.path.join(options['process-path'], resource_path, filename)), recursive=True)
return files
def read_file(filename, config: dict):
with open(filename, encoding="utf-8") as f:
content = f.read()
if "xslt" in config:
xsltParam = config.get("xslt", None)
if not xsltParam:
raise ValueError(f"Invalid value for xsl file: '{xsltParam}'")
xslTransformerFile = findFile(xsltParam)
if len(xslTransformerFile) == 0:
raise ValueError(f"xsl transformer file not found: '{xsltParam}'")
elif len(xslTransformerFile) > 1:
raise ValueError(f"Ambiguous xsl transformer file: '{xsltParam}'")
else:
xslTransformerFile = xslTransformerFile[0]
pf.debug(f"[INFO] xslt transform {filename} with {xslTransformerFile}")
dom = xml.parse(filename, xml.XMLParser(recover=True))
xslt = xml.parse(xslTransformerFile)
if not xslt:
raise IOError("Unable to read XSLT file '{xslt}'")
transform = xml.XSLT(xslt)
transformedDom = transform(dom)
content = str(transformedDom)
if "startLine" in config or "endLine" in config:
lines = content.split("\n")
startLine = config.get("startLine", 1) - 1
endLine = config.get("endLine", len(lines))
# count from the end of file
if startLine < 0:
startLine += len(lines)
if endLine < 0:
endLine += len(lines) + 1
result = lines[startLine:endLine]
content = "\n".join(result)
if "snippetStart" in config or "snippetEnd" in config:
start = 0
length = len(content)
snippets = []
includeSnippetDelimiters = config.get("includeSnippetDelimiters", False)
while start < length:
if "snippetStart" in config:
pos = content.find(config["snippetStart"], start)
else:
pos = -1
if pos != -1:
start = pos
else:
# If not found for the first time, start from the beginning
if start != 0:
break
if not includeSnippetDelimiters:
start += len(config.get("snippetStart", ""))
# Skip whitespaces until newline
pos = skipWhitespaces(content[start:])
if pos == None:
break
start += pos
if "snippetEnd" in config:
end = content.find(config["snippetEnd"], start)
else:
end = -1
# no snippetEnd means the end of file
if end == -1:
snippets.append(content[start:])
break
if includeSnippetDelimiters:
end += len(config.get("snippetEnd", ""))
subEnd = end
else:
# Skip whitespaces until newline
pos = skipWhitespaces(content[start:end][::-1])
if pos == None:
subEnd = end
else:
subEnd = end - pos
snippets.append(content[start:subEnd])
start = end
content = "\n".join(snippets)
if "dedent" in config:
content = "\n".join(dedent(content, config["dedent"]))
return content
def action(elem, doc):
global options
# Try to read inherited options from temp file
if options is None:
options = parseOptions(doc)
# Change dir to entry file
entry = options["include-entry"]
if not entry["entered"]:
os.chdir(entry["path"])
entry["entered"] = True
# --- Include statement ---
if isinstance(elem, pf.Para):
includeType, name, config = is_include_line(elem)
if includeType == INCLUDE_INVALID:
return
files = findFile(name)
if len(files) == 0:
msg = f"Included file not found: {name}"
if Env.NotFoundError:
raise IOError(msg)
else:
pf.debug(f"[WARNING] {msg}")
return
# order
include_order = options['include-order']
if include_order == 'natural':
files = natsorted(files)
elif include_order == 'alphabetical':
files = sorted(files)
elif include_order == 'default':
pass
else:
raise ValueError('Invalid file order: ' + include_order)
elements = []
for fn in files:
pf.debug(f"[INFO] including file '{fn}'", end="", flush=True)
if not os.path.isfile(fn):
raise IOError(f"Included file not found: {fn}")
pf.debug(f"... ok")
raw = read_file(fn, config)
# Save current path
cur_path = os.getcwd()
# Change to included file's path so that sub-include's path is correct
target = os.path.dirname(fn)
# Empty means relative to current dir
if not target:
target = '.'
currentPath = options["current-path"]
options["current-path"] = os.path.normpath(os.path.join(currentPath, target))
os.chdir(target)
# pass options by temp files
with open(TEMP_FILE, 'w+') as f:
json.dump(options, f)
# Add recursive include support
new_elems = None
new_metadata = None
if includeType == 1:
# Set file format
if "format" in config:
fmt = config["format"]
else:
fmt = formatFromPath(fn)
# default use markdown
if fmt is None:
fmt = "markdown"
# copy since pf will modify this argument
pandoc_options = list(options["pandoc-options"])
if "raw" in config:
rawFmt = config.get("raw")
# raw block
new_elems = [pf.RawBlock(raw, format=rawFmt)]
else:
new_doc = pf.convert_text(
raw,
input_format=fmt,
standalone=True,
extra_args=pandoc_options,
pandoc_path=Env.PandocBin
)
new_metadata = new_doc.get_metadata(builtin=False)
new_elems = new_doc.content.list
else:
# Read header from yaml
# Use pf to preserve all info
new_metadata = pf.convert_text(
f"---\n{raw}\n---",
standalone=True,
pandoc_path=Env.PandocBin
).get_metadata(builtin=False)
# Merge metadata
if new_metadata is not None:
for key in new_metadata.content:
if not key in doc.metadata.content:
doc.metadata[key] = new_metadata[key]
# delete temp file (the file might have been deleted in subsequent executions)
if os.path.exists(TEMP_FILE):
os.remove(TEMP_FILE)
# Restore to current path
os.chdir(cur_path)
options["current-path"] = currentPath
# incremement headings
increment = config.get('incrementSection', 0)
if increment:
for new_elem in new_elems:
if isinstance(new_elem, pf.Header):
new_elem.level += increment
if new_elems != None:
elements += new_elems
return elements
# --- Code Blocks ---
elif isinstance(elem, pf.CodeBlock):
includeType, name, config = is_code_include(elem)
if includeType == 0:
return
# Enable shell-style wildcards
files = findFile(name)
if len(files) == 0:
msg = f"Included file not found: {name}"
if Env.NotFoundError:
raise IOError(msg)
else:
pf.debug(f"[WARNING] {msg}")
return
codes = []
for fn in files:
codes.append(read_file(fn, config))
elem.text = "\n".join(codes)
# --- Images ---
elif isinstance(elem, pf.Image):
rewritePath = options.get("rewrite-path", True)
if not rewritePath:
return
url = elem.url
# try to parse the url first
result = urlparse(url)
# url
if result.scheme != "":
return
# absolute path
if os.path.isabs(url):
return
# rewrite relative path
elem.url = str(
Path(options["include-entry"]["path"])
.joinpath(options["current-path"])
.joinpath(url)
)
def main(doc=None):
return pf.run_filter(action, doc=doc)
if __name__ == '__main__':
main()
|