Changeset - b0715a788432
[Not reviewed]
default
0 4 0
Marcin Kuzminski - 15 years ago 2010-07-24 00:21:57
marcin@python-works.com
Added new style error display,
fixed changing repo name to existing one
some sa session remove added
rename repo BIG bug, when renaming to existing name was fixed
4 files changed with 69 insertions and 39 deletions:
0 comments (0 inline, 0 general)
pylons_app/controllers/admin/repos.py
Show inline comments
 
@@ -13,17 +13,12 @@
 
# GNU General Public License for more details.
 
# 
 
# You should have received a copy of the GNU General Public License
 
# along with this program; if not, write to the Free Software
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
# MA  02110-1301, USA.
 
"""
 
Created on April 7, 2010
 
admin controller for pylons
 
@author: marcink
 
"""
 
from formencode import htmlfill
 
from operator import itemgetter
 
from pylons import request, response, session, tmpl_context as c, url
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 
from pylons_app.lib import helpers as h
 
@@ -32,12 +27,18 @@ from pylons_app.lib.base import BaseCont
 
from pylons_app.lib.utils import invalidate_cache
 
from pylons_app.model.forms import RepoForm
 
from pylons_app.model.hg_model import HgModel
 
from pylons_app.model.repo_model import RepoModel
 
import formencode
 
import logging
 
import traceback
 
"""
 
Created on April 7, 2010
 
admin controller for pylons
 
@author: marcink
 
"""
 
log = logging.getLogger(__name__)
 

	
 
class ReposController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
@@ -59,30 +60,37 @@ class ReposController(BaseController):
 
    
 
    def create(self):
 
        """POST /repos: Create a new item"""
 
        # url('repos')
 
        repo_model = RepoModel()
 
        _form = RepoForm()()
 
        form_result = None
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            repo_model.create(form_result, c.hg_app_user)
 
            invalidate_cache('cached_repo_list')
 
            h.flash(_('created repository %s') % form_result['repo_name'],
 
                    category='success')
 
                                                             
 
        except formencode.Invalid as errors:
 
            c.form_errors = errors.error_dict
 
            c.new_repo = errors.value['repo_name']
 
            return htmlfill.render(
 
                 render('admin/repos/repo_add.html'),
 
                render('admin/repos/repo_add.html'),
 
                defaults=errors.value,
 
                encoding="UTF-8")        
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")      
 

	
 
        except Exception:
 
            h.flash(_('error occured during creation of repository %s') \
 
                    % form_result['repo_name'], category='error')
 
            log.error(traceback.format_exc())
 
            if form_result:
 
                msg = _('error occured during creation of repository %s') \
 
                    % form_result['repo_name']
 
            else:
 
                msg = _('error occured during creation of repository') 
 
            h.flash(msg, category='error')
 
            
 
        return redirect('repos')
 

	
 
    def new(self, format='html'):
 
        """GET /repos/new: Form to create a new item"""
 
        new_repo = request.GET.get('repo', '')
 
@@ -96,33 +104,40 @@ class ReposController(BaseController):
 
        #    <input type="hidden" name="_method" value="PUT" />
 
        # Or using helpers:
 
        #    h.form(url('repo', repo_name=ID),
 
        #           method='put')
 
        # url('repo', repo_name=ID)
 
        repo_model = RepoModel()
 
        _form = RepoForm(edit=True)()
 
        changed_name = repo_name
 
        _form = RepoForm(edit=True, old_data={'repo_name':repo_name})()
 
        
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            repo_model.update(repo_name, form_result)
 
            invalidate_cache('cached_repo_list')
 
            h.flash(_('Repository %s updated succesfully' % repo_name),
 
                    category='success')
 
                           
 
            changed_name = form_result['repo_name']
 
        except formencode.Invalid as errors:
 
            c.repo_info = repo_model.get(repo_name)
 
            c.users_array = repo_model.get_users_js()
 
            errors.value.update({'user':c.repo_info.user.username})
 
            c.form_errors = errors.error_dict
 
            return htmlfill.render(
 
                 render('admin/repos/repo_edit.html'),
 
                render('admin/repos/repo_edit.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 
 
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occured during update of repository %s') \
 
                    % form_result['repo_name'], category='error')
 
        return redirect(url('repos'))
 
                    % repo_name, category='error')
 
            
 
        
 
        return redirect(url('edit_repo', repo_name=changed_name))
 
    
 
    def delete(self, repo_name):
 
        """DELETE /repos/repo_name: Delete an existing item"""
 
        # Forms posted to this method should contain a hidden field:
 
        #    <input type="hidden" name="_method" value="DELETE" />
 
        # Or using helpers:
