PageRenderTime 91ms CodeModel.GetById 83ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/hyde/ext/plugins/urls.py

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