Esempio n. 1
0
def get_news() -> List[Dict[str, Any]]:
    """Gets the context for the newslist from the article files in `news/`

    Returns:
        List[Dict[str, any]]: One Dict per news article with keys and values:
            `title` (str): article title (plain text)
            `lede` (str): article lede (HTML)
            `date` (datetime.date): date of initial publication
            `article_name`: filename of the article file (Jinja or Markdown)
            with the extension removed.
    """
    news = []
    for filename in os.listdir(os.path.join(ROOT_DIR, "templates", "content", "news")):
        if filename.endswith(".md"):
            template_name = os.path.join(
                "content", "news", removesuffix(filename, ".md") + ".html.jinja2"
            )
        else:
            template_name = os.path.join("content", "news", filename)
        title = get_template_attribute(template_name, "title")
        lede = get_template_attribute(template_name, "lede")
        published = date.fromisoformat(filename[:10])
        news.append(
            {
                "title": title.strip(),
                "lede": lede.strip(),
                "date": published,
                "article_name": removesuffix(removesuffix(filename, ".md"), ".html.jinja2"),
            }
        )
        if len(lede) == 0:
            print("No lede found for", filename)
    news.sort(key=itemgetter("date"), reverse=True)
    return news
Esempio n. 2
0
def get_all_routes() -> List[str]:
    """Provided for future contingency but currently unused; explicitly provides
    a list of all URL routes (including static routes) that flask_frozen can
    call without relying on discovery via url_for

    Returns:
        List[str]: URL routes
    """
    # not currently used
    routes = []

    for filename in os.listdir(os.path.join(ROOT_DIR, "templates", "content")):
        if filename.endswith((".html.jinja2", ".xml.jinja2")):
            routes.append("/" + removesuffix(filename, ".jinja2"))

    for filename in os.listdir(
            os.path.join(ROOT_DIR, "templates", "content", "news")):
        routes.append(
            "/news/" +
            removesuffix(removesuffix(filename, ".html.jinja2"), ".md") +
            ".html")

    routes.extend(list(get_server_page_routes()))

    routes.extend(list(get_static_routes()))

    return routes
Esempio n. 3
0
def get_server_page_routes() -> Generator[str, None, None]:
    """Yields URL routes for the server pages, since they're not linked from the main website.

    Yields:
        Generator[str, None, None]: URL routes
    """
    for filename in os.listdir(
            os.path.join(ROOT_DIR, "templates", "content", "servers")):
        yield "/servers/" + removesuffix(
            removesuffix(filename, ".html.jinja2"), ".md").replace(
                os.sep, "/") + ".html"
Esempio n. 4
0
    def get_source(
            self, environment: Environment,
            template: str) -> Tuple[str, str, Optional[Callable[[], bool]]]:
        """Superclass override (https://jinja.palletsprojects.com/en/3.0.x/api/#loaders)

        When told to find a template with name `foo.html.jinja2`, will attempt to find a template
        with name `foo.md` and wrangle it into Jinja format.

        Raises:
            TemplateNotFound: [description]

        Returns:
            Tuple[str,str,Optional[Callable[[],bool]]]: (source, filename, is_uptodate);
                `source` is the Jinja template source,
                `filename` is the path to the file that Jinja can use for stack
                traces,
                `is_uptodate` (if provided) is used for template reloading; if
                it returns `False` then the template is reloaded.
        """

        template = template.replace("/", os.sep)
        # `template` (as given in arguments) is a Jinja path (/ on all paths)
        # from hereon we can assume it is an OS-compatible path.

        if self.prefix_allowlist is None or not template.startswith(
                self.prefix_allowlist):
            raise TemplateNotFound(template)

        filename = os.path.join(self.searchpath,
                                removesuffix(template, ".html.jinja2") + ".md")
        if os.path.exists(filename):
            with open(filename, encoding='utf-8') as fd:
                metadata, content = frontmatter.parse(fd.read())
                # NB: readlines() returns a list of lines WITH \n at the end

                title = metadata["title"]

            source = ("""
            {% extends "article.html.jinja2" %}
            {% block title %}""" + title + """{% endblock title %}
            {% set parts | split_lede %}{% filter markdown() %}{% raw -%}""" +
                      content + """{% endraw %}{% endfilter %}{% endset %}
            {% block lede %}{{ parts.lede }}{% endblock lede %}
            {% block text %}{{ parts.text }}{% endblock text %}
            """)

            return (source, filename, None)
            # TODO: add 3rd tuple argument for autoreloading
        else:
            raise TemplateNotFound(template)
Esempio n. 5
0
    def test_suffix(self):
        """Tests for hacksoc_org.util.removesuffix"""
        self.assertEqual(removesuffix("Hello, World!", ""), "Hello, World!")
        self.assertEqual(removesuffix("Hello, World!", "World!"), "Hello, ")
        self.assertEqual(removesuffix("Hello, World!", "Hello, World!"), "")
        self.assertEqual(removesuffix("Hello, World!", "World"),
                         "Hello, World!")

        self.assertEqual(removesuffix("", "World!"), "")
        self.assertEqual(removesuffix("World!", "Hello, World!"), "World!")
Esempio n. 6
0
    def get_source(
        self, environment: "Environment", template: str
    ) -> Tuple[str, Optional[str], Optional[Callable[[], bool]]]:
        """Superclass override (https://jinja.palletsprojects.com/en/3.0.x/api/#loaders)

        When told to find a template with name `foo.html.jinja2`, will attempt to find a template
        with name `foo.md` and wrangle it into Jinja format.

        Raises:
            TemplateNotFound: [description]

        Returns:
            Tuple[str,str,Optional[Callable[[],bool]]]: (source, filename, is_uptodate);
                `source` is the Jinja template source,
                `filename` is the path to the file that Jinja can use for stack traces,
                `is_uptodate` (if provided) is used for template reloading; if it returns `False`
                then the template is reloaded.
        """
        template = template.replace("/", os.sep)
        # `template` (as given in arguments) is a Jinja path (/ on all paths)
        # from hereon we can assume it is an OS-compatible path.

        if self.prefix_allowlist is None or not template.startswith(
                self.prefix_allowlist):
            raise TemplateNotFound(template)

        filename = os.path.join(self.path,
                                removesuffix(template, ".html.jinja2") + ".md")

        if os.path.exists(filename):
            with open(filename, encoding='utf-8') as fd:
                metadata, markdown = frontmatter.parse(fd.read())
                assert isinstance(metadata, dict)
                source = """
                    {% extends "server.html.jinja2" %}
                """
                for k, v in metadata.items():
                    source += f"{{% set {k} = {repr(v)} %}}\n"

                source += ("""{% block body %}{% filter markdown() %}\n""" +
                           markdown +
                           """\n{% endfilter %}{% endblock body %}""")

                return (source, filename, None)

        else:
            raise TemplateNotFound(filename)