Changeset - 260a7a01b054
[Not reviewed]
beta
0 23 0
Mads Kiilerich - 13 years ago 2013-03-28 01:10:45
madski@unity3d.com
follow Python conventions for boolean values

True and False might be singletons and the "default" values for "boolean"
expressions, but "all" values in Python has a boolean value and should be
evaluated as such. Checking with 'is True' and 'is False' is thus confusing,
error prone and unnessarily complex.

If we anywhere rely and nullable boolean fields from the database layer and
don't want the null value to be treated as False then we should check
explicitly for null with 'is None'.
23 files changed with 37 insertions and 37 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/notifications.py
Show inline comments
 
@@ -150,24 +150,24 @@ class NotificationsController(BaseContro
 
        no = Notification.get(notification_id)
 

	
 
        owner = any(un.user.user_id == c.rhodecode_user.user_id
 
                    for un in no.notifications_to_users)
 

	
 
        if no and (h.HasPermissionAny('hg.admin', 'repository.admin')() or owner):
 
            unotification = NotificationModel()\
 
                            .get_user_notification(c.user.user_id, no)
 

	
 
            # if this association to user is not valid, we don't want to show
 
            # this message
 
            if unotification:
 
                if unotification.read is False:
 
                if not unotification.read:
 
                    unotification.mark_as_read()
 
                    Session().commit()
 
                c.notification = no
 

	
 
                return render('admin/notifications/show_notification.html')
 

	
 
        return abort(403)
 

	
 
    def edit(self, notification_id, format='html'):
 
        """GET /_admin/notifications/id/edit: Form to edit an existing item"""
 
        # url('edit_notification', notification_id=ID)
rhodecode/controllers/admin/repos_groups.py
Show inline comments
 
@@ -339,25 +339,25 @@ class ReposGroupsController(BaseControll
 

	
 
        c.group = c.repos_group = ReposGroupModel()._get_repos_group(group_name)
 
        c.group_repos = c.group.repositories.all()
 

	
 
        #overwrite our cached list with current filter
 
        gr_filter = c.group_repos
 
        c.repo_cnt = 0
 

	
 
        groups = RepoGroup.query().order_by(RepoGroup.group_name)\
 
            .filter(RepoGroup.group_parent_id == c.group.group_id).all()
 
        c.groups = self.scm_model.get_repos_groups(groups)
 

	
 
        if c.visual.lightweight_dashboard is False:
 
        if not c.visual.lightweight_dashboard:
 
            c.repos_list = self.scm_model.get_repos(all_repos=gr_filter)
 
        ## lightweight version of dashboard
 
        else:
 
            c.repos_list = Repository.query()\
 
                            .filter(Repository.group_id == c.group.group_id)\
 
                            .order_by(func.lower(Repository.repo_name))\
 
                            .all()
 

	
 
            repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
 
                                                       admin=False)
 
            #json used to render the grid
 
            c.data = json.dumps(repos_data)
rhodecode/controllers/files.py
Show inline comments
 
@@ -407,25 +407,25 @@ class FilesController(BaseRepoController
 
        ext = None
 
        subrepos = request.GET.get('subrepos') == 'true'
 

	
 
        for a_type, ext_data in settings.ARCHIVE_SPECS.items():
 
            archive_spec = fname.split(ext_data[1])
 
            if len(archive_spec) == 2 and archive_spec[1] == '':
 
                fileformat = a_type or ext_data[1]
 
                revision = archive_spec[0]
 
                ext = ext_data[1]
 

	
 
        try:
 
            dbrepo = RepoModel().get_by_repo_name(repo_name)
 
            if dbrepo.enable_downloads is False:
 
            if not dbrepo.enable_downloads:
 
                return _('downloads disabled')
 

	
 
            if c.rhodecode_repo.alias == 'hg':
 
                # patch and reset hooks section of UI config to not run any
 
                # hooks on fetching archives with subrepos
 
                for k, v in c.rhodecode_repo._repo.ui.configitems('hooks'):
 
                    c.rhodecode_repo._repo.ui.setconfig('hooks', k, None)
 

	
 
            cs = c.rhodecode_repo.get_changeset(revision)
 
            content_type = settings.ARCHIVE_SPECS[fileformat][0]
 
        except ChangesetDoesNotExistError:
 
            return _('Unknown revision %s') % revision
rhodecode/controllers/home.py
Show inline comments
 
@@ -43,25 +43,25 @@ log = logging.getLogger(__name__)
 

	
 

	
 
class HomeController(BaseController):
 

	
 
    @LoginRequired()
 
    def __before__(self):
 
        super(HomeController, self).__before__()
 

	
 
    def index(self):
 
        c.groups = self.scm_model.get_repos_groups()
 
        c.group = None
 

	
 
        if c.visual.lightweight_dashboard is False:
 
        if not c.visual.lightweight_dashboard:
 
            c.repos_list = self.scm_model.get_repos()
 
        ## lightweight version of dashboard
 
        else:
 
            c.repos_list = Repository.query()\
 
                            .filter(Repository.group_id == None)\
 
                            .order_by(func.lower(Repository.repo_name))\
 
                            .all()
 

	
 
            repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
 
                                                       admin=False)
 
            #json used to render the grid
 
            c.data = json.dumps(repos_data)
rhodecode/controllers/login.py
Show inline comments
 
@@ -67,25 +67,25 @@ class LoginController(BaseController):
 
                c.form_result = login_form.to_python(dict(request.POST))
 
                # form checks for username/password, now we're authenticated
 
                username = c.form_result['username']
 
                user = User.get_by_username(username, case_insensitive=True)
 
                auth_user = AuthUser(user.user_id)
 
                auth_user.set_authenticated()
 
                cs = auth_user.get_cookie_store()
 
                session['rhodecode_user'] = cs
 
                user.update_lastlogin()
 
                Session().commit()
 

	
 
                # If they want to be remembered, update the cookie
 
                if c.form_result['remember'] is not False:
 
                if c.form_result['remember']:
 
                    _year = (datetime.datetime.now() +
 
                             datetime.timedelta(seconds=60 * 60 * 24 * 365))
 
                    session._set_cookie_expires(_year)
 

	
 
                session.save()
 

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

	
 
                # dumps session attrs back to cookie
 
                session._update_cookie_out()
 

	
rhodecode/lib/auth.py
Show inline comments
 
@@ -372,25 +372,25 @@ class  AuthUser(object):
 
            dbuser = login_container_auth(self.username)
 
            if dbuser is not None:
 
                log.debug('filling all attributes to object')
 
                for k, v in dbuser.get_dict().items():
 
                    setattr(self, k, v)
 
                self.set_authenticated()
 
                is_user_loaded = True
 
        else:
 
            log.debug('No data in %s that could been used to log in' % self)
 

	
 
        if not is_user_loaded:
 
            # if we cannot authenticate user try anonymous
 
            if self.anonymous_user.active is True:
 
            if self.anonymous_user.active:
 
                user_model.fill_data(self, user_id=self.anonymous_user.user_id)
 
                # then we set this user is logged in
 
                self.is_authenticated = True
 
            else:
 
                self.user_id = None
 
                self.username = None
 
                self.is_authenticated = False
 

	
 
        if not self.username:
 
            self.username = 'None'
 

	
 
        log.debug('Auth User is now %s' % self)
rhodecode/lib/celerylib/__init__.py
Show inline comments
 
@@ -115,16 +115,16 @@ def get_session():
 
        engine = engine_from_config(config, 'sqlalchemy.db1.')
 
        init_model(engine)
 
    sa = meta.Session()
 
    return sa
 

	
 

	
 
def dbsession(func):
 
    def __wrapper(func, *fargs, **fkwargs):
 
        try:
 
            ret = func(*fargs, **fkwargs)
 
            return ret
 
        finally:
 
            if CELERY_ON and CELERY_EAGER is False:
 
            if CELERY_ON and not CELERY_EAGER:
 
                meta.Session.remove()
 

	
 
    return decorator(__wrapper, func)
rhodecode/lib/db_manage.py
Show inline comments
 
@@ -60,27 +60,27 @@ def notify(msg):
 
class DbManage(object):
 
    def __init__(self, log_sql, dbconf, root, tests=False, cli_args={}):
 
        self.dbname = dbconf.split('/')[-1]
 
        self.tests = tests
 
        self.root = root
 
        self.dburi = dbconf
 
        self.log_sql = log_sql
 
        self.db_exists = False
 
        self.cli_args = cli_args
 
        self.init_db()
 
        global ask_ok
 

	
 
        if self.cli_args.get('force_ask') is True:
 
        if self.cli_args.get('force_ask'):
 
            ask_ok = lambda *args, **kwargs: True
 
        elif self.cli_args.get('force_ask') is False:
 
        elif not self.cli_args.get('force_ask'):
 
            ask_ok = lambda *args, **kwargs: False
 

	
 
    def init_db(self):
 
        engine = create_engine(self.dburi, echo=self.log_sql)
 
        init_model(engine)
 
        self.sa = Session()
 

	
 
    def create_tables(self, override=False):
 
        """
 
        Create a auth database
 
        """
 

	
 
@@ -580,25 +580,25 @@ class DbManage(object):
 

	
 
        elif not os.path.isabs(path):
 
            path_ok = False
 
            log.error('Given path %s is not an absolute path' % path)
 

	
 
        # check write access
 
        elif not os.access(path, os.W_OK) and path_ok:
 
            path_ok = False
 
            log.error('No write permission to given path %s' % path)
 

	
 
        if retries == 0:
 
            sys.exit('max retries reached')
 
        if path_ok is False:
 
        if not path_ok:
 
            retries -= 1
 
            return self.config_prompt(test_repo_path, retries)
 

	
 
        real_path = os.path.normpath(os.path.realpath(path))
 

	
 
        if real_path != os.path.normpath(path):
 
            if not ask_ok(('Path looks like a symlink, Rhodecode will store '
 
                           'given path as %s ? [y/n]') % (real_path)):
 
                log.error('Canceled by user')
 
                sys.exit(-1)
 

	
 
        return real_path
rhodecode/lib/diffs.py
Show inline comments
 
@@ -412,25 +412,25 @@ class DiffProcessor(object):
 

	
 
            _files.append({
 
                'filename':         head['b_path'],
 
                'old_revision':     head['a_blob_id'],
 
                'new_revision':     head['b_blob_id'],
 
                'chunks':           chunks,
 
                'operation':        op,
 
                'stats':            stats,
 
            })
 

	
 
        sorter = lambda info: {'A': 0, 'M': 1, 'D': 2}.get(info['operation'])
 

	
 
        if inline_diff is False:
 
        if not inline_diff:
 
            return diff_container(sorted(_files, key=sorter))
 

	
 
        # highlight inline changes
 
        for diff_data in _files:
 
            for chunk in diff_data['chunks']:
 
                lineiter = iter(chunk)
 
                try:
 
                    while 1:
 
                        line = lineiter.next()
 
                        if line['action'] not in ['unmod', 'context']:
 
                            nextline = lineiter.next()
 
                            if nextline['action'] in ['unmod', 'context'] or \
rhodecode/lib/hooks.py
Show inline comments
 
@@ -134,25 +134,25 @@ def log_pull_action(ui, repo, **kwargs):
 

	
 
    user = User.get_by_username(ex.username)
 
    action = 'pull'
 
    action_logger(user, action, ex.repository, ex.ip, commit=True)
 
    # extension hook call
 
    from rhodecode import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'PULL_HOOK', None)
 
    if isfunction(callback):
 
        kw = {}
 
        kw.update(ex)
 
        callback(**kw)
 

	
 
    if ex.make_lock is True:
 
    if ex.make_lock:
 
        Repository.lock(Repository.get_by_repo_name(ex.repository), user.user_id)
 
        #msg = 'Made lock on repo `%s`' % repository
 
        #sys.stdout.write(msg)
 

	
 
    if ex.locked_by[0]:
 
        locked_by = User.get(ex.locked_by[0]).username
 
        _http_ret = HTTPLockedRC(ex.repository, locked_by)
 
        if str(_http_ret.code).startswith('2'):
 
            #2xx Codes don't raise exceptions
 
            sys.stdout.write(_http_ret.title)
 
    return 0
 

	
 
