autopages.py 2.0 KB

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