git @ Cat's Eye Technologies The-Glosscubator / master script / build_readmes / formatters.py
master

Tree @master (Download .tar.gz)

formatters.py @masterraw · history · blame

# SPDX-FileCopyrightText: Chris Pressey, the original author of this work, has dedicated it to the public domain.
# For more information, please refer to <https://unlicense.org/>
# SPDX-License-Identifier: Unlicense

"""
Handles all formatting of different types of entries (webpages, books, papers, etc.)
"""
import re

from argparse import ArgumentParser
import json
import re
import os
import subprocess
from collections import defaultdict

from feedmark.loader import read_document_from


UNLICENSE_HEADER = """<!--
{}-FileCopyrightText: Chris Pressey, the original author of this work, has dedicated it to the public domain.

{}-License-Identifier: CC0-1.0
-->
""".format('SPDX', 'SPDX')


def make_anchor(title):
    return re.sub(
        r'[-\/\s]',
        '-',
        re.sub(r'[^\w\s\/-]', '', title).strip().lower()
    )


def format_see_also_link(topic, parent=".."):
    title = topic  # TODO no, get this from caller
    return (
        '[{}]({}/{}/README.md#{})'.format(
            title,
            parent,
            topic.replace(' ', '%20'),
            make_anchor(title)
        )
    )


def format_see_also_links(see_also, **kwargs):
    return ', '.join([format_see_also_link(topic, **kwargs) for topic in see_also])


def format_webpage(webpage):
    url = webpage["properties"].get("url")
    is_heading = webpage["properties"].get("is-heading")
    if url:
        return "[{}]({})".format(
            webpage["title"],
            url,
        )
    elif is_heading:
        return "### {}".format(webpage["title"])
    else:
        raise NotImplementedError("ouch")


def format_paper(paper):
    url = paper["properties"].get("url")
    if url:
        return "[{}]({})".format(
            paper["title"],
            url,
        )
    else:
        onlines = paper["properties"].get("online", [])
        online_at = " (online @ {})".format(', '.join(onlines)) if onlines else ""

        return "{}{}".format(
            paper["title"], online_at,
        )


def format_repo(repo):
    url = repo["properties"].get("url")
    return "[{}]({})".format(
        repo["title"],
        url,
    )


def format_book(book):
    onlines = book["properties"].get("online", [])
    online_at = " (online @ {})".format(', '.join(onlines)) if onlines else ""

    borrows = book["properties"].get("borrow", [])
    borrow_at = " (borrow @ {})".format(', '.join(borrows)) if borrows else ""

    borrowwpds = book["properties"].get("borrow-with-print-disabilities", [])
    borrowwpd_at = " (borrow with print disabilities @ {})".format(', '.join(borrowwpds)) if borrowwpds else ""

    return "{}{}{}{}".format(
        book["title"], online_at, borrow_at, borrowwpd_at
    )


def format_entry(entry, formatter_function, source_topic=None):
    s = ""
    if source_topic:
        s += "_(in {})_ ".format(format_see_also_link(source_topic))
    s += formatter_function(entry)
    rating = entry["properties"].get("rating", "TODO")
    if rating != "TODO" and not entry["properties"].get("url", "").startswith("https://en.wikipedia"):
        if rating == "1":
            s += " ★"
        elif rating == "2":
            s += " ★★"
        elif rating == "3":
            s += " ★★★"
        elif rating == "0":
            pass
        elif rating == "classic":
            s += " 🏛️"
        else:
            raise NotImplementedError(repr(rating))
    commentary_link = entry["properties"].get("commentary_link", None)
    if commentary_link:
        s += " [💭]({})".format(commentary_link)
    s += "\n\n"
    return s