Add Site reference to Output, clean up template url handling
The following changes have been made all with template cleanup in mind: - Make Output.url relative to the origin root - Keep weakref to Site in all Output objects. - Add several helpers to get urls from Site: home_url(), tag_url(tag), section_url(section) and tags_url(). - Add helpers to Index to get pagination urls: pagination_url(n) - Clean up templates by making use of these new facilities
This commit is contained in:
@@ -13,10 +13,11 @@ else:
|
||||
|
||||
|
||||
class Article(Content):
|
||||
def __init__(self, source: Path, meta: dict[str, Any]):
|
||||
def __init__(self, site: Site, source: Path, meta: dict[str, Any]):
|
||||
if "tags" not in meta:
|
||||
log.warning("no tags for article in '%s'", source)
|
||||
super().__init__(
|
||||
site,
|
||||
source,
|
||||
meta["section"],
|
||||
meta["slug"],
|
||||
@@ -27,15 +28,15 @@ class Article(Content):
|
||||
)
|
||||
self.title: str = meta["title"]
|
||||
|
||||
def write(self, site: Site) -> None:
|
||||
def write(self) -> None:
|
||||
content, summary = md.parse(self.read_body(), self.summary is None)
|
||||
if summary is not None:
|
||||
self.summary = summary
|
||||
|
||||
template = site.jinja_env.get_template("article.html")
|
||||
html = template.render(article=self, content=content, site=site)
|
||||
template = self.site.jinja_env.get_template("article.html")
|
||||
html = template.render(page=self, content=content, site=self.site)
|
||||
|
||||
out_path = site.output_path / self.destination
|
||||
out_path = self.site.output_path / self.destination
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(html, encoding="utf-8")
|
||||
log.debug("Rendered %s -> %s", self.source, out_path)
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
from omicron.ssg.output.output import Output
|
||||
from pathlib import Path
|
||||
from datetime import date
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from omicron.ssg.site import Site
|
||||
else:
|
||||
Site = "omicron.ssg.site.Site"
|
||||
|
||||
|
||||
class ContentError(RuntimeError):
|
||||
pass
|
||||
@@ -13,6 +19,7 @@ class Content(Output):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
site: Site,
|
||||
source: Path,
|
||||
section: str,
|
||||
slug: str,
|
||||
@@ -21,7 +28,7 @@ class Content(Output):
|
||||
tags: set[str] | None = None,
|
||||
summary: str | None = None,
|
||||
):
|
||||
super().__init__(Content.build_path(section, slug))
|
||||
super().__init__(site, Content.build_path(section, slug))
|
||||
if tags is None:
|
||||
tags = set()
|
||||
self.source = source
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from typing import Any, cast, TYPE_CHECKING
|
||||
from omicron.ssg.output.content import Content, ContentError
|
||||
from omicron.ssg.output.article import Article
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from omicron.ssg.site import Site
|
||||
else:
|
||||
Site = "omicron.ssg.site.Site"
|
||||
|
||||
FRONTMATTER_CONTENT = {".md"}
|
||||
CONTENT_EXTENSIONS = FRONTMATTER_CONTENT | {".yml"}
|
||||
|
||||
@@ -31,7 +36,7 @@ def read_frontmatter(path: Path) -> dict[str, Any]:
|
||||
return cast(dict[str, Any], data)
|
||||
|
||||
|
||||
def create_content(path: Path) -> Content:
|
||||
def create_content(site: Site, path: Path) -> Content:
|
||||
if path.suffix in FRONTMATTER_CONTENT:
|
||||
meta = read_frontmatter(path)
|
||||
elif path.suffix == ".yml":
|
||||
@@ -40,6 +45,6 @@ def create_content(path: Path) -> Content:
|
||||
raise ContentError(f"Unhandled file type for '{path}'")
|
||||
|
||||
if meta["type"] == "article":
|
||||
return Article(path, meta)
|
||||
return Article(site, path, meta)
|
||||
else:
|
||||
raise ContentError(f"Invalid type '{meta['type']}' for '{path}'")
|
||||
|
||||
@@ -13,12 +13,12 @@ else:
|
||||
|
||||
|
||||
class File(Output):
|
||||
def __init__(self, path: Path, source: Path):
|
||||
super().__init__(path)
|
||||
def __init__(self, site: Site, path: Path, source: Path):
|
||||
super().__init__(site, path)
|
||||
self.source = source
|
||||
|
||||
def write(self, site: Site) -> None:
|
||||
dest = site.output_path / self.destination
|
||||
def write(self) -> None:
|
||||
dest = self.site.output_path / self.destination
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(self.source, dest)
|
||||
log.debug("Copied %s -> %s", self.source, dest)
|
||||
|
||||
+20
-17
@@ -17,19 +17,24 @@ else:
|
||||
class Index(Output):
|
||||
def __init__(
|
||||
self,
|
||||
site: Site,
|
||||
kind: Literal["root", "section", "tag"],
|
||||
items: list[Content],
|
||||
page_num: int,
|
||||
total_pages: int,
|
||||
label: str | None,
|
||||
):
|
||||
super().__init__(Index.build_path(kind, page_num, label))
|
||||
super().__init__(site, Index.build_path(kind, page_num, label))
|
||||
self.kind = kind
|
||||
self.items = items
|
||||
self.page_num = page_num
|
||||
self.total_pages = total_pages
|
||||
self.label = label
|
||||
|
||||
def pagination_url(self, n: int) -> str:
|
||||
path = Index.build_path(self.kind, n, self.label)
|
||||
return self.site.by_path[path].url
|
||||
|
||||
@staticmethod
|
||||
def build_path(
|
||||
kind: Literal["root", "section", "tag"],
|
||||
@@ -51,23 +56,17 @@ class Index(Output):
|
||||
path = Path("tags") / label / file
|
||||
return path
|
||||
|
||||
def write(self, site: Site) -> None:
|
||||
template = site.jinja_env.get_template("index.html")
|
||||
html = template.render(
|
||||
site=site,
|
||||
items=self.items,
|
||||
page_num=self.page_num,
|
||||
total_pages=self.total_pages,
|
||||
kind=self.kind,
|
||||
label=self.label,
|
||||
)
|
||||
dest = site.output_path / self.destination
|
||||
def write(self) -> None:
|
||||
template = self.site.jinja_env.get_template("index.html")
|
||||
html = template.render(site=self.site, page=self)
|
||||
dest = self.site.output_path / self.destination
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(html, encoding="utf-8")
|
||||
log.debug("Wrote %s", dest)
|
||||
|
||||
|
||||
def make_index_pages(
|
||||
site: Site,
|
||||
items: list[Content],
|
||||
kind: Literal["root", "section", "tag"],
|
||||
label: str | None,
|
||||
@@ -80,19 +79,23 @@ def make_index_pages(
|
||||
kind,
|
||||
f" ({label})" if label else "",
|
||||
)
|
||||
return [Index(kind, [], 1, 1, label)]
|
||||
return [Index(site, kind, [], 1, 1, label)]
|
||||
num_pages = ceil(len(sorted_items) / items_per_page)
|
||||
return [
|
||||
Index(kind, list(page_items), i + 1, num_pages, label)
|
||||
Index(site, kind, list(page_items), i + 1, num_pages, label)
|
||||
for i, page_items in enumerate(batched(sorted_items, items_per_page))
|
||||
]
|
||||
|
||||
|
||||
def discover_index(site: Site) -> list[Index]:
|
||||
outputs: list[Index] = []
|
||||
outputs.extend(make_index_pages(site.content, "root", None, site.items_per_page))
|
||||
outputs.extend(
|
||||
make_index_pages(site, site.content, "root", None, site.items_per_page)
|
||||
)
|
||||
for section, items in site.by_section.items():
|
||||
outputs.extend(make_index_pages(items, "section", section, site.items_per_page))
|
||||
outputs.extend(
|
||||
make_index_pages(site, items, "section", section, site.items_per_page)
|
||||
)
|
||||
for tag, items in site.by_tag.items():
|
||||
outputs.extend(make_index_pages(items, "tag", tag, site.items_per_page))
|
||||
outputs.extend(make_index_pages(site, items, "tag", tag, site.items_per_page))
|
||||
return outputs
|
||||
|
||||
@@ -12,12 +12,12 @@ else:
|
||||
|
||||
|
||||
class Memory(Output):
|
||||
def __init__(self, destination: Path, content: str):
|
||||
super().__init__(destination)
|
||||
def __init__(self, site: Site, destination: Path, content: str):
|
||||
super().__init__(site, destination)
|
||||
self.content = content
|
||||
|
||||
def write(self, site: Site) -> None:
|
||||
dest = site.output_path / self.destination
|
||||
def write(self) -> None:
|
||||
dest = self.site.output_path / self.destination
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(self.content, encoding="utf-8")
|
||||
log.debug("Wrote %s", dest)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import weakref
|
||||
from typing import TYPE_CHECKING
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
@@ -9,14 +10,22 @@ else:
|
||||
|
||||
|
||||
class Output(ABC):
|
||||
def __init__(self, destination: Path):
|
||||
def __init__(self, site: Site, destination: Path):
|
||||
self._site_ref = weakref.ref(site)
|
||||
self.destination = destination
|
||||
url = "/" + destination.as_posix()
|
||||
url = url.removesuffix("/index.html")
|
||||
if url == "":
|
||||
url = "/"
|
||||
url = site.base_dir + "/" + destination.as_posix()
|
||||
url = url.removesuffix("/index.html") or "/"
|
||||
self.url = url
|
||||
|
||||
@property
|
||||
def site(self) -> Site:
|
||||
obj = self._site_ref()
|
||||
if obj is None:
|
||||
raise ReferenceError(
|
||||
f"Site for output {self.destination} has been garbage collected"
|
||||
)
|
||||
return obj
|
||||
|
||||
@abstractmethod
|
||||
def write(self, site: Site) -> None:
|
||||
def write(self) -> None:
|
||||
pass
|
||||
|
||||
@@ -12,18 +12,20 @@ else:
|
||||
|
||||
|
||||
class Tags(Output):
|
||||
def __init__(self, tags: list[tuple[str, int]]):
|
||||
super().__init__(Path("tags/index.html"))
|
||||
PATH = Path("tags/index.html")
|
||||
|
||||
def __init__(self, site: Site, tags: list[tuple[str, int]]):
|
||||
super().__init__(site, Tags.PATH)
|
||||
self.tags = tags
|
||||
|
||||
def write(self, site: Site) -> None:
|
||||
template = site.jinja_env.get_template("tags.html")
|
||||
html = template.render(site=site, tags=self.tags)
|
||||
dest = site.output_path / self.destination
|
||||
def write(self) -> None:
|
||||
template = self.site.jinja_env.get_template("tags.html")
|
||||
html = template.render(site=self.site, page=self)
|
||||
dest = self.site.output_path / self.destination
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(html, encoding="utf-8")
|
||||
log.debug("Wrote %s", dest)
|
||||
|
||||
|
||||
def discover_tags(site: Site) -> Tags:
|
||||
return Tags(site.tags_by_count)
|
||||
return Tags(site, site.tags_by_count)
|
||||
|
||||
+21
-5
@@ -9,6 +9,8 @@ from omicron.ssg.output import (
|
||||
is_content,
|
||||
create_content,
|
||||
File,
|
||||
Index,
|
||||
Tags,
|
||||
Memory,
|
||||
discover_index,
|
||||
discover_tags,
|
||||
@@ -98,6 +100,20 @@ class Site:
|
||||
)
|
||||
self.by_path[output.destination] = output
|
||||
|
||||
def home_url(self) -> str:
|
||||
return self.base_dir or "/"
|
||||
|
||||
def section_url(self, section: str) -> str:
|
||||
path = Index.build_path("section", 1, section)
|
||||
return self.by_path[path].url
|
||||
|
||||
def tag_url(self, tag: str) -> str:
|
||||
path = Index.build_path("tag", 1, tag)
|
||||
return self.by_path[path].url
|
||||
|
||||
def tags_url(self) -> str:
|
||||
return self.by_path[Tags.PATH].url
|
||||
|
||||
def update_tags_by_count(self) -> None:
|
||||
tags = [(tag, len(items)) for tag, items in self.by_tag.items()]
|
||||
tags.sort(key=lambda x: x[1], reverse=True)
|
||||
@@ -110,7 +126,7 @@ class Site:
|
||||
for file in assets_path.rglob("*"):
|
||||
if file.is_file():
|
||||
path = Path("assets") / file.relative_to(assets_path)
|
||||
asset = File(path, file)
|
||||
asset = File(self, path, file)
|
||||
self.add_by_path(asset)
|
||||
self.other_outputs.append(asset)
|
||||
log.debug("Discovered template asset %s", path)
|
||||
@@ -118,13 +134,13 @@ class Site:
|
||||
def discover(self) -> None:
|
||||
log.info("Discovering content...")
|
||||
self.discover_assets()
|
||||
pygments = Memory(Path("assets/pygments.css"), highlight_style())
|
||||
pygments = Memory(self, Path("assets/pygments.css"), highlight_style())
|
||||
self.other_outputs.append(pygments)
|
||||
self.add_by_path(pygments)
|
||||
content_path = self.site_path / "content"
|
||||
for file in content_path.rglob("*"):
|
||||
if file.is_file() and is_content(file):
|
||||
content = create_content(file)
|
||||
content = create_content(self, file)
|
||||
self.add_by_path(content)
|
||||
self.add_by_section(content)
|
||||
self.add_by_tag(content)
|
||||
@@ -149,6 +165,6 @@ class Site:
|
||||
self.discover()
|
||||
self.output_path.mkdir(parents=True, exist_ok=True)
|
||||
for content in self.content:
|
||||
content.write(self)
|
||||
content.write()
|
||||
for output in self.other_outputs:
|
||||
output.write(self)
|
||||
output.write()
|
||||
|
||||
@@ -1,31 +1,29 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ article.title }} — {{ site.name }}{% endblock %}
|
||||
|
||||
{% block head %}<link rel="canonical" href="{{ site.origin }}{{ site.base_dir }}{{ article.url }}">{% endblock %}
|
||||
{% block title %}{{ page.title }} — {{ site.name }}{% endblock %}
|
||||
|
||||
{% block breadcrumb %}
|
||||
<nav aria-label="breadcrumb">
|
||||
<a href="{{ site.base_dir or "/" }}">{{ site.name }}</a> ›
|
||||
<a href="{{ site.base_dir }}/{{ article.section }}">{{ article.section }}</a> ›
|
||||
{{ article.title }}
|
||||
<a href="{{ site.home_url() }}">{{ site.name }}</a> ›
|
||||
<a href="{{ site.section_url(page.section) }}">{{ page.section }}</a> ›
|
||||
{{ page.title }}
|
||||
</nav>
|
||||
{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
<article>
|
||||
<header>
|
||||
<h1>{{ article.title }}</h1>
|
||||
<h1>{{ page.title }}</h1>
|
||||
<p>
|
||||
<time datetime="{{ article.created }}">{{ article.created }}</time>
|
||||
{% if article.updated %}
|
||||
· Updated <time datetime="{{ article.updated }}">{{ article.updated }}</time>
|
||||
<time datetime="{{ page.created }}">{{ page.created }}</time>
|
||||
{% if page.updated %}
|
||||
· Updated <time datetime="{{ page.updated }}">{{ page.updated }}</time>
|
||||
{% endif %}
|
||||
</p>
|
||||
{% if article.tags %}
|
||||
{% if page.tags %}
|
||||
<ul>
|
||||
{% for tag in article.tags | sort %}
|
||||
<li><a href="{{ site.base_dir }}/tags/{{ tag }}">{{ tag }}</a></li>
|
||||
{% for tag in page.tags | sort %}
|
||||
<li><a href="{{ site.tag_url(tag) }}">{{ tag }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
|
||||
@@ -6,11 +6,12 @@
|
||||
<title>{% block title %}{{ site.name }}{% endblock %}</title>
|
||||
<link rel="stylesheet" href="{{ site.base_dir }}/assets/style.css">
|
||||
<link rel="stylesheet" href="{{ site.base_dir }}/assets/pygments.css">
|
||||
<link rel="canonical" href="{{ site.origin }}{{ page.url }}">
|
||||
{% block head %}{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
{% block breadcrumb %}<a href="{{ site.base_dir or "/" }}">{{ site.name }}</a>{% endblock %}
|
||||
{% block breadcrumb %}<a href="{{ site.home_url() }}">{{ site.name }}</a>{% endblock %}
|
||||
</header>
|
||||
<main>
|
||||
{% block main %}{% endblock %}
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
{% extends "base.html" %}
|
||||
{% set base_path = ("/" + label) if kind == "section" else (("/tags/" + label) if kind == "tag" else "") %}
|
||||
{% set heading = label or "" %}
|
||||
|
||||
{% block title %}{% if heading %}{{ heading }} — {% endif %}{{ site.name }}{% if page_num > 1 %} — Page {{ page_num }}{% endif %}{% endblock %}
|
||||
{% block title %}{% if page.label %}{{ page.label }} — {% endif %}{{ site.name }}{% if page.page_num > 1 %} — Page {{ page.page_num }}{% endif %}{% endblock %}
|
||||
|
||||
{% block head %}
|
||||
<link rel="canonical" href="{{ site.origin }}{{ site.base_dir }}{% if page_num == 1 %}{{ base_path or "/" }}{% else %}{{ base_path }}/page-{{ page_num }}.html{% endif %}">
|
||||
{% if page_num > 1 %}<meta name="robots" content="noindex, follow">{% endif %}
|
||||
{% if page.page_num > 1 %}<meta name="robots" content="noindex, follow">{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block breadcrumb %}
|
||||
{% if kind == "section" %}
|
||||
{% if page.kind == "section" %}
|
||||
<nav aria-label="breadcrumb">
|
||||
<a href="{{ site.base_dir or "/" }}">{{ site.name }}</a> ›
|
||||
{{ label }}
|
||||
<a href="{{ site.home_url() }}">{{ site.name }}</a> ›
|
||||
{{ page.label }}
|
||||
</nav>
|
||||
{% elif kind == "tag" %}
|
||||
{% elif page.kind == "tag" %}
|
||||
<nav aria-label="breadcrumb">
|
||||
<a href="{{ site.base_dir or "/" }}">{{ site.name }}</a> ›
|
||||
<a href="{{ site.base_dir }}/tags">Tags</a> ›
|
||||
{{ label }}
|
||||
<a href="{{ site.home_url() }}">{{ site.name }}</a> ›
|
||||
<a href="{{ site.tags_url() }}">Tags</a> ›
|
||||
{{ page.label }}
|
||||
</nav>
|
||||
{% else %}
|
||||
{{ super() }}
|
||||
@@ -27,28 +24,28 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
{% if heading %}<h1>{{ heading }}</h1>{% endif %}
|
||||
{% for item in items %}
|
||||
{% if page.label %}<h1>{{ page.label }}</h1>{% endif %}
|
||||
{% for item in page.items %}
|
||||
<article>
|
||||
<header>
|
||||
<h2><a href="{{ site.base_dir }}{{ item.url }}">{{ item.title }}</a></h2>
|
||||
<h2><a href="{{ item.url }}">{{ item.title }}</a></h2>
|
||||
<time datetime="{{ item.created }}">{{ item.created }}</time>
|
||||
</header>
|
||||
{% if item.summary %}<p>{{ item.summary }}</p>{% endif %}
|
||||
</article>
|
||||
{% endfor %}
|
||||
{% if total_pages > 1 %}
|
||||
{% if page.total_pages > 1 %}
|
||||
<nav>
|
||||
{% if page_num > 1 %}
|
||||
<a href="{{ site.base_dir }}{% if page_num - 1 == 1 %}{{ base_path or "/" }}{% else %}{{ base_path }}/page-{{ page_num - 1 }}.html{% endif %}">← Newer</a>
|
||||
{% if page.page_num > 1 %}
|
||||
<a href="{{ page.pagination_url(page.page_num - 1) }}">← Newer</a>
|
||||
{% endif %}
|
||||
{% for p in range(1, total_pages + 1) %}
|
||||
{% if p == page_num %}<strong>{{ p }}</strong>
|
||||
{% else %}<a href="{{ site.base_dir }}{% if p == 1 %}{{ base_path or "/" }}{% else %}{{ base_path }}/page-{{ p }}.html{% endif %}">{{ p }}</a>
|
||||
{% for p in range(1, page.total_pages + 1) %}
|
||||
{% if p == page.page_num %}<strong>{{ p }}</strong>
|
||||
{% else %}<a href="{{ page.pagination_url(p) }}">{{ p }}</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% if page_num < total_pages %}
|
||||
<a href="{{ site.base_dir }}{{ base_path }}/page-{{ page_num + 1 }}.html">Older →</a>
|
||||
{% if page.page_num < page.total_pages %}
|
||||
<a href="{{ page.pagination_url(page.page_num + 1) }}">Older →</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
|
||||
@@ -2,13 +2,9 @@
|
||||
|
||||
{% block title %}Tags — {{ site.name }}{% endblock %}
|
||||
|
||||
{% block head %}
|
||||
<link rel="canonical" href="{{ site.origin }}{{ site.base_dir }}/tags">
|
||||
{% endblock %}
|
||||
|
||||
{% block breadcrumb %}
|
||||
<nav aria-label="breadcrumb">
|
||||
<a href="{{ site.base_dir or "/" }}">{{ site.name }}</a> ›
|
||||
<a href="{{ site.home_url() }}">{{ site.name }}</a> ›
|
||||
Tags
|
||||
</nav>
|
||||
{% endblock %}
|
||||
@@ -16,8 +12,8 @@
|
||||
{% block main %}
|
||||
<h1>Tags</h1>
|
||||
<ul>
|
||||
{% for tag, count in tags %}
|
||||
<li><a href="{{ site.base_dir }}/tags/{{ tag }}">{{ tag }}</a> ({{ count }})</li>
|
||||
{% for tag, count in page.tags %}
|
||||
<li><a href="{{ site.tag_url(tag) }}">{{ tag }}</a> ({{ count }})</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user