39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
import logging
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING
|
|
from xml.etree.ElementTree import Element, ElementTree, SubElement
|
|
from omicron.ssg.output.output import Output
|
|
from omicron.ssg.output.content import Content
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
if TYPE_CHECKING:
|
|
from omicron.ssg.site import Site
|
|
else:
|
|
Site = "omicron.ssg.site.Site"
|
|
|
|
|
|
class Sitemap(Output):
|
|
PATH = Path("sitemap.xml")
|
|
NAMESPACE = "http://www.sitemaps.org/schemas/sitemap/0.9"
|
|
|
|
def __init__(self, site: Site):
|
|
super().__init__(site, Sitemap.PATH)
|
|
|
|
def write(self) -> None:
|
|
urlset = Element("urlset", xmlns=Sitemap.NAMESPACE)
|
|
for entry in self.site.by_path.values():
|
|
if not entry.in_sitemap:
|
|
continue
|
|
|
|
url = SubElement(urlset, "url")
|
|
SubElement(url, "loc").text = f"{self.site.config.origin}{entry.url}"
|
|
if isinstance(entry, Content):
|
|
lastmod = entry.updated or entry.created
|
|
SubElement(url, "lastmod").text = lastmod.isoformat()
|
|
|
|
dest = self.site.output_path / self.destination
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
ElementTree(urlset).write(dest, encoding="utf-8", xml_declaration=True)
|
|
log.debug("Wrote %s", dest)
|