def cleanup(self):
        for gist_id in self._gist_ids:
            gist = Gist.get(gist_id)
            if gist:
                Session().delete(gist)

        Session().commit()
 def validate_python(self, value, state):
     existing = Gist.get_by_access_id(value)
     if existing:
         msg = M(self, 'gistid_taken', state)
         raise formencode.Invalid(
             msg, value, state, error_dict={'gistid': msg}
         )
Ejemplo n.º 3
0
    def get_gist_files(self, gist_access_id, revision=None):
        """
        Get files for given gist

        :param gist_access_id:
        """
        repo = Gist.get_by_access_id(gist_access_id)
        commit = repo.scm_instance().get_commit(commit_id=revision)
        return commit, [n for n in commit.get_node('/')]
Ejemplo n.º 4
0
    def get_gist_files(self, gist_access_id):
        """
        Get files for given gist

        :param gist_access_id:
        """
        repo = Gist.get_by_access_id(gist_access_id)
        cs = repo.scm_instance.get_changeset()
        return (
         cs, [n for n in cs.get_node('/')]
        )
Ejemplo n.º 5
0
    def index(self, format='html'):
        """GET /admin/gists: All items in the collection"""
        # url('gists')
        c.show_private = request.GET.get('private') and c.rhodecode_user.username != 'default'
        c.show_public = request.GET.get('public') and c.rhodecode_user.username != 'default'

        gists = Gist().query()\
            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time()))\
            .order_by(Gist.created_on.desc())
        if c.show_private:
            c.gists = gists.filter(Gist.gist_type == Gist.GIST_PRIVATE)\
                             .filter(Gist.gist_owner == c.rhodecode_user.user_id)
        elif c.show_public:
            c.gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)\
                             .filter(Gist.gist_owner == c.rhodecode_user.user_id)

        else:
            c.gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)
        p = safe_int(request.GET.get('page', 1), 1)
        c.gists_pager = Page(c.gists, page=p, items_per_page=10)
        return render('admin/gists/index.html')
Ejemplo n.º 6
0
    def index(self, format='html'):
        """GET /admin/gists: All items in the collection"""
        # url('gists')
        c.show_private = request.GET.get(
            'private') and c.rhodecode_user.username != 'default'
        c.show_public = request.GET.get(
            'public') and c.rhodecode_user.username != 'default'

        gists = Gist().query()\
            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time()))\
            .order_by(Gist.created_on.desc())
        if c.show_private:
            c.gists = gists.filter(Gist.gist_type == Gist.GIST_PRIVATE)\
                             .filter(Gist.gist_owner == c.rhodecode_user.user_id)
        elif c.show_public:
            c.gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)\
                             .filter(Gist.gist_owner == c.rhodecode_user.user_id)

        else:
            c.gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)
        p = safe_int(request.GET.get('page', 1), 1)
        c.gists_pager = Page(c.gists, page=p, items_per_page=10)
        return render('admin/gists/index.html')
Ejemplo n.º 7
0
    def check_revision(self, gist_id):
        c.gist = Gist.get_or_404(gist_id)
        last_rev = c.gist.scm_instance().get_commit()
        success = True
        revision = request.GET.get('revision')

        ##TODO: maybe move this to model ?
        if revision != last_rev.raw_id:
            log.error('Last revision %s is different then submitted %s' %
                      (revision, last_rev))
            # our gist has newer version than we
            success = False

        return {'success': success}
Ejemplo n.º 8
0
    def _add_gist_to_context(self, gist_id):
        c.gist = Gist.get_or_404(gist_id)

        # Check if this gist is expired
        if c.gist.gist_expires != -1:
            if time.time() > c.gist.gist_expires:
                log.error('Gist expired at %s',
                          time_to_datetime(c.gist.gist_expires))
                raise HTTPNotFound()

        # check if this gist requires a login
        is_default_user = c.rhodecode_user.username == User.DEFAULT_USER
        if c.gist.acl_level == Gist.ACL_LEVEL_PRIVATE and is_default_user:
            log.error("Anonymous user %s tried to access protected gist `%s`",
                      c.rhodecode_user, gist_id)
            raise HTTPNotFound()
