Esempio n. 1
0
    def update(self, repo, **kwargs):
        try:
            cur_repo = self._get_repo(repo)
            source_repo_name = cur_repo.repo_name
            if 'user' in kwargs:
                cur_repo.user = User.get_by_username(kwargs['user'])

            if 'repo_group' in kwargs:
                cur_repo.group = RepoGroup.get(kwargs['repo_group'])
            log.debug('Updating repo %s with params:%s', cur_repo, kwargs)

            update_keys = [(1, 'repo_enable_downloads'),
                           (1, 'repo_description'), (1, 'repo_enable_locking'),
                           (1, 'repo_landing_rev'), (1, 'repo_private'),
                           (1, 'repo_enable_statistics'), (0, 'clone_uri'),
                           (0, 'fork_id')]
            for strip, k in update_keys:
                if k in kwargs:
                    val = kwargs[k]
                    if strip:
                        k = remove_prefix(k, 'repo_')
                    if k == 'clone_uri':
                        from rhodecode.model.validators import Missing
                        _change = kwargs.get('clone_uri_change')
                        if _change in [Missing, 'OLD']:
                            # we don't change the value, so use original one
                            val = cur_repo.clone_uri

                    setattr(cur_repo, k, val)

            new_name = cur_repo.get_new_name(kwargs['repo_name'])
            cur_repo.repo_name = new_name

            # if private flag is set, reset default permission to NONE
            if kwargs.get('repo_private'):
                EMPTY_PERM = 'repository.none'
                RepoModel().grant_user_permission(repo=cur_repo,
                                                  user=User.DEFAULT_USER,
                                                  perm=EMPTY_PERM)

            # handle extra fields
            for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
                                kwargs):
                k = RepositoryField.un_prefix_key(field)
                ex_field = RepositoryField.get_by_key_name(key=k,
                                                           repo=cur_repo)
                if ex_field:
                    ex_field.field_value = kwargs[field]
                    self.sa.add(ex_field)
            self.sa.add(cur_repo)

            if source_repo_name != new_name:
                # rename repository
                self._rename_filesystem_repo(old=source_repo_name,
                                             new=new_name)

            return cur_repo
        except Exception:
            log.error(traceback.format_exc())
            raise
Esempio n. 2
0
    def update(self, org_repo_name, **kwargs):
        try:
            cur_repo = self.get_by_repo_name(org_repo_name, cache=False)

            if 'user' in kwargs:
                cur_repo.user = User.get_by_username(kwargs['user'])

            if 'repo_group' in kwargs:
                cur_repo.group = RepoGroup.get(kwargs['repo_group'])

            for strip, k in [
                (1, 'repo_enable_downloads'), (1, 'repo_description'),
                (1, 'repo_enable_locking'), (1, 'repo_landing_rev'),
                (0, 'clone_uri'), (1, 'repo_private'),
                (1, 'repo_enable_statistics')
            ]:
                if k in kwargs:
                    val = kwargs[k]
                    if strip:
                        k = remove_prefix(k, 'repo_')
                    setattr(cur_repo, k, val)

            new_name = cur_repo.get_new_name(kwargs['repo_name'])
            cur_repo.repo_name = new_name
            #if private flag is set, reset default permission to NONE

            if kwargs.get('repo_private'):
                EMPTY_PERM = 'repository.none'
                RepoModel().grant_user_permission(repo=cur_repo,
                                                  user='******',
                                                  perm=EMPTY_PERM)
            #handle extra fields
            for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
                                kwargs):
                k = RepositoryField.un_prefix_key(field)
                ex_field = RepositoryField.get_by_key_name(key=k,
                                                           repo=cur_repo)
                if ex_field:
                    ex_field.field_value = kwargs[field]
                    self.sa.add(ex_field)
            self.sa.add(cur_repo)

            if org_repo_name != new_name:
                # rename repository
                self.__rename_repo(old=org_repo_name, new=new_name)

            return cur_repo
        except Exception:
            log.error(traceback.format_exc())
            raise
