"""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'
Source status: {esc(words.label(words.SOURCE_STATUS, key))}
' f'
{len(recs)}{esc(words.meaning(words.SOURCE_STATUS, key))}{esc(of_these)}
') 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 trackTrails') 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)))}.

' if other else ""}

By licence

{head.format("Licence")} {group_rows(by_licence, lic_label)}

By track source

{head.format("Track source")} {group_rows(by_source, source_label)}
{elev_credit}
""" doc_html = render_doc(read_doc(repo_root, "SOURCES.md"), site, drop_h1=True) body = (f'
{BREAD}
  • Sources
  • ' f'

    Sources

    ' f'

    Where the tracks come from, and the terms each source states.

    ' f'
    {computed}' f'
    {doc_html}
    ') return "Sources", "Where each trail track comes from: licences, track sources and source terms.", Markup(body) def logos_page(records, site, repo_root): """(title, description, body) for /logos/.""" notice_html = link_requests(render_sections(read_doc(repo_root, "NOTICE.md"), site, ["Logos and marks", "Removal"]), site) with_logo = [r for r in sorted(records, key=lambda r: r["name"].lower()) if "shield" in r["derived"]["files"]] cards = "" for r in with_logo: sh = r.get("shield", {}) src = sh.get("logo_source", "") if src.startswith(("http://", "https://")): src_html = Markup(f'{esc(src)}') elif src: src_html = esc(src) else: src_html = Markup("Not recorded") cards += f"""
  • {common.plate(r, size="lg", link=True, alt="")}

    {common.name(r)}

    Holder
    {esc(sh.get("logo_owner", "") or "Not recorded")}
    Taken from
    {src_html}
  • """ counts = collections.Counter(r.get("shield", {}).get("status", "") for r in records) body = f"""
    {BREAD}
  • Logos
  • Logos

    Logos are shown only to identify each trail. They belong to their holders.

    {notice_html}{f'

    Ask for a track or logo to be removed, or its credit changed.

    ' if site.is_github else ""}

    Every logo in the dataset

    {len(with_logo)} records include a logo file.

    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('

    Data and downloads

    Bulk files, the stable per-trail URLs, and the licences.

    Bulk downloads

    {len(records)} records. Sizes are this build's.

    {rows}
    FileWhat it holdsSize

    Each track in the archives keeps its source’s terms and needs its source’s credit, as given in the trail’s release.txt; trails.csv gives each record’s licence too.

    Per-trail files

    Every record has a stable directory. Replace <id> with a record id (for example long-trail): /trails/<id>/<id>.geojson, /trails/<id>/<id>.gpx, /trails/<id>/<id>-alternates.geojson (and .gpx), /trails/<id>/map.json, /trails/<id>/trail.toml and /trails/<id>/release.txt. The trail page is /trails/<id>/. Track files exist only where the record includes a track; the record says why when it does not.

    {prow}
    File under /trails/<id>/What it holds

    Licences

    {lrow}
    WhatTermsText

    Licence texts: CC0-1.0 (LICENSE), CC0-1.0.txt, MIT.txt, CC-BY-4.0.txt, ODbL-1.0.txt.

    Reference

    """ return "Data", "Bulk downloads, stable per-trail file URLs, the record schema and licences.", Markup(body) def schema_page(site, repo_root): doc_html = render_doc(read_doc(repo_root, "docs/schema.md"), site, drop_h1=True) body = f"""
    {BREAD}
  • Data
  • Record schema
  • Reference

    Record schema

    {doc_html}
    """ return "Record schema", "Every field of a trail record (trail.toml) and what it means.", Markup(body) def changelog_page(site, repo_root): doc_html = render_doc(read_doc(repo_root, "CHANGELOG.md"), site, drop_h1=True) body = f"""
    {BREAD}
  • Data
  • Changelog
  • Reference

    Changelog

    {doc_html}
    """ return "Changelog", "What changed in the dataset, release by release.", Markup(body) def copy_licences(out_dir, repo_root): """Copy LICENSE and LICENSES/*.txt to /licences/. Returns file names copied.""" import shutil dest = os.path.join(out_dir, "licences") os.makedirs(dest, exist_ok=True) copied = [] for base in (repo_root, REAL_ROOT): lic = os.path.join(base, "LICENSE") if os.path.isfile(lic): shutil.copyfile(lic, os.path.join(dest, "LICENSE")) copied.append("LICENSE") break for base in (repo_root, REAL_ROOT): d = os.path.join(base, "LICENSES") if os.path.isdir(d): for name in sorted(os.listdir(d)): if name.endswith(".txt"): shutil.copyfile(os.path.join(d, name), os.path.join(dest, name)) copied.append(name) break return copied