textbundle.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #-*- conding: utf-8 -*-
  2. import os
  3. import logging
  4. import shutil
  5. from glob import glob
  6. from pelican import readers
  7. from pelican import signals
  8. from markdown import Markdown
  9. logger = logging.getLogger(__name__)
  10. class TextbundleReader(readers.MarkdownReader):
  11. enabled = Markdown
  12. path_mappings = {}
  13. file_extensions = ['textbundle']
  14. # You need to have a read method, which takes a filename and returns
  15. # some content and the associated metadata.
  16. def read(self, filename):
  17. md_filename = "{}/text.md".format(filename)
  18. logger.debug('Found textbundle {}'.format(filename))
  19. return super(TextbundleReader, self).read(md_filename)
  20. def add_reader(readers):
  21. readers.reader_classes['textbundle'] = TextbundleReader
  22. def copy_article_assets(generator):
  23. logging.debug('Copy Article textbundle assets')
  24. inspect_content_items(generator.articles, generator.output_path)
  25. def copy_page_assets(generator):
  26. logging.debug('Copy Page textbundle assets')
  27. inspect_content_items(generator.pages, generator.output_path)
  28. def inspect_content_items(content_items, output_path):
  29. """
  30. Check if there are files in the assets/ foldr of a textbundle have to be
  31. copied to the output folder.
  32. """
  33. for item in content_items:
  34. foldername = os.path.join(
  35. output_path,
  36. os.path.dirname(item.save_as),
  37. 'assets'
  38. )
  39. assets = glob("{}/assets/*.*".format(os.path.dirname(item.source_path)))
  40. if len(assets) > 0:
  41. copy_assets_to_outputfolder(assets, foldername)
  42. def copy_assets_to_outputfolder(assets, foldername):
  43. """
  44. Copy all files from the assets/ folder of a textbundle to the output folder.
  45. """
  46. if not os.path.exists(foldername):
  47. os.makedirs(foldername)
  48. for asset in assets:
  49. asset_path = os.path.join(foldername, os.path.basename(asset))
  50. if not os.path.exists(asset_path):
  51. logger.debug('copying asset {} to {}'.format(asset, foldername))
  52. shutil.copy2(asset, asset_path)
  53. else:
  54. logger.debug('skipping existing asset {}'.format(foldername))
  55. def register():
  56. signals.readers_init.connect(add_reader)
  57. signals.article_generator_finalized.connect(copy_article_assets)
  58. signals.page_generator_finalized.connect(copy_page_assets)