autopages.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import logging
  2. import os
  3. import os.path
  4. from pelican import signals
  5. from pelican.contents import Page
  6. logger = logging.getLogger("autopages")
  7. def yield_files(root):
  8. root = os.path.realpath(os.path.abspath(root))
  9. for dirpath, dirnames, filenames in os.walk(root):
  10. for dirname in list(dirnames):
  11. try:
  12. if dirname.startswith("."):
  13. dirnames.remove(dirname)
  14. except IndexError:
  15. # duplicate already removed?
  16. pass
  17. for filename in filenames:
  18. if filename.startswith("."):
  19. continue
  20. yield os.path.join(dirpath, filename)
  21. def make_page(readers, context, filename):
  22. base_path, filename = os.path.split(filename)
  23. page = readers.read_file(base_path, filename, Page, None, context)
  24. slug, _ = os.path.splitext(filename)
  25. return slug, page
  26. def make_pages(readers, context, path):
  27. pages = {}
  28. for filename in yield_files(path):
  29. try:
  30. slug, page = make_page(readers, context, filename)
  31. except Exception:
  32. logger.exception("Could not make autopage for %r", filename)
  33. continue
  34. pages[slug] = page
  35. return pages
  36. def create_autopages(article_generator):
  37. settings = article_generator.settings
  38. readers = article_generator.readers
  39. context = article_generator.context
  40. authors_path = settings.get("AUTHOR_PAGE_PATH", "authors")
  41. categories_path = settings.get("CATEGORY_PAGE_PATH", "categories")
  42. tags_path = settings.get("TAG_PAGE_PATH", "tags")
  43. author_pages = make_pages(readers, context, authors_path)
  44. category_pages = make_pages(readers, context, categories_path)
  45. tag_pages = make_pages(readers, context, tags_path)
  46. for author, _ in article_generator.authors:
  47. author.page = author_pages.get(author.slug, "")
  48. for category, _ in article_generator.categories:
  49. category.page = category_pages.get(category.slug, "")
  50. for tag in article_generator.tags:
  51. tag.page = tag_pages.get(tag.slug, "")
  52. def register():
  53. signals.article_generator_finalized.connect(create_autopages)