pylons_app/controllers/settings.py
Show inline comments
 
#!/usr/bin/env python
 
# encoding: utf-8
 
# settings controller for pylons
 
# Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
 
 
 
# 
 
# This program is free software; you can redistribute it and/or
 
# modify it under the terms of the GNU General Public License
 
# as published by the Free Software Foundation; version 2
 
# of the License or (at your opinion) any later version of the license.
 
# 
 
# This program is distributed in the hope that it will be useful,
 
@@ -14,29 +14,30 @@
 
# GNU General Public License for more details.
 
# 
 
# You should have received a copy of the GNU General Public License
 
# along with this program; if not, write to the Free Software
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
# MA  02110-1301, USA.
 
"""
 
Created on June 30, 2010
 
settings controller for pylons
 
@author: marcink
 
"""
 
from formencode import htmlfill
 
from pylons import tmpl_context as c, request, url
 
from pylons.controllers.util import redirect
 
from pylons.i18n.translation import _
 
from pylons_app.lib.auth import LoginRequired, HasRepoPermissionAllDecorator
 
from pylons_app.lib.base import BaseController, render
 
from pylons_app.lib.utils import invalidate_cache
 
from pylons_app.model.forms import RepoSettingsForm
 
from pylons_app.model.repo_model import RepoModel
 
import formencode
 
import logging
 
import pylons_app.lib.helpers as h
 
import traceback
 
"""
 
Created on June 30, 2010
 
settings controller for pylons
 
@author: marcink
 
"""
 
log = logging.getLogger(__name__)
 

	
 
class SettingsController(BaseController):
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAllDecorator('repository.admin')           
 
@@ -68,28 +69,30 @@ class SettingsController(BaseController)
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )  
 

	
 
    def update(self, repo_name):
 
        repo_model = RepoModel()
 
        _form = RepoSettingsForm(edit=True)()
 
        _form = RepoSettingsForm(edit=True, old_data={'repo_name':repo_name})()
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            repo_model.update(repo_name, form_result)
 
            invalidate_cache('cached_repo_list')
 
            h.flash(_('Repository %s updated succesfully' % repo_name),
 
                    category='success')
 
                           
 
        except formencode.Invalid as errors:
 
            c.repo_info = repo_model.get(repo_name)
 
            c.users_array = repo_model.get_users_js()
 
            errors.value.update({'user':c.repo_info.user.username})
 
            c.form_errors = errors.error_dict
 
            return htmlfill.render(
 
                 render('admin/repos/repo_edit.html'),
 
                render('settings/repo_settings.html'),
 
                defaults=errors.value,
 
                encoding="UTF-8")
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8") 
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occured during update of repository %s') \
 
                    % form_result['repo_name'], category='error')
 
                    
 
        return redirect(url('repo_settings_home', repo_name=repo_name))
 
        return redirect(url('repo_settings_home', repo_name=form_result['repo_name']))
pylons_app/model/forms.py
Show inline comments
 
