"""Document-backed pages: /sources/, /logos/, /about/, /data/ and sub-pages.
Markdown goes through olt.md; relative links are rewritten to site pages.
Repository paths with no site page become repository links when repo_url
is set, and plain text otherwise (never a dead link).
"""
import collections
import os
import re
from . import common, elevation, facets, md, words
from .markup import Markup, esc
REAL_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def read_doc(repo_root, relpath):
"""Read a repository document, falling back to this checkout's copy."""
for base in (repo_root, REAL_ROOT):
path = os.path.join(base, *relpath.split("/"))
if os.path.isfile(path):
with open(path, encoding="utf-8") as f:
return f.read()
return ""
_PAGE_MAP = {
"docs/schema.md": "/data/schema/",
"schema.md": "/data/schema/",
"notice.md": "/logos/",
"sources.md": "/sources/",
"contributing.md": "/about/",
"changelog.md": "/data/changelog/",
"readme.md": "/about/",
"license": "/licences/LICENSE",
"trails.csv": "/data/trails.csv",
"trails.json": "/data/trails.json",
"index.geojson": "/data/index.geojson",
"overview.geojson": "/data/overview.geojson",
}
def _classify(href, site):
"""Site href for a Markdown destination, or None to drop the link."""
if not href or href.startswith(("#", "/", "http://", "https://", "mailto:", "tel:")):
return href
path, _, frag = href.partition("#")
norm = path[2:] if path.startswith("./") else path
while norm.startswith("../"):
norm = norm[3:]
key = norm.lower()
if key in _PAGE_MAP:
return _PAGE_MAP[key] + (f"#{frag}" if frag else "")
if key.startswith("licenses/") and key.endswith(".txt"):
return "/licences/" + norm.split("/", 1)[1] + (f"#{frag}" if frag else "")
if site.repo_url:
return site.blob_url(norm) + (f"#{frag}" if frag else "")
return None
def make_link_rewrite(site):
"""md.render link_rewrite: the site href, or None (md.py then keeps the link's text only)."""
return lambda href: _classify(href, site)
def _link_text(html, phrase, url):
"""Link each occurrence of phrase in the text of html (not inside a tag or an existing link)."""
out, depth = [], 0
for part in re.split(r"(<[^>]*>)", html):
if part.startswith("<"):
if re.match(r"]", part):
depth += 1
elif part.startswith("{phrase}')
out.append(part)
return "".join(out)
def link_requests(html, site):
"""Link the documents' own words asking readers to open an issue or to write
to the maintainers, when site.toml says where (repo_url, contact_url).
The wording is left as the documents have it; with neither set, nothing changes."""
issue = site.issues_url or site.contact_url
contact = site.contact_url or site.repo_url
if issue:
for phrase in ("Open an issue", "open an issue", "opening an issue"):
html = _link_text(html, phrase, issue)
if contact:
for phrase in ("writing to the repository maintainers", "write to the repository maintainers"):
html = _link_text(html, phrase, contact)
return Markup(html)
def render_doc(text, site, *, heading_offset=0, drop_h1=False):
"""Render Markdown to HTML with rewritten links and scrollable tables."""
if drop_h1:
text = re.sub(r"\A# [^\n]*\n+", "", text, count=1)
html = md.render(text, heading_offset=heading_offset,
link_rewrite=make_link_rewrite(site))
html = html.replace("
", '
')
html = html.replace("
", "
")
return Markup(html)
def sections_map(text):
return dict(md.split_sections(text, level=2))
def render_sections(text, site, titles, *, level=2):
"""Render named level-2 sections only, each under its own heading."""
found = sections_map(text) if level == 2 else {}
out = []
for title in titles:
body = found.get(title)
if body is None:
continue
out.append(md.render(f"## {title}\n\n{body}", link_rewrite=make_link_rewrite(site)))
html = "\n".join(out)
html = html.replace("
", '
')
html = html.replace("
", "
")
return Markup(html)
def _record_links(recs):
"""The records as a link list, one name per line."""
return Markup('
")
def _group_by(records, keyfn):
groups = collections.defaultdict(list)
for r in records:
groups[keyfn(r)].append(r)
for recs in groups.values():
recs.sort(key=lambda r: r["name"].lower())
return groups
def sources_page(records, site, repo_root):
"""(title, description, body) for /sources/."""
by_licence = _group_by(records, lambda r: r.get("source", {}).get("licence", "") or "unknown")
by_source = _group_by(records, lambda r: r.get("source", {}).get("line_source", "") or "none (no line included)")
by_status = _group_by(records, lambda r: r.get("source", {}).get("status", "") or "none")
def measured(recs):
return sum(1 for r in recs if r.get("verification", {}).get("verified"))
n_measured = measured(records)
status_cells = (f'
Track measured
{n_measured}Records whose track was '
f'downloaded and measured (verification), whatever its source
')
for key in ("verified", "osm-only", "found", "none"):
recs = by_status.get(key, [])
k = measured(recs)
of_these = (f"; {k} of these measured" if k and k < len(recs) else
"; all measured" if k and k == len(recs) and key != "verified" else "")
status_cells += (f'
')
other = [k for k in by_status if k not in ("verified", "osm-only", "found", "none")]
def group_rows(groups, label_of):
rows = ""
for key in sorted(groups, key=lambda k: (-len(groups[k]), str(k).lower())):
recs = groups[key]
lines = sum(1 for r in recs if common.has_line(r))
rows += (f'
{label_of(key)}
{len(recs)}
'
f'
{lines}
{_record_links(recs)}
')
return rows
def source_label(k):
# A record with no track holds a value such as "none (no line included)"; say it in words.
if str(k).strip().lower().startswith(("none (no line", "none (no track")):
return "None (no track included)"
return esc(k)
def lic_label(k):
return Markup(f'{esc(words.label(words.LICENCES, k))} {esc(k)}')
head = ('
{0}
Records
'
'
With a track
Trails
')
elev_models = {}
for r in records:
src = (elevation.get(r) or {}).get("source") or {}
if src.get("attribution"):
key = (src.get("model", ""), src.get("url", ""), src["attribution"])
elev_models[key] = elev_models.get(key, 0) + 1
elev_credit = ""
if elev_models:
items = ""
for (model, url, attribution), n in sorted(elev_models.items()):
model_html = (f'{esc(model)}' if url else esc(model)) if model else "The elevation model"
items += (f'
{model_html}, used for {n} trail{"s" if n != 1 else ""}.
'
f'
{esc(attribution)}
')
elev_credit = (f'
Elevation model
'
f'
The elevation figures and profiles on the trail pages were computed '
f'from each track and this model. Its credit, as it gives it:
{items}
')
computed = f"""
At a glance
Counted from the {len(records)} records. Each trail page names its own source, licence and credit.
The source status says where a track was looked for; whether it was measured is counted separately.
{status_cells}
{f'
Other source status values: {esc(", ".join(map(str, other)))}.
No logo file is included for the other records: {counts["no-logo-exists"]} are recorded as
having no logo (no-logo-exists) and {counts["logo-not-found"]} as
logo not found (logo-not-found).
"""
return "Logos", "Trail logos, their holders, and how a holder can ask for removal.", Markup(body)
BREAD = Markup('