@@ -193,25 +193,25 @@ def log_push_action(ui, repo, **kwargs):
 
    action = action % ','.join(revs)
 

	
 
    action_logger(ex.username, action, ex.repository, ex.ip, commit=True)
 

	
 
    # extension hook call
 
    from rhodecode import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'PUSH_HOOK', None)
 
    if isfunction(callback):
 
        kw = {'pushed_revs': revs}
 
        kw.update(ex)
 
        callback(**kw)
 

	
 
    if ex.make_lock is False:
 
    if not ex.make_lock:
 
        Repository.unlock(Repository.get_by_repo_name(ex.repository))
 
        msg = 'Released lock on repo `%s`\n' % ex.repository
 
        sys.stdout.write(msg)
 

	
 
    if ex.locked_by[0]:
 
        locked_by = User.get(ex.locked_by[0]).username
 
        _http_ret = HTTPLockedRC(ex.repository, locked_by)
 
        if str(_http_ret.code).startswith('2'):
 
            #2xx Codes don't raise exceptions
 
            sys.stdout.write(_http_ret.title)
 

	
 
    return 0
rhodecode/lib/middleware/simplegit.py
Show inline comments
 
@@ -117,46 +117,46 @@ class SimpleGit(BaseVCSController):
 
        environ['pylons.status_code_redirect'] = True
 

	
 
        #======================================================================
 
        # EXTRACT REPOSITORY NAME FROM ENV
 
        #======================================================================
 
        try:
 
            repo_name = self.__get_repository(environ)
 
            log.debug('Extracted repo name is %s' % repo_name)
 
        except:
 
            return HTTPInternalServerError()(environ, start_response)
 

	
 
        # quick check if that dir exists...
 
        if is_valid_repo(repo_name, self.basepath, 'git') is False:
 
        if not is_valid_repo(repo_name, self.basepath, 'git'):
 
            return HTTPNotFound()(environ, start_response)
 

	
 
        #======================================================================
 
        # GET ACTION PULL or PUSH
 
        #======================================================================
 
        action = self.__get_action(environ)
 

	
 
        #======================================================================
 
        # CHECK ANONYMOUS PERMISSION
 
        #======================================================================
 
        if action in ['pull', 'push']:
 
            anonymous_user = self.__get_user('default')
 
            username = anonymous_user.username
 
            anonymous_perm = self._check_permission(action, anonymous_user,
 
                                                    repo_name, ip_addr)
 

	
 
            if anonymous_perm is not True or anonymous_user.active is False:
 
                if anonymous_perm is not True:
 
            if not anonymous_perm or not anonymous_user.active:
 
                if not anonymous_perm:
 
                    log.debug('Not enough credentials to access this '
 
                              'repository as anonymous user')
 
                if anonymous_user.active is False:
 
                if not anonymous_user.active:
 
                    log.debug('Anonymous access is disabled, running '
 
                              'authentication')
 
                #==============================================================
 
                # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
 
                # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
 
                #==============================================================
 

	
 
                # Attempting to retrieve username from the container
 
                username = get_container_username(environ, self.config)
 

	
 
                # If not authenticated by the container, running basic auth
 
                if not username:
 
