Changeset - cf51bbfb120e
[Not reviewed]
beta
0 60 0
Marcin Kuzminski - 14 years ago 2011-12-29 06:35:51
marcin@python-works.com
auto white-space removal
60 files changed with 167 insertions and 215 deletions:
0 comments (0 inline, 0 general)
rhodecode/config/routing.py
Show inline comments
 
@@ -134,13 +134,13 @@ def make_map(config):
 
        m.connect('repo_pull', "/repo_pull/{repo_name:.*}",
 
                  action="repo_pull", conditions=dict(method=["PUT"],
 
                                                      function=check_repo))
 
        m.connect('repo_as_fork', "/repo_as_fork/{repo_name:.*}",
 
                  action="repo_as_fork", conditions=dict(method=["PUT"],
 
                                                      function=check_repo))
 
        
 

	
 
    with rmap.submapper(path_prefix=ADMIN_PREFIX,
 
                        controller='admin/repos_groups') as m:
 
        m.connect("repos_groups", "/repos_groups",
 
                  action="create", conditions=dict(method=["POST"]))
 
        m.connect("repos_groups", "/repos_groups",
 
                  action="index", conditions=dict(method=["GET"]))
rhodecode/controllers/admin/notifications.py
Show inline comments
 
@@ -18,13 +18,13 @@ log = logging.getLogger(__name__)
 

	
 

	
 
class NotificationsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('notification', 'notifications', controller='_admin/notifications', 
 
    #     map.resource('notification', 'notifications', controller='_admin/notifications',
 
    #         path_prefix='/_admin', name_prefix='_admin_')
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def __before__(self):
 
        super(NotificationsController, self).__before__()
rhodecode/controllers/admin/repos.py
Show inline comments
 
@@ -109,13 +109,13 @@ class ReposController(BaseController):
 
            c.stats_percentage = 0
 
        else:
 
            c.stats_percentage = '%.2f' % ((float((last_rev)) /
 
                                            c.repo_last_rev) * 100)
 

	
 
        defaults = RepoModel()._get_defaults(repo_name)
 
        
 

	
 
        c.repos_list = [('', _('--REMOVE FORK--'))]
 
        c.repos_list += [(x.repo_id, x.repo_name) for x in
 
                   Repository.query().order_by(Repository.repo_name).all()]
 
        return defaults
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
@@ -390,22 +390,22 @@ class ReposController(BaseController):
 
        return redirect(url('edit_repo', repo_name=repo_name))
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def repo_as_fork(self, repo_name):
 
        """
 
        Mark given repository as a fork of another
 
        
 

	
 
        :param repo_name:
 
        """
 
        try:
 
            fork_id = request.POST.get('id_fork_of')
 
            repo = ScmModel().mark_as_fork(repo_name, fork_id,
 
                                    self.rhodecode_user.username)
 
            fork = repo.fork.repo_name if repo.fork else _('Nothing')
 
            Session.commit()
 
            h.flash(_('Marked repo %s as fork of %s' % (repo_name,fork)), 
 
            h.flash(_('Marked repo %s as fork of %s' % (repo_name,fork)),
 
                    category='success')
 
        except Exception, e:
 
            raise
 
            h.flash(_('An error occurred during this operation'),
 
                    category='error')
 

	
rhodecode/controllers/admin/repos_groups.py
Show inline comments
 
@@ -223,8 +223,6 @@ class ReposGroupsController(BaseControll
 
        return htmlfill.render(
 
            render('admin/repos_groups/repos_groups_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )
 

	
 

	
rhodecode/controllers/admin/users.py
Show inline comments
 
@@ -185,13 +185,13 @@ class UsersController(BaseController):
 
    def update_perm(self, id):
 
        """PUT /users_perm/id: Update an existing item"""
 
        # url('user_perm', id=ID, method='put')
 

	
 
        grant_perm = request.POST.get('create_repo_perm', False)
 
        user_model = UserModel()
 
        
 

	
 
        if grant_perm:
 
            perm = Permission.get_by_key('hg.create.none')
 
            user_model.revoke_perm(id, perm)
 

	
 
            perm = Permission.get_by_key('hg.create.repository')
 
            user_model.grant_perm(id, perm)
rhodecode/controllers/admin/users_groups.py
Show inline comments
 
@@ -110,15 +110,15 @@ class UsersGroupsController(BaseControll
 
        c.users_group = UsersGroup.get(id)
 
        c.group_members = [(x.user_id, x.user.username) for x in
 
                           c.users_group.members]
 

	
 
        c.available_members = [(x.user_id, x.username) for x in
 
                               self.sa.query(User).all()]
 
        
 

	
 
        available_members = [safe_unicode(x[0]) for x in c.available_members]
 
        
 

	
 
        users_group_form = UsersGroupForm(edit=True,
 
                                          old_data=c.users_group.get_dict(),
 
                                          available_members=available_members)()
 

	
 
        try:
 
            form_result = users_group_form.to_python(request.POST)
 
@@ -207,13 +207,13 @@ class UsersGroupsController(BaseControll
 
            UsersGroupModel().revoke_perm(id, perm)
 

	
 
            perm = Permission.get_by_key('hg.create.repository')
 
            UsersGroupModel().grant_perm(id, perm)
 
            h.flash(_("Granted 'repository create' permission to user"),
 
                    category='success')
 
            
 

	
 
            Session.commit()
 
        else:
 
            perm = Permission.get_by_key('hg.create.repository')
 
            UsersGroupModel().revoke_perm(id, perm)
 

	
 
            perm = Permission.get_by_key('hg.create.none')
rhodecode/controllers/api/__init__.py
Show inline comments
 
@@ -4,25 +4,25 @@
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    JSON RPC controller
 

	
 
    :created_on: Aug 20, 2011
 
    :author: marcink
 
    :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>    
 
    :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# 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,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# 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.
 

	
 
import inspect
 
@@ -223,13 +223,13 @@ class JSONRPCController(WSGIController):
 
            json_exc = JSONRPCError('Internal server error')
 
            self._error = str(json_exc)
 

	
 
        if self._error is not None:
 
            raw_response = None
 

	
 
        response = dict(id=self._req_id, result=raw_response, 
 
        response = dict(id=self._req_id, result=raw_response,
 
                        error=self._error)
 

	
 
        try:
 
            return json.dumps(response)
 
        except TypeError, e:
 
            log.debug('Error encoding response: %s', e)
 
@@ -256,7 +256,6 @@ class JSONRPCController(WSGIController):
 
                                 "method name.")
 

	
 
        if isinstance(func, types.MethodType):
 
            return func
 
        else:
 
            raise AttributeError("No such method: %s" % self._req_method)
 

	
rhodecode/controllers/bookmarks.py
Show inline comments
 
@@ -42,13 +42,13 @@ class BookmarksController(BaseRepoContro
 
    def __before__(self):
 
        super(BookmarksController, self).__before__()
 

	
 
    def index(self):
 
        if c.rhodecode_repo.alias != 'hg':
 
            raise HTTPNotFound()
 
        
 

	
 
        c.repo_bookmarks = OrderedDict()
 

	
 
        bookmarks = [(name, c.rhodecode_repo.get_changeset(hash_)) for \
 
                 name, hash_ in c.rhodecode_repo._repo._bookmarks.items()]
 
        ordered_tags = sorted(bookmarks, key=lambda x: x[1].date, reverse=True)
 
        for name, cs_book in ordered_tags:
rhodecode/controllers/changelog.py
Show inline comments
 
@@ -68,27 +68,27 @@ class ChangelogController(BaseRepoContro
 
            c.size = int(session.get('changelog_size', default))
 

	
 
        p = int(request.params.get('page', 1))
 
        branch_name = request.params.get('branch', None)
 
        try:
 
            if branch_name:
 
                collection = [z for z in 
 
                              c.rhodecode_repo.get_changesets(start=0, 
 
                collection = [z for z in
 
                              c.rhodecode_repo.get_changesets(start=0,
 
                                                    branch_name=branch_name)]
 
                c.total_cs = len(collection)
 
            else:
 
                collection = list(c.rhodecode_repo)
 
                c.total_cs = len(c.rhodecode_repo)
 

	
 
        
 

	
 
            c.pagination = RepoPage(collection, page=p, item_count=c.total_cs,
 
                                    items_per_page=c.size, branch=branch_name)
 
        except (RepositoryError, ChangesetDoesNotExistError, Exception), e:
 
            log.error(traceback.format_exc())
 
            h.flash(str(e), category='warning')
 
            return redirect(url('home'))        
 
            return redirect(url('home'))
 

	
 
        self._graph(c.rhodecode_repo, collection, c.total_cs, c.size, p)
 

	
 
        c.branch_name = branch_name
 
        c.branch_filters = [('',_('All Branches'))] + \
 
            [(k,k) for k in c.rhodecode_repo.branches.keys()]
 
@@ -136,7 +136,6 @@ class ChangelogController(BaseRepoContro
 
            for (id, type, ctx, vtx, edges) in c.dag:
 
                if type != graphmod.CHANGESET:
 
                    continue
 
                data.append(['', vtx, edges])
 

	
 
        c.jsdata = json.dumps(data)
 

	
rhodecode/controllers/files.py
Show inline comments
 
@@ -414,13 +414,13 @@ class FilesController(BaseRepoController
 
                c.changeset_2 = c.rhodecode_repo.get_changeset(diff2)
 
                node2 = c.changeset_2.get_node(f_path)
 
            else:
 
                c.changeset_2 = EmptyChangeset(repo=c.rhodecode_repo)
 
                node2 = FileNode('.', '', changeset=c.changeset_2)
 
        except RepositoryError:
 
            return redirect(url('files_home', repo_name=c.repo_name, 
 
            return redirect(url('files_home', repo_name=c.repo_name,
 
                                f_path=f_path))
 

	
 
        if c.action == 'download':
 
            _diff = diffs.get_gitdiff(node1, node2,
 
                                      ignore_whitespace=ignore_whitespace,
 
                                      context=line_context)
 
@@ -487,7 +487,6 @@ class FilesController(BaseRepoController
 
    def nodelist(self, repo_name, revision, f_path):
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            cs = self.__get_cs_or_redirect(revision, repo_name)
 
            _d, _f = ScmModel().get_nodes(repo_name, cs.raw_id, f_path,
 
                                          flat=False)
 
            return _d + _f
 

	
rhodecode/controllers/home.py
Show inline comments
 
@@ -63,7 +63,6 @@ class HomeController(BaseController):
 
        if request.is_xhr:
 
            c.rhodecode_db_repo = Repository.get_by_repo_name(c.repo_name)
 
            c.rhodecode_repo = c.rhodecode_db_repo.scm_instance
 
            return render('/switch_to_list.html')
 
        else:
 
            return HTTPBadRequest()
 

	
rhodecode/controllers/login.py
Show inline comments
 
@@ -78,13 +78,13 @@ class LoginController(BaseController):
 
                session.save()
 

	
 
                log.info('user %s is now authenticated and stored in '
 
                         'session, session attrs %s' % (username, cs))
 
                user.update_lastlogin()
 
                Session.commit()
 
                
 

	
 
                if c.came_from:
 
                    return redirect(c.came_from)
 
                else:
 
                    return redirect(url('home'))
 

	
 
            except formencode.Invalid, errors:
rhodecode/controllers/summary.py
Show inline comments
 
@@ -230,7 +230,6 @@ class SummaryController(BaseRepoControll
 
        for name, chs in c.rhodecode_repo.tags.items():
 
            #chs = chs.split(':')[-1]
 
            tags_group[0].append((chs, name),)
 
        download_l.append(tags_group)
 

	
 
        return download_l
 

	
rhodecode/lib/__init__.py
Show inline comments
 
@@ -113,18 +113,18 @@ def str2bool(_str):
 
    return _str in ('t', 'true', 'y', 'yes', 'on', '1')
 

	
 

	
 
def convert_line_endings(line, mode):
 
    """
 
    Converts a given line  "line end" accordingly to given mode
 
    
 

	
 
    Available modes are::
 
        0 - Unix
 
        1 - Mac
 
        2 - DOS
 
    
 

	
 
    :param line: given line to convert
 
    :param mode: mode to convert to
 
    :rtype: str
 
    :return: converted line according to mode
 
    """
 
    from string import replace
 
@@ -180,13 +180,13 @@ def generate_api_key(username, salt=None
 
    return hashlib.sha1(username + salt).hexdigest()
 

	
 

	
 
def safe_unicode(str_, from_encoding='utf8'):
 
    """
 
    safe unicode function. Does few trick to turn str_ into unicode
 
     
 

	
 
    In case of UnicodeDecode error we try to return it with encoding detected
 
    by chardet library if it fails fallback to unicode with errors replaced
 

	
 
    :param str_: string to decode
 
    :rtype: unicode
 
    :returns: unicode object
 
@@ -213,13 +213,13 @@ def safe_unicode(str_, from_encoding='ut
 
    except (ImportError, UnicodeDecodeError, Exception):
 
        return unicode(str_, from_encoding, 'replace')
 

	
 
def safe_str(unicode_, to_encoding='utf8'):
 
    """
 
    safe str function. Does few trick to turn unicode_ into string
 
     
 

	
 
    In case of UnicodeEncodeError we try to return it with encoding detected
 
    by chardet library if it fails fallback to string with errors replaced
 

	
 
    :param unicode_: unicode to encode
 
    :rtype: str
 
    :returns: str object
 
@@ -251,13 +251,13 @@ def safe_str(unicode_, to_encoding='utf8
 

	
 

	
 

	
 
def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
 
    """
 
    Custom engine_from_config functions that makes sure we use NullPool for
 
    file based sqlite databases. This prevents errors on sqlite. This only 
 
    file based sqlite databases. This prevents errors on sqlite. This only
 
    applies to sqlalchemy versions < 0.7.0
 

	
 
    """
 
    import sqlalchemy
 
    from sqlalchemy import engine_from_config as efc
 
    import logging
 
@@ -310,13 +310,13 @@ def engine_from_config(configuration, pr
 
    return engine
 

	
 

	
 
def age(curdate):
 
    """
 
    turns a datetime into an age string.
 
    
 

	
 
    :param curdate: datetime object
 
    :rtype: unicode
 
    :returns: unicode words describing age
 
    """
 

	
 
    from datetime import datetime
 
@@ -347,16 +347,16 @@ def age(curdate):
 
    return _(u'just now')
 

	
 

	
 
def uri_filter(uri):
 
    """
 
    Removes user:password from given url string
 
    
 

	
 
    :param uri:
 
    :rtype: unicode
 
    :returns: filtered list of strings  
 
    :returns: filtered list of strings
 
    """
 
    if not uri:
 
        return ''
 

	
 
    proto = ''
 

	
 
@@ -379,28 +379,28 @@ def uri_filter(uri):
 
    return filter(None, [proto, host, port])
 

	
 

	
 
def credentials_filter(uri):
 
    """
 
    Returns a url with removed credentials
 
    
 

	
 
    :param uri:
 
    """
 

	
 
    uri = uri_filter(uri)
 
    #check if we have port
 
    if len(uri) > 2 and uri[2]:
 
        uri[2] = ':' + uri[2]
 

	
 
    return ''.join(uri)
 

	
 
def get_changeset_safe(repo, rev):
 
    """
 
    Safe version of get_changeset if this changeset doesn't exists for a 
 
    Safe version of get_changeset if this changeset doesn't exists for a
 
    repo it returns a Dummy one instead
 
    
 

	
 
    :param repo:
 
    :param rev:
 
    """
 
    from vcs.backends.base import BaseRepository
 
    from vcs.exceptions import RepositoryError
 
    if not isinstance(repo, BaseRepository):
 
@@ -416,13 +416,13 @@ def get_changeset_safe(repo, rev):
 

	
 

	
 
def get_current_revision(quiet=False):
 
    """
 
    Returns tuple of (number, id) from repository containing this package
 
    or None if repository could not be found.
 
    
 

	
 
    :param quiet: prints error for fetching revision if True
 
    """
 

	
 
    try:
 
        from vcs import get_repo
 
        from vcs.utils.helpers import get_scm
 
@@ -437,13 +437,13 @@ def get_current_revision(quiet=False):
 
                   "was: %s" % err)
 
        return None
 

	
 
def extract_mentioned_users(s):
 
    """
 
    Returns unique usernames from given string s that have @mention
 
    
 

	
 
    :param s: string to get mentions
 
    """
 
    usrs = {}
 
    for username in re.findall(r'(?:^@|\s@)(\w+)', s):
 
        usrs[username] = username
 

	
rhodecode/lib/annotate.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.lib.annotate
 
    ~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Anontation library for usage in rhodecode, previously part of vcs
 
    
 

	
 
    :created_on: Dec 4, 2011
 
    :author: marcink
 
    :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>    
 
    :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 

	
 
from vcs.exceptions import VCSError
 
from vcs.nodes import FileNode
 
from pygments.formatters import HtmlFormatter
rhodecode/lib/auth.py
Show inline comments
 
@@ -53,13 +53,13 @@ from rhodecode.model.db import Permissio
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class PasswordGenerator(object):
 
    """
 
    This is a simple class for generating password from different sets of 
 
    This is a simple class for generating password from different sets of
 
    characters
 
    usage::
 

	
 
        passwd_gen = PasswordGenerator()
 
        #print 8-letter password containing only big and small letters
 
            of alphabet
 
@@ -128,26 +128,26 @@ def get_crypt_password(password):
 
def check_password(password, hashed):
 
    return RhodeCodeCrypto.hash_check(password, hashed)
 

	
 
def generate_api_key(str_, salt=None):
 
    """
 
    Generates API KEY from given string
 
    
 

	
 
    :param str_:
 
    :param salt:
 
    """
 

	
 
    if salt is None:
 
        salt = _RandomNameSequence().next()
 

	
 
    return hashlib.sha1(str_ + salt).hexdigest()
 

	
 

	
 
def authfunc(environ, username, password):
 
    """
 
    Dummy authentication wrapper function used in Mercurial and Git for 
 
    Dummy authentication wrapper function used in Mercurial and Git for
 
    access control.
 

	
 
    :param environ: needed only for using in Basic auth
 
    """
 
    return authenticate(username, password)
 

	
 
@@ -223,14 +223,14 @@ def authenticate(username, password):
 
                 'email': get_ldap_attr('ldap_attr_email'),
 
                }
 

	
 
                if user_model.create_ldap(username, password, user_dn,
 
                                          user_attrs):
 
                    log.info('created new ldap user %s', username)
 
                    
 
                Session.commit()    
 

	
 
                Session.commit()
 
                return True
 
            except (LdapUsernameError, LdapPasswordError,):
 
                pass
 
            except (Exception,):
 
                log.error(traceback.format_exc())
 
                pass
 
@@ -251,13 +251,13 @@ def login_container_auth(username):
 

	
 
    if not user.active:
 
        return None
 

	
 
    user.update_lastlogin()
 
    Session.commit()
 
    
 

	
 
    log.debug('User %s is now logged in by container authentication',
 
              user.username)
 
    return user
 

	
 
def get_container_username(environ, config):
 
    username = None
 
@@ -308,21 +308,21 @@ class  AuthUser(object):
 
        is_user_loaded = False
 

	
 
        # try go get user by api key
 
        if self._api_key and self._api_key != self.anonymous_user.api_key:
 
            log.debug('Auth User lookup by API KEY %s', self._api_key)
 
            is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
 
        # lookup by userid    
 
        # lookup by userid
 
        elif (self.user_id is not None and
 
              self.user_id != self.anonymous_user.user_id):
 
            log.debug('Auth User lookup by USER ID %s', self.user_id)
 
            is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
 
        # lookup by username
 
        elif self.username and \
 
            str2bool(config.get('container_auth_enabled', False)):
 
            
 

	
 
            log.debug('Auth User lookup by USER NAME %s', self.username)
 
            dbuser = login_container_auth(self.username)
 
            if dbuser is not None:
 
                for k, v in dbuser.get_dict().items():
 
                    setattr(self, k, v)
 
                self.set_authenticated()
 
@@ -693,7 +693,6 @@ class HasPermissionAnyMiddleware(object)
 
                                                self.username, self.repo_name)
 
        if self.required_perms.intersection(self.user_perms):
 
            log.debug('permission granted')
 
            return True
 
        log.debug('permission denied')
 
        return False
 

	
rhodecode/lib/backup_manager.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.lib.backup_manager
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Mercurial repositories backup manager, it allows to backups all 
 
    Mercurial repositories backup manager, it allows to backups all
 
    repositories and send it to backup server using RSA key via ssh.
 

	
 
    :created_on: Feb 28, 2010
 
    :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
rhodecode/lib/base.py
Show inline comments
 
@@ -172,7 +172,6 @@ class BaseRepoController(BaseController)
 
                          'cannot be created as an scm instance', c.repo_name)
 

	
 
                redirect(url('home'))
 

	
 
            c.repository_followers = self.scm_model.get_followers(c.repo_name)
 
            c.repository_forks = self.scm_model.get_forks(c.repo_name)
 

	
rhodecode/lib/celerylib/tasks.py
Show inline comments
 
@@ -111,13 +111,13 @@ def get_commits_stats(repo_name, ts_min_
 

	
 
        co_day_auth_aggr = {}
 
        commits_by_day_aggregate = {}
 
        repo = Repository.get_by_repo_name(repo_name)
 
        if repo is None:
 
            return True
 
        
 

	
 
        repo = repo.scm_instance
 
        repo_size = repo.count()
 
        # return if repo have no revisions
 
        if repo_size < 1:
 
            lock.release()
 
            return True
 
@@ -361,13 +361,13 @@ def send_email(recipients, subject, body
 

	
 

	
 
@task(ignore_result=True)
 
def create_repo_fork(form_data, cur_user):
 
    """
 
    Creates a fork of repository using interval VCS methods
 
    
 

	
 
    :param form_data:
 
    :param cur_user:
 
    """
 
    from rhodecode.model.repo import RepoModel
 

	
 
    log = get_logger(create_repo_fork)
 
@@ -389,15 +389,15 @@ def create_repo_fork(form_data, cur_user
 
    backend = get_backend(alias)
 
    backend(safe_str(destination_fork_path), create=True,
 
            src_url=safe_str(source_repo_path),
 
            update_after_clone=update_after_clone)
 
    action_logger(cur_user, 'user_forked_repo:%s' % fork_name,
 
                   org_repo_name, '', Session)
 
    
 

	
 
    action_logger(cur_user, 'user_created_fork:%s' % fork_name,
 
                   fork_name, '', Session)    
 
                   fork_name, '', Session)
 
    # finally commit at latest possible stage
 
    Session.commit()
 

	
 
def __get_codes_stats(repo_name):
 
    repo = Repository.get_by_repo_name(repo_name).scm_instance
 

	
rhodecode/lib/compat.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.lib.compat
 
    ~~~~~~~~~~~~~~~~~~~~
 

	
 
    Python backward compatibility functions and common libs
 
    
 
    
 

	
 

	
 
    :created_on: Oct 7, 2011
 
    :author: marcink
 
    :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>    
 
    :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# 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, either version 3 of the License, or
 
# (at your option) any later version.
 
@@ -87,13 +87,13 @@ class _Nil(object):
 

	
 
_nil = _Nil()
 

	
 
class _odict(object):
 
    """Ordered dict data structure, with O(1) complexity for dict operations
 
    that modify one element.
 
    
 

	
 
    Overwriting values doesn't change their original sequential order.
 
    """
 

	
 
    def _dict_impl(self):
 
        return None
 

	
rhodecode/lib/dbmigrate/migrate/__init__.py
Show inline comments
 
@@ -5,7 +5,7 @@
 
   using Python.
 
"""
 

	
 
from rhodecode.lib.dbmigrate.migrate.versioning import *
 
from rhodecode.lib.dbmigrate.migrate.changeset import *
 

	
 
__version__ = '0.7.3.dev'
 
\ No newline at end of file
 
__version__ = '0.7.3.dev'
rhodecode/lib/dbmigrate/migrate/changeset/__init__.py
Show inline comments
 
@@ -9,13 +9,13 @@ import warnings
 

	
 
import sqlalchemy
 
from sqlalchemy import __version__ as _sa_version
 

	
 
warnings.simplefilter('always', DeprecationWarning)
 

	
 
_sa_version = tuple(int(re.match("\d+", x).group(0)) 
 
_sa_version = tuple(int(re.match("\d+", x).group(0))
 
                    for x in _sa_version.split("."))
 
SQLA_06 = _sa_version >= (0, 6)
 
SQLA_07 = _sa_version >= (0, 7)
 

	
 
del re
 
del _sa_version
rhodecode/lib/dbmigrate/migrate/versioning/genmodel.py
Show inline comments
 
@@ -279,7 +279,6 @@ class ModelGenerator(object):
 
                    connection.execute(getCopyStatement())
 
                    connection.execute('DROP TABLE %s' % tempName)
 
                    trans.commit()
 
                except:
 
                    trans.rollback()
 
                    raise
 

	
rhodecode/lib/dbmigrate/migrate/versioning/repository.py
Show inline comments
 
@@ -150,13 +150,13 @@ class Repository(pathed.Pathed):
 
            templates_path=t_path, **opts)
 

	
 
        return cls(path)
 

	
 
    def create_script(self, description, **k):
 
        """API to :meth:`migrate.versioning.version.Collection.create_new_python_version`"""
 
        
 

	
 
        k['use_timestamp_numbering'] = self.use_timestamp_numbering
 
        self.versions.create_new_python_version(description, **k)
 

	
 
    def create_script_sql(self, database, description, **k):
 
        """API to :meth:`migrate.versioning.version.Collection.create_new_sql_version`"""
 
        k['use_timestamp_numbering'] = self.use_timestamp_numbering
rhodecode/lib/dbmigrate/migrate/versioning/version.py
Show inline comments
 
@@ -57,13 +57,13 @@ class Collection(pathed.Pathed):
 

	
 
    def __init__(self, path):
 
        """Collect current version scripts in repository
 
        and store them in self.versions
 
        """
 
        super(Collection, self).__init__(path)
 
        
 

	
 
        # Create temporary list of files, allowing skipped version numbers.
 
        files = os.listdir(path)
 
        if '1' in files:
 
            # deprecation
 
            raise Exception('It looks like you have a repository in the old '
 
                'format (with directories for each version). '
 
@@ -108,13 +108,13 @@ class Collection(pathed.Pathed):
 

	
 
        filename = '%03d%s.py' % (ver, extra)
 
        filepath = self._version_path(filename)
 

	
 
        script.PythonScript.create(filepath, **k)
 
        self.versions[ver] = Version(ver, self.path, [filename])
 
        
 

	
 
    def create_new_sql_version(self, database, description, **k):
 
        """Create SQL files for new version"""
 
        ver = self._next_ver_num(k.pop('use_timestamp_numbering', False))
 
        self.versions[ver] = Version(ver, self.path, [])
 

	
 
        extra = str_to_filename(description)
 
@@ -128,13 +128,13 @@ class Collection(pathed.Pathed):
 
        # Create new files.
 
        for op in ('upgrade', 'downgrade'):
 
            filename = '%03d%s_%s_%s.sql' % (ver, extra, database, op)
 
            filepath = self._version_path(filename)
 
            script.SqlScript.create(filepath, **k)
 
            self.versions[ver].add_script(filepath)
 
        
 

	
 
    def version(self, vernum=None):
 
        """Returns latest Version if vernum is not given.
 
        Otherwise, returns wanted version"""
 
        if vernum is None:
 
            vernum = self.latest
 
        return self.versions[VerNum(vernum)]
 
@@ -147,13 +147,13 @@ class Collection(pathed.Pathed):
 
        """Returns path of file in versions repository"""
 
        return os.path.join(self.path, str(ver))
 

	
 

	
 
class Version(object):
 
    """A single version in a collection
 
    :param vernum: Version Number 
 
    :param vernum: Version Number
 
    :param path: Path to script files
 
    :param filelist: List of scripts
 
    :type vernum: int, VerNum
 
    :type path: string
 
    :type filelist: list
 
    """
 
@@ -164,13 +164,13 @@ class Version(object):
 
        # Collect scripts in this folder
 
        self.sql = dict()
 
        self.python = None
 

	
 
        for script in filelist:
 
            self.add_script(os.path.join(path, script))
 
    
 

	
 
    def script(self, database=None, operation=None):
 
        """Returns SQL or Python Script"""
 
        for db in (database, 'default'):
 
            # Try to return a .sql script first
 
            try:
 
                return self.sql[db][operation]
 
@@ -193,13 +193,13 @@ class Version(object):
 

	
 
    SQL_FILENAME = re.compile(r'^.*\.sql')
 

	
 
    def _add_script_sql(self, path):
 
        basename = os.path.basename(path)
 
        match = self.SQL_FILENAME.match(basename)
 
        
 

	
 
        if match:
 
            basename = basename.replace('.sql', '')
 
            parts = basename.split('_')
 
            if len(parts) < 3:
 
                raise exceptions.ScriptError(
 
                    "Invalid SQL script name %s " % basename + \
rhodecode/lib/dbmigrate/schema/__init__.py
Show inline comments
 
@@ -2,13 +2,13 @@
 
"""
 
    rhodecode.lib.dbmigrate.schema
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 

	
 
    Schemas for migrations
 
    
 
    
 

	
 

	
 
    :created_on: Nov 1, 2011
 
    :author: marcink
 
    :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>    
 
    :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
 
    :license: <name>, see LICENSE_FILE for more details.
 
"""
rhodecode/lib/dbmigrate/schema/db_1_1_0.py
Show inline comments
 
@@ -88,7 +88,7 @@ class CacheInvalidation(Base, BaseModel)
 
    def __init__(self, cache_key, cache_args=''):
 
        self.cache_key = cache_key
 
        self.cache_args = cache_args
 
        self.cache_active = False
 

	
 
    def __repr__(self):
 
        return "<CacheInvalidation('%s:%s')>" % (self.cache_id, self.cache_key)
 
\ No newline at end of file
 
        return "<CacheInvalidation('%s:%s')>" % (self.cache_id, self.cache_key)
rhodecode/lib/dbmigrate/schema/db_1_2_0.py
Show inline comments
 
@@ -1041,25 +1041,25 @@ class CacheInvalidation(Base, BaseModel)
 
    @classmethod
 
    def invalidate(cls, key):
 
        """
 
        Returns Invalidation object if this given key should be invalidated
 
        None otherwise. `cache_active = False` means that this cache
 
        state is not valid and needs to be invalidated
 
        
 

	
 
        :param key:
 
        """
 
        return cls.query()\
 
                .filter(CacheInvalidation.cache_key == key)\
 
                .filter(CacheInvalidation.cache_active == False)\
 
                .scalar()
 

	
 
    @classmethod
 
    def set_invalidate(cls, key):
 
        """
 
        Mark this Cache key for invalidation
 
        
 

	
 
        :param key:
 
        """
 

	
 
        log.debug('marking %s for invalidation' % key)
 
        inv_obj = Session.query(cls)\
 
            .filter(cls.cache_key == key).scalar()
 
@@ -1077,13 +1077,13 @@ class CacheInvalidation(Base, BaseModel)
 
            Session.rollback()
 

	
 
    @classmethod
 
    def set_valid(cls, key):
 
        """
 
        Mark this cache key as active and currently cached
 
        
 

	
 
        :param key:
 
        """
 
        inv_obj = Session.query(CacheInvalidation)\
 
            .filter(CacheInvalidation.cache_key == key).scalar()
 
        inv_obj.cache_active = True
 
        Session.add(inv_obj)
 
@@ -1092,7 +1092,6 @@ class CacheInvalidation(Base, BaseModel)
 
class DbMigrateVersion(Base, BaseModel):
 
    __tablename__ = 'db_migrate_version'
 
    __table_args__ = {'extend_existing':True}
 
    repository_id = Column('repository_id', String(250), primary_key=True)
 
    repository_path = Column('repository_path', Text)
 
    version = Column('version', Integer)
 

	
rhodecode/lib/dbmigrate/schema/db_1_3_0.py
Show inline comments
 
@@ -18,7 +18,7 @@
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# 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, see <http://www.gnu.org/licenses/>.
 
\ No newline at end of file
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
rhodecode/lib/dbmigrate/versions/002_version_1_1_0.py
Show inline comments
 
@@ -68,13 +68,13 @@ def upgrade(migrate_engine):
 

	
 
    #==========================================================================
 
    # Add table `user_followings`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_1_0 import UserFollowing
 
    UserFollowing().__table__.create()
 
    
 

	
 
    #==========================================================================
 
    # Add table `cache_invalidation`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_1_0 import CacheInvalidation
 
    CacheInvalidation().__table__.create()
 

	
rhodecode/lib/dbmigrate/versions/003_version_1_2_0.py
Show inline comments
 
@@ -80,13 +80,13 @@ def upgrade(migrate_engine):
 

	
 
    clone_uri = Column("clone_uri", String(length=255, convert_unicode=False,
 
                                           assert_unicode=None),
 
                        nullable=True, unique=False, default=None)
 

	
 
    clone_uri.create(Repository().__table__)
 
    
 

	
 
    #ADD downloads column#
 
    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
 
    enable_downloads.create(Repository().__table__)
 

	
 
    #ADD column created_on
 
    created_on = Column('created_on', DateTime(timezone=False), nullable=True,
 
@@ -103,14 +103,14 @@ def upgrade(migrate_engine):
 
    #==========================================================================
 
    # Upgrade of `user_followings` table
 
    #==========================================================================
 

	
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UserFollowing
 

	
 
    follows_from = Column('follows_from', DateTime(timezone=False), 
 
                          nullable=True, unique=None, 
 
    follows_from = Column('follows_from', DateTime(timezone=False),
 
                          nullable=True, unique=None,
 
                          default=datetime.datetime.now)
 
    follows_from.create(UserFollowing().__table__)
 

	
 
    return
 

	
 

	
rhodecode/lib/dbmigrate/versions/004_version_1_3_0.py
Show inline comments
 
@@ -15,13 +15,13 @@ log = logging.getLogger(__name__)
 

	
 
def upgrade(migrate_engine):
 
    """ Upgrade operations go here.
 
    Don't create your own engine; bind migrate_engine to your metadata
 
    """
 

	
 
    
 

	
 

	
 
    return
 

	
 

	
 
def downgrade(migrate_engine):
 
    meta = MetaData()
rhodecode/lib/helpers.py
Show inline comments
 
@@ -582,13 +582,13 @@ class RepoPage(Page):
 
        if self.item_count > 0:
 
            self.first_page = 1
 
            self.page_count = int(math.ceil(float(self.item_count) /
 
                                            self.items_per_page))
 
            self.last_page = self.first_page + self.page_count - 1
 

	
 
            # Make sure that the requested page number is the range of 
 
            # Make sure that the requested page number is the range of
 
            # valid pages
 
            if self.page > self.last_page:
 
                self.page = self.last_page
 
            elif self.page < self.first_page:
 
                self.page = self.first_page
 

	
 
@@ -629,13 +629,13 @@ class RepoPage(Page):
 

	
 

	
 
def changed_tooltip(nodes):
 
    """
 
    Generates a html string for changed nodes in changeset page.
 
    It limits the output to 30 entries
 
    
 

	
 
    :param nodes: LazyNodesGenerator
 
    """
 
    if nodes:
 
        pref = ': <br/> '
 
        suf = ''
 
        if len(nodes) > 30:
 
@@ -648,16 +648,16 @@ def changed_tooltip(nodes):
 

	
 

	
 
def repo_link(groups_and_repos):
 
    """
 
    Makes a breadcrumbs link to repo within a group
 
    joins &raquo; on each group to create a fancy link
 
    
 

	
 
    ex::
 
        group >> subgroup >> repo
 
    
 

	
 
    :param groups_and_repos:
 
    """
 
    groups, repo_name = groups_and_repos
 

	
 
    if not groups:
 
        return repo_name
 
@@ -669,13 +669,13 @@ def repo_link(groups_and_repos):
 
                       " &raquo; " + repo_name)
 

	
 
def fancy_file_stats(stats):
 
    """
 
    Displays a fancy two colored bar for number of added/deleted
 
    lines of code on file
 
    
 

	
 
    :param stats: two element list of added/deleted lines of code
 
    """
 

	
 
    a, d, t = stats[0], stats[1], stats[0] + stats[1]
 
    width = 100
 
    unit = float(width) / (t or 1)
 
@@ -742,11 +742,11 @@ def rst(source):
 
    return literal('<div class="rst-block">%s</div>' %
 
                   MarkupRenderer.rst(source))
 

	
 
def rst_w_mentions(source):
 
    """
 
    Wrapped rst renderer with @mention highlighting
 
    
 

	
 
    :param source:
 
    """
 
    return literal('<div class="rst-block">%s</div>' %
 
                   MarkupRenderer.rst_with_mentions(source))
rhodecode/lib/markup_renderer.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.lib.markup_renderer
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    
 

	
 
    Renderer for markup languages with ability to parse using rst or markdown
 
    
 

	
 
    :created_on: Oct 27, 2011
 
    :author: marcink
 
    :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software: you can redistribute it and/or modify
 
@@ -30,24 +30,24 @@ import logging
 
from rhodecode.lib import safe_unicode
 

	
 
log = logging.getLogger(__name__)
 

	
 
class MarkupRenderer(object):
 
    RESTRUCTUREDTEXT_DISALLOWED_DIRECTIVES = ['include', 'meta', 'raw']
 
    
 

	
 
    MARKDOWN_PAT = re.compile(r'md|mkdn?|mdown|markdown',re.IGNORECASE)
 
    RST_PAT = re.compile(r're?st',re.IGNORECASE)
 
    PLAIN_PAT = re.compile(r'readme',re.IGNORECASE)
 
    
 

	
 
    def __detect_renderer(self, source, filename=None):
 
        """
 
        runs detection of what renderer should be used for generating html
 
        from a markup language
 
        
 

	
 
        filename can be also explicitly a renderer name
 
        
 

	
 
        :param source:
 
        :param filename:
 
        """
 

	
 
        if MarkupRenderer.MARKDOWN_PAT.findall(filename):
 
            detected_renderer = 'markdown'
 
@@ -63,13 +63,13 @@ class MarkupRenderer(object):
 

	
 
    def render(self, source, filename=None):
 
        """
 
        Renders a given filename using detected renderer
 
        it detects renderers based on file extension or mimetype.
 
        At last it will just do a simple html replacing new lines with <br/>
 
        
 

	
 
        :param file_name:
 
        :param source:
 
        """
 

	
 
        renderer = self.__detect_renderer(source, filename)
 
        readme_data = renderer(source)
 
@@ -127,13 +127,12 @@ class MarkupRenderer(object):
 
            log.warning('Install docutils to use this function')
 
            return cls.plain(source)
 

	
 
    @classmethod
 
    def rst_with_mentions(cls, source):
 
        mention_pat = re.compile(r'(?:^@|\s@)(\w+)')
 
        
 

	
 
        def wrapp(match_obj):
 
            uname = match_obj.groups()[0]
 
            return ' **@%(uname)s** ' % {'uname':uname}
 
        mention_hl = mention_pat.sub(wrapp, source).strip()
 
        return cls.rst(mention_hl)
 

	
rhodecode/lib/middleware/simplegit.py
Show inline comments
 
@@ -158,13 +158,13 @@ class SimpleGit(BaseVCSController):
 
                #==============================================================
 

	
 
                if action in ['pull', 'push']:
 
                    try:
 
                        user = self.__get_user(username)
 
                        if user is None or not user.active:
 
                            return HTTPForbidden()(environ, start_response)                        
 
                            return HTTPForbidden()(environ, start_response)
 
                        username = user.username
 
                    except:
 
                        log.error(traceback.format_exc())
 
                        return HTTPInternalServerError()(environ,
 
                                                         start_response)
 

	
 
@@ -196,13 +196,13 @@ class SimpleGit(BaseVCSController):
 
            log.error(traceback.format_exc())
 
            return HTTPInternalServerError()(environ, start_response)
 

	
 
    def __make_app(self, repo_name, repo_path):
 
        """
 
        Make an wsgi application using dulserver
 
        
 

	
 
        :param repo_name: name of the repository
 
        :param repo_path: full path to the repository
 
        """
 

	
 
        _d = {'/' + repo_name: Repo(repo_path)}
 
        backend = dulserver.DictBackend(_d)
rhodecode/lib/middleware/simplehg.py
Show inline comments
 
@@ -222,15 +222,15 @@ class SimpleHg(BaseVCSController):
 
                    return 'pull'
 

	
 

	
 
    def __inject_extras(self, repo_path, baseui, extras={}):
 
        """
 
        Injects some extra params into baseui instance
 
        
 

	
 
        also overwrites global settings with those takes from local hgrc file
 
        
 

	
 
        :param baseui: baseui instance
 
        :param extras: dict with extra params to put into baseui
 
        """
 

	
 
        hgrc = os.path.join(repo_path, '.hg', 'hgrc')
 

	
 
@@ -246,7 +246,6 @@ class SimpleHg(BaseVCSController):
 

	
 
        if repoui:
 
            #overwrite our ui instance with the section from hgrc file
 
            for section in ui_sections:
 
                for k, v in repoui.configitems(section):
 
                    baseui.setconfig(section, k, v)
 

	
rhodecode/lib/rcmail/exceptions.py
Show inline comments
 
@@ -2,10 +2,10 @@
 
class InvalidMessage(RuntimeError):
 
    """
 
    Raised if message is missing vital headers, such
 
    as recipients or sender address.
 
    """
 

	
 
class BadHeaders(RuntimeError): 
 
class BadHeaders(RuntimeError):
 
    """
 
    Raised if message contains newlines in headers.
 
    """
rhodecode/lib/rcmail/message.py
Show inline comments
 
@@ -10,17 +10,17 @@ class Attachment(object):
 
    :param filename: filename of attachment
 
    :param content_type: file mimetype
 
    :param data: the raw file data, either as string or file obj
 
    :param disposition: content-disposition (if any)
 
    """
 

	
 
    def __init__(self, 
 
                 filename=None, 
 
                 content_type=None, 
 
    def __init__(self,
 
                 filename=None,
 
                 content_type=None,
 
                 data=None,
 
                 disposition=None): 
 
                 disposition=None):
 

	
 
        self.filename = filename
 
        self.content_type = content_type
 
        self.disposition = disposition or 'attachment'
 
        self._data = data
 

	
 
@@ -44,17 +44,17 @@ class Message(object):
 
    :param cc: CC list
 
    :param bcc: BCC list
 
    :param extra_headers: dict of extra email headers
 
    :param attachments: list of Attachment instances
 
    """
 

	
 
    def __init__(self, 
 
                 subject=None, 
 
                 recipients=None, 
 
                 body=None, 
 
                 html=None, 
 
    def __init__(self,
 
                 subject=None,
 
                 recipients=None,
 
                 body=None,
 
                 html=None,
 
                 sender=None,
 
                 cc=None,
 
                 bcc=None,
 
                 extra_headers=None,
 
                 attachments=None):
 

	
 
@@ -75,23 +75,23 @@ class Message(object):
 
        return set(self.recipients) | set(self.bcc or ()) | set(self.cc or ())
 

	
 
    def to_message(self):
 
        """
 
        Returns raw email.Message instance.Validates message first.
 
        """
 
        
 

	
 
        self.validate()
 

	
 
        return self.get_response().to_message()
 

	
 
    def get_response(self):
 
        """
 
        Creates a Lamson MailResponse instance
 
        """
 

	
 
        response = MailResponse(Subject=self.subject, 
 
        response = MailResponse(Subject=self.subject,
 
                                To=self.recipients,
 
                                From=self.sender,
 
                                Body=self.body,
 
                                Html=self.html)
 

	
 
        if self.bcc:
 
@@ -99,36 +99,36 @@ class Message(object):
 

	
 
        if self.cc:
 
            response.base['Cc'] = self.cc
 

	
 
        for attachment in self.attachments:
 

	
 
            response.attach(attachment.filename, 
 
                            attachment.content_type, 
 
                            attachment.data, 
 
            response.attach(attachment.filename,
 
                            attachment.content_type,
 
                            attachment.data,
 
                            attachment.disposition)
 

	
 
        response.update(self.extra_headers)
 

	
 
        return response
 
    
 

	
 
    def is_bad_headers(self):
 
        """
 
        Checks for bad headers i.e. newlines in subject, sender or recipients.
 
        """
 
       
 

	
 
        headers = [self.subject, self.sender]
 
        headers += list(self.send_to)
 
        headers += self.extra_headers.values()
 

	
 
        for val in headers:
 
            for c in '\r\n':
 
                if c in val:
 
                    return True
 
        return False
 
        
 

	
 
    def validate(self):
 
        """
 
        Checks if message is valid and raises appropriate exception.
 
        """
 

	
 
        if not self.recipients:
 
@@ -143,30 +143,30 @@ class Message(object):
 
        if self.is_bad_headers():
 
            raise BadHeaders
 

	
 
    def add_recipient(self, recipient):
 
        """
 
        Adds another recipient to the message.
 
        
 

	
 
        :param recipient: email address of recipient.
 
        """
 
        
 

	
 
        self.recipients.append(recipient)
 

	
 
    def add_cc(self, recipient):
 
        """
 
        Adds an email address to the CC list. 
 
        Adds an email address to the CC list.
 

	
 
        :param recipient: email address of recipient.
 
        """
 

	
 
        self.cc.append(recipient)
 

	
 
    def add_bcc(self, recipient):
 
        """
 
        Adds an email address to the BCC list. 
 
        Adds an email address to the BCC list.
 

	
 
        :param recipient: email address of recipient.
 
        """
 

	
 
        self.bcc.append(recipient)
 

	
 
@@ -175,8 +175,6 @@ class Message(object):
 
        Adds an attachment to the message.
 

	
 
        :param attachment: an **Attachment** instance.
 
        """
 

	
 
        self.attachments.append(attachment)
 

	
 

	
rhodecode/lib/rcmail/response.py
Show inline comments
 
@@ -45,26 +45,26 @@ ADDRESS_HEADERS_WHITELIST = ['From', 'To
 
DEFAULT_ENCODING = "utf-8"
 
VALUE_IS_EMAIL_ADDRESS = lambda v: '@' in v
 

	
 
def normalize_header(header):
 
    return string.capwords(header.lower(), '-')
 

	
 
class EncodingError(Exception): 
 
class EncodingError(Exception):
 
    """Thrown when there is an encoding error."""
 
    pass
 

	
 
class MailBase(object):
 
    """MailBase is used as the basis of lamson.mail and contains the basics of
 
    encoding an email.  You actually can do all your email processing with this
 
    class, but it's more raw.
 
    """
 
    def __init__(self, items=()):
 
        self.headers = dict(items)
 
        self.parts = []
 
        self.body = None
 
        self.content_encoding = {'Content-Type': (None, {}), 
 
        self.content_encoding = {'Content-Type': (None, {}),
 
                                 'Content-Disposition': (None, {}),
 
                                 'Content-Transfer-Encoding': (None, {})}
 

	
 
    def __getitem__(self, key):
 
        return self.headers.get(normalize_header(key), None)
 

	
 
@@ -309,13 +309,13 @@ class MailResponse(object):
 

	
 
    def keys(self):
 
        return self.base.keys()
 

	
 
def to_message(mail):
 
    """
 
    Given a MailBase message, this will construct a MIMEPart 
 
    Given a MailBase message, this will construct a MIMEPart
 
    that is canonicalized for use with the Python email API.
 
    """
 
    ctype, params = mail.content_encoding['Content-Type']
 

	
 
    if not ctype:
 
        if mail.parts:
rhodecode/lib/utils.py
Show inline comments
 
@@ -198,13 +198,13 @@ def is_valid_repo(repo_name, base_path):
 
    except VCSError:
 
        return False
 

	
 
def is_valid_repos_group(repos_group_name, base_path):
 
    """
 
    Returns True if given path is a repos group False otherwise
 
    
 

	
 
    :param repo_name:
 
    :param base_path:
 
    """
 
    full_path = os.path.join(base_path, repos_group_name)
 

	
 
    # check if it's not a repo
 
@@ -458,13 +458,13 @@ def add_cache(settings):
 
#==============================================================================
 
# TEST FUNCTIONS AND CREATORS
 
#==============================================================================
 
def create_test_index(repo_location, config, full_index):
 
    """
 
    Makes default test index
 
    
 

	
 
    :param config: test config
 
    :param full_index:
 
    """
 

	
 
    from rhodecode.lib.indexers.daemon import WhooshIndexingDaemon
 
    from rhodecode.lib.pidlock import DaemonLock, LockHeld
 
@@ -594,7 +594,7 @@ class BasePasterCommand(Command):
 
        Loads the pylons configuration.
 
        """
 
        from pylons import config as pylonsconfig
 

	
 
        path_to_ini_file = os.path.realpath(conf)
 
        conf = paste.deploy.appconfig('config:' + path_to_ini_file)
 
        pylonsconfig.init_app(conf.global_conf, conf.local_conf)
 
\ No newline at end of file
 
        pylonsconfig.init_app(conf.global_conf, conf.local_conf)
rhodecode/model/db.py
Show inline comments
 
@@ -93,23 +93,23 @@ class BaseModel(object):
 
        """return column names for this model """
 
        return class_mapper(cls).c.keys()
 

	
 
    def get_dict(self, serialized=False):
 
        """
 
        return dict with keys and values corresponding
 
        to this model data 
 
        to this model data
 
        """
 

	
 
        d = {}
 
        for k in self._get_keys():
 
            d[k] = getattr(self, k)
 

	
 
        # also use __json__() if present to get additional fields
 
        if hasattr(self, '__json__'):
 
            for k, val in self.__json__().iteritems():
 
                d[k] = val 
 
                d[k] = val
 
        return d
 

	
 
    def get_appstruct(self):
 
        """return list with keys and values tupples corresponding
 
        to this model data """
 

	
 
@@ -967,25 +967,25 @@ class CacheInvalidation(Base, BaseModel)
 
    @classmethod
 
    def invalidate(cls, key):
 
        """
 
        Returns Invalidation object if this given key should be invalidated
 
        None otherwise. `cache_active = False` means that this cache
 
        state is not valid and needs to be invalidated
 
        
 

	
 
        :param key:
 
        """
 
        return cls.query()\
 
                .filter(CacheInvalidation.cache_key == key)\
 
                .filter(CacheInvalidation.cache_active == False)\
 
                .scalar()
 

	
 
    @classmethod
 
    def set_invalidate(cls, key):
 
        """
 
        Mark this Cache key for invalidation
 
        
 

	
 
        :param key:
 
        """
 

	
 
        log.debug('marking %s for invalidation' % key)
 
        inv_obj = Session.query(cls)\
 
            .filter(cls.cache_key == key).scalar()
 
@@ -1003,13 +1003,13 @@ class CacheInvalidation(Base, BaseModel)
 
            Session.rollback()
 

	
 
    @classmethod
 
    def set_valid(cls, key):
 
        """
 
        Mark this cache key as active and currently cached
 
        
 

	
 
        :param key:
 
        """
 
        inv_obj = CacheInvalidation.query()\
 
            .filter(CacheInvalidation.cache_key == key).scalar()
 
        inv_obj.cache_active = True
 
        Session.add(inv_obj)
 
@@ -1034,13 +1034,13 @@ class ChangesetComment(Base, BaseModel):
 

	
 
    @classmethod
 
    def get_users(cls, revision):
 
        """
 
        Returns user associated with this changesetComment. ie those
 
        who actually commented
 
        
 

	
 
        :param cls:
 
        :param revision:
 
        """
 
        return Session.query(User)\
 
                .filter(cls.revision == revision)\
 
                .join(ChangesetComment.author).all()
 
@@ -1117,7 +1117,6 @@ class UserNotification(Base, BaseModel):
 
class DbMigrateVersion(Base, BaseModel):
 
    __tablename__ = 'db_migrate_version'
 
    __table_args__ = {'extend_existing':True}
 
    repository_id = Column('repository_id', String(250), primary_key=True)
 
    repository_path = Column('repository_path', Text)
 
    version = Column('version', Integer)
 

	
rhodecode/model/forms.py
Show inline comments
 
@@ -480,13 +480,13 @@ class LoginForm(formencode.Schema):
 
                            messages={
 
                                'empty':_('Please enter a password'),
 
                                'tooShort':_('Enter %(min)i characters or more')}
 
                                )
 

	
 
    remember = StringBoolean(if_missing=False)
 
    
 

	
 
    chained_validators = [ValidAuth]
 

	
 
def UserForm(edit=False, old_data={}):
 
    class _UserForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = True
rhodecode/model/notification.py
Show inline comments
 
@@ -65,13 +65,13 @@ class NotificationModel(BaseModel):
 
        Creates notification of given type
 

	
 
        :param created_by: int, str or User instance. User who created this
 
            notification
 
        :param subject:
 
        :param body:
 
        :param recipients: list of int, str or User objects, when None 
 
        :param recipients: list of int, str or User objects, when None
 
            is given send to all admins
 
        :param type_: type of notification
 
        :param with_email: send email with this notification
 
        :param email_kwargs: additional dict to pass as args to email template
 
        """
 
        from rhodecode.lib.celerylib import tasks, run_task
 
@@ -203,19 +203,17 @@ class EmailNotificationModel(BaseModel):
 
            self.TYPE_DEFAULT:'email_templates/default.html'
 
        }
 

	
 
    def get_email_tmpl(self, type_, **kwargs):
 
        """
 
        return generated template for email based on given type
 
        
 

	
 
        :param type_:
 
        """
 

	
 
        base = self.email_types.get(type_, self.email_types[self.TYPE_DEFAULT])
 
        email_template = self._tmpl_lookup.get_template(base)
 
        # translator inject
 
        _kwargs = {'_':_}
 
        _kwargs.update(kwargs)
 
        log.debug('rendering tmpl %s with kwargs %s' % (base, _kwargs))
 
        return email_template.render(**_kwargs)
 

	
 

	
rhodecode/model/repo.py
Show inline comments
 
@@ -91,15 +91,15 @@ class RepoModel(BaseModel):
 
                                     len(gr.members))
 
                                        for gr in users_groups])
 
        return users_groups_array
 

	
 
    def _get_defaults(self, repo_name):
 
        """
 
        Get's information about repository, and returns a dict for 
 
        Get's information about repository, and returns a dict for
 
        usage in forms
 
        
 

	
 
        :param repo_name:
 
        """
 

	
 
        repo_info = Repository.get_by_repo_name(repo_name)
 

	
 
        if repo_info is None:
 
@@ -296,13 +296,13 @@ class RepoModel(BaseModel):
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def create_fork(self, form_data, cur_user):
 
        """
 
        Simple wrapper into executing celery task for fork creation
 
        
 

	
 
        :param form_data:
 
        :param cur_user:
 
        """
 
        from rhodecode.lib.celerylib import tasks, run_task
 
        run_task(tasks.create_repo_fork, form_data, cur_user)
 

	
 
@@ -337,13 +337,13 @@ class RepoModel(BaseModel):
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def delete_stats(self, repo_name):
 
        """
 
        removes stats for given repo
 
        
 

	
 
        :param repo_name:
 
        """
 
        try:
 
            obj = self.sa.query(Statistics)\
 
                    .filter(Statistics.repository == \
 
                        self.get_by_repo_name(repo_name)).one()
 
@@ -424,7 +424,6 @@ class RepoModel(BaseModel):
 
                    os.path.join(rm_path, 'rm__.%s' % alias))
 
        # disable repo
 
        shutil.move(rm_path, os.path.join(self.repos_path, 'rm__%s__%s' \
 
                                          % (datetime.today()\
 
                                             .strftime('%Y%m%d_%H%M%S_%f'),
 
                                            repo.repo_name)))
 

	
rhodecode/model/repo_permission.py
Show inline comments
 
@@ -60,13 +60,13 @@ class RepositoryPermissionModel(BaseMode
 
    def get_users_group_permission(self, repository, users_group):
 
        return UsersGroupRepoToPerm.query() \
 
                .filter(UsersGroupRepoToPerm.users_group == users_group) \
 
                .filter(UsersGroupRepoToPerm.repository == repository) \
 
                .scalar()
 

	
 
    def update_users_group_permission(self, repository, users_group, 
 
    def update_users_group_permission(self, repository, users_group,
 
                                      permission):
 
        permission = Permission.get_by_key(permission)
 
        current = self.get_users_group_permission(repository, users_group)
 
        if current:
 
            if not current.permission is permission:
 
                current.permission = permission
 
@@ -91,7 +91,7 @@ class RepositoryPermissionModel(BaseMode
 
    def update_or_delete_users_group_permission(self, repository, user_group,
 
                                              permission):
 
        if permission:
 
            self.update_users_group_permission(repository, user_group,
 
                                               permission)
 
        else:
 
            self.delete_users_group_permission(repository, user_group)
 
\ No newline at end of file
 
            self.delete_users_group_permission(repository, user_group)
rhodecode/model/repos_group.py
Show inline comments
 
@@ -65,13 +65,13 @@ class ReposGroupModel(BaseModel):
 

	
 
        os.makedirs(create_path)
 

	
 
    def __rename_group(self, old, new):
 
        """
 
        Renames a group on filesystem
 
        
 

	
 
        :param group_name:
 
        """
 

	
 
        if old == new:
 
            log.debug('skipping group rename')
 
            return
 
@@ -89,13 +89,13 @@ class ReposGroupModel(BaseModel):
 
                            'existing dir %s' % new_path)
 
        shutil.move(old_path, new_path)
 

	
 
    def __delete_group(self, group):
 
        """
 
        Deletes a group from a filesystem
 
        
 

	
 
        :param group: instance of group from database
 
        """
 
        paths = group.full_path.split(RepoGroup.url_sep())
 
        paths = os.sep.join(paths)
 

	
 
        rm_path = os.path.join(self.repos_path, paths)
 
@@ -133,13 +133,13 @@ class ReposGroupModel(BaseModel):
 
            new_path = repos_group.full_path
 

	
 
            self.sa.add(repos_group)
 

	
 
            self.__rename_group(old_path, new_path)
 

	
 
            # we need to get all repositories from this new group and 
 
            # we need to get all repositories from this new group and
 
            # rename them accordingly to new group path
 
            for r in repos_group.repositories:
 
                r.repo_name = r.get_new_name(r.just_name)
 
                self.sa.add(r)
 

	
 
            return repos_group
rhodecode/model/user.py
Show inline comments
 
@@ -94,13 +94,13 @@ class UserModel(BaseModel):
 

	
 

	
 
    def create_or_update(self, username, password, email, name, lastname,
 
                         active=True, admin=False, ldap_dn=None):
 
        """
 
        Creates a new instance if not found, or updates current one
 
        
 

	
 
        :param username:
 
        :param password:
 
        :param email:
 
        :param active:
 
        :param name:
 
        :param lastname:
 
@@ -137,13 +137,13 @@ class UserModel(BaseModel):
 
            raise
 

	
 

	
 
    def create_for_container_auth(self, username, attrs):
 
        """
 
        Creates the given user if it's not already in the database
 
        
 

	
 
        :param username:
 
        :param attrs:
 
        """
 
        if self.get_by_username(username, case_insensitive=True) is None:
 

	
 
            # autogenerate email for container account without one
 
@@ -170,13 +170,13 @@ class UserModel(BaseModel):
 
        return None
 

	
 
    def create_ldap(self, username, password, user_dn, attrs):
 
        """
 
        Checks if user is in database, if not creates this user marked
 
        as ldap user
 
        
 

	
 
        :param username:
 
        :param password:
 
        :param user_dn:
 
        :param attrs:
 
        """
 
        from rhodecode.lib.auth import get_crypt_password
 
@@ -280,13 +280,13 @@ class UserModel(BaseModel):
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def delete(self, user):
 
        user = self.__get_user(user)
 
        
 

	
 
        try:
 
            if user.username == 'default':
 
                raise DefaultUserException(
 
                                _("You can't remove this user since it's"
 
                                  " crucial for entire application"))
 
            if user.repositories:
 
@@ -495,13 +495,13 @@ class UserModel(BaseModel):
 

	
 

	
 
    def revoke_perm(self, user, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class '
 
                            'got %s instead' % type(perm))
 
        
 

	
 
        user = self.__get_user(user)
 
        
 

	
 
        obj = UserToPerm.query().filter(UserToPerm.user == user)\
 
                .filter(UserToPerm.permission == perm).scalar()
 
        if obj:
 
            self.sa.delete(obj)
rhodecode/model/users_group.py
Show inline comments
 
@@ -79,21 +79,21 @@ class UsersGroupModel(BaseModel):
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def delete(self, users_group):
 
        try:
 
            users_group = self.__get_users_group(users_group)
 
            
 

	
 
            # check if this group is not assigned to repo
 
            assigned_groups = UsersGroupRepoToPerm.query()\
 
                .filter(UsersGroupRepoToPerm.users_group == users_group).all()
 

	
 
            if assigned_groups:
 
                raise UsersGroupsAssignedException('RepoGroup assigned to %s' %
 
                                                   assigned_groups)
 
            
 

	
 
            self.sa.delete(users_group)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def add_user_to_group(self, users_group, user):
 
@@ -138,15 +138,13 @@ class UsersGroupModel(BaseModel):
 
        self.sa.add(new)
 

	
 

	
 
    def revoke_perm(self, users_group, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 
        
 

	
 
        users_group = self.__get_users_group(users_group)
 
        
 

	
 
        obj = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == users_group)\
 
            .filter(UsersGroupToPerm.permission == perm).one()
 
        self.sa.delete(obj)
 

	
 

	
rhodecode/tests/__init__.py
Show inline comments
 
@@ -41,13 +41,13 @@ __all__ = [
 

	
 
# Invoke websetup with the current config file
 
# SetupCommand('setup-app').run([config_file])
 

	
 
##RUNNING DESIRED TESTS
 
# nosetests -x rhodecode.tests.functional.test_admin_settings:TestSettingsController.test_my_account
 
# nosetests --pdb --pdb-failures 
 
# nosetests --pdb --pdb-failures
 
environ = {}
 

	
 
#SOME GLOBALS FOR TESTS
 

	
 
TESTS_TMP_PATH = jn('/', 'tmp', 'rc_test_%s' % _RandomNameSequence().next())
 
TEST_USER_ADMIN_LOGIN = 'test_admin'
 
@@ -104,7 +104,6 @@ class TestController(TestCase):
 
    def _get_logged_user(self):
 
        return User.get_by_username(self._logged_username)
 

	
 
    def checkSessionFlash(self, response, msg):
 
        self.assertTrue('flash' in response.session)
 
        self.assertTrue(msg in response.session['flash'][0][1])
 

	
rhodecode/tests/functional/test_admin_ldap_settings.py
Show inline comments
 
@@ -19,13 +19,13 @@ class TestLdapSettingsController(TestCon
 
        self.assertTrue('LDAP administration' in response.body)
 

	
 
    def test_ldap_save_settings(self):
 
        self.log_user()
 
        if skip_ldap_test:
 
            raise SkipTest('skipping due to missing ldap lib')
 
        
 

	
 
        test_url = url(controller='admin/ldap_settings',
 
                       action='ldap_settings')
 

	
 
        response = self.app.post(url=test_url,
 
            params={'ldap_host' : u'dc.example.com',
 
                    'ldap_port' : '999',
 
@@ -50,13 +50,13 @@ class TestLdapSettingsController(TestCon
 
                               'Ldap settings updated successfully')
 

	
 
    def test_ldap_error_form(self):
 
        self.log_user()
 
        if skip_ldap_test:
 
            raise SkipTest('skipping due to missing ldap lib')
 
                
 

	
 
        test_url = url(controller='admin/ldap_settings',
 
                       action='ldap_settings')
 

	
 
        response = self.app.post(url=test_url,
 
            params={'ldap_host' : '',
 
                    'ldap_port' : 'i-should-be-number',
 
@@ -68,19 +68,19 @@ class TestLdapSettingsController(TestCon
 
                    'ldap_filter':'',
 
                    'ldap_search_scope':'BASE',
 
                    'ldap_attr_login':'', #  <----- missing required input
 
                    'ldap_attr_firstname':'',
 
                    'ldap_attr_lastname':'',
 
                    'ldap_attr_email':'' })
 
        
 

	
 
        self.assertTrue("""<span class="error-message">The LDAP Login"""
 
                        """ attribute of the CN must be specified""" in
 
                        response.body)
 
        
 
        
 
        
 

	
 

	
 

	
 
        self.assertTrue("""<span class="error-message">Please """
 
                        """enter a number</span>""" in response.body)
 

	
 
    def test_ldap_login(self):
 
        pass
 

	
rhodecode/tests/functional/test_admin_users.py
Show inline comments
 
@@ -20,23 +20,23 @@ class TestAdminUsersController(TestContr
 
        password = 'test12'
 
        password_confirmation = password
 
        name = 'name'
 
        lastname = 'lastname'
 
        email = 'mail@mail.com'
 

	
 
        response = self.app.post(url('users'), 
 
        response = self.app.post(url('users'),
 
                                 {'username':username,
 
                                   'password':password,
 
                                   'password_confirmation':password_confirmation,
 
                                   'name':name,
 
                                   'active':True,
 
                                   'lastname':lastname,
 
                                   'email':email})
 

	
 

	
 
        self.assertTrue('''created user %s''' % (username) in 
 
        self.assertTrue('''created user %s''' % (username) in
 
                        response.session['flash'][0])
 

	
 
        new_user = self.Session.query(User).\
 
            filter(User.username == username).one()
 

	
 
        self.assertEqual(new_user.username,username)
 
@@ -105,18 +105,18 @@ class TestAdminUsersController(TestContr
 
        response = response.follow()
 

	
 
        new_user = self.Session.query(User)\
 
            .filter(User.username == username).one()
 
        response = self.app.delete(url('user', id=new_user.user_id))
 

	
 
        self.assertTrue("""successfully deleted user""" in 
 
        self.assertTrue("""successfully deleted user""" in
 
                        response.session['flash'][0])
 

	
 

	
 
    def test_delete_browser_fakeout(self):
 
        response = self.app.post(url('user', id=1), 
 
        response = self.app.post(url('user', id=1),
 
                                 params=dict(_method='delete'))
 

	
 
    def test_show(self):
 
        response = self.app.get(url('user', id=1))
 

	
 
    def test_show_as_xml(self):
rhodecode/tests/functional/test_admin_users_groups.py
Show inline comments
 
@@ -82,10 +82,6 @@ class TestAdminUsersGroupsController(Tes
 

	
 
    def test_add_create_permission(self):
 
        pass
 

	
 
    def test_revoke_members(self):
 
        pass
 

	
 

	
 

	
 

	
rhodecode/tests/functional/test_branches.py
Show inline comments
 
@@ -6,12 +6,6 @@ class TestBranchesController(TestControl
 
        self.log_user()
 
        response = self.app.get(url(controller='branches',
 
                                    action='index', repo_name=HG_REPO))
 
        response.mustcontain("""<a href="/%s/files/27cd5cce30c96924232dffcd24178a07ffeb5dfc/">default</a>""" % HG_REPO)
 
        response.mustcontain("""<a href="/%s/files/97e8b885c04894463c51898e14387d80c30ed1ee/">git</a>""" % HG_REPO)
 
        response.mustcontain("""<a href="/%s/files/2e6a2bf9356ca56df08807f4ad86d480da72a8f4/">web</a>""" % HG_REPO)
 

	
 

	
 

	
 

	
 

	
 

	
rhodecode/tests/functional/test_changeset_comments.py
Show inline comments
 
@@ -134,10 +134,6 @@ class TestChangeSetCommentrController(Te
 
        self.assertEqual(len(comments), 0)
 

	
 
        response = self.app.get(url(controller='changeset', action='index',
 
                                repo_name=HG_REPO, revision=rev))
 
        self.assertTrue('''<div class="comments-number">0 comment(s)'''
 
                        ''' (0 inline)</div>''' in response.body)
 

	
 

	
 

	
 

	
rhodecode/tests/functional/test_files.py
Show inline comments
 
@@ -311,16 +311,13 @@ removed extra unicode conversion in diff
 
                                    f_path=f_path))
 

	
 
        assert "There is no file nor directory at the given path: %r at revision %r" % (f_path, rev[:12]) in response.session['flash'][0][1], 'No flash message'
 

	
 
    def test_ajaxed_files_list(self):
 
        self.log_user()
 
        rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' 
 
        rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc'
 
        response = self.app.get(url('files_nodelist_home',repo_name=HG_REPO,
 
                                    f_path='/',
 
                                    revision=rev),
 
                                extra_environ={'HTTP_X_PARTIAL_XHR':'1'},
 
                                )
 
        self.assertTrue("vcs/web/simplevcs/views/repository.py" in response.body)
 

	
 

	
 

	
rhodecode/tests/functional/test_summary.py
Show inline comments
 
@@ -6,13 +6,13 @@ from rhodecode.lib.utils import invalida
 
class TestSummaryController(TestController):
 

	
 
    def test_index(self):
 
        self.log_user()
 
        ID = Repository.get_by_repo_name(HG_REPO).repo_id
 
        response = self.app.get(url(controller='summary',
 
                                    action='index', 
 
                                    action='index',
 
                                    repo_name=HG_REPO))
 

	
 
        #repo type
 
        response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
 
                        """title="Mercurial repository" alt="Mercurial """
 
                        """repository" src="/images/icons/hgicon.png"/>""")
 
@@ -41,13 +41,13 @@ class TestSummaryController(TestControll
 
        response.mustcontain("""<input style="display:none;width:80%;margin-left:105px" type="text" id="clone_url_id" readonly="readonly" value="http://test_admin@localhost:80/_1"/>""")
 

	
 
    def test_index_by_id(self):
 
        self.log_user()
 
        ID = Repository.get_by_repo_name(HG_REPO).repo_id
 
        response = self.app.get(url(controller='summary',
 
                                    action='index', 
 
                                    action='index',
 
                                    repo_name='_%s' % ID))
 

	
 
        #repo type
 
        response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
 
                        """title="Mercurial repository" alt="Mercurial """
 
                        """repository" src="/images/icons/hgicon.png"/>""")
rhodecode/tests/functional/test_tags.py
Show inline comments
 
@@ -7,7 +7,6 @@ class TestTagsController(TestController)
 
        response = self.app.get(url(controller='tags', action='index', repo_name=HG_REPO))
 
        response.mustcontain("""<a href="/%s/files/27cd5cce30c96924232dffcd24178a07ffeb5dfc/">tip</a>""" % HG_REPO)
 
        response.mustcontain("""<a href="/%s/files/fd4bdb5e9b2a29b4393a4ac6caef48c17ee1a200/">0.1.4</a>""" % HG_REPO)
 
        response.mustcontain("""<a href="/%s/files/17544fbfcd33ffb439e2b728b5d526b1ef30bfcf/">0.1.3</a>""" % HG_REPO)
 
        response.mustcontain("""<a href="/%s/files/a7e60bff65d57ac3a1a1ce3b12a70f8a9e8a7720/">0.1.2</a>""" % HG_REPO)
 
        response.mustcontain("""<a href="/%s/files/eb3a60fc964309c1a318b8dfe26aa2d1586c85ae/">0.1.1</a>""" % HG_REPO)
 

	
rhodecode/tests/rhodecode_crawler.py
Show inline comments
 
@@ -3,13 +3,13 @@
 
    rhodecode.tests.test_crawer
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Test for crawling a project for memory usage
 
    This should be runned just as regular script together
 
    with a watch script that will show memory usage.
 
    
 

	
 
    watch -n1 ./rhodecode/tests/mem_watch
 

	
 
    :created_on: Apr 21, 2010
 
    :author: marcink
 
    :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
rhodecode/tests/test_libs.py
Show inline comments
 
@@ -2,13 +2,13 @@
 
"""
 
    rhodecode.tests.test_libs
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 

	
 
    Package for testing various lib/helper functions in rhodecode
 
    
 

	
 
    :created_on: Jun 9, 2011
 
    :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# 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
 
@@ -109,8 +109,6 @@ class TestLibs(unittest.TestCase):
 
        sample = ("@first hi there @marcink here's my email marcin@email.com "
 
                  "@lukaszb check it pls @ ttwelve @D[] @one@two@three "
 
                  "@MARCIN    @maRCiN @2one_more22")
 
        s = ['2one_more22', 'D', 'MARCIN', 'first', 'lukaszb',
 
             'maRCiN', 'marcink', 'one']
 
        self.assertEqual(s, extract_mentioned_users(sample))
 

	
 

	
rhodecode/tests/test_models.py
Show inline comments
 
@@ -158,13 +158,13 @@ class TestReposGroups(unittest.TestCase)
 
        self.assertEqual(r.repo_name, os.path.join('g2', 'g1', r.just_name))
 

	
 
class TestUser(unittest.TestCase):
 
    def __init__(self, methodName='runTest'):
 
        Session.remove()
 
        super(TestUser, self).__init__(methodName=methodName)
 
        
 

	
 
    def test_create_and_remove(self):
 
        usr = UserModel().create_or_update(username=u'test_user', password=u'qweqwe',
 
                                     email=u'u232@rhodecode.org',
 
                                     name=u'u1', lastname=u'u1')
 
        Session.commit()
 
        self.assertEqual(User.get_by_username(u'test_user'), usr)
 
@@ -367,19 +367,19 @@ class TestUsers(unittest.TestCase):
 
        super(TestUsers, self).__init__(methodName=methodName)
 

	
 
    def setUp(self):
 
        self.u1 = UserModel().create_or_update(username=u'u1',
 
                                        password=u'qweqwe',
 
                                        email=u'u1@rhodecode.org',
 
                                        name=u'u1', lastname=u'u1')        
 
                                        name=u'u1', lastname=u'u1')
 

	
 
    def tearDown(self):
 
        perm = Permission.query().all()
 
        for p in perm:
 
            UserModel().revoke_perm(self.u1, p)
 
            
 

	
 
        UserModel().delete(self.u1)
 
        Session.commit()
 

	
 
    def test_add_perm(self):
 
        perm = Permission.query().all()[0]
 
        UserModel().grant_perm(self.u1, perm)
 
@@ -399,12 +399,6 @@ class TestUsers(unittest.TestCase):
 
        self.assertEqual(UserModel().has_perm(self.u1, perm), True)
 

	
 
        #revoke
 
        UserModel().revoke_perm(self.u1, perm)
 
        Session.commit()
 
        self.assertEqual(UserModel().has_perm(self.u1, perm),False)
 
        
 
    
 

	
 
        
 

	
 

	
0 comments (0 inline, 0 general)