/hyde/ext/plugins/urls.py

http://github.com/hyde/hyde · Python · 73 lines · 34 code · 11 blank · 28 comment · 8 complexity · 4582b41b1481d1744f072fc4989ad4db MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. """
  3. Contains classes and utilities related to hyde urls.
  4. """
  5. from hyde.plugin import Plugin
  6. from hyde.site import Site
  7. from functools import wraps
  8. from fswrap import File
  9. class UrlCleanerPlugin(Plugin):
  10. """
  11. Url Cleaner plugin for hyde. Adds to hyde the ability to generate clean
  12. urls.
  13. Configuration example
  14. ---------------------
  15. #yaml
  16. urlcleaner:
  17. index_file_names:
  18. # Identifies the files that represents a directory listing.
  19. # These file names are automatically stripped away when
  20. # the content_url function is called.
  21. - index.html
  22. strip_extensions:
  23. # The following extensions are automatically removed when
  24. # generating the urls using content_url function.
  25. - html
  26. # This option will append a slash to the end of directory paths
  27. append_slash: true
  28. """
  29. def __init__(self, site):
  30. super(UrlCleanerPlugin, self).__init__(site)
  31. def begin_site(self):
  32. """
  33. Replace the content_url method in the site object with a custom method
  34. that cleans urls based on the given configuration.
  35. """
  36. config = self.site.config
  37. if not hasattr(config, 'urlcleaner'):
  38. return
  39. if (hasattr(Site, '___url_cleaner_patched___')):
  40. return
  41. settings = config.urlcleaner
  42. def clean_url(urlgetter):
  43. @wraps(urlgetter)
  44. def wrapper(site, path, safe=None):
  45. url = urlgetter(site, path, safe)
  46. index_file_names = getattr(settings,
  47. 'index_file_names',
  48. ['index.html'])
  49. rep = File(url)
  50. if rep.name in index_file_names:
  51. url = rep.parent.path.rstrip('/')
  52. if hasattr(settings, 'append_slash') and \
  53. settings.append_slash:
  54. url += '/'
  55. elif hasattr(settings, 'strip_extensions'):
  56. if rep.kind in settings.strip_extensions:
  57. url = rep.parent.child(rep.name_without_extension)
  58. return url or '/'
  59. return wrapper
  60. Site.___url_cleaner_patched___ = True
  61. Site.content_url = clean_url(Site.content_url)