@@ -175,25 +175,25 @@ class SimpleGit(BaseVCSController):
 
                #==============================================================
 
                try:
 
                    user = self.__get_user(username)
 
                    if user is None or not user.active:
 
                        return HTTPForbidden()(environ, start_response)
 
                    username = user.username
 
                except:
 
                    log.error(traceback.format_exc())
 
                    return HTTPInternalServerError()(environ, start_response)
 

	
 
                #check permissions for this repository
 
                perm = self._check_permission(action, user, repo_name, ip_addr)
 
                if perm is not True:
 
                if not perm:
 
                    return HTTPForbidden()(environ, start_response)
 

	
 
        # extras are injected into UI object and later available
 
        # in hooks executed by rhodecode
 
        from rhodecode import CONFIG
 
        server_url = get_server_url(environ)
 
        extras = {
 
            'ip': ip_addr,
 
            'username': username,
 
            'action': action,
 
            'repository': repo_name,
 
            'scm': 'git',
rhodecode/lib/middleware/simplehg.py
Show inline comments
 
@@ -80,46 +80,46 @@ class SimpleHg(BaseVCSController):
 
        environ['pylons.status_code_redirect'] = True
 

	
 
        #======================================================================
 
        # EXTRACT REPOSITORY NAME FROM ENV
 
        #======================================================================
 
        try:
 
            repo_name = environ['REPO_NAME'] = self.__get_repository(environ)
 
            log.debug('Extracted repo name is %s' % repo_name)
 
        except:
 
            return HTTPInternalServerError()(environ, start_response)
 

	
 
        # quick check if that dir exists...
 
        if is_valid_repo(repo_name, self.basepath, 'hg') is False:
 
        if not is_valid_repo(repo_name, self.basepath, 'hg'):
 
            return HTTPNotFound()(environ, start_response)
 

	
 
        #======================================================================
 
        # GET ACTION PULL or PUSH
 
        #======================================================================
 
        action = self.__get_action(environ)
 

	
 
        #======================================================================
 
        # CHECK ANONYMOUS PERMISSION
 
        #======================================================================
 
        if action in ['pull', 'push']:
 
            anonymous_user = self.__get_user('default')
 
            username = anonymous_user.username
 
            anonymous_perm = self._check_permission(action, anonymous_user,
 
                                                    repo_name, ip_addr)
 

	
 
            if anonymous_perm is not True or anonymous_user.active is False:
 
                if anonymous_perm is not True:
 
            if not anonymous_perm or not anonymous_user.active:
 
                if not anonymous_perm:
 
                    log.debug('Not enough credentials to access this '
 
                              'repository as anonymous user')
 
                if anonymous_user.active is False:
 
                if not anonymous_user.active:
 
                    log.debug('Anonymous access is disabled, running '
 
                              'authentication')
 
                #==============================================================
 
                # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
 
                # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
 
                #==============================================================
 

	
 
                # Attempting to retrieve username from the container
 
                username = get_container_username(environ, self.config)
 

	
 
                # If not authenticated by the container, running basic auth
 
                if not username:
 
@@ -138,25 +138,25 @@ class SimpleHg(BaseVCSController):
 
                #==============================================================
 
                try:
 
                    user = self.__get_user(username)
 
                    if user is None or not user.active:
 
                        return HTTPForbidden()(environ, start_response)
 
                    username = user.username
 
                except:
 
                    log.error(traceback.format_exc())
 
                    return HTTPInternalServerError()(environ, start_response)
 

	
 
                #check permissions for this repository
 
                perm = self._check_permission(action, user, repo_name, ip_addr)
 
                if perm is not True:
 
                if not perm:
 
                    return HTTPForbidden()(environ, start_response)
 

	
 
        # extras are injected into mercurial UI object and later available
 
        # in hg hooks executed by rhodecode
 
        from rhodecode import CONFIG
 
        server_url = get_server_url(environ)
 
        extras = {
 
            'ip': ip_addr,
 
            'username': username,
 
            'action': action,
 
            'repository': repo_name,
 
            'scm': 'hg',
rhodecode/lib/rcmail/response.py
Show inline comments
 
@@ -435,19 +435,19 @@ def properly_encode_header(value, encode
 
    it.  Since random headers could have an email address, and email addresses
 
    have weird special formatting rules, we have to check for it.
 

	
 
    Normally this works fine, but in Librelist, we need to "obfuscate" email
 
    addresses by changing the '@' to '-AT-'.  This is where
 
    VALUE_IS_EMAIL_ADDRESS exists.  It's a simple lambda returning True/False
 
    to check if a header value has an email address.  If you need to make this
 
    check different, then change this.
 
    """
 
    try:
 
        return value.encode("ascii")
 
    except UnicodeEncodeError:
 
        if not_email is False and VALUE_IS_EMAIL_ADDRESS(value):
 
        if not not_email and VALUE_IS_EMAIL_ADDRESS(value):
 
            # this could have an email address, make sure we don't screw it up
 
            name, address = parseaddr(value)
 
            return '"%s" <%s>' % (
 
                encoder.header_encode(name.encode("utf-8")), address)
 

	
 
        return encoder.header_encode(value.encode("utf-8"))
rhodecode/model/db.py
Show inline comments
 
@@ -1689,25 +1689,25 @@ class CacheInvalidation(Base, BaseModel)
 
        state is not valid and needs to be invalidated
 

	
 
        :param key:
 
        """
 
        repo_name = key
 
        repo_name = remove_suffix(repo_name, '_README')
 
        repo_name = remove_suffix(repo_name, '_RSS')
 
        repo_name = remove_suffix(repo_name, '_ATOM')
 

	
 
        cache_key = cls._get_cache_key(key)
 
        inv = cls._get_or_create_inv_obj(cache_key, repo_name)
 

	
 
        if inv and inv.cache_active is False:
 
        if inv and not inv.cache_active:
 
            return inv
 

	
 
    @classmethod
 
    def set_invalidate(cls, key=None, repo_name=None):
 
        """
 
        Mark this Cache key for invalidation, either by key or whole
 
        cache sets based on repo_name
 

	
 
        :param key:
 
        """
 
        invalidated_keys = []
 
        if key:
rhodecode/model/notification.py
Show inline comments
 
@@ -91,25 +91,25 @@ class NotificationModel(BaseModel):
 
            )
 
        else:
 
            # empty recipients means to all admins
 
            recipients_objs = User.query().filter(User.admin == True).all()
 
            log.debug('sending notifications %s to admins: %s' % (
 
                type_, recipients_objs)
 
            )
 
        notif = Notification.create(
 
            created_by=created_by_obj, subject=subject,
 
            body=body, recipients=recipients_objs, type_=type_
 
        )
 

	
 
        if with_email is False:
 
        if not with_email:
 
            return notif
 

	
 
        #don't send email to person who created this comment
 
        rec_objs = set(recipients_objs).difference(set([created_by_obj]))
 

	
 
        # send email with notification to all other participants
 
        for rec in rec_objs:
 
            if not email_subject:
 
                email_subject = NotificationModel()\
 
                                    .make_description(notif, show_age=False)
 
            type_ = type_
 
            email_body = None  # we set body to none, we just send HTML emails
rhodecode/model/permission.py
Show inline comments
 
@@ -111,25 +111,25 @@ class PermissionModel(BaseModel):
 
                    self.sa.add(p)
 

	
 
            #stage 2 update all default permissions for repos if checked
 
            if form_result['overwrite_default_repo'] == True:
 
                _def_name = form_result['default_repo_perm'].split('repository.')[-1]
 
                _def = self.get_permission_by_name('repository.' + _def_name)
 
                # repos
 
                for r2p in self.sa.query(UserRepoToPerm)\
 
                               .filter(UserRepoToPerm.user == perm_user)\
 
                               .all():
 

	
 
                    #don't reset PRIVATE repositories
 
                    if r2p.repository.private is False:
 
                    if not r2p.repository.private:
 
                        r2p.permission = _def
 
                        self.sa.add(r2p)
 

	
 
            if form_result['overwrite_default_group'] == True:
 
                _def_name = form_result['default_group_perm'].split('group.')[-1]
 
                # groups
 
                _def = self.get_permission_by_name('group.' + _def_name)
 
                for g2p in self.sa.query(UserRepoGroupToPerm)\
 
                               .filter(UserRepoGroupToPerm.user == perm_user)\
 
                               .all():
 
                    g2p.permission = _def
 
                    self.sa.add(g2p)
rhodecode/model/user.py
Show inline comments
 
@@ -123,25 +123,25 @@ class UserModel(BaseModel):
 
            log.debug('creating new user %s' % username)
 
            new_user = User()
 
            edit = False
 
        else:
 
            log.debug('updating user %s' % username)
 
            new_user = user
 
            edit = True
 

	
 
        try:
 
            new_user.username = username
 
            new_user.admin = admin
 
            # set password only if creating an user or password is changed
 
            if edit is False or user.password != password:
 
            if not edit or user.password != password:
 
                new_user.password = get_crypt_password(password)
 
                new_user.api_key = generate_api_key(username)
 
            new_user.email = email
 
            new_user.active = active
 
            new_user.ldap_dn = safe_unicode(ldap_dn) if ldap_dn else None
 
            new_user.name = firstname
 
            new_user.lastname = lastname
 
            self.sa.add(new_user)
 
            return new_user
 
        except (DatabaseError,):
 
            log.error(traceback.format_exc())
 
            raise
rhodecode/model/users_group.py
Show inline comments
 
@@ -93,25 +93,25 @@ class UserGroupModel(BaseModel):
 
        group and users
 

	
 
        :param users_group:
 
        :param force:
 
        """
 
        try:
 
            users_group = self.__get_users_group(users_group)
 

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

	
 
            if assigned_groups and force is False:
 
            if assigned_groups and not force:
 
                raise UserGroupsAssignedException('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):
 
        users_group = self.__get_users_group(users_group)
 
        user = self._get_user(user)
 

	
rhodecode/model/validators.py
Show inline comments
 
@@ -271,25 +271,25 @@ def ValidAuth():
 
            'invalid_username': _(u'invalid user name'),
 
            'disabled_account': _(u'Your account is disabled')
 
        }
 

	
 
        def validate_python(self, value, state):
 
            from rhodecode.lib.auth import authenticate
 

	
 
            password = value['password']
 
            username = value['username']
 

	
 
            if not authenticate(username, password):
 
                user = User.get_by_username(username)
 
                if user and user.active is False:
 
                if user and not user.active:
 
                    log.warning('user %s is disabled' % username)
 
                    msg = M(self, 'disabled_account', state)
 
                    raise formencode.Invalid(msg, value, state,
 
                        error_dict=dict(username=msg)
 
                    )
 
                else:
 
                    log.warning('user %s failed to authenticate' % username)
 
                    msg = M(self, 'invalid_username', state)
 
                    msg2 = M(self, 'invalid_password', state)
 
                    raise formencode.Invalid(msg, value, state,
 
                        error_dict=dict(username=msg, password=msg2)
 
                    )
 
@@ -494,25 +494,25 @@ def CanWriteGroup(old_data=None):
 
            val = HasReposGroupPermissionAny('group.write', 'group.admin')
 
            can_create_repos = HasPermissionAny('hg.admin', 'hg.create.repository')
 
            forbidden = not val(gr_name, 'can write into group validator')
 
            value_changed = True  # old_data['repo_group'].get('group_id') != safe_int(value)
 
            if value_changed:  # do check if we changed the value
 
                #parent group need to be existing
 
                if gr and forbidden:
 
                    msg = M(self, 'permission_denied', state)
 
                    raise formencode.Invalid(msg, value, state,
 
                        error_dict=dict(repo_type=msg)
 
                    )
 
                ## check if we can write to root location !
 
                elif gr is None and can_create_repos() is False:
 
                elif gr is None and not can_create_repos():
 
                    msg = M(self, 'permission_denied_root', state)
 
                    raise formencode.Invalid(msg, value, state,
 
                        error_dict=dict(repo_type=msg)
 
                    )
 

	
 
    return _validator
 

	
 

	
 
def CanCreateGroup(can_create_in_root=False):
 
    class _validator(formencode.validators.FancyValidator):
 
        messages = {
 
            'permission_denied': _(u"You don't have permissions "
 
@@ -524,25 +524,25 @@ def CanCreateGroup(can_create_in_root=Fa
 
            if value in [-1, "-1"]:
 
                return None
 
            return value
 

	
 
        def validate_python(self, value, state):
 
            gr = RepoGroup.get(value)
 
            gr_name = gr.group_name if gr else None  # None means ROOT location
 

	
 
            if can_create_in_root and gr is None:
 
                #we can create in root, we're fine no validations required
 
                return
 

	
 
            forbidden_in_root = gr is None and can_create_in_root is False
 
            forbidden_in_root = gr is None and not can_create_in_root
 
            val = HasReposGroupPermissionAny('group.admin')
 
            forbidden = not val(gr_name, 'can create group validator')
 
            if forbidden_in_root or forbidden:
 
                msg = M(self, 'permission_denied', state)
 
                raise formencode.Invalid(msg, value, state,
 
                    error_dict=dict(group_parent_id=msg)
 
                )
 

	
 
    return _validator
 

	
 

	
 
def ValidPerms(type_='repo'):
rhodecode/templates/files/files_source.html
Show inline comments
 
@@ -16,25 +16,25 @@
 
            <div class="left item"><pre class="tooltip" title="${h.tooltip(h.fmt_date(c.file_changeset.date))}">${h.link_to("r%s:%s" % (c.file_changeset.revision,h.short_id(c.file_changeset.raw_id)),h.url('changeset_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id))}</pre></div>
 
            <div class="left item"><pre>${h.format_byte_size(c.file.size,binary=True)}</pre></div>
 
            <div class="left item last"><pre>${c.file.mimetype}</pre></div>
 
            <div class="buttons">
 
              %if c.annotate:
 
                ${h.link_to(_('show source'),    h.url('files_home',         repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="ui-btn")}
 
              %else:
 
                ${h.link_to(_('show annotation'),h.url('files_annotate_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="ui-btn")}
 
              %endif
 
              ${h.link_to(_('show as raw'),h.url('files_raw_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="ui-btn")}
 
              ${h.link_to(_('download as raw'),h.url('files_rawfile_home',repo_name=c.repo_name,revision=c.file_changeset.raw_id,f_path=c.f_path),class_="ui-btn")}
 
              % if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name):
 
               % if c.on_branch_head and c.changeset.branch and c.file.is_binary is False:
 
               % if c.on_branch_head and c.changeset.branch and not c.file.is_binary:
 
                ${h.link_to(_('edit on branch:%s') % c.changeset.branch,h.url('files_edit_home',repo_name=c.repo_name,revision=c.changeset.branch,f_path=c.f_path),class_="ui-btn")}
 
               %else:
 
                ${h.link_to(_('edit on branch:?'), '#', class_="ui-btn disabled tooltip", title=_('Editing files allowed only when on branch head revision'))}
 
               % endif
 
              % endif
 
            </div>
 
        </div>
 
        <div class="author">
 
            <div class="gravatar">
 
                <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(c.file_changeset.author),16)}"/>
 
            </div>
 
            <div title="${c.file_changeset.author}" class="user">${h.person(c.file_changeset.author)}</div>
rhodecode/templates/index_base.html
Show inline comments
 
@@ -63,25 +63,25 @@
 
                    </tr>
 
                  % endfor
 
              </table>
 
            </div>
 
            <div id="group-user-paginator" style="padding: 0px 0px 0px 0px"></div>
 
            <div style="height: 20px"></div>
 
            % endif
 
            <div id="welcome" style="display:none;text-align:center">
 
                <h1><a href="${h.url('home')}">${c.rhodecode_name} ${c.rhodecode_version}</a></h1>
 
            </div>
 
             <%cnt=0%>
 
             <%namespace name="dt" file="/data_table/_dt_elements.html"/>
 
            % if c.visual.lightweight_dashboard is False:
 
            % if not c.visual.lightweight_dashboard:
 
              ## old full detailed version
 
            <div id='repos_list_wrap' class="yui-skin-sam">
 
            <table id="repos_list">
 
            <thead>
 
                <tr>
 
                    <th class="left"></th>
 
                    <th class="left">${_('Name')}</th>
 
                    <th class="left">${_('Description')}</th>
 
                    <th class="left">${_('Last change')}</th>
 
                    <th class="left">${_('Tip')}</th>
 
                    <th class="left">${_('Owner')}</th>
 
                    <th class="left">${_('Atom')}</th>
 
@@ -122,25 +122,25 @@
 
                </tr>
 
            %endfor
 
            </tbody>
 
            </table>
 
            </div>
 
            % else:
 
              ## lightweight version
 
                <div class="yui-skin-sam" id="repos_list_wrap"></div>
 
                <div id="user-paginator" style="padding: 0px 0px 0px 0px"></div>
 
            % endif
 
        </div>
 
    </div>
 
    % if c.visual.lightweight_dashboard is False:
 
    % if not c.visual.lightweight_dashboard:
 
    <script>
 
      YUD.get('repo_count').innerHTML = ${cnt+1 if cnt else 0};
 

	
 
      // groups table sorting
 
      var myColumnDefs = [
 
          {key:"name",label:"${_('Group name')}",sortable:true,
 
              sortOptions: { sortFunction: groupNameSort }},
 
          {key:"desc",label:"${_('Description')}",sortable:true},
 
      ];
 

	
 
      var myDataSource = new YAHOO.util.DataSource(YUD.get("groups_list"));
 

	
rhodecode/templates/summary/summary.html
Show inline comments
 
@@ -137,25 +137,25 @@ ${self.context_bar('summary')}
 
                   %endif
 
                %endif
 
              </div>
 
             </div>
 

	
 
             <div class="field">
 
              <div class="label-summary">
 
                  <label>${_('Download')}:</label>
 
              </div>
 
              <div class="input ${summary(c.show_stats)}">
 
                %if len(c.rhodecode_repo.revisions) == 0:
 
                  ${_('There are no downloads yet')}
 
                %elif c.enable_downloads is False:
 
                %elif not c.enable_downloads:
 
                  ${_('Downloads are disabled for this repository')}
 
                    %if h.HasPermissionAll('hg.admin')('enable downloads on from summary'):
 
                        ${h.link_to(_('enable'),h.url('edit_repo',repo_name=c.repo_name),class_="ui-btn")}
 
                    %endif
 
                %else:
 
                    ${h.select('download_options',c.rhodecode_repo.get_changeset().raw_id,c.download_options)}
 
                         <span id="${'zip_link'}">${h.link_to(_('Download as zip'), h.url('files_archive_home',repo_name=c.dbrepo.repo_name,fname='tip.zip'),class_="archive_icon ui-btn")}</span>
 
                    <span style="vertical-align: bottom">
 
                        <input id="archive_subrepos" type="checkbox" name="subrepos" />
 
                        <label for="archive_subrepos" class="tooltip" title="${h.tooltip(_('Check this to download archive with subrepos'))}" >${_('with subrepos')}</label>
 
                    </span>
 
                %endif
rhodecode/tests/scripts/test_concurency.py
Show inline comments
 
@@ -174,25 +174,25 @@ def test_clone_with_credentials(no_error
 
    clone_url = 'http://%(user)s:%(pass)s@%(host)s/%(cloned_repo)s' % \
 
                  {'user': USER,
 
                   'pass': PASS,
 
                   'host': HOST,
 
                   'cloned_repo': repo, }
 

	
 
    dest = path + seq
 
    if method == 'pull':
 
        stdout, stderr = Command(cwd).execute(backend, method, '--cwd', dest, clone_url)
 
    else:
 
        stdout, stderr = Command(cwd).execute(backend, method, clone_url, dest)
 
        print stdout,'sdasdsadsa'
 
        if no_errors is False:
 
        if not no_errors:
 
            if backend == 'hg':
 
                assert """adding file changes""" in stdout, 'no messages about cloning'
 
                assert """abort""" not in stderr , 'got error from clone'
 
            elif backend == 'git':
 
                assert """Cloning into""" in stdout, 'no messages about cloning'
 

	
 
if __name__ == '__main__':
 
    try:
 
        create_test_user(force=False)
 
        seq = None
 
        import time
 

	
0 comments (0 inline, 0 general)