Esempio n. 3
0
    def test_api_add_field_to_repo(self, backend):
        repo = backend.create_repo()
        repo_name = repo.repo_name
        id_, params = build_data(
            self.apikey, 'add_field_to_repo',
            repoid=repo_name,
            key='extra_field',
            label='extra_field_label',
            description='extra_field_desc')
        response = api_call(self.app, params)
        expected = {
            'msg': 'Added new repository field `extra_field`',
            'success': True,
        }
        assert_ok(id_, expected, given=response.body)

        repo = Repository.get_by_repo_name(repo_name)
        repo_field = RepositoryField.get_by_key_name('extra_field', repo)
        _data = repo_field.get_dict()
        assert _data['field_desc'] == 'extra_field_desc'
        assert _data['field_key'] == 'extra_field'
        assert _data['field_label'] == 'extra_field_label'

        id_, params = build_data(
            self.apikey, 'add_field_to_repo',
            repoid=repo_name,
            key='extra_field',
            label='extra_field_label',
            description='extra_field_desc')
        response = api_call(self.app, params)
        expected = 'Field with key `extra_field` exists for repo `%s`' % (
            repo_name)
        assert_error(id_, expected, given=response.body)
Esempio n. 4
0
    def update(self, org_repo_name, **kwargs):
        try:
            cur_repo = self.get_by_repo_name(org_repo_name, cache=False)

            if 'user' in kwargs:
                cur_repo.user = User.get_by_username(kwargs['user'])

            if 'repo_group' in kwargs:
                cur_repo.group = RepoGroup.get(kwargs['repo_group'])

            for strip, k in [(1, 'repo_enable_downloads'),
                      (1, 'repo_description'), (1, 'repo_enable_locking'),
                      (1, 'repo_landing_rev'), (0, 'clone_uri'),
                      (1, 'repo_private'), (1, 'repo_enable_statistics')]:
                if k in kwargs:
                    val = kwargs[k]
                    if strip:
                        k = remove_prefix(k, 'repo_')
                    setattr(cur_repo, k, val)

            new_name = cur_repo.get_new_name(kwargs['repo_name'])
            cur_repo.repo_name = new_name
            #if private flag is set, reset default permission to NONE

            if kwargs.get('repo_private'):
                EMPTY_PERM = 'repository.none'
                RepoModel().grant_user_permission(
                    repo=cur_repo, user='******', perm=EMPTY_PERM
                )
            #handle extra fields
            for field in filter(lambda k: k.startswith(RepositoryField.PREFIX), kwargs):
                k = RepositoryField.un_prefix_key(field)
                ex_field = RepositoryField.get_by_key_name(key=k, repo=cur_repo)
                if ex_field:
                    ex_field.field_value = kwargs[field]
                    self.sa.add(ex_field)
            self.sa.add(cur_repo)

            if org_repo_name != new_name:
                # rename repository
                self.__rename_repo(old=org_repo_name, new=new_name)

            return cur_repo
        except Exception:
            log.error(traceback.format_exc())
            raise