Ejemplo n.º 9
0
    def delete(self, gist_id):
        """DELETE /admin/gists/gist_id: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('gist', gist_id=ID),
        #           method='delete')
        # url('gist', gist_id=ID)
        c.gist = Gist.get_or_404(gist_id)

        owner = c.gist.gist_owner == c.rhodecode_user.user_id
        if not (h.HasPermissionAny('hg.admin')() or owner):
            raise HTTPForbidden()

        GistModel().delete(c.gist)
        Session().commit()
        h.flash(_('Deleted gist %s') % c.gist.gist_access_id,
                category='success')

        return redirect(url('gists'))
Ejemplo n.º 10
0
    def show(self, gist_id, format='html', revision='tip', f_path=None):
        """GET /admin/gists/gist_id: Show a specific item"""
        # url('gist', gist_id=ID)
        c.gist = Gist.get_or_404(gist_id)

        #check if this gist is not expired
        if c.gist.gist_expires != -1:
            if time.time() > c.gist.gist_expires:
                log.error('Gist expired at %s' %
                          (time_to_datetime(c.gist.gist_expires)))
                raise HTTPNotFound()
        try:
            c.file_changeset, c.files = GistModel().get_gist_files(gist_id)
        except VCSError:
            log.error(traceback.format_exc())
            raise HTTPNotFound()
        if format == 'raw':
            content = '\n\n'.join([f.content for f in c.files if (f_path is None or f.path == f_path)])
            response.content_type = 'text/plain'
            return content
        return render('admin/gists/show.html')
Ejemplo n.º 11
0
    def show(self, gist_id, format='html', revision='tip', f_path=None):
        """GET /admin/gists/gist_id: Show a specific item"""
        # url('gist', gist_id=ID)
        c.gist = Gist.get_or_404(gist_id)

        #check if this gist is not expired
        if c.gist.gist_expires != -1:
            if time.time() > c.gist.gist_expires:
                log.error('Gist expired at %s' %
                          (time_to_datetime(c.gist.gist_expires)))
                raise HTTPNotFound()
        try:
            c.file_changeset, c.files = GistModel().get_gist_files(gist_id)
        except VCSError:
            log.error(traceback.format_exc())
            raise HTTPNotFound()
        if format == 'raw':
            content = '\n\n'.join([
                f.content for f in c.files
                if (f_path is None or f.path == f_path)
            ])
            response.content_type = 'text/plain'
            return content
        return render('admin/gists/show.html')
Ejemplo n.º 12
0
 def tearDown(self):
     for g in Gist.get_all():
         GistModel().delete(g)
     Session().commit()
Ejemplo n.º 13
0
    def create(self, description, owner, gist_mapping,
               gist_type=Gist.GIST_PUBLIC, lifetime=-1):
        """

        :param description: description of the gist
        :param owner: user who created this gist
        :param gist_mapping: mapping {filename:{'content':content},...}
        :param gist_type: type of gist private/public
        :param lifetime: in minutes, -1 == forever
        """
        gist_id = safe_unicode(unique_id(20))
        lifetime = safe_int(lifetime, -1)
        gist_expires = time.time() + (lifetime * 60) if lifetime != -1 else -1
        log.debug('set GIST expiration date to: %s'
                  % (time_to_datetime(gist_expires)
                   if gist_expires != -1 else 'forever'))
        #create the Database version
        gist = Gist()
        gist.gist_description = description
        gist.gist_access_id = gist_id
        gist.gist_owner = owner.user_id
        gist.gist_expires = gist_expires
        gist.gist_type = safe_unicode(gist_type)
        self.sa.add(gist)
        self.sa.flush()
        if gist_type == Gist.GIST_PUBLIC:
            # use DB ID for easy to use GIST ID
            gist_id = safe_unicode(gist.gist_id)
            gist.gist_access_id = gist_id
            self.sa.add(gist)

        gist_repo_path = os.path.join(GIST_STORE_LOC, gist_id)
        log.debug('Creating new %s GIST repo in %s' % (gist_type, gist_repo_path))
        repo = RepoModel()._create_repo(repo_name=gist_repo_path, alias='hg',
                                        parent=None)

        processed_mapping = {}
        for filename in gist_mapping:
            if filename != os.path.basename(filename):
                raise Exception('Filename cannot be inside a directory')

            content = gist_mapping[filename]['content']
            #TODO: expand support for setting explicit lexers
#             if lexer is None:
#                 try:
#                     lexer = pygments.lexers.guess_lexer_for_filename(filename,content)
#                 except pygments.util.ClassNotFound:
#                     lexer = 'text'
            processed_mapping[filename] = {'content': content}

        # now create single multifile commit
        message = 'added file'
        message += 's: ' if len(processed_mapping) > 1 else ': '
        message += ', '.join([x for x in processed_mapping])

        #fake RhodeCode Repository object
        fake_repo = AttributeDict(dict(
            repo_name=gist_repo_path,
            scm_instance_no_cache=lambda: repo,
        ))
        ScmModel().create_nodes(
            user=owner.user_id, repo=fake_repo,
            message=message,
            nodes=processed_mapping,
            trigger_push_hook=False
        )
        # store metadata inside the gist, this can be later used for imports
        # or gist identification
        metadata = {
            'gist_db_id': gist.gist_id,
            'gist_access_id': gist.gist_access_id,
            'gist_owner_id': owner.user_id,
            'gist_type': gist.gist_type,
            'gist_exipres': gist.gist_expires
        }
        with open(os.path.join(repo.path, '.hg', GIST_METADATA_FILE), 'wb') as f:
            f.write(json.dumps(metadata))
        return gist
Ejemplo n.º 14
0
    def index(self):
        """GET /admin/gists: All items in the collection"""
        # url('gists')
        not_default_user = c.rhodecode_user.username != User.DEFAULT_USER
        c.show_private = request.GET.get('private') and not_default_user
        c.show_public = request.GET.get('public') and not_default_user
        c.show_all = request.GET.get('all') and c.rhodecode_user.admin

        gists = _gists = Gist().query()\
            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time()))\
            .order_by(Gist.created_on.desc())

        c.active = 'public'
        # MY private
        if c.show_private and not c.show_public:
            gists = _gists.filter(Gist.gist_type == Gist.GIST_PRIVATE)\
                        .filter(Gist.gist_owner == c.rhodecode_user.user_id)
            c.active = 'my_private'
        # MY public
        elif c.show_public and not c.show_private:
            gists = _gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)\
                        .filter(Gist.gist_owner == c.rhodecode_user.user_id)
            c.active = 'my_public'
        # MY public+private
        elif c.show_private and c.show_public:
            gists = _gists.filter(or_(Gist.gist_type == Gist.GIST_PUBLIC,
                                      Gist.gist_type == Gist.GIST_PRIVATE))\
                        .filter(Gist.gist_owner == c.rhodecode_user.user_id)
            c.active = 'my_all'
        # Show all by super-admin
        elif c.show_all:
            c.active = 'all'
            gists = _gists

        # default show ALL public gists
        if not c.show_public and not c.show_private and not c.show_all:
            gists = _gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)
            c.active = 'public'

        from rhodecode.lib.utils import PartialRenderer
        _render = PartialRenderer('data_table/_dt_elements.html')

        data = []

        for gist in gists:
            data.append({
                'created_on':
                _render('gist_created', gist.created_on),
                'created_on_raw':
                gist.created_on,
                'type':
                _render('gist_type', gist.gist_type),
                'access_id':
                _render('gist_access_id', gist.gist_access_id,
                        gist.owner.full_contact),
                'author':
                _render('gist_author', gist.owner.full_contact,
                        gist.created_on, gist.gist_expires),
                'author_raw':
                h.escape(gist.owner.full_contact),
                'expires':
                _render('gist_expires', gist.gist_expires),
                'description':
                _render('gist_description', gist.gist_description)
            })
        c.data = json.dumps(data)
        return render('admin/gists/index.html')
Ejemplo n.º 15
0
 def tearDown(self):
     for g in Gist.get_all():
         GistModel().delete(g)
     Session().commit()
Ejemplo n.º 16
0
    def create(self, description, owner, gist_mapping,
               gist_type=Gist.GIST_PUBLIC, lifetime=-1, gist_id=None,
               gist_acl_level=Gist.ACL_LEVEL_PRIVATE):
        """
        Create a gist

        :param description: description of the gist
        :param owner: user who created this gist
        :param gist_mapping: mapping {filename:{'content':content},...}
        :param gist_type: type of gist private/public
        :param lifetime: in minutes, -1 == forever
        :param gist_acl_level: acl level for this gist
        """
        owner = self._get_user(owner)
        gist_id = safe_unicode(gist_id or unique_id(20))
        lifetime = safe_int(lifetime, -1)
        gist_expires = time.time() + (lifetime * 60) if lifetime != -1 else -1
        expiration = (time_to_datetime(gist_expires)
                      if gist_expires != -1 else 'forever')
        log.debug('set GIST expiration date to: %s', expiration)
        # create the Database version
        gist = Gist()
        gist.gist_description = description
        gist.gist_access_id = gist_id
        gist.gist_owner = owner.user_id
        gist.gist_expires = gist_expires
        gist.gist_type = safe_unicode(gist_type)
        gist.acl_level = gist_acl_level
        self.sa.add(gist)
        self.sa.flush()
        if gist_type == Gist.GIST_PUBLIC:
            # use DB ID for easy to use GIST ID
            gist_id = safe_unicode(gist.gist_id)
            gist.gist_access_id = gist_id
            self.sa.add(gist)

        gist_repo_path = os.path.join(GIST_STORE_LOC, gist_id)
        log.debug('Creating new %s GIST repo in %s', gist_type, gist_repo_path)
        repo = RepoModel()._create_filesystem_repo(
            repo_name=gist_id, repo_type='hg', repo_group=GIST_STORE_LOC,
            use_global_config=True)

        processed_mapping = {}
        for filename in gist_mapping:
            if filename != os.path.basename(filename):
                raise Exception('Filename cannot be inside a directory')

            content = gist_mapping[filename]['content']
            # TODO: expand support for setting explicit lexers
#             if lexer is None:
#                 try:
#                     guess_lexer = pygments.lexers.guess_lexer_for_filename
#                     lexer = guess_lexer(filename,content)
#                 except pygments.util.ClassNotFound:
#                     lexer = 'text'
            processed_mapping[filename] = {'content': content}

        # now create single multifile commit
        message = 'added file'
        message += 's: ' if len(processed_mapping) > 1 else ': '
        message += ', '.join([x for x in processed_mapping])

        # fake RhodeCode Repository object
        fake_repo = AttributeDict({
            'repo_name': gist_repo_path,
            'scm_instance': lambda *args, **kwargs: repo,
        })

        ScmModel().create_nodes(
            user=owner.user_id, repo=fake_repo,
            message=message,
            nodes=processed_mapping,
            trigger_push_hook=False
        )

        self._store_metadata(repo, gist.gist_id, gist.gist_access_id,
                             owner.user_id, owner.username, gist.gist_type,
                             gist.gist_expires, gist_acl_level)
        return gist