Last active
February 10, 2023 22:59
-
-
Save elfsternberg/1067919d5f4afaa1a31cabd610f0f8c9 to your computer and use it in GitHub Desktop.
Helper functions for manipulating Zola content files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import toml | |
from typing import List, Dict, Any | |
# I use Zola as my primary static site generator, and these are the functions I | |
# use regularly with python scripts to access, manipulate, and modify the | |
# headers and content. | |
def get_file_metablock_markers(lines: List[str], filename: str) -> List[int]: | |
"""Return the start and stop of the TOML frontmatter from a Zola file""" | |
markers = list( | |
map( | |
lambda a: a[0], | |
filter(lambda l: l[1].strip() == "+++", enumerate(lines)), | |
) | |
) | |
if len(markers) < 2: | |
sys.stderr.write( | |
"'{}' does not seem to have a metablock".format(filename) | |
) | |
sys.exit(1) | |
return markers | |
def read_file_metablock(filename: str) -> str: | |
"""Return the text of a Zola file's TOML frontmatter""" | |
with open(filename, "r") as fileobj: | |
lines = fileobj.readlines() | |
markers = get_file_metablock_markers(lines, filename) | |
return "".join(lines[markers[0] + 1 : markers[1]]) | |
def get_file_metablock(filename: str, key=None) -> Dict[str, Any]: | |
"""Return the frontmatter of a Zola content file as a dictionary | |
Zola content uses a TOML block at the top of the file, marked off with three | |
plus symbols. This function returns the contents of that TOML block parsed | |
into a dictionary tree. | |
""" | |
try: | |
ret = toml.loads(read_file_metablock(filename)) | |
return ret | |
except toml.TomlDecodeError as err: | |
print("{} \n at: {}".format(err, filename)) | |
sys.exit(1) | |
def get_file_content(filename: str) -> str: | |
"""Return the markdown content of a Zola content file as an array of lines | |
Zola content uses a TOML block at the top of the file, marked off with three | |
plus symbols. This function returns the text content, split by lines, of the markdown. | |
""" | |
with open(filename, "r") as fileobj: | |
lines = fileobj.readlines() | |
markers = get_file_metablock_markers(lines, filename) | |
return lines[markers[1] + 1 :] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment