freehg / repos / views.py

from freehg.repos.models import Repo
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.contrib.auth import login, authenticate
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

from freehg.repos.forms import (NewRepoForm, NewAccountForm, LoginForm,
        EditRepoForm)

from mercurial import hg, ui, util
from binascii import hexlify, unhexlify

rfc822date = lambda x: util.datestr(x, "%a, %d %b %Y %H:%M:%S")

def frontpage(request):
    print type(request)
    if request.POST.get('reponame', False):
        repo_form = NewRepoForm(request.POST)
    else:
        repo_form = NewRepoForm()

    if request.user.is_authenticated():
        repo_form.user = request.user
        new_account_form = login_form = None
    else:
        post_names = set(n for n,v in request.POST.items() if v)
        print post_names
        if post_names.intersection(('newaccount', 'new-username',
                    'new-password1', 'new-password2')):
            new_account_form = NewAccountForm(request.POST, prefix='new')
            if new_account_form.is_valid():
                user = User.objects.create_user(
                        new_account_form.cleaned_data['username'],
                        '',
                        new_account_form.cleaned_data['password1'])
                user.save()
                user = authenticate(
                        username=new_account_form.cleaned_data['username'],
                        password=new_account_form.cleaned_data['password1'])
                login(request, user)
                user.message_set.create(message=
                        "Your account has been created. Welcome to FreeHG.org!")
                repo_form.user = user
        else:
            new_account_form = NewAccountForm(prefix='new')
        if post_names.intersection(('username', 'password')):
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                user = login_form.user
                login(request, user)
                user.message_set.create(message="You have been logged in.")
                repo_form.user = user
        else:
            login_form = LoginForm()

    if repo_form.user and repo_form.is_bound and repo_form.is_valid():
        repo = repo_form.create_repo()
        repo.save()
        request.user.message_set.create(message=
                "Repository '%s' created." % repo.name)
        return HttpResponseRedirect(repo.get_absolute_url())

    return render_to_response('frontpage.html',
        dict(
            repo_form=repo_form,
            new_account_form=new_account_form,
            login_form=login_form,
        ), context_instance=RequestContext(request)
    )

def summary(request, username, reponame):
    repo = get_object_or_404(Repo, name=reponame, owner__username=username)
    hgrepo = hg.repository(ui.ui(), repo.file_path)
    has_tip = hgrepo.changelog.tip() != '\x00'*20
    tip_hex = hexlify(hgrepo.changelog.tip())[:12]
    from mercurial.hgweb.hgweb_mod import hgweb
    from mercurial.hgweb.common import style_map
    from mercurial import templater
    from django.conf import settings
    web = hgweb(hgrepo, name=repo.get_long_name())
    web.refresh()
    def motd(**map):
        yield web.config("web", "motd", "")
    templatepath = settings.HG_TEMPLATE_PATH
    mapfile = mapfile = style_map(templatepath, "freehg")
    web.t = templater.templater(mapfile, templater.common_filters,
                                     defaults={"url": request.build_absolute_uri(),
                                               "staticurl": "/static/",
                                               "urlbase": "/",
                                               "repo": repo.get_long_name(),
                                               "header": "",
                                               "footer": "",
                                               "motd": motd,
                                               "rawfileheader": "FIXME",
                                               "sessionvars": tuple(),
                                               })
    from cStringIO import StringIO
    content = []
    def write(*things):
        for thing in things:
            if hasattr(thing, "__iter__"):
                for part in thing:
                    write(part)
            else:
                # FIXME I have a feeling that this isn't correct.
                content.append(str(thing).decode('utf8'))
    write(web.summary())

    return render_to_response('repos/summary.html',
        dict(
            repo=repo,
            has_tip=has_tip,
            tip_hex=tip_hex,
            content=u''.join(content),
        ), context_instance=RequestContext(request)
    )

@login_required
def edit_repo(request, username, reponame):
    if username != request.user.username:
        from django.http import HttpResponseForbidden
        return HttpResponseForbidden(
                "You don't have permission to edit this repository.")
    repo = get_object_or_404(Repo, owner__username=username, name=reponame)

    if request.method == 'POST':
        form = EditRepoForm(repo, request.POST)
        if form.is_valid():
            old_path = repo.file_path
            new_name = form.cleaned_data['reponame']
            repo.name = form.cleaned_data['reponame']
            repo.long_name = form.cleaned_data['long_name']
            repo.description = form.cleaned_data['description']
            if old_path != repo.file_path:
                # FIXME move this into the pre_save signal or something? (just
                # as soon as I figure out how to determin the previous value.)
                # FIXME Have some sort of error handling?
                import os
                os.rename(old_path, repo.file_path)
            repo.save()
            return HttpResponseRedirect(repo.get_absolute_url())
    else:
        form = EditRepoForm(repo)
    return render_to_response('repos/edit.html',
        dict(
            repo=repo,
            form=form,
        ), context_instance=RequestContext(request)
    )

@login_required
def delete_repo(request, username, reponame):
    if username != request.user.username:
        from django.http import HttpResponseForbidden
        return HttpResponseForbidden(
                "You don't have permission to delete this repository.")
    repo = get_object_or_404(Repo, owner__username=username, name=reponame)

    if request.POST.get('confirm'):
        repo.delete()
        return HttpResponseRedirect('/repo_deleted/')
    return render_to_response('repos/delete.html',
            dict(repo=repo),
            context_instance=RequestContext(request))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.