Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Metadata without delimiters #21

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 63 additions & 11 deletions full_yaml_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,27 @@

class FullYamlMetadataExtension(markdown.Extension):
"""Extension for parsing YAML metadata part with Python-Markdown."""
def __init__(self, **kwargs):
self.config = {
"yaml_loader": [
yaml.FullLoader,
"YAML loader to use. Default: yaml.FullLoader",
],
"allow_missing_delimiters": [
False,
"Attempt to split by blank line if metadata delimiters were "
"not found. Default: False",
],
}
super().__init__(**kwargs)

def extendMarkdown(self, md: markdown.Markdown, *args, **kwargs):
md.registerExtension(self)
md.Meta = None
md.preprocessors.register(
FullYamlMetadataPreprocessor(md), "full_yaml_metadata", 1
FullYamlMetadataPreprocessor(md, self.getConfigs()),
"full_yaml_metadata",
1,
)


Expand All @@ -21,27 +37,63 @@ class FullYamlMetadataPreprocessor(markdown.preprocessors.Preprocessor):

"""

def __init__(self, md, config):
super().__init__(md)
self.config = config

def run(self, lines: list) -> list:
meta_lines, lines = self.split_by_meta_and_content(lines)
metadata, content_lines = self.parse_meta_delimited(lines)
if metadata is None and self.config.get("allow_missing_delimiters"):
metadata, content_lines = self.parse_meta_fuzzy(lines)
self.md.Meta = metadata

return content_lines

self.md.Meta = yaml.load("\n".join(meta_lines), Loader=yaml.FullLoader)
return lines
def parse_meta_block(self, meta):
loader = self.config.get("yaml_loader", yaml.FullLoader)
return yaml.load(meta, Loader=loader)

def split_by_meta_and_content(self, lines: list) -> typing.Tuple[list]:
def parse_meta_delimited(self, lines: list) -> typing.Tuple[dict, list]:
"""
Find and parse YAML data in text by looking for delimiters.
"""
meta_lines = []
if lines[0] != "---":
return meta_lines, lines
# YAML metadata delimiters not found
return None, lines

lines.pop(0)
for line in lines: # type: str
content_lines = []
for i, line in enumerate(lines[1:], start=1): # type: str
if line in ("---", "..."):
content_starts_at = lines.index(line) + 1
lines = lines[content_starts_at:]
content_starts_at = i + 1
content_lines = lines[content_starts_at:]
break

meta_lines.append(line)

return meta_lines, lines
metadata = self.parse_meta_block("\n".join(meta_lines))
return metadata, content_lines

def parse_meta_fuzzy(self, lines: list) -> typing.Tuple[dict, list]:
"""
Find and parse YAML data in text by splitting by the first blank line.
"""

content_starts_at = lines.index('') + 1
meta_lines = lines[:content_starts_at]
content_lines = lines[content_starts_at:]

try:
metadata = self.parse_meta_block("\n".join(meta_lines))
except yaml.error.YAMLError:
return None, lines

# Prevent false-positives if the text does not begin with a
# metadata block
if isinstance(metadata, str):
return None, lines

return metadata, content_lines


def makeExtension(*args, **kwargs):
Expand Down
1 change: 1 addition & 0 deletions setup.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python3
import os

from setuptools import setup
Expand Down