esphome-docs/sitemap.py

52 lines
1.8 KiB
Python
Raw Normal View History

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"""
app.connect('html-page-context', add_html_link)
app.connect('build-finished', create_sitemap)
app.sitemap_links = []
2019-05-15 10:54:51 +02:00
return {"version": "1.0.0",
"parallel_read_safe": True,
"parallel_write_safe": True}
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
2019-02-07 14:19:22 +01:00
if link == 'index.html':
2018-11-15 13:57:53 +01:00
priority = 1.0
2019-02-17 10:28:43 +01:00
link = ''
elif link.endswith('index.html'):
priority += 0.25
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")
2018-11-15 13:57:53 +01:00
ET.ElementTree(root).write(filename,
xml_declaration=True,
encoding='utf-8',
method="xml")
2019-02-17 10:28:43 +01:00
2019-02-17 10:37:21 +01:00
with open(os.path.join(app.builder.outdir, 'robots.txt'), 'wt') as f:
if os.getenv('PRODUCTION') != 'YES':
2019-02-17 10:28:43 +01:00
f.write('User-agent: *\nDisallow: /\n')
2019-02-17 10:37:21 +01:00
else:
f.write('User-agent: *\nDisallow: \n\n'
'Sitemap: https://esphome.io/sitemap.xml\n')