b19b16df2679d911e08270f4ce61e027412ce654
[mediagoblin.git] / mediagoblin / tools / theme.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """
18 """
19
20
21 import pkg_resources
22 import os
23
24 from configobj import ConfigObj
25
26
27 BUILTIN_THEME_DIR = pkg_resources.resource_filename('mediagoblin', 'themes')
28
29
30 def themedata_for_theme_dir(name, theme_dir):
31 """
32 Given a theme directory, extract important theme information.
33 """
34 # open config
35 config = ConfigObj(os.path.join(theme_dir, 'theme.ini'))
36
37 templates_dir = os.path.join(theme_dir, 'templates')
38 if not os.path.exists(templates_dir):
39 templates_dir = None
40
41 assets_dir = os.path.join(theme_dir, 'assets')
42 if not os.path.exists(assets_dir):
43 assets_dir = None
44
45 themedata = {
46 'name': config.get('name', name),
47 'description': config.get('description'),
48 'dir': theme_dir,
49 'templates_dir': templates_dir,
50 'assets_dir': assets_dir,
51 'config': config}
52
53 return themedata
54
55
56 def register_themes(app_config, builtin_dir=BUILTIN_THEME_DIR):
57 """
58 Register all themes relevant to this application.
59 """
60 registry = {}
61
62 def _install_themes_in_dir(directory):
63 for themedir in os.listdir(directory):
64 abs_themedir = os.path.join(directory, themedir)
65 if not os.path.isdir(abs_themedir):
66 continue
67
68 themedata = themedata_for_theme_dir(themedir, abs_themedir)
69 registry[themedir] = themedata
70
71 # Built-in themes
72 if os.path.exists(builtin_dir):
73 _install_themes_in_dir(builtin_dir)
74
75 # Installed themes
76 theme_install_dir = app_config.get('theme_install_dir')
77 if theme_install_dir and os.path.exists(theme_install_dir):
78 _install_themes_in_dir(theme_install_dir)
79
80 current_theme_name = app_config.get('theme')
81 if current_theme_name \
82 and registry.has_key(current_theme_name):
83 current_theme = registry[current_theme_name]
84 else:
85 current_theme = None
86
87 return registry, current_theme
88