2019-02-17 10:28:43 +01:00
|
|
|
import os
|
2018-11-15 13:57:53 +01:00
|
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
|
|
|
|
|
|
def setup(app):
|
|
|
|
"""Setup connects events to the sitemap builder"""
|
2021-03-07 19:29:02 +01:00
|
|
|
app.connect("html-page-context", add_html_link)
|
|
|
|
app.connect("build-finished", create_sitemap)
|
2018-11-15 13:57:53 +01:00
|
|
|
app.sitemap_links = []
|
2019-07-28 12:41:15 +02:00
|
|
|
|
2021-03-07 19:29:02 +01:00
|
|
|
is_production = os.getenv("PRODUCTION") == "YES"
|
2019-07-28 12:41:15 +02:00
|
|
|
|
2021-03-07 19:29:02 +01:00
|
|
|
return {
|
|
|
|
"version": "1.0.0",
|
|
|
|
"parallel_read_safe": True,
|
|
|
|
"parallel_write_safe": not is_production,
|
|
|
|
}
|
2018-11-15 13:57:53 +01:00
|
|
|
|
|
|
|
|
|
|
|
def add_html_link(app, pagename, templatename, context, doctree):
|
|
|
|
"""As each page is built, collect page names for the sitemap"""
|
|
|
|
app.sitemap_links.append(pagename + ".html")
|
|
|
|
|
|
|
|
|
|
|
|
def create_sitemap(app, exception):
|
|
|
|
"""Generates the sitemap.xml from the collected HTML page links"""
|
|
|
|
root = ET.Element("urlset")
|
|
|
|
root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
|
2019-05-15 10:54:51 +02:00
|
|
|
app.sitemap_links.sort()
|
2018-11-15 13:57:53 +01:00
|
|
|
|
|
|
|
for link in app.sitemap_links:
|
|
|
|
url = ET.SubElement(root, "url")
|
|
|
|
priority = 0.5
|
2021-03-07 19:29:02 +01:00
|
|
|
if link == "index.html":
|
2018-11-15 13:57:53 +01:00
|
|
|
priority = 1.0
|
2021-03-07 19:29:02 +01:00
|
|
|
link = ""
|
|
|
|
elif link.endswith("index.html"):
|
2019-02-17 10:28:43 +01:00
|
|
|
priority += 0.25
|
2021-03-07 19:29:02 +01:00
|
|
|
link = link[: -len("index.html")]
|
|
|
|
if link.endswith(".html"):
|
|
|
|
link = link[: -len(".html")]
|
|
|
|
ET.SubElement(url, "loc").text = app.builder.config.html_baseurl + "/" + link
|
2018-11-15 13:57:53 +01:00
|
|
|
ET.SubElement(url, "priority").text = str(priority)
|
|
|
|
|
2019-02-17 10:28:43 +01:00
|
|
|
filename = os.path.join(app.outdir, "sitemap.xml")
|
2021-03-07 19:29:02 +01:00
|
|
|
ET.ElementTree(root).write(
|
|
|
|
filename, xml_declaration=True, encoding="utf-8", method="xml"
|
|
|
|
)
|
|
|
|
|
|
|
|
with open(os.path.join(app.builder.outdir, "robots.txt"), "wt") as f:
|
|
|
|
if os.getenv("PRODUCTION") != "YES":
|
|
|
|
f.write("User-agent: *\nDisallow: /\n")
|
2019-02-17 10:37:21 +01:00
|
|
|
else:
|
2021-03-07 19:29:02 +01:00
|
|
|
f.write(
|
|
|
|
"User-agent: *\nDisallow: \n\n"
|
|
|
|
"Sitemap: https://esphome.io/sitemap.xml\n"
|
|
|
|
)
|