aboutsummaryrefslogtreecommitdiffstats
path: root/pydis_site/apps/content/utils.py
diff options
context:
space:
mode:
authorGravatar Kieran Siek <[email protected]>2021-03-26 14:40:59 +0800
committerGravatar GitHub <[email protected]>2021-03-26 14:40:59 +0800
commit494c63a51a778253e8f90868338d42bd41a700a9 (patch)
treeb48cf80d9b5af914e058d5bd0c616f81972e040b /pydis_site/apps/content/utils.py
parentMerge pull request #427 from python-discord/ks123/dewikification/event-pages (diff)
parentRemove guide reference to `markdown2`. (diff)
Merge pull request #393 from ks129/guides-app
Dewikification - Create content app
Diffstat (limited to 'pydis_site/apps/content/utils.py')
-rw-r--r--pydis_site/apps/content/utils.py57
1 files changed, 57 insertions, 0 deletions
diff --git a/pydis_site/apps/content/utils.py b/pydis_site/apps/content/utils.py
new file mode 100644
index 00000000..726c991f
--- /dev/null
+++ b/pydis_site/apps/content/utils.py
@@ -0,0 +1,57 @@
+from pathlib import Path
+from typing import Dict, Tuple
+
+import frontmatter
+import markdown
+import yaml
+from django.http import Http404
+from markdown.extensions.toc import TocExtension
+
+
+def get_category(path: Path) -> Dict[str, str]:
+ """Load category information by name from _info.yml."""
+ if not path.is_dir():
+ raise Http404("Category not found.")
+
+ return yaml.safe_load(path.joinpath("_info.yml").read_text(encoding="utf-8"))
+
+
+def get_categories(path: Path) -> Dict[str, Dict]:
+ """Get information for all categories."""
+ categories = {}
+
+ for item in path.iterdir():
+ if item.is_dir():
+ categories[item.name] = get_category(item)
+
+ return categories
+
+
+def get_category_pages(path: Path) -> Dict[str, Dict]:
+ """Get all page names and their metadata at a category path."""
+ pages = {}
+
+ for item in path.glob("*.md"):
+ if item.is_file():
+ pages[item.stem] = frontmatter.load(item).metadata
+
+ return pages
+
+
+def get_page(path: Path) -> Tuple[str, Dict]:
+ """Get one specific page."""
+ if not path.is_file():
+ raise Http404("Page not found.")
+
+ metadata, content = frontmatter.parse(path.read_text(encoding="utf-8"))
+ html = markdown.markdown(
+ content,
+ extensions=[
+ "extra",
+ # Empty string for marker to disable text searching for [TOC]
+ # By using a metadata key instead, we save time on long markdown documents
+ TocExtension(title="Table of Contents:", permalink=True, marker="")
+ ]
+ )
+
+ return str(html), metadata