Example #1
0
    def edit(self, gist_id, format='html'):
        """GET /admin/gists/gist_id/edit: Form to edit an existing item"""
        # url('edit_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()

        self.__load_defaults(extra_values=('0', _('unmodified')))
        rendered = render('admin/gists/edit.html')

        if request.POST:
            rpost = request.POST
            nodes = {}
            for org_filename, filename, mimetype, content in zip(
                                                    rpost.getall('org_files'),
                                                    rpost.getall('files'),
                                                    rpost.getall('mimetypes'),
                                                    rpost.getall('contents')):

                nodes[org_filename] = {
                    'org_filename': org_filename,
                    'filename': filename,
                    'content': content,
                    'lexer': mimetype,
                }
            try:
                GistModel().update(
                    gist=c.gist,
                    description=rpost['description'],
                    owner=c.gist.owner,
                    gist_mapping=nodes,
                    gist_type=c.gist.gist_type,
                    lifetime=rpost['lifetime']
                )

                Session().commit()
                h.flash(_('Successfully updated gist content'), category='success')
            except NodeNotChangedError:
                # raised if nothing was changed in repo itself. We anyway then
                # store only DB stuff for gist
                Session().commit()
                h.flash(_('Successfully updated gist data'), category='success')
            except Exception:
                log.error(traceback.format_exc())
                h.flash(_('Error occurred during update of gist %s') % gist_id,
                        category='error')

            return redirect(url('gist', gist_id=gist_id))

        return rendered
Example #2
0
 def destroy_gists(self, gistid=None):
     for g in Gist.query():
         if gistid:
             if gistid == g.gist_access_id:
                 GistModel().delete(g)
         else:
             GistModel().delete(g)
     Session().commit()
Example #3
0
    def delete(self, gist_id):
        gist = GistModel().get_gist(gist_id)
        owner = gist.owner_id == request.authuser.user_id
        if h.HasPermissionAny('hg.admin')() or owner:
            GistModel().delete(gist)
            Session().commit()
            h.flash(_('Deleted gist %s') % gist.gist_access_id,
                    category='success')
        else:
            raise HTTPForbidden()

        raise HTTPFound(location=url('gists'))
Example #4
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)
        gist = GistModel().get_gist(gist_id)
        owner = gist.gist_owner == c.authuser.user_id
        if h.HasPermissionAny('hg.admin')() or owner:
            GistModel().delete(gist)
            Session().commit()
            h.flash(_('Deleted gist %s') % gist.gist_access_id, category='success')
        else:
            raise HTTPForbidden()

        return redirect(url('gists'))
Example #5
0
def _create_gist(f_name, content='some gist', lifetime=-1,
                 description='gist-desc', gist_type='public',
                 owner=base.TEST_USER_ADMIN_LOGIN):
    gist_mapping = {
        f_name: {'content': content}
    }
    owner = User.get_by_username(owner)
    gist = GistModel().create(description, owner=owner, ip_addr=base.IP_ADDR,
                       gist_mapping=gist_mapping, gist_type=gist_type,
                       lifetime=lifetime)
    Session().commit()
    return gist
Example #6
0
    def show(self, gist_id, revision='tip', format='html', f_path=None):
        c.gist = Gist.get_or_404(gist_id)

        if c.gist.is_expired:
            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, revision=revision)
        except VCSError:
            log.error(traceback.format_exc())
            raise HTTPNotFound()
        if format == 'raw':
            content = '\n\n'.join(
                safe_str(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')
Example #7
0
    def create_gist(self, **kwargs):
        form_data = {
            'description': u'new-gist',
            'owner': TEST_USER_ADMIN_LOGIN,
            'gist_type': Gist.GIST_PUBLIC,
            'lifetime': -1,
            'gist_mapping': {
                'filename1.txt': {
                    'content': 'hello world'
                },
            }
        }
        form_data.update(kwargs)
        gist = GistModel().create(description=form_data['description'],
                                  owner=form_data['owner'],
                                  gist_mapping=form_data['gist_mapping'],
                                  gist_type=form_data['gist_type'],
                                  lifetime=form_data['lifetime'])
        Session().commit()

        return gist
Example #8
0
    def show(self, gist_id, revision='tip', format='html', 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,
                                                            revision=revision)
        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')
Example #9
0
    def create(self):
        self.__load_defaults()
        gist_form = GistForm([x[0] for x in c.lifetime_values])()
        try:
            form_result = gist_form.to_python(dict(request.POST))
            # TODO: multiple files support, from the form
            filename = form_result['filename'] or Gist.DEFAULT_FILENAME
            nodes = {
                filename: {
                    'content': form_result['content'],
                    'lexer': form_result['mimetype']  # None is autodetect
                }
            }
            _public = form_result['public']
            gist_type = Gist.GIST_PUBLIC if _public else Gist.GIST_PRIVATE
            gist = GistModel().create(description=form_result['description'],
                                      owner=request.authuser.user_id,
                                      ip_addr=request.ip_addr,
                                      gist_mapping=nodes,
                                      gist_type=gist_type,
                                      lifetime=form_result['lifetime'])
            Session().commit()
            new_gist_id = gist.gist_access_id
        except formencode.Invalid as errors:
            defaults = errors.value

            return formencode.htmlfill.render(render('admin/gists/new.html'),
                                              defaults=defaults,
                                              errors=errors.error_dict or {},
                                              prefix_error=False,
                                              encoding="UTF-8",
                                              force_defaults=False)

        except Exception as e:
            log.error(traceback.format_exc())
            h.flash(_('Error occurred during gist creation'), category='error')
            raise HTTPFound(location=url('new_gist'))
        raise HTTPFound(location=url('gist', gist_id=new_gist_id))
Example #10
0
    def create(self):
        """POST /admin/gists: Create a new item"""
        # url('gists')
        self.__load_defaults()
        gist_form = GistForm([x[0] for x in c.lifetime_values])()
        try:
            form_result = gist_form.to_python(dict(request.POST))
            #TODO: multiple files support, from the form
            filename = form_result['filename'] or Gist.DEFAULT_FILENAME
            nodes = {
                filename: {
                    'content': form_result['content'],
                    'lexer': form_result['mimetype']  # None is autodetect
                }
            }
            _public = form_result['public']
            gist_type = Gist.GIST_PUBLIC if _public else Gist.GIST_PRIVATE
            gist = GistModel().create(
                description=form_result['description'],
                owner=c.authuser.user_id,
                gist_mapping=nodes,
                gist_type=gist_type,
                lifetime=form_result['lifetime']
            )
            Session().commit()
            new_gist_id = gist.gist_access_id
        except formencode.Invalid, errors:
            defaults = errors.value

            return formencode.htmlfill.render(
                render('admin/gists/new.html'),
                defaults=defaults,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8",
                force_defaults=False)
Example #11
0
 def teardown_method(self, method):
     for g in Gist.query():
         GistModel().delete(g)
     Session().commit()
Example #12
0
 def tearDown(self):
     for g in Gist.get_all():
         GistModel().delete(g)
     Session().commit()