Skip to content

Instantly share code, notes, and snippets.

@joachimesque
Created December 3, 2022 21:26
Show Gist options
  • Save joachimesque/fe434408c94492036134aef7c7434c99 to your computer and use it in GitHub Desktop.
Save joachimesque/fe434408c94492036134aef7c7434c99 to your computer and use it in GitHub Desktop.
Convert a Grav pages tree to a Kirby content tree
# pip install frontmatter
# python script.py
import glob
import os
import pathlib
import re
import shutil
import frontmatter # https://pypi.org/project/python-frontmatter/
reg_exp = r"([\d]{2}\.)|([\d]{4}-[\d]{2}-[\d]{2}-)"
def convert_path(match_obj):
# normal page name
if match_obj.group(1) is not None:
return f"{match_obj.group(1).replace('.', '')}_"
# date page name
if match_obj.group(2) is not None:
return f"{match_obj.group(2).replace('-', '')}_"
def get_new_content(path):
with open(path) as f:
grav_content = frontmatter.load(f)
kirby_content = ""
for k in grav_content.keys():
kirby_content += f"{k.capitalize()}: {grav_content[k]}\n----\n"
if "date" not in grav_content.keys():
date_match = re.search(r"[\d]{4}-[\d]{2}-[\d]{2}", str(path))
if date_match:
kirby_content += f"Date: {date_match[0]}\n----\n"
kirby_content += f"Text:\n{grav_content}"
return kirby_content
for filename in glob.iglob("pages/**/*.md", recursive=True):
post_path = pathlib.Path(filename)
new_path = re.sub(reg_exp, convert_path, str(post_path.parent))
new_path = new_path.replace("pages", "content")
new_path = pathlib.Path(new_path)
save_path = new_path / "billet.txt"
os.makedirs(os.path.dirname(save_path), exist_ok=True)
files = os.listdir(post_path.parent)
for fname in files:
if not fname.endswith(".md"):
shutil.copy2(post_path.parent / fname, new_path)
print("<>", new_path)
new_file_content = get_new_content(post_path)
with open(save_path, "w+") as w:
w.write(new_file_content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment