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
 
@@ -156,13 +156,13 @@ class NotificationsController(BaseContro
 
            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')
 

	
rhodecode/controllers/admin/repos_groups.py
Show inline comments
 
@@ -345,13 +345,13 @@ class ReposGroupsController(BaseControll
 
        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))\
rhodecode/controllers/files.py
Show inline comments
 
@@ -413,13 +413,13 @@ class FilesController(BaseRepoController
 
                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'):
rhodecode/controllers/home.py
Show inline comments
 
@@ -49,13 +49,13 @@ class HomeController(BaseController):
 
        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))\
rhodecode/controllers/login.py
Show inline comments
 
@@ -73,13 +73,13 @@ class LoginController(BaseController):
 
                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()
 

	
rhodecode/lib/auth.py
Show inline comments
 
@@ -378,13 +378,13 @@ class  AuthUser(object):
 
                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
rhodecode/lib/celerylib/__init__.py
Show inline comments
 
@@ -121,10 +121,10 @@ def get_session():
 
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
 
@@ -66,15 +66,15 @@ class DbManage(object):
 
        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()
 
@@ -586,13 +586,13 @@ class DbManage(object):
 
        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):
rhodecode/lib/diffs.py
Show inline comments
 
@@ -418,13 +418,13 @@ class DiffProcessor(object):
 
                '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)
rhodecode/lib/hooks.py
Show inline comments
 
@@ -140,13 +140,13 @@ def log_pull_action(ui, repo, **kwargs):
 
    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
 
@@ -199,13 +199,13 @@ def log_push_action(ui, repo, **kwargs):
 
    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
rhodecode/lib/middleware/simplegit.py
Show inline comments
 
@@ -123,13 +123,13 @@ class SimpleGit(BaseVCSController):
 
            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)
 
@@ -140,17 +140,17 @@ class SimpleGit(BaseVCSController):
 
        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
 
                #==============================================================
 
@@ -181,13 +181,13 @@ class SimpleGit(BaseVCSController):
 
                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)
rhodecode/lib/middleware/simplehg.py
Show inline comments
 
@@ -86,13 +86,13 @@ class SimpleHg(BaseVCSController):
 
            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)
 
@@ -103,17 +103,17 @@ class SimpleHg(BaseVCSController):
 
        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
 
                #==============================================================
 
@@ -144,13 +144,13 @@ class SimpleHg(BaseVCSController):
 
                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)
rhodecode/lib/rcmail/response.py
Show inline comments
 
@@ -441,13 +441,13 @@ def properly_encode_header(value, encode
 
    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
 
@@ -1695,13 +1695,13 @@ class CacheInvalidation(Base, BaseModel)
 
        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
rhodecode/model/notification.py
Show inline comments
 
@@ -97,13 +97,13 @@ class NotificationModel(BaseModel):
 
            )
 
        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
rhodecode/model/permission.py
Show inline comments
 
@@ -117,13 +117,13 @@ class PermissionModel(BaseModel):
 
                # 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
rhodecode/model/user.py
Show inline comments
 
@@ -129,13 +129,13 @@ class UserModel(BaseModel):
 
            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
rhodecode/model/users_group.py
Show inline comments
 
@@ -99,13 +99,13 @@ class UserGroupModel(BaseModel):
 
            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())
rhodecode/model/validators.py
Show inline comments
 
@@ -277,13 +277,13 @@ def ValidAuth():
 

	
 
            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:
 
@@ -500,13 +500,13 @@ def CanWriteGroup(old_data=None):
 
                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
 
@@ -530,13 +530,13 @@ def CanCreateGroup(can_create_in_root=Fa
 
            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)
rhodecode/templates/files/files_source.html
Show inline comments
 
@@ -22,13 +22,13 @@
 
              %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>
rhodecode/templates/index_base.html
Show inline comments
 
@@ -69,13 +69,13 @@
 
            % 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>
 
@@ -128,13 +128,13 @@
 
              ## 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,
rhodecode/templates/summary/summary.html
Show inline comments
 
@@ -143,13 +143,13 @@ ${self.context_bar('summary')}
 
              <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)}
rhodecode/tests/scripts/test_concurency.py
Show inline comments
 
@@ -180,13 +180,13 @@ def test_clone_with_credentials(no_error
 
    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'
 

	
0 comments (0 inline, 0 general)