Esempio n. 5
0
    def update(self, repo_name):
        """
        PUT /repos/repo_name: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('repo', repo_name=ID),
        #           method='put')
        # url('repo', repo_name=ID)

        self.__load_data(repo_name)
        c.active = 'settings'
        c.repo_fields = RepositoryField.query()\
            .filter(RepositoryField.repository == c.repo_info).all()

        repo_model = RepoModel()
        changed_name = repo_name

        # override the choices with extracted revisions !
        c.personal_repo_group = RepoGroup.get_by_group_name(
            c.rhodecode_user.username)
        repo = Repository.get_by_repo_name(repo_name)
        old_data = {
            'repo_name': repo_name,
            'repo_group': repo.group.get_dict() if repo.group else {},
            'repo_type': repo.repo_type,
        }
        _form = RepoForm(edit=True,
                         old_data=old_data,
                         repo_groups=c.repo_groups_choices,
                         landing_revs=c.landing_revs_choices,
                         allow_disabled=True)()

        try:
            form_result = _form.to_python(dict(request.POST))
            repo = repo_model.update(repo_name, **form_result)
            ScmModel().mark_for_invalidation(repo_name)
            h.flash(_('Repository %s updated successfully') % repo_name,
                    category='success')
            changed_name = repo.repo_name
            action_logger(c.rhodecode_user, 'admin_updated_repo', changed_name,
                          self.ip_addr, self.sa)
            Session().commit()
        except formencode.Invalid as errors:
            defaults = self.__load_data(repo_name)
            defaults.update(errors.value)
            return htmlfill.render(render('admin/repos/repo_edit.html'),
                                   defaults=defaults,
                                   errors=errors.error_dict or {},
                                   prefix_error=False,
                                   encoding="UTF-8",
                                   force_defaults=False)

        except Exception:
            log.exception("Exception during update of repository")
            h.flash(_('Error occurred during update of repository %s') \
                    % repo_name, category='error')
        return redirect(url('edit_repo', repo_name=changed_name))
Esempio n. 6
0
 def delete_repo_field(self, repo_name, field_id):
     field = RepositoryField.get_or_404(field_id)
     try:
         Session().delete(field)
         Session().commit()
     except Exception, e:
         log.error(traceback.format_exc())
         msg = _('An error occurred during removal of field')
         h.flash(msg, category='error')
Esempio n. 7
0
 def delete_repo_field(self, repo_name, field_id):
     field = RepositoryField.get_or_404(field_id)
     try:
         Session().delete(field)
         Session().commit()
     except Exception, e:
         log.error(traceback.format_exc())
         msg = _('An error occurred during removal of field')
         h.flash(msg, category='error')
Esempio n. 8
0
 def delete_repo_field(self, repo_name, field_id):
     field = RepositoryField.get_or_404(field_id)
     try:
         RepoModel().delete_repo_field(repo_name, field.field_key)
         Session().commit()
     except Exception as e:
         log.exception("Exception during removal of field")
         msg = _('An error occurred during removal of field')
         h.flash(msg, category='error')
     return redirect(url('edit_repo_fields', repo_name=repo_name))
Esempio n. 9
0
    def edit_fields(self, repo_name):
        """GET /repo_name/settings: Form to edit an existing item"""
        # url('edit_repo', repo_name=ID)
        c.repo_info = self._load_repo(repo_name)
        c.repo_fields = RepositoryField.query()\
            .filter(RepositoryField.repository == c.repo_info).all()
        c.active = 'fields'
        if request.POST:

            return redirect(url('repo_edit_fields'))
        return render('admin/repos/repo_edit.html')
Esempio n. 10
0
    def __load_data(self, repo_name=None):
        """
        Load defaults settings for edit, and update

        :param repo_name:
        """
        self.__load_defaults()

        c.repo_info = db_repo = Repository.get_by_repo_name(repo_name)
        repo = db_repo.scm_instance

        if c.repo_info is None:
            h.not_mapped_error(repo_name)
            return redirect(url('repos'))

        ##override defaults for exact repo info here git/hg etc
        choices, c.landing_revs = ScmModel().get_repo_landing_revs(c.repo_info)
        c.landing_revs_choices = choices

        c.default_user_id = User.get_by_username('default').user_id
        c.in_public_journal = UserFollowing.query()\
            .filter(UserFollowing.user_id == c.default_user_id)\
            .filter(UserFollowing.follows_repository == c.repo_info).scalar()

        if c.repo_info.stats:
            # this is on what revision we ended up so we add +1 for count
            last_rev = c.repo_info.stats.stat_on_revision + 1
        else:
            last_rev = 0
        c.stats_revision = last_rev

        c.repo_last_rev = repo.count() if repo.revisions else 0

        if last_rev == 0 or c.repo_last_rev == 0:
            c.stats_percentage = 0
        else:
            c.stats_percentage = '%.2f' % ((float(
                (last_rev)) / c.repo_last_rev) * 100)

        c.repo_fields = RepositoryField.query()\
            .filter(RepositoryField.repository == db_repo).all()

        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()
            if x.repo_id != c.repo_info.repo_id
        ]

        defaults['id_fork_of'] = db_repo.fork.repo_id if db_repo.fork else ''
        return defaults
Esempio n. 11
0
    def __load_data(self, repo_name=None):
        """
        Load defaults settings for edit, and update

        :param repo_name:
        """
        self.__load_defaults()

        c.repo_info = db_repo = Repository.get_by_repo_name(repo_name)
        repo = db_repo.scm_instance

        if c.repo_info is None:
            h.not_mapped_error(repo_name)
            return redirect(url('repos'))

        ##override defaults for exact repo info here git/hg etc
        choices, c.landing_revs = ScmModel().get_repo_landing_revs(c.repo_info)
        c.landing_revs_choices = choices

        c.default_user_id = User.get_default_user().user_id
        c.in_public_journal = UserFollowing.query()\
            .filter(UserFollowing.user_id == c.default_user_id)\
            .filter(UserFollowing.follows_repository == c.repo_info).scalar()

        if c.repo_info.stats:
            # this is on what revision we ended up so we add +1 for count
            last_rev = c.repo_info.stats.stat_on_revision + 1
        else:
            last_rev = 0
        c.stats_revision = last_rev

        c.repo_last_rev = repo.count() if repo.revisions else 0

        if last_rev == 0 or c.repo_last_rev == 0:
            c.stats_percentage = 0
        else:
            c.stats_percentage = '%.2f' % ((float((last_rev)) /
                                            c.repo_last_rev) * 100)

        c.repo_fields = RepositoryField.query()\
            .filter(RepositoryField.repository == db_repo).all()

        defaults = RepoModel()._get_defaults(repo_name)

        _repos = Repository.query().order_by(Repository.repo_name).all()
        read_access_repos = RepoList(_repos)
        c.repos_list = [('', _('--REMOVE FORK--'))]
        c.repos_list += [(x.repo_id, x.repo_name)
                         for x in read_access_repos
                         if x.repo_id != c.repo_info.repo_id]

        defaults['id_fork_of'] = db_repo.fork.repo_id if db_repo.fork else ''
        return defaults
Esempio n. 12
0
    def edit(self, repo_name):
        """GET /repo_name/settings: Form to edit an existing item"""
        # url('edit_repo', repo_name=ID)
        defaults = self.__load_data(repo_name)
        if 'clone_uri' in defaults:
            del defaults['clone_uri']

        c.repo_fields = RepositoryField.query()\
            .filter(RepositoryField.repository == c.repo_info).all()
        c.personal_repo_group = RepoGroup.get_by_group_name(
            c.rhodecode_user.username)
        c.active = 'settings'
        return htmlfill.render(render('admin/repos/repo_edit.html'),
                               defaults=defaults,
                               encoding="UTF-8",
                               force_defaults=False)
Esempio n. 13
0
    def add_repo_field(self,
                       repo_name,
                       field_key,
                       field_label,
                       field_value='',
                       field_type='str',
                       field_desc=''):

        repo = self._get_repo(repo_name)

        new_field = RepositoryField()
        new_field.repository = repo
        new_field.field_key = field_key
        new_field.field_type = field_type  # python type
        new_field.field_value = field_value
        new_field.field_desc = field_desc
        new_field.field_label = field_label
        self.sa.add(new_field)
        return new_field
Esempio n. 14
0
    def create_repo_field(self, repo_name):
        try:
            form_result = RepoFieldForm()().to_python(dict(request.POST))
            new_field = RepositoryField()
            new_field.repository = Repository.get_by_repo_name(repo_name)
            new_field.field_key = form_result['new_field_key']
            new_field.field_type = form_result['new_field_type']  # python type
            new_field.field_value = form_result[
                'new_field_value']  # set initial blank value
            new_field.field_desc = form_result['new_field_desc']
            new_field.field_label = form_result['new_field_label']
            Session().add(new_field)
            Session().commit()

        except Exception, e:
            log.error(traceback.format_exc())
            msg = _('An error occurred during creation of field')
            if isinstance(e, formencode.Invalid):
                msg += ". " + e.msg
            h.flash(msg, category='error')
Esempio n. 15
0
    def create_repo_field(self, repo_name):
        try:
            form_result = RepoFieldForm()().to_python(dict(request.POST))
            new_field = RepositoryField()
            new_field.repository = Repository.get_by_repo_name(repo_name)
            new_field.field_key = form_result['new_field_key']
            new_field.field_type = form_result['new_field_type']  # python type
            new_field.field_value = form_result['new_field_value']  # set initial blank value
            new_field.field_desc = form_result['new_field_desc']
            new_field.field_label = form_result['new_field_label']
            Session().add(new_field)
            Session().commit()

        except Exception, e:
            log.error(traceback.format_exc())
            msg = _('An error occurred during creation of field')
            if isinstance(e, formencode.Invalid):
                msg += ". " + e.msg
            h.flash(msg, category='error')
Esempio n. 16
0
 def delete_repo_field(self, repo_name, field_key):
     repo = self._get_repo(repo_name)
     field = RepositoryField.get_by_key_name(field_key, repo)
     if field:
         self.sa.delete(field)