@@ -121,40 +121,47 @@ class ValidAuth(formencode.validators.Fa
 
                log.warning('user %s is disabled', username)
 
                raise formencode.Invalid(self.message('disabled_account',
 
                                         state=State_obj),
 
                                         value, state,
 
                                         error_dict=self.e_dict_disable)
 
            
 
        meta.Session.remove()                
 
        meta.Session.remove()
 

	
 
                   
 
class ValidRepoUser(formencode.validators.FancyValidator):
 
            
 
    def to_python(self, value, state):
 
        sa = meta.Session
 
        try:
 
            self.user_db = sa.query(User)\
 
                .filter(User.active == True)\
 
                .filter(User.username == value).one()
 
        except Exception:
 
            raise formencode.Invalid(_('This username is not valid'),
 
                                     value, state)
 
        meta.Session.remove()            
 
        return self.user_db.user_id
 

	
 
def ValidRepoName(edit=False):    
 
def ValidRepoName(edit, old_data):    
 
    class _ValidRepoName(formencode.validators.FancyValidator):
 
            
 
        def to_python(self, value, state):
 
            slug = h.repo_name_slug(value)
 
            if slug in ['_admin']:
 
                raise formencode.Invalid(_('This repository name is disallowed'),
 
                                         value, state)
 
            sa = meta.Session
 
            if sa.query(Repository).get(slug) and not edit:
 
                raise formencode.Invalid(_('This repository already exists'),
 
                                         value, state)
 
                        
 
            
 
            if old_data.get('repo_name') != value or not edit:    
 
                sa = meta.Session
 
                if sa.query(Repository).get(slug):
 
                    raise formencode.Invalid(_('This repository already exists') ,
 
                                             value, state)
 
                meta.Session.remove()
 
            return slug 
 
        
 
        
 
    return _ValidRepoName
 

	
 
class ValidPerms(formencode.validators.FancyValidator):
 
    messages = {'perm_new_user_name':_('This username is not valid')}
 
    
 
    def to_python(self, value, state):
 
@@ -240,31 +247,31 @@ def UserForm(edit=False):
 
        name = UnicodeString(strip=True, min=3, not_empty=True)
 
        lastname = UnicodeString(strip=True, min=3, not_empty=True)
 
        email = Email(not_empty=True)
 
        
 
    return _UserForm
 

	
 
def RepoForm(edit=False):
 
def RepoForm(edit=False, old_data={}):
 
    class _RepoForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit))
 
        repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
 
        description = UnicodeString(strip=True, min=3, not_empty=True)
 
        private = StringBoolean(if_missing=False)
 
        
 
        if edit:
 
            user = All(Int(not_empty=True), ValidRepoUser)
 
        
 
        chained_validators = [ValidPerms]
 
    return _RepoForm
 

	
 
def RepoSettingsForm(edit=False):
 
def RepoSettingsForm(edit=False, old_data={}):
 
    class _RepoForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit))
 
        repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
 
        description = UnicodeString(strip=True, min=3, not_empty=True)
 
        private = StringBoolean(if_missing=False)
 
        
 
        chained_validators = [ValidPerms, ValidSettings]
 
    return _RepoForm
 

	
pylons_app/model/repo_model.py
Show inline comments
 
@@ -51,12 +51,13 @@ class RepoModel(object):
 
        return users_array        
 
        
 
    
 
    def update(self, repo_id, form_data):
 
        try:
 
            if repo_id != form_data['repo_name']:
 
                #rename our data
 
                self.__rename_repo(repo_id, form_data['repo_name'])
 
            cur_repo = self.sa.query(Repository).get(repo_id)
 
            for k, v in form_data.items():
 
                if k == 'user':
 
                    cur_repo.user_id = v
 
                else:
 
@@ -147,15 +148,19 @@ class RepoModel(object):
 
        if check_repo(repo_name, g.base_path):
 
            log.info('creating repo %s in %s', repo_name, repo_path)
 
            from vcs.backends.hg import MercurialRepository
 
            MercurialRepository(repo_path, create=True)
 

	
 
    def __rename_repo(self, old, new):
 
        log.info('renaming repoo from %s to %s', old, new)
 
        log.info('renaming repo from %s to %s', old, new)
 
        
 
        old_path = os.path.join(g.base_path, old)
 
        new_path = os.path.join(g.base_path, new)
 
        if os.path.isdir(new_path):
 
            raise Exception('Was trying to rename to already existing dir %s',
 
                            new_path)        
 
        shutil.move(old_path, new_path)
 
    
 
    def __delete_repo(self, name):
 
        rm_path = os.path.join(g.base_path, name)
 
        log.info("Removing %s", rm_path)
 
        #disable hg 
0 comments (0 inline, 0 general)