##// END OF EJS Templates
Added initial query skipp when seting up the app....
marcink -
r365:ec7b76d4 default
parent child Browse files
Show More
@@ -1,73 +1,73 b''
1 """Pylons environment configuration"""
1 """Pylons environment configuration"""
2 from mako.lookup import TemplateLookup
2 from mako.lookup import TemplateLookup
3 from pylons.configuration import PylonsConfig
3 from pylons.configuration import PylonsConfig
4 from pylons.error import handle_mako_error
4 from pylons.error import handle_mako_error
5 from pylons_app.config.routing import make_map
5 from pylons_app.config.routing import make_map
6 from pylons_app.lib.auth import set_available_permissions, set_base_path
6 from pylons_app.lib.auth import set_available_permissions, set_base_path
7 from pylons_app.lib.utils import repo2db_mapper, make_ui, set_hg_app_config
7 from pylons_app.lib.utils import repo2db_mapper, make_ui, set_hg_app_config
8 from pylons_app.model import init_model
8 from pylons_app.model import init_model
9 from pylons_app.model.hg_model import _get_repos_cached_initial
9 from pylons_app.model.hg_model import _get_repos_cached_initial
10 from sqlalchemy import engine_from_config
10 from sqlalchemy import engine_from_config
11 import logging
11 import logging
12 import os
12 import os
13 import pylons_app.lib.app_globals as app_globals
13 import pylons_app.lib.app_globals as app_globals
14 import pylons_app.lib.helpers
14 import pylons_app.lib.helpers
15
15
16 log = logging.getLogger(__name__)
16 log = logging.getLogger(__name__)
17
17
18 def load_environment(global_conf, app_conf):
18 def load_environment(global_conf, app_conf, initial=False):
19 """Configure the Pylons environment via the ``pylons.config``
19 """Configure the Pylons environment via the ``pylons.config``
20 object
20 object
21 """
21 """
22 config = PylonsConfig()
22 config = PylonsConfig()
23
23
24 # Pylons paths
24 # Pylons paths
25 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
25 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26 paths = dict(root=root,
26 paths = dict(root=root,
27 controllers=os.path.join(root, 'controllers'),
27 controllers=os.path.join(root, 'controllers'),
28 static_files=os.path.join(root, 'public'),
28 static_files=os.path.join(root, 'public'),
29 templates=[os.path.join(root, 'templates')])
29 templates=[os.path.join(root, 'templates')])
30
30
31 # Initialize config with the basic options
31 # Initialize config with the basic options
32 config.init_app(global_conf, app_conf, package='pylons_app', paths=paths)
32 config.init_app(global_conf, app_conf, package='pylons_app', paths=paths)
33
33
34 config['routes.map'] = make_map(config)
34 config['routes.map'] = make_map(config)
35 config['pylons.app_globals'] = app_globals.Globals(config)
35 config['pylons.app_globals'] = app_globals.Globals(config)
36 config['pylons.h'] = pylons_app.lib.helpers
36 config['pylons.h'] = pylons_app.lib.helpers
37
37
38 # Setup cache object as early as possible
38 # Setup cache object as early as possible
39 import pylons
39 import pylons
40 pylons.cache._push_object(config['pylons.app_globals'].cache)
40 pylons.cache._push_object(config['pylons.app_globals'].cache)
41
41
42 # Create the Mako TemplateLookup, with the default auto-escaping
42 # Create the Mako TemplateLookup, with the default auto-escaping
43 config['pylons.app_globals'].mako_lookup = TemplateLookup(
43 config['pylons.app_globals'].mako_lookup = TemplateLookup(
44 directories=paths['templates'],
44 directories=paths['templates'],
45 error_handler=handle_mako_error,
45 error_handler=handle_mako_error,
46 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
46 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
47 input_encoding='utf-8', default_filters=['escape'],
47 input_encoding='utf-8', default_filters=['escape'],
48 imports=['from webhelpers.html import escape'])
48 imports=['from webhelpers.html import escape'])
49
49
50 #sets the c attribute access when don't existing attribute are accessed
50 #sets the c attribute access when don't existing attribute are accessed
51 config['pylons.strict_tmpl_context'] = True
51 config['pylons.strict_tmpl_context'] = True
52
52
53 #MULTIPLE DB configs
53 #MULTIPLE DB configs
54 # Setup the SQLAlchemy database engine
54 # Setup the SQLAlchemy database engine
55 if config['debug']:
55 if config['debug']:
56 #use query time debugging.
56 #use query time debugging.
57 from pylons_app.lib.timerproxy import TimerProxy
57 from pylons_app.lib.timerproxy import TimerProxy
58 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.',
58 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.',
59 proxy=TimerProxy())
59 proxy=TimerProxy())
60 else:
60 else:
61 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.')
61 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.')
62
62
63 init_model(sa_engine_db1)
63 init_model(sa_engine_db1)
64 config['pylons.app_globals'].baseui = make_ui('db')
64 config['pylons.app_globals'].baseui = make_ui('db')
65
65
66 repo2db_mapper(_get_repos_cached_initial(config['pylons.app_globals']))
66 repo2db_mapper(_get_repos_cached_initial(config['pylons.app_globals'], initial))
67 set_available_permissions(config)
67 set_available_permissions(config)
68 set_base_path(config)
68 set_base_path(config)
69 set_hg_app_config(config)
69 set_hg_app_config(config)
70 # CONFIGURATION OPTIONS HERE (note: all config options will override
70 # CONFIGURATION OPTIONS HERE (note: all config options will override
71 # any Pylons config options)
71 # any Pylons config options)
72
72
73 return config
73 return config
@@ -1,209 +1,210 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 # repos controller for pylons
3 # repos controller for pylons
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
5 # This program is free software; you can redistribute it and/or
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; version 2
7 # as published by the Free Software Foundation; version 2
8 # of the License or (at your opinion) any later version of the license.
8 # of the License or (at your opinion) any later version of the license.
9 #
9 #
10 # This program is distributed in the hope that it will be useful,
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
13 # GNU General Public License for more details.
14 #
14 #
15 # You should have received a copy of the GNU General Public License
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 # MA 02110-1301, USA.
18 # MA 02110-1301, USA.
19 """
20 Created on April 7, 2010
21 admin controller for pylons
22 @author: marcink
23 """
19 from formencode import htmlfill
24 from formencode import htmlfill
20 from operator import itemgetter
25 from operator import itemgetter
21 from pylons import request, response, session, tmpl_context as c, url
26 from pylons import request, response, session, tmpl_context as c, url
22 from pylons.controllers.util import abort, redirect
27 from pylons.controllers.util import abort, redirect
23 from pylons.i18n.translation import _
28 from pylons.i18n.translation import _
24 from pylons_app.lib import helpers as h
29 from pylons_app.lib import helpers as h
25 from pylons_app.lib.auth import LoginRequired, HasPermissionAllDecorator
30 from pylons_app.lib.auth import LoginRequired, HasPermissionAllDecorator
26 from pylons_app.lib.base import BaseController, render
31 from pylons_app.lib.base import BaseController, render
27 from pylons_app.lib.utils import invalidate_cache
32 from pylons_app.lib.utils import invalidate_cache
28 from pylons_app.model.forms import RepoForm
33 from pylons_app.model.forms import RepoForm
29 from pylons_app.model.hg_model import HgModel
34 from pylons_app.model.hg_model import HgModel
30 from pylons_app.model.repo_model import RepoModel
35 from pylons_app.model.repo_model import RepoModel
31 import formencode
36 import formencode
32 import logging
37 import logging
33 import traceback
38 import traceback
34 """
39 from paste.httpexceptions import HTTPInternalServerError
35 Created on April 7, 2010
40
36 admin controller for pylons
37 @author: marcink
38 """
39 log = logging.getLogger(__name__)
41 log = logging.getLogger(__name__)
40
42
41 class ReposController(BaseController):
43 class ReposController(BaseController):
42 """REST Controller styled on the Atom Publishing Protocol"""
44 """REST Controller styled on the Atom Publishing Protocol"""
43 # To properly map this controller, ensure your config/routing.py
45 # To properly map this controller, ensure your config/routing.py
44 # file has a resource setup:
46 # file has a resource setup:
45 # map.resource('repo', 'repos')
47 # map.resource('repo', 'repos')
46
48
47 @LoginRequired()
49 @LoginRequired()
48 @HasPermissionAllDecorator('hg.admin')
50 @HasPermissionAllDecorator('hg.admin')
49 def __before__(self):
51 def __before__(self):
50 c.admin_user = session.get('admin_user')
52 c.admin_user = session.get('admin_user')
51 c.admin_username = session.get('admin_username')
53 c.admin_username = session.get('admin_username')
52 super(ReposController, self).__before__()
54 super(ReposController, self).__before__()
53
55
54 def index(self, format='html'):
56 def index(self, format='html'):
55 """GET /repos: All items in the collection"""
57 """GET /repos: All items in the collection"""
56 # url('repos')
58 # url('repos')
57 cached_repo_list = HgModel().get_repos()
59 cached_repo_list = HgModel().get_repos()
58 c.repos_list = sorted(cached_repo_list, key=itemgetter('name_sort'))
60 c.repos_list = sorted(cached_repo_list, key=itemgetter('name_sort'))
59 return render('admin/repos/repos.html')
61 return render('admin/repos/repos.html')
60
62
61 def create(self):
63 def create(self):
62 """POST /repos: Create a new item"""
64 """POST /repos: Create a new item"""
63 # url('repos')
65 # url('repos')
64 repo_model = RepoModel()
66 repo_model = RepoModel()
65 _form = RepoForm()()
67 _form = RepoForm()()
66 form_result = {}
68 form_result = {}
67 try:
69 try:
68 form_result = _form.to_python(dict(request.POST))
70 form_result = _form.to_python(dict(request.POST))
69 repo_model.create(form_result, c.hg_app_user)
71 repo_model.create(form_result, c.hg_app_user)
70 invalidate_cache('cached_repo_list')
72 invalidate_cache('cached_repo_list')
71 h.flash(_('created repository %s') % form_result['repo_name'],
73 h.flash(_('created repository %s') % form_result['repo_name'],
72 category='success')
74 category='success')
73
75
74 except formencode.Invalid as errors:
76 except formencode.Invalid as errors:
75 c.new_repo = errors.value['repo_name']
77 c.new_repo = errors.value['repo_name']
76 return htmlfill.render(
78 return htmlfill.render(
77 render('admin/repos/repo_add.html'),
79 render('admin/repos/repo_add.html'),
78 defaults=errors.value,
80 defaults=errors.value,
79 errors=errors.error_dict or {},
81 errors=errors.error_dict or {},
80 prefix_error=False,
82 prefix_error=False,
81 encoding="UTF-8")
83 encoding="UTF-8")
82
84
83 except Exception:
85 except Exception:
84 log.error(traceback.format_exc())
86 log.error(traceback.format_exc())
85 msg = _('error occured during creation of repository %s') \
87 msg = _('error occured during creation of repository %s') \
86 % form_result.get('repo_name')
88 % form_result.get('repo_name')
87 h.flash(msg, category='error')
89 h.flash(msg, category='error')
88
90
89 return redirect('repos')
91 return redirect('repos')
90
92
91 def new(self, format='html'):
93 def new(self, format='html'):
92 """GET /repos/new: Form to create a new item"""
94 """GET /repos/new: Form to create a new item"""
93 new_repo = request.GET.get('repo', '')
95 new_repo = request.GET.get('repo', '')
94 c.new_repo = h.repo_name_slug(new_repo)
96 c.new_repo = h.repo_name_slug(new_repo)
95
97
96 return render('admin/repos/repo_add.html')
98 return render('admin/repos/repo_add.html')
97
99
98 def update(self, repo_name):
100 def update(self, repo_name):
99 """PUT /repos/repo_name: Update an existing item"""
101 """PUT /repos/repo_name: Update an existing item"""
100 # Forms posted to this method should contain a hidden field:
102 # Forms posted to this method should contain a hidden field:
101 # <input type="hidden" name="_method" value="PUT" />
103 # <input type="hidden" name="_method" value="PUT" />
102 # Or using helpers:
104 # Or using helpers:
103 # h.form(url('repo', repo_name=ID),
105 # h.form(url('repo', repo_name=ID),
104 # method='put')
106 # method='put')
105 # url('repo', repo_name=ID)
107 # url('repo', repo_name=ID)
106 repo_model = RepoModel()
108 repo_model = RepoModel()
107 changed_name = repo_name
109 changed_name = repo_name
108 _form = RepoForm(edit=True, old_data={'repo_name':repo_name})()
110 _form = RepoForm(edit=True, old_data={'repo_name':repo_name})()
109
111
110 try:
112 try:
111 form_result = _form.to_python(dict(request.POST))
113 form_result = _form.to_python(dict(request.POST))
112 repo_model.update(repo_name, form_result)
114 repo_model.update(repo_name, form_result)
113 invalidate_cache('cached_repo_list')
115 invalidate_cache('cached_repo_list')
114 h.flash(_('Repository %s updated succesfully' % repo_name),
116 h.flash(_('Repository %s updated succesfully' % repo_name),
115 category='success')
117 category='success')
116 changed_name = form_result['repo_name']
118 changed_name = form_result['repo_name']
117 except formencode.Invalid as errors:
119 except formencode.Invalid as errors:
118 c.repo_info = repo_model.get(repo_name)
120 c.repo_info = repo_model.get(repo_name)
119 c.users_array = repo_model.get_users_js()
121 c.users_array = repo_model.get_users_js()
120 errors.value.update({'user':c.repo_info.user.username})
122 errors.value.update({'user':c.repo_info.user.username})
121 return htmlfill.render(
123 return htmlfill.render(
122 render('admin/repos/repo_edit.html'),
124 render('admin/repos/repo_edit.html'),
123 defaults=errors.value,
125 defaults=errors.value,
124 errors=errors.error_dict or {},
126 errors=errors.error_dict or {},
125 prefix_error=False,
127 prefix_error=False,
126 encoding="UTF-8")
128 encoding="UTF-8")
127
129
128 except Exception:
130 except Exception:
129 log.error(traceback.format_exc())
131 log.error(traceback.format_exc())
130 h.flash(_('error occured during update of repository %s') \
132 h.flash(_('error occured during update of repository %s') \
131 % repo_name, category='error')
133 % repo_name, category='error')
132
134
133
134 return redirect(url('edit_repo', repo_name=changed_name))
135 return redirect(url('edit_repo', repo_name=changed_name))
135
136
136 def delete(self, repo_name):
137 def delete(self, repo_name):
137 """DELETE /repos/repo_name: Delete an existing item"""
138 """DELETE /repos/repo_name: Delete an existing item"""
138 # Forms posted to this method should contain a hidden field:
139 # Forms posted to this method should contain a hidden field:
139 # <input type="hidden" name="_method" value="DELETE" />
140 # <input type="hidden" name="_method" value="DELETE" />
140 # Or using helpers:
141 # Or using helpers:
141 # h.form(url('repo', repo_name=ID),
142 # h.form(url('repo', repo_name=ID),
142 # method='delete')
143 # method='delete')
143 # url('repo', repo_name=ID)
144 # url('repo', repo_name=ID)
144
145
145 repo_model = RepoModel()
146 repo_model = RepoModel()
146 repo = repo_model.get(repo_name)
147 repo = repo_model.get(repo_name)
147 if not repo:
148 if not repo:
148 h.flash(_('%s repository is not mapped to db perhaps'
149 h.flash(_('%s repository is not mapped to db perhaps'
149 ' it was moved or renamed from the filesystem'
150 ' it was moved or renamed from the filesystem'
150 ' please run the application again'
151 ' please run the application again'
151 ' in order to rescan repositories') % repo_name,
152 ' in order to rescan repositories') % repo_name,
152 category='error')
153 category='error')
153
154
154 return redirect(url('repos'))
155 return redirect(url('repos'))
155 try:
156 try:
156 repo_model.delete(repo)
157 repo_model.delete(repo)
157 invalidate_cache('cached_repo_list')
158 invalidate_cache('cached_repo_list')
158 h.flash(_('deleted repository %s') % repo_name, category='success')
159 h.flash(_('deleted repository %s') % repo_name, category='success')
159 except Exception:
160 except Exception:
160 h.flash(_('An error occured during deletion of %s') % repo_name,
161 h.flash(_('An error occured during deletion of %s') % repo_name,
161 category='error')
162 category='error')
162
163
163 return redirect(url('repos'))
164 return redirect(url('repos'))
164
165
165 def delete_perm_user(self, repo_name):
166 def delete_perm_user(self, repo_name):
166 """
167 """
167 DELETE an existing repository permission user
168 DELETE an existing repository permission user
168 @param repo_name:
169 @param repo_name:
169 """
170 """
170
171
171 try:
172 try:
172 repo_model = RepoModel()
173 repo_model = RepoModel()
173 repo_model.delete_perm_user(request.POST, repo_name)
174 repo_model.delete_perm_user(request.POST, repo_name)
174 except Exception as e:
175 except Exception as e:
175 h.flash(_('An error occured during deletion of repository user'),
176 h.flash(_('An error occured during deletion of repository user'),
176 category='error')
177 category='error')
177
178 raise HTTPInternalServerError()
178
179
179 def show(self, repo_name, format='html'):
180 def show(self, repo_name, format='html'):
180 """GET /repos/repo_name: Show a specific item"""
181 """GET /repos/repo_name: Show a specific item"""
181 # url('repo', repo_name=ID)
182 # url('repo', repo_name=ID)
182
183
183 def edit(self, repo_name, format='html'):
184 def edit(self, repo_name, format='html'):
184 """GET /repos/repo_name/edit: Form to edit an existing item"""
185 """GET /repos/repo_name/edit: Form to edit an existing item"""
185 # url('edit_repo', repo_name=ID)
186 # url('edit_repo', repo_name=ID)
186 repo_model = RepoModel()
187 repo_model = RepoModel()
187 c.repo_info = repo = repo_model.get(repo_name)
188 c.repo_info = repo = repo_model.get(repo_name)
188 if not repo:
189 if not repo:
189 h.flash(_('%s repository is not mapped to db perhaps'
190 h.flash(_('%s repository is not mapped to db perhaps'
190 ' it was created or renamed from the filesystem'
191 ' it was created or renamed from the filesystem'
191 ' please run the application again'
192 ' please run the application again'
192 ' in order to rescan repositories') % repo_name,
193 ' in order to rescan repositories') % repo_name,
193 category='error')
194 category='error')
194
195
195 return redirect(url('repos'))
196 return redirect(url('repos'))
196 defaults = c.repo_info.__dict__
197 defaults = c.repo_info.__dict__
197 defaults.update({'user':c.repo_info.user.username})
198 defaults.update({'user':c.repo_info.user.username})
198 c.users_array = repo_model.get_users_js()
199 c.users_array = repo_model.get_users_js()
199
200
200 for p in c.repo_info.repo2perm:
201 for p in c.repo_info.repo2perm:
201 defaults.update({'perm_%s' % p.user.username:
202 defaults.update({'perm_%s' % p.user.username:
202 p.permission.permission_name})
203 p.permission.permission_name})
203
204
204 return htmlfill.render(
205 return htmlfill.render(
205 render('admin/repos/repo_edit.html'),
206 render('admin/repos/repo_edit.html'),
206 defaults=defaults,
207 defaults=defaults,
207 encoding="UTF-8",
208 encoding="UTF-8",
208 force_defaults=False
209 force_defaults=False
209 )
210 )
@@ -1,138 +1,121 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 # summary controller for pylons
3 # summary controller for pylons
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
5 #
5 #
6 # This program is free software; you can redistribute it and/or
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; version 2
8 # as published by the Free Software Foundation; version 2
9 # of the License or (at your opinion) any later version of the license.
9 # of the License or (at your opinion) any later version of the license.
10 #
10 #
11 # This program is distributed in the hope that it will be useful,
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
14 # GNU General Public License for more details.
15 #
15 #
16 # You should have received a copy of the GNU General Public License
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 # MA 02110-1301, USA.
19 # MA 02110-1301, USA.
20 """
20 """
21 Created on April 18, 2010
21 Created on April 18, 2010
22 summary controller for pylons
22 summary controller for pylons
23 @author: marcink
23 @author: marcink
24 """
24 """
25 from datetime import datetime, timedelta
25 from datetime import datetime, timedelta
26 from pylons import tmpl_context as c, request
26 from pylons import tmpl_context as c, request
27 from pylons_app.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
27 from pylons_app.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
28 from pylons_app.lib.base import BaseController, render
28 from pylons_app.lib.base import BaseController, render
29 from pylons_app.lib.helpers import person
29 from pylons_app.lib.helpers import person
30 from pylons_app.lib.utils import OrderedDict
30 from pylons_app.lib.utils import OrderedDict
31 from pylons_app.model.hg_model import HgModel
31 from pylons_app.model.hg_model import HgModel
32 from time import mktime
32 from time import mktime
33 from webhelpers.paginate import Page
33 from webhelpers.paginate import Page
34 import calendar
34 import calendar
35 import logging
35 import logging
36
36
37 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
38
38
39 class SummaryController(BaseController):
39 class SummaryController(BaseController):
40
40
41 @LoginRequired()
41 @LoginRequired()
42 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
42 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
43 'repository.admin')
43 'repository.admin')
44 def __before__(self):
44 def __before__(self):
45 super(SummaryController, self).__before__()
45 super(SummaryController, self).__before__()
46
46
47 def index(self):
47 def index(self):
48 hg_model = HgModel()
48 hg_model = HgModel()
49 c.repo_info = hg_model.get_repo(c.repo_name)
49 c.repo_info = hg_model.get_repo(c.repo_name)
50 c.repo_changesets = Page(list(c.repo_info[:10]), page=1, items_per_page=20)
50 c.repo_changesets = Page(list(c.repo_info[:10]), page=1, items_per_page=20)
51 e = request.environ
51 e = request.environ
52 uri = u'%(protocol)s://%(user)s@%(host)s/%(repo_name)s' % {
52 uri = u'%(protocol)s://%(user)s@%(host)s/%(repo_name)s' % {
53 'protocol': e.get('wsgi.url_scheme'),
53 'protocol': e.get('wsgi.url_scheme'),
54 'user':str(c.hg_app_user.username),
54 'user':str(c.hg_app_user.username),
55 'host':e.get('HTTP_HOST'),
55 'host':e.get('HTTP_HOST'),
56 'repo_name':c.repo_name, }
56 'repo_name':c.repo_name, }
57 c.clone_repo_url = uri
57 c.clone_repo_url = uri
58 c.repo_tags = {}
58 c.repo_tags = {}
59 for name, hash in c.repo_info.tags.items()[:10]:
59 for name, hash in c.repo_info.tags.items()[:10]:
60 c.repo_tags[name] = c.repo_info.get_changeset(hash)
60 c.repo_tags[name] = c.repo_info.get_changeset(hash)
61
61
62 c.repo_branches = {}
62 c.repo_branches = {}
63 for name, hash in c.repo_info.branches.items()[:10]:
63 for name, hash in c.repo_info.branches.items()[:10]:
64 c.repo_branches[name] = c.repo_info.get_changeset(hash)
64 c.repo_branches[name] = c.repo_info.get_changeset(hash)
65
65
66 c.commit_data = self.__get_commit_stats(c.repo_info)
66 c.commit_data = self.__get_commit_stats(c.repo_info)
67
67
68 return render('summary/summary.html')
68 return render('summary/summary.html')
69
69
70
70
71
71
72 def __get_commit_stats(self, repo):
72 def __get_commit_stats(self, repo):
73 aggregate = OrderedDict()
73 aggregate = OrderedDict()
74
74
75
76 #graph range
75 #graph range
77 td = datetime.today()
76 td = datetime.today()
78 y = td.year
77 y = td.year
79 m = td.month
78 m = td.month
80 d = td.day
79 d = td.day
81 c.ts_min = mktime((y, (td - timedelta(days=calendar.mdays[m] - 1)).month, d, 0, 0, 0, 0, 0, 0,))
80 c.ts_min = mktime((y, (td - timedelta(days=calendar.mdays[m] - 1)).month, d, 0, 0, 0, 0, 0, 0,))
82 c.ts_max = mktime((y, m, d, 0, 0, 0, 0, 0, 0,))
81 c.ts_max = mktime((y, m, d, 0, 0, 0, 0, 0, 0,))
83
82
84
85 # #generate this monhts keys
86 # dates_range = OrderedDict()
87 # year_range = range(2010, datetime.today().year + 1)
88 # month_range = range(1, datetime.today().month + 1)
89 #
90 #
91 #
92 # for y in year_range:
93 # for m in month_range:
94 # for d in range(1, calendar.mdays[m] + 1):
95 # k = '%s-%s-%s' % (y, m, d)
96 # timetupple = [int(x) for x in k.split('-')]
97 # timetupple.extend([0 for _ in xrange(6)])
98 # k = mktime(timetupple)
99 # dates_range[k] = 0
100
83
101 def author_key_cleaner(k):
84 def author_key_cleaner(k):
102 k = person(k)
85 k = person(k)
103 return k
86 return k
104
87
105 for cs in repo:
88 for cs in repo:
106 k = '%s-%s-%s' % (cs.date.timetuple()[0], cs.date.timetuple()[1],
89 k = '%s-%s-%s' % (cs.date.timetuple()[0], cs.date.timetuple()[1],
107 cs.date.timetuple()[2])
90 cs.date.timetuple()[2])
108 timetupple = [int(x) for x in k.split('-')]
91 timetupple = [int(x) for x in k.split('-')]
109 timetupple.extend([0 for _ in xrange(6)])
92 timetupple.extend([0 for _ in xrange(6)])
110 k = mktime(timetupple)
93 k = mktime(timetupple)
111 if aggregate.has_key(author_key_cleaner(cs.author)):
94 if aggregate.has_key(author_key_cleaner(cs.author)):
112 if aggregate[author_key_cleaner(cs.author)].has_key(k):
95 if aggregate[author_key_cleaner(cs.author)].has_key(k):
113 aggregate[author_key_cleaner(cs.author)][k] += 1
96 aggregate[author_key_cleaner(cs.author)][k] += 1
114 else:
97 else:
115 #aggregate[author_key_cleaner(cs.author)].update(dates_range)
98 #aggregate[author_key_cleaner(cs.author)].update(dates_range)
116 if k >= c.ts_min and k <= c.ts_max:
99 if k >= c.ts_min and k <= c.ts_max:
117 aggregate[author_key_cleaner(cs.author)][k] = 1
100 aggregate[author_key_cleaner(cs.author)][k] = 1
118 else:
101 else:
119 if k >= c.ts_min and k <= c.ts_max:
102 if k >= c.ts_min and k <= c.ts_max:
120 aggregate[author_key_cleaner(cs.author)] = OrderedDict()
103 aggregate[author_key_cleaner(cs.author)] = OrderedDict()
121 #aggregate[author_key_cleaner(cs.author)].update(dates_range)
104 #aggregate[author_key_cleaner(cs.author)].update(dates_range)
122 aggregate[author_key_cleaner(cs.author)][k] = 1
105 aggregate[author_key_cleaner(cs.author)][k] = 1
123
106
124 d = ''
107 d = ''
125 tmpl0 = u""""%s":%s"""
108 tmpl0 = u""""%s":%s"""
126 tmpl1 = u"""{label:"%s",data:%s},"""
109 tmpl1 = u"""{label:"%s",data:%s},"""
127 for author in aggregate:
110 for author in aggregate:
128 d += tmpl0 % (author.decode('utf8'),
111 d += tmpl0 % (author.decode('utf8'),
129 tmpl1 \
112 tmpl1 \
130 % (author.decode('utf8'),
113 % (author.decode('utf8'),
131 [[x, aggregate[author][x]] for x in aggregate[author]]))
114 [[x, aggregate[author][x]] for x in aggregate[author]]))
132 if d == '':
115 if d == '':
133 d = '"%s":{label:"%s",data:[[0,0],]}' \
116 d = '"%s":{label:"%s",data:[[0,0],]}' \
134 % (author_key_cleaner(repo.contact),
117 % (author_key_cleaner(repo.contact),
135 author_key_cleaner(repo.contact))
118 author_key_cleaner(repo.contact))
136 return d
119 return d
137
120
138
121
@@ -1,23 +1,23 b''
1 """Setup the pylons_app application"""
1 """Setup the pylons_app application"""
2
2
3 from os.path import dirname as dn, join as jn
3 from os.path import dirname as dn, join as jn
4 from pylons_app.config.environment import load_environment
4 from pylons_app.config.environment import load_environment
5 from pylons_app.lib.db_manage import DbManage
5 from pylons_app.lib.db_manage import DbManage
6 import logging
6 import logging
7 import os
7 import os
8 import sys
8 import sys
9
9
10 log = logging.getLogger(__name__)
10 log = logging.getLogger(__name__)
11
11
12 ROOT = dn(dn(os.path.realpath(__file__)))
12 ROOT = dn(dn(os.path.realpath(__file__)))
13 sys.path.append(ROOT)
13 sys.path.append(ROOT)
14
14
15 def setup_app(command, conf, vars):
15 def setup_app(command, conf, vars):
16 """Place any commands to setup pylons_app here"""
16 """Place any commands to setup pylons_app here"""
17 dbmanage = DbManage(log_sql=True)
17 dbmanage = DbManage(log_sql=True)
18 dbmanage.create_tables(override=True)
18 dbmanage.create_tables(override=True)
19 dbmanage.config_prompt()
19 dbmanage.config_prompt()
20 dbmanage.admin_prompt()
20 dbmanage.admin_prompt()
21 dbmanage.create_permissions()
21 dbmanage.create_permissions()
22 load_environment(conf.global_conf, conf.local_conf)
22 load_environment(conf.global_conf, conf.local_conf, initial=True)
23
23
General Comments 0
You need to be logged in to leave comments. Login now