Changeset - 91b38dc6d891
[Not reviewed]
default
0 10 0
Søren Løvborg - 9 years ago 2016-08-03 16:07:39
sorenl@unity3d.com
model: refactor and simplify _get_instance

_get_instance is a BaseModel method, but never uses "self". Instead
it takes a class argument, which indicates that it's better suited as
a classmethod on said classes.

Also rename to something more descriptive, remove leading underscore
since it's not a private API, and refactor for readability.
10 files changed with 47 insertions and 44 deletions:
0 comments (0 inline, 0 general)
kallithea/model/__init__.py
Show inline comments
 
@@ -37,25 +37,25 @@ Original author and date, and relevant c
 
       conf = appconfig('config:development.ini', relative_to = './../../')
 
       load_environment(conf.global_conf, conf.local_conf)
 

	
 
       engine = engine_from_config(config, 'sqlalchemy.')
 
       init_model(engine)
 
       # RUN YOUR CODE HERE
 

	
 
"""
 

	
 

	
 
import logging
 
from kallithea.model import meta
 
from kallithea.lib.utils2 import safe_str, obfuscate_url_pw
 
from kallithea.lib.utils2 import obfuscate_url_pw
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
def init_model(engine):
 
    """
 
    Initializes db session, bind the engine with the metadata,
 
    Call this before using any of the tables or classes in the model,
 
    preferably once in application start
 

	
 
    :param engine: engine to bind to
 
    """
 
@@ -69,64 +69,41 @@ class BaseModel(object):
 
    Base Model for all Kallithea models, it adds sql alchemy session
 
    into instance of model
 

	
 
    :param sa: If passed it reuses this session instead of creating a new one
 
    """
 

	
 
    def __init__(self, sa=None):
 
        if sa is not None:
 
            self.sa = sa
 
        else:
 
            self.sa = meta.Session()
 

	
 
    def _get_instance(self, cls, instance, callback=None):
 
        """
 
        Gets instance of given cls using some simple lookup mechanism.
 

	
 
        :param cls: class to fetch
 
        :param instance: int or Instance
 
        :param callback: callback to call if all lookups failed
 
        """
 

	
 
        if isinstance(instance, cls):
 
            return instance
 
        elif isinstance(instance, (int, long)) or safe_str(instance).isdigit():
 
            return cls.get(instance)
 
        else:
 
            if instance is not None:
 
                if callback is None:
 
                    raise Exception(
 
                        'given object must be int, long or Instance of %s '
 
                        'got %s, no callback provided' % (cls, type(instance))
 
                    )
 
                else:
 
                    return callback(instance)
 

	
 
    def _get_user(self, user):
 
        """
 
        Helper method to get user by ID, or username fallback
 

	
 
        :param user: UserID, username, or User instance
 
        """
 
        from kallithea.model.db import User
 
        return self._get_instance(User, user,
 
        return User.guess_instance(user,
 
                                  callback=User.get_by_username)
 

	
 
    def _get_repo(self, repository):
 
        """
 
        Helper method to get repository by ID, or repository name
 

	
 
        :param repository: RepoID, repository name or Repository Instance
 
        """
 
        from kallithea.model.db import Repository
 
        return self._get_instance(Repository, repository,
 
        return Repository.guess_instance(repository,
 
                                  callback=Repository.get_by_repo_name)
 

	
 
    def _get_perm(self, permission):
 
        """
 
        Helper method to get permission by ID, or permission name
 

	
 
        :param permission: PermissionID, permission_name or Permission instance
 
        """
 
        from kallithea.model.db import Permission
 
        return self._get_instance(Permission, permission,
 
        return Permission.guess_instance(permission,
 
                                  callback=Permission.get_by_key)
kallithea/model/changeset_status.py
Show inline comments
 
@@ -41,25 +41,25 @@ class ChangesetStatusModel(BaseModel):
 
                          with_revisions=False):
 
        repo = self._get_repo(repo)
 

	
 
        q = ChangesetStatus.query() \
 
            .filter(ChangesetStatus.repo == repo)
 
        if not with_revisions:
 
            # only report the latest vote across all users! TODO: be smarter!
 
            q = q.filter(ChangesetStatus.version == 0)
 

	
 
        if revision:
 
            q = q.filter(ChangesetStatus.revision == revision)
 
        elif pull_request:
 
            pull_request = self._get_instance(PullRequest, pull_request)
 
            pull_request = PullRequest.guess_instance(pull_request)
 
            q = q.filter(ChangesetStatus.pull_request == pull_request)
 
        else:
 
            raise Exception('Please specify revision or pull_request')
 
        q = q.order_by(ChangesetStatus.version.asc())
 
        return q
 

	
 
    def _calculate_status(self, statuses):
 
        """
 
        Given a list of statuses, calculate the resulting status, according to
 
        the policy: approve if consensus, reject when at least one reject.
 
        """
 

	
 
@@ -150,25 +150,25 @@ class ChangesetStatusModel(BaseModel):
 
            mess around this manually
 
        """
 
        repo = self._get_repo(repo)
 

	
 
        q = ChangesetStatus.query()
 
        if revision is not None:
 
            assert pull_request is None
 
            q = q.filter(ChangesetStatus.repo == repo)
 
            q = q.filter(ChangesetStatus.revision == revision)
 
            revisions = [revision]
 
        else:
 
            assert pull_request is not None
 
            pull_request = self._get_instance(PullRequest, pull_request)
 
            pull_request = PullRequest.guess_instance(pull_request)
 
            repo = pull_request.org_repo
 
            q = q.filter(ChangesetStatus.repo == repo)
 
            q = q.filter(ChangesetStatus.revision.in_(pull_request.revisions))
 
            revisions = pull_request.revisions
 
        cur_statuses = q.all()
 

	
 
        #if statuses exists and last is associated with a closed pull request
 
        # we need to check if we can allow this status change
 
        if (dont_allow_on_closed_pull_request and cur_statuses
 
            and getattr(cur_statuses[0].pull_request, 'status', '')
 
                == PullRequest.STATUS_CLOSED):
 
            raise StatusChangeOnClosedPullRequestError(
kallithea/model/comment.py
Show inline comments
 
@@ -169,25 +169,25 @@ class ChangesetCommentsModel(BaseModel):
 
        repo = self._get_repo(repo)
 
        user = self._get_user(user)
 
        comment = ChangesetComment()
 
        comment.repo = repo
 
        comment.author = user
 
        comment.text = text
 
        comment.f_path = f_path
 
        comment.line_no = line_no
 

	
 
        if revision is not None:
 
            comment.revision = revision
 
        elif pull_request is not None:
 
            pull_request = self._get_instance(PullRequest, pull_request)
 
            pull_request = PullRequest.guess_instance(pull_request)
 
            comment.pull_request = pull_request
 
        else:
 
            raise Exception('Please specify revision or pull_request_id')
 

	
 
        Session().add(comment)
 
        Session().flush()
 

	
 
        if send_email:
 
            (subj, body, recipients, notification_type,
 
             email_kwargs) = self._get_notification_data(
 
                                repo, comment, user,
 
                                comment_text=text,
 
@@ -210,25 +210,25 @@ class ChangesetCommentsModel(BaseModel):
 
                subj = _('[Mention]') + ' ' + subj
 
                # FIXME: this subject is wrong and unused!
 
                NotificationModel().create(
 
                    created_by=user, subject=subj, body=body,
 
                    recipients=mention_recipients,
 
                    type_=notification_type,
 
                    email_kwargs=email_kwargs
 
                )
 

	
 
        return comment
 

	
 
    def delete(self, comment):
 
        comment = self._get_instance(ChangesetComment, comment)
 
        comment = ChangesetComment.guess_instance(comment)
 
        Session().delete(comment)
 

	
 
        return comment
 

	
 
    def get_comments(self, repo_id, revision=None, pull_request=None):
 
        """
 
        Gets general comments for either revision or pull_request.
 

	
 
        Returns a list, ordered by creation date.
 
        """
 
        return self._get_comments(repo_id, revision=revision, pull_request=pull_request,
 
                                  inline=False)
 
@@ -255,18 +255,18 @@ class ChangesetCommentsModel(BaseModel):
 

	
 
        if inline:
 
            q = q.filter(ChangesetComment.line_no != None) \
 
                .filter(ChangesetComment.f_path != None)
 
        else:
 
            q = q.filter(ChangesetComment.line_no == None) \
 
                .filter(ChangesetComment.f_path == None)
 

	
 
        if revision is not None:
 
            q = q.filter(ChangesetComment.revision == revision) \
 
                .filter(ChangesetComment.repo_id == repo_id)
 
        elif pull_request is not None:
 
            pull_request = self._get_instance(PullRequest, pull_request)
 
            pull_request = PullRequest.guess_instance(pull_request)
 
            q = q.filter(ChangesetComment.pull_request == pull_request)
 
        else:
 
            raise Exception('Please specify either revision or pull_request')
 

	
 
        return q.order_by(ChangesetComment.created_on).all()
kallithea/model/db.py
Show inline comments
 
@@ -113,24 +113,50 @@ class BaseModel(object):
 
                setattr(self, k, populate_dict[k])
 

	
 
    @classmethod
 
    def query(cls):
 
        return Session().query(cls)
 

	
 
    @classmethod
 
    def get(cls, id_):
 
        if id_:
 
            return cls.query().get(id_)
 

	
 
    @classmethod
 
    def guess_instance(cls, value, callback=None):
 
        """Haphazardly attempt to convert `value` to a `cls` instance.
 

	
 
        If `value` is None or already a `cls` instance, return it. If `value`
 
        is a number (or looks like one if you squint just right), assume it's
 
        a database primary key and let SQLAlchemy sort things out. Otherwise,
 
        fall back to resolving it using `callback` (if specified); this could
 
        e.g. be a function that looks up instances by name (though that won't
 
        work if the name begins with a digit). Otherwise, raise Exception.
 
        """
 

	
 
        if value is None:
 
            return None
 
        if isinstance(value, cls):
 
            return value
 
        if isinstance(value, (int, long)) or safe_str(value).isdigit():
 
            return cls.get(value)
 
        if callback is not None:
 
            return callback(value)
 

	
 
        raise Exception(
 
            'given object must be int, long or Instance of %s '
 
            'got %s, no callback provided' % (cls, type(value))
 
        )
 

	
 
    @classmethod
 
    def get_or_404(cls, id_):
 
        try:
 
            id_ = int(id_)
 
        except (TypeError, ValueError):
 
            raise HTTPNotFound
 

	
 
        res = cls.query().get(id_)
 
        if res is None:
 
            raise HTTPNotFound
 
        return res
 

	
 
    @classmethod
kallithea/model/gist.py
Show inline comments
 
@@ -44,25 +44,25 @@ log = logging.getLogger(__name__)
 
GIST_STORE_LOC = '.rc_gist_store'
 
GIST_METADATA_FILE = '.rc_gist_metadata'
 

	
 

	
 
class GistModel(BaseModel):
 

	
 
    def _get_gist(self, gist):
 
        """
 
        Helper method to get gist by ID, or gist_access_id as a fallback
 

	
 
        :param gist: GistID, gist_access_id, or Gist instance
 
        """
 
        return self._get_instance(Gist, gist, callback=Gist.get_by_access_id)
 
        return Gist.guess_instance(gist, callback=Gist.get_by_access_id)
 

	
 
    def __delete_gist(self, gist):
 
        """
 
        removes gist from filesystem
 

	
 
        :param gist: gist object
 
        """
 
        root_path = RepoModel().repos_path
 
        rm_path = os.path.join(root_path, GIST_STORE_LOC, gist.gist_access_id)
 
        log.info("Removing %s", rm_path)
 
        shutil.rmtree(rm_path)
 

	
kallithea/model/notification.py
Show inline comments
 
@@ -131,25 +131,25 @@ class NotificationModel(BaseModel):
 
                                .get_email_tmpl(type_, 'txt', **txt_kwargs)
 
            email_html_body = EmailNotificationModel() \
 
                                .get_email_tmpl(type_, 'html', **html_kwargs)
 

	
 
            run_task(tasks.send_email, [rec.email], email_subject, email_txt_body,
 
                     email_html_body, headers, author=created_by_obj)
 

	
 
        return notif
 

	
 
    def delete(self, user, notification):
 
        # we don't want to remove actual notification just the assignment
 
        try:
 
            notification = self._get_instance(Notification, notification)
 
            notification = Notification.guess_instance(notification)
 
            user = self._get_user(user)
 
            if notification and user:
 
                obj = UserNotification.query() \
 
                        .filter(UserNotification.user == user) \
 
                        .filter(UserNotification.notification
 
                                == notification) \
 
                        .one()
 
                Session().delete(obj)
 
                return True
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise
 
@@ -169,25 +169,25 @@ class NotificationModel(BaseModel):
 
                                 Notification.notification_id)) \
 
            .options(joinedload('notification')) \
 
            .options(subqueryload('notification.created_by_user')) \
 
            .order_by(Notification.created_on.desc())
 

	
 
        if filter_:
 
            q = q.filter(Notification.type_.in_(filter_))
 

	
 
        return q
 

	
 
    def mark_read(self, user, notification):
 
        try:
 
            notification = self._get_instance(Notification, notification)
 
            notification = Notification.guess_instance(notification)
 
            user = self._get_user(user)
 
            if notification and user:
 
                obj = UserNotification.query() \
 
                        .filter(UserNotification.user == user) \
 
                        .filter(UserNotification.notification
 
                                == notification) \
 
                        .one()
 
                obj.read = True
 
                Session().add(obj)
 
                return True
 
        except Exception:
 
            log.error(traceback.format_exc())
 
@@ -214,25 +214,25 @@ class NotificationModel(BaseModel):
 
        return UserNotification.query() \
 
                .filter(UserNotification.read == False) \
 
                .filter(UserNotification.user == user).count()
 

	
 
    def get_unread_for_user(self, user):
 
        user = self._get_user(user)
 
        return [x.notification for x in UserNotification.query() \
 
                .filter(UserNotification.read == False) \
 
                .filter(UserNotification.user == user).all()]
 

	
 
    def get_user_notification(self, user, notification):
 
        user = self._get_user(user)
 
        notification = self._get_instance(Notification, notification)
 
        notification = Notification.guess_instance(notification)
 

	
 
        return UserNotification.query() \
 
            .filter(UserNotification.notification == notification) \
 
            .filter(UserNotification.user == user).scalar()
 

	
 
    def make_description(self, notification, show_age=True):
 
        """
 
        Creates a human readable description based on properties
 
        of notification object
 
        """
 
        #alias
 
        _n = notification
kallithea/model/pull_request.py
Show inline comments
 
@@ -188,43 +188,43 @@ class PullRequestModel(BaseModel):
 
                                       type_=Notification.TYPE_PULL_REQUEST,
 
                                       email_kwargs=email_kwargs)
 

	
 
    def mention_from_description(self, user, pr, old_description=''):
 
        mention_recipients = (extract_mentioned_users(pr.description) -
 
                              extract_mentioned_users(old_description))
 

	
 
        log.debug("Mentioning %s", mention_recipients)
 
        self.__add_reviewers(user, pr, set(), mention_recipients)
 

	
 
    def update_reviewers(self, user, pull_request, reviewers_ids):
 
        reviewers_ids = set(reviewers_ids)
 
        pull_request = self._get_instance(PullRequest, pull_request)
 
        pull_request = PullRequest.guess_instance(pull_request)
 
        current_reviewers = PullRequestReviewers.query() \
 
            .options(joinedload('user')) \
 
            .filter_by(pull_request=pull_request) \
 
            .all()
 
        current_reviewer_users = set(x.user for x in current_reviewers)
 
        new_reviewer_users = set(self._get_valid_reviewers(reviewers_ids))
 

	
 
        to_add = new_reviewer_users - current_reviewer_users
 
        to_remove = current_reviewer_users - new_reviewer_users
 

	
 
        if not to_add and not to_remove:
 
            return # all done
 

	
 
        log.debug("Adding %s reviewers", to_add)
 
        self.__add_reviewers(user, pull_request, to_add, set())
 

	
 
        log.debug("Removing %s reviewers", to_remove)
 
        for prr in current_reviewers:
 
            if prr.user in to_remove:
 
                Session().delete(prr)
 

	
 
    def delete(self, pull_request):
 
        pull_request = self._get_instance(PullRequest, pull_request)
 
        pull_request = PullRequest.guess_instance(pull_request)
 
        Session().delete(pull_request)
 

	
 
    def close_pull_request(self, pull_request):
 
        pull_request = self._get_instance(PullRequest, pull_request)
 
        pull_request = PullRequest.guess_instance(pull_request)
 
        pull_request.status = PullRequest.STATUS_CLOSED
 
        pull_request.updated_on = datetime.datetime.now()
 
        Session().add(pull_request)
kallithea/model/repo.py
Show inline comments
 
@@ -50,29 +50,29 @@ from kallithea.lib import helpers as h
 
from kallithea.lib.auth import HasRepoPermissionAny, HasUserGroupPermissionAny
 
from kallithea.lib.exceptions import AttachedForksError
 
from kallithea.model.scm import UserGroupList
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class RepoModel(BaseModel):
 

	
 
    URL_SEPARATOR = Repository.url_sep()
 

	
 
    def _get_user_group(self, users_group):
 
        return self._get_instance(UserGroup, users_group,
 
        return UserGroup.guess_instance(users_group,
 
                                  callback=UserGroup.get_by_group_name)
 

	
 
    def _get_repo_group(self, repo_group):
 
        return self._get_instance(RepoGroup, repo_group,
 
        return RepoGroup.guess_instance(repo_group,
 
                                  callback=RepoGroup.get_by_group_name)
 

	
 
    def _create_default_perms(self, repository, private):
 
        # create default permission
 
        default = 'repository.read'
 
        def_user = User.get_default_user()
 
        for p in def_user.user_perms:
 
            if p.permission.permission_name.startswith('repository.'):
 
                default = p.permission.permission_name
 
                break
 

	
 
        default_perm = 'repository.none' if private else default
kallithea/model/repo_group.py
Show inline comments
 
@@ -35,29 +35,29 @@ import datetime
 
from kallithea.lib.utils2 import LazyProperty
 

	
 
from kallithea.model import BaseModel
 
from kallithea.model.db import RepoGroup, Ui, UserRepoGroupToPerm, \
 
    User, Permission, UserGroupRepoGroupToPerm, UserGroup, Repository
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class RepoGroupModel(BaseModel):
 

	
 
    def _get_user_group(self, users_group):
 
        return self._get_instance(UserGroup, users_group,
 
        return UserGroup.guess_instance(users_group,
 
                                  callback=UserGroup.get_by_group_name)
 

	
 
    def _get_repo_group(self, repo_group):
 
        return self._get_instance(RepoGroup, repo_group,
 
        return RepoGroup.guess_instance(repo_group,
 
                                  callback=RepoGroup.get_by_group_name)
 

	
 
    @LazyProperty
 
    def repos_path(self):
 
        """
 
        Gets the repositories root path from database
 
        """
 

	
 
        q = Ui.get_by_key('paths', '/')
 
        return q.ui_value
 

	
 
    def _create_default_perms(self, new_group):
kallithea/model/user_group.py
Show inline comments
 
@@ -31,25 +31,25 @@ from kallithea.model import BaseModel
 
from kallithea.model.db import UserGroupMember, UserGroup, \
 
    UserGroupRepoToPerm, Permission, UserGroupToPerm, User, UserUserGroupToPerm, \
 
    UserGroupUserGroupToPerm
 
from kallithea.lib.exceptions import UserGroupsAssignedException, \
 
    RepoGroupAssignmentError
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UserGroupModel(BaseModel):
 

	
 
    def _get_user_group(self, user_group):
 
        return self._get_instance(UserGroup, user_group,
 
        return UserGroup.guess_instance(user_group,
 
                                  callback=UserGroup.get_by_group_name)
 

	
 
    def _create_default_perms(self, user_group):
 
        # create default permission
 
        default_perm = 'usergroup.read'
 
        def_user = User.get_default_user()
 
        for p in def_user.user_perms:
 
            if p.permission.permission_name.startswith('usergroup.'):
 
                default_perm = p.permission.permission_name
 
                break
 

	
 
        user_group_to_perm = UserUserGroupToPerm()
0 comments (0 inline, 0 general)