Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow publishing category feeds #185

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,18 @@ Will result in:

Default: `None`.

### Category feeds

Enables generating separate feeds for each category.

Default: `false`.

### Category feeds directory

Directory to put category feeds into

Default: `rss_dir`.

----

## Integration
Expand Down
12 changes: 12 additions & 0 deletions docs/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,18 @@
"markdownDescription": "https://guts.github.io/mkdocs-rss-plugin/configuration/#url-parameters",
"type": "object",
"default": null
},
"category_feeds": {
"title": "Separate feeds for each category",
"markdownDescription": "https://guts.github.io/mkdocs-rss-plugin/configuration/#category_feeds",
"type": "boolean",
"default": false
},
"category_feeds_dir": {
"title": "Directory to put category feeds into",
"markdownDescription": "https://guts.github.io/mkdocs-rss-plugin/configuration/#category_feeds_directory",
"type": "string",
"default": "rss"
}
},
"additionalProperties": false
Expand Down
2 changes: 2 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ plugins:
utm_source: "documentation"
utm_medium: "RSS"
utm_campaign: "feed-syndication"
category_feeds: false
category_feeds_dir: rss
- search

theme:
Expand Down
132 changes: 82 additions & 50 deletions mkdocs_rss_plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
# ########## Libraries #############
# ##################################

# standard library
import logging

# standard library
import os
from copy import deepcopy
from datetime import datetime
from email.utils import formatdate
Expand Down Expand Up @@ -58,6 +60,8 @@ class GitRssPlugin(BasePlugin):
("match_path", config_options.Type(str, default=".*")),
("pretty_print", config_options.Type(bool, default=False)),
("url_parameters", config_options.Type(dict, default=None)),
("category_feeds", config_options.Type(bool, default=False)),
("category_feeds_dir", config_options.Type(str, default="rss")),
)

def __init__(self):
Expand All @@ -71,9 +75,13 @@ def __init__(self):
self.meta_default_time = None
# pages storage
self.pages_to_filter = []
# config
self.category_feeds = False
self.category_feeds_dir = "rss"
# prepare output feeds
self.feed_created = dict
self.feed_updated = dict
self.category_feed = dict

def on_config(self, config: config_options.Config) -> dict:
"""The config event is the first event called on build and
Expand Down Expand Up @@ -123,6 +131,9 @@ def on_config(self, config: config_options.Config) -> dict:
# pattern to match pages included in output
self.match_path_pattern = compile(self.config.get("match_path"))

self.category_feeds = self.config.get("category_feeds")
self.category_feeds_dir = self.config.get("category_feeds_dir")

# date handling
if self.config.get("date_from_meta") is not None:
self.src_date_created = self.config.get("date_from_meta").get(
Expand Down Expand Up @@ -162,6 +173,7 @@ def on_config(self, config: config_options.Config) -> dict:
# create 2 final dicts
self.feed_created = deepcopy(base_feed)
self.feed_updated = deepcopy(base_feed)
self.category_feed = deepcopy(base_feed)

# final feed url
if base_feed.get("html_url"):
Expand Down Expand Up @@ -272,6 +284,41 @@ def on_page_content(
)
)

def render_feed(self, pretty_print: bool, feed_name: str, feed: dict):
if pretty_print:
# load Jinja environment and template
env = Environment(
autoescape=select_autoescape(["html", "xml"]),
loader=FileSystemLoader(self.tpl_folder),
)

template = env.get_template(self.tpl_file.name)

# write feed to file
with feed_name.open(mode="w", encoding="UTF8") as fifeed:
fifeed.write(template.render(feed=feed))
else:
# load Jinja environment and template
env = Environment(
autoescape=select_autoescape(["html", "xml"]),
loader=FileSystemLoader(self.tpl_folder),
lstrip_blocks=True,
trim_blocks=True,
)
template = env.get_template(self.tpl_file.name)

# write feed to file stripping out spaces and new lines
with feed_name.open(mode="w", encoding="UTF8") as fifeed:
prev_char = ""
for char in template.render(feed=feed):
if char == "\n":
continue
if char == " " and prev_char == " ":
prev_char = char
continue
prev_char = char
fifeed.write(char)

def on_post_build(self, config: config_options.Config) -> dict:
"""The post_build event does not alter any variables. \
Use this event to call post-build scripts. \
Expand Down Expand Up @@ -312,52 +359,37 @@ def on_post_build(self, config: config_options.Config) -> dict:
)
)

# write feeds according to the pretty print option
if pretty_print:
# load Jinja environment and template
env = Environment(
autoescape=select_autoescape(["html", "xml"]),
loader=FileSystemLoader(self.tpl_folder),
)

template = env.get_template(self.tpl_file.name)

# write feeds to files
with out_feed_created.open(mode="w", encoding="UTF8") as fifeed_created:
fifeed_created.write(template.render(feed=self.feed_created))

with out_feed_updated.open(mode="w", encoding="UTF8") as fifeed_updated:
fifeed_updated.write(template.render(feed=self.feed_updated))

else:
# load Jinja environment and template
env = Environment(
autoescape=select_autoescape(["html", "xml"]),
loader=FileSystemLoader(self.tpl_folder),
lstrip_blocks=True,
trim_blocks=True,
)
template = env.get_template(self.tpl_file.name)

# write feeds to files stripping out spaces and new lines
with out_feed_created.open(mode="w", encoding="UTF8") as fifeed_created:
prev_char = ""
for char in template.render(feed=self.feed_created):
if char == "\n":
continue
if char == " " and prev_char == " ":
prev_char = char
continue
prev_char = char
fifeed_created.write(char)

with out_feed_updated.open(mode="w", encoding="UTF8") as fifeed_updated:
for char in template.render(feed=self.feed_updated):
if char == "\n":
prev_char = char
continue
if char == " " and prev_char == " ":
prev_char = char
continue
prev_char = char
fifeed_updated.write(char)
# Render main feeds
self.render_feed(pretty_print, out_feed_created, self.feed_created)
self.render_feed(pretty_print, out_feed_updated, self.feed_updated)

# Render category feeds if enabled
if self.category_feeds:
feeds = {}
# collect feeds of pages per category
for page in self.pages_to_filter:
for category in page.categories:
feeds.setdefault(category, []).append(page)

# Ensure target directory exists
path = Path(config.get("site_dir")) / self.category_feeds_dir
os.makedirs(path, exist_ok=True)

for category, pages in feeds.items():
# Create a feed per category
filename = f"{category}.xml"
feed = deepcopy(self.category_feed)
feed["rss_url"] = (
self.category_feed.get("html_url")
+ self.category_feeds_dir
+ "/"
+ filename
)
feed.get("entries").extend(
self.util.filter_pages(
pages=pages,
length=self.config.get("length", 20),
attribute="created",
)
)
self.render_feed(pretty_print, path / filename, feed)
4 changes: 4 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ def test_plugin_config_defaults(self):
"pretty_print": False,
"match_path": ".*",
"url_parameters": None,
"category_feeds": False,
"category_feeds_dir": "rss",
}

# load
Expand All @@ -92,6 +94,8 @@ def test_plugin_config_image(self):
"pretty_print": False,
"match_path": ".*",
"url_parameters": None,
"category_feeds": False,
"category_feeds_dir": "rss",
}

# custom config
Expand Down