Commits

Anonymous committed 63707a4

Move everything under transifex/

Comments (0)

Files changed (1022)

__init__.py

-def get_version():
-    return 'devel'

actionlog/__init__.py

-def get_version():
-    return 'devel'

actionlog/models.py

-import datetime
-from django.db import models
-from django.contrib.contenttypes.models import ContentType
-from django.contrib.auth.models import User
-from django.conf import settings
-from django.utils.translation import ugettext_lazy as _
-from django.utils.encoding import smart_unicode
-from django.utils.encoding import force_unicode
-from django.shortcuts import get_object_or_404
-from django.template import (loader, Context, TemplateDoesNotExist)
-from django.utils.translation import (get_language, activate)
-from notification.models import NoticeType
-
-def _get_formatted_message(label, context):
-    """
-    Return a message that is a rendered template with the given context using 
-    the default language of the system.
-    """
-    current_language = get_language()
-
-    # Setting the environment to the default language
-    activate(settings.LANGUAGE_CODE)
-
-    c = Context(context)
-    try:
-        msg = loader.get_template('notification/%s/notice.html' % label).render(c)
-    except TemplateDoesNotExist:
-        #TODO: Maybe send an alert to the admins
-        msg = None
-
-    # Reset environment to original language
-    activate(current_language)
-
-    return msg
-
-class LogEntry(models.Model):
-    user = models.ForeignKey(User, blank=True, null=True, 
-            related_name="tx_user_action")
-
-    object_id = models.IntegerField(blank=True, null=True)
-    content_type = models.ForeignKey(ContentType, blank=True, null=True,
-                                     related_name="tx_object")
-
-    action_type = models.ForeignKey(NoticeType)
-    action_time = models.DateTimeField()
-    object_name = models.CharField(blank=True, max_length=200)
-    message = models.TextField(blank=True, null=True)
-
-    class Meta:
-        verbose_name = _('log entry')
-        verbose_name_plural = _('log entries')
-        ordering = ('-action_time',)
-
-    def __repr__(self):
-        return smart_unicode(self.action_time)
-
-
-    def save(self, *args, **kwargs):
-        """Save the object in the database."""
-        if self.action_time is None:
-           self.action_time = datetime.datetime.now()
-        super(LogEntry, self).save(*args, **kwargs)
-
-def action_logging(user, object_list, action_type, message=None, context=None):
-    """ 
-    Add ActionLog using a set of parameters
-    
-    user: The user that did the action.
-    object_list: A list of objects that should be created the actionlog for.
-    action_type: Label of a type of action from the NoticeType model.
-    message: A message to be included at the actionlog. If no message is passed
-             it will try do render a message using the notice.html from the
-             notification application.
-    contex: To render the message using the notification files, sometimes it is 
-            necessary to pass some vars by using a context.
-
-    Usage:
-        al = 'project_component_added'
-        context = {'component': object}
-        action_logging(request.user, [object], al , context=context):
-    """
-
-    if context is None:
-        context = {}
-
-    if message is None:
-        message = _get_formatted_message(action_type, context)
-
-    action_type_obj = get_object_or_404(NoticeType, label=action_type)
-
-    time = datetime.datetime.now()
-
-    try:
-        for object in object_list:
-            l = LogEntry(
-                    user_id = user.pk, 
-                    content_type = ContentType.objects.get_for_model(object),
-                    object_id = object.pk,
-                    object_name = force_unicode(object)[:200], 
-                    action_type = action_type_obj,
-                    action_time = time,
-                    message = message)
-            l.save()
-    except TypeError:
-        raise TypeError("The 'object_list' parameter must be iterable")

actionlog/templates/object_action_list.html

-{% load i18n %}
-{% if action_list %}
-    <table id="change-history">
-        <thead>
-        <tr>
-            <th scope="col">{% trans 'Date/time' %}</th>
-            <th scope="col">{% trans 'User' %}</th>
-            <th scope="col">{% trans 'Action' %}</th>
-        </tr>
-        </thead>
-        <tbody>
-        {% for action in action_list %}
-        <tr>
-            <th scope="row">{{ action.action_time|date:_("DATETIME_FORMAT") }}</th>
-            <td>{{ action.user.username }}{% if action.user.get_full_name %} ({{ action.user.get_full_name }}){% endif %}</td>
-            <td>{{ action.change_message }}</td>
-        </tr>
-        {% endfor %}
-        </tbody>
-    </table>
-{% else %}
-    <p>{% trans "No history recorded yet." %}</p>
-{% endif %}

actionlog/templatetags/__init__.py

-def get_version():
-    return 'devel'

actionlog/templatetags/tx_action_log.py

-from django import template
-from actionlog.models import LogEntry
-
-register = template.Library()
-
-class LogNode(template.Node):
-    def __init__(self, limit, varname, user=None, object=None):
-        self.limit, self.varname, self.object , self.user = (limit, varname,
-                                                             object, user)
-
-    def __repr__(self):
-        return "<GetLog Node>"
-
-#    def entries_for_object(self, object):
-#        model = object.model
-#        opts = model._meta
-#        app_label = opts.app_label
-#        action_list = LogEntry.objects.filter(
-#            object_id = object.id,
-#            content_type__id__exact = ContentType.objects.get_for_model(model).id
-#        ).select_related().order_by('action_time')
-#        # If no history was found, see whether this object even exists.
-
-    def render(self, context):
-        if self.user is not None:
-            if not self.user.isdigit():
-                self.user = context[self.user].id
-            context[self.varname] = LogEntry.objects.filter(
-                user__id__exact=self.user).select_related(
-                'content_type', 'user')[:self.limit]
-            return ''
-        if self.object is not None:
-            from django.contrib.contenttypes.models import ContentType
-            obj = context[self.object]
-            obj_id = obj.id
-            ctype = ContentType.objects.get_for_model(obj)
-            context[self.varname] = LogEntry.objects.filter(object_id__exact=obj_id, content_type__pk=ctype.id).select_related('content_type', 'user')[:self.limit]
-            return ''
-        return ''
-
-class DoGetLog:
-    """
-    Populates a template variable with the log for the given criteria.
-
-    Usage::
-
-        {% get_log <limit> as <varname> [for object <context_var_containing_user_obj>] %}
-
-    Examples::
-
-        {% get_log 10 as action_log for_object foo %}
-        {% get_log 10 as action_log for_user 23 %}
-        {% get_log 10 as action_log for_user current_user %}
-
-    Note that ``context_var_containing_user_obj`` can be a hard-coded integer
-    (object ID) or the name of a template context variable containing the user
-    object whose ID you want.
-    """
-
-    def __init__(self, tag_name):
-        self.tag_name = tag_name
-
-    def __call__(self, parser, token):
-        tokens = token.contents.split()
-        if len(tokens) < 4:
-            raise template.TemplateSyntaxError, \
-                "'%s' statements requires two arguments" % self.tag_name
-        if not tokens[1].isdigit():
-            raise template.TemplateSyntaxError, \
-                "First argument in '%s' must be an integer" % self.tag_name
-        if tokens[2] != 'as':
-            raise template.TemplateSyntaxError, \
-                "Second argument in '%s' must be 'as'" % self.tag_name
-        if len(tokens) > 4:
-            if tokens[4] == 'for_user':
-                return LogNode(limit=tokens[1], varname=tokens[3],
-                               user=(len(tokens) > 5 and tokens[5] or None))
-            elif tokens[4] == 'for_object':
-                return LogNode(limit=tokens[1], varname=tokens[3],
-                               object=(len(tokens) > 5 and tokens[5] or None))
-            else:
-                raise template.TemplateSyntaxError, \
-                    "Fourth argument in '%s' must be either 'user' or " \
-                    "'object'" % self.tag_name
-
-register.tag('get_log', DoGetLog('get_log'))

build-tools/SPECS/transifex.spec.in

   * git support
 
 %prep
-%setup -qcTn %{name}
-tar --strip-components 1 -zxf %{SOURCE0}
+%setup -q
 sed -e 's!share/locale!.*/locale!' /usr/lib/rpm/find-lang.sh > my-find-lang.sh
 
 %build
+cd transifex
 rm -rf .hg* build-tools
 rm -r vcs/tests
 python manage.py syncdb --noinput
+cd ..
 cd docs
 make html
 cd ..
 # Django's compilemessages command seems to walk all over the place
 #python manage.py compilemessages
-find locale -name django.po -execdir msgfmt --check-format -o django.mo {} \;
+find transifex/locale -name django.po -execdir msgfmt --check-format -o django.mo {} \;
 
 %install
 rm -rf $RPM_BUILD_ROOT
+cd transifex
 mkdir -p $RPM_BUILD_ROOT%{_datadir}/%{name}
 find -mindepth 1 -maxdepth 1 -type d \( \( -name .hg -o \
     -name build-tools -o -name docs -o -name settings \) -prune -o \
 sed -e 's!\[\[confpath\]\]!%{confdir}!' %{SOURCE1} > \
     $RPM_BUILD_ROOT%{_datadir}/%{name}/settings.py
 
+cd ..
+
 sh my-find-lang.sh $RPM_BUILD_ROOT django transifex.lst
 
 %clean

codebases/__init__.py

-class CodebaseError(StandardError):
-    pass
-
-def need_browser(fn):
-    """Decorator to initialize the unit.browser when it is needed."""
-
-    def browser_fn(self, *args, **kw):
-        if not (hasattr(self, 'browser') and self.browser):
-            self._init_browser()
-        return fn(self, *args, **kw)
-    return browser_fn

codebases/forms.py

-from django import forms
-
-from codebases.models import Unit
-
-class UnitForm(forms.ModelForm):
-    class Meta:
-        model = Unit
-        exclude = ('name',)

codebases/models.py

-"""
-This module contains a model that is expected to be used for the
-codebases used by Transifex. The following definitions are used:
-
-resource: A file within a codebase
-codebase: A collection of files (VCS repo, tarball, etc.) that contains
-  resources, some or all of which are to be translated
-"""
-import operator
-
-from django.db import models
-from django.utils.translation import ugettext_lazy as _
-
-import settings
-from codebases import need_browser
-from txcommon.log import log_model
-from txcommon.models import inclusive_fields
-
-UNIT_CHOICES = settings.CODEBASE_CHOICES.items()
-UNIT_CHOICES.sort(key=operator.itemgetter(0))
-
-class Unit(models.Model):
-    """
-    An abstract codebase; a VCS repo, tarball, or some other piece of
-    code.
-
-    The following methods should be implemented by children:
-      prepare
-      teardown
-      get_files
-      get_rev
-      submit
-    """
-    name = models.CharField(_('Name'), unique=True, max_length=100)
-    root = models.CharField(_('Root'), max_length=255,
-        help_text=_("The URL of the codebase"))
-    type = models.CharField(_('Type'), max_length=10,
-        choices=UNIT_CHOICES,
-        help_text=_('The codebase type (%s)' %
-                    ', '.join(settings.CODEBASE_CHOICES)))
-    last_checkout = models.DateTimeField(null=True, editable=False,
-        help_text=_("The last time this unit was updated"))
-
-    created = models.DateTimeField(auto_now_add=True, editable=False)
-    modified = models.DateTimeField(auto_now=True, editable=False)
-
-    def __repr__(self):
-        return '<Unit: %(name)s)>' % {'name': self.name}
-
-    class Meta:
-        verbose_name = _('unit')
-        verbose_name_plural = _('units')
-        ordering  = ('name',)
-        get_latest_by = 'created'
-
-    def prepare(self):
-        """
-        Prepares the codebase for use by Transifex by downloading,
-        extracting, etc.
-        """
-        raise NotImplementedError()
-
-    def teardown(self):
-        """
-        Cleans out any downloads used by the codebase
-        """
-        raise NotImplementedError()
-
-    def get_files(self, filter):
-        """
-        Returns one or more resources within to the codebase as given
-        by the filter
-        """
-        raise NotImplementedError()
-
-    def get_rev(self, path):
-        """
-        Returns the current revision of either the codebase or of a
-        resource within it
-        """
-        raise NotImplementedError()
-
-    def submit(self, files, message, user):
-        """
-        Replaces one or more of the resources in a codebase with
-        supplied contents
-        """
-        raise NotImplementedError()
-
-    def promote(self):
-        '''
-        Returns a descendent model that refers to this codebase
-        '''
-        for cls in Unit.__subclasses__():
-            if self.type in cls.unit_types:
-                return cls.bootstrap(self)
-        else:
-            raise ValueError('Unknown unit type %r' % self.type)
-
-    @classmethod
-    def bootstrap(cls, unit):
-        '''
-        Creates a descendent from a Unit and returns it, saving if a
-        new Unit descendant is created
-        '''
-        try:
-            newunit = cls.objects.get(pk=unit.pk)
-        except cls.DoesNotExist:
-            newunit = cls()
-            newunit.pk = unit.pk
-            cls.bootstrap_extra(newunit)
-            for field in inclusive_fields(type(unit)):
-                setattr(newunit, field.name, getattr(unit, field.name))
-            newunit.save()
-        return newunit
-
-    @classmethod
-    def bootstrap_extra(cls, unit):
-        '''
-        Extra initialization after bootstrapping
-        Descendents should override as necessary
-        '''
-        pass
-
-log_model(Unit)
 
 # You can set these variables from the command line.
 SPHINXOPTS    =
-SPHINXBUILD   = env PYTHONPATH=".." DJANGO_SETTINGS_MODULE="settings" sphinx-build
+SPHINXBUILD   = env PYTHONPATH="../transifex" DJANGO_SETTINGS_MODULE="settings" sphinx-build
 PAPER         =
 
 # Internal variables.

external/__init__.py

Empty file removed.

external/csrf/__init__.py

Empty file removed.

external/csrf/middleware.py

-"""
-Cross Site Request Forgery Middleware.
-
-This module provides a middleware that implements protection
-against request forgeries from other sites.
-
-Copyright (c) Django Software Foundation and individual contributors.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
-    1. Redistributions of source code must retain the above copyright notice, 
-       this list of conditions and the following disclaimer.
-    
-    2. Redistributions in binary form must reproduce the above copyright 
-       notice, this list of conditions and the following disclaimer in the
-       documentation and/or other materials provided with the distribution.
-
-    3. Neither the name of Django nor the names of its contributors may be used
-       to endorse or promote products derived from this software without
-       specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-
-import re
-import itertools
-try:
-    from functools import wraps
-except ImportError:
-    from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.
-
-from django.conf import settings
-from django.http import HttpResponseForbidden
-from django.utils.hashcompat import md5_constructor
-from django.utils.safestring import mark_safe
-
-_ERROR_MSG = mark_safe('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><body><h1>403 Forbidden</h1><p>Cross Site Request Forgery detected. Request aborted.</p></body></html>')
-
-_POST_FORM_RE = \
-    re.compile(r'(<form\W[^>]*\bmethod=(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
-
-_HTML_TYPES = ('text/html', 'application/xhtml+xml')
-
-def _make_token(session_id):
-    return md5_constructor(settings.SECRET_KEY + session_id).hexdigest()
-
-class CsrfViewMiddleware(object):
-    """
-    Middleware that requires a present and correct csrfmiddlewaretoken
-    for POST requests that have an active session.
-    """
-    def process_view(self, request, callback, callback_args, callback_kwargs):
-        if request.method == 'POST':
-            if getattr(callback, 'csrf_exempt', False):
-                return None
-
-            if request.is_ajax():
-                return None
-
-            try:
-                session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]
-            except KeyError:
-                # No session, no check required
-                return None
-
-            csrf_token = _make_token(session_id)
-            # check incoming token
-            try:
-                request_csrf_token = request.POST['csrfmiddlewaretoken']
-            except KeyError:
-                return HttpResponseForbidden(_ERROR_MSG)
-
-            if request_csrf_token != csrf_token:
-                return HttpResponseForbidden(_ERROR_MSG)
-
-        return None
-
-class CsrfResponseMiddleware(object):
-    """
-    Middleware that post-processes a response to add a
-    csrfmiddlewaretoken if the response/request have an active
-    session.
-    """
-    def process_response(self, request, response):
-        if getattr(response, 'csrf_exempt', False):
-            return response
-
-        csrf_token = None
-        try:
-            # This covers a corner case in which the outgoing response
-            # both contains a form and sets a session cookie.  This
-            # really should not be needed, since it is best if views
-            # that create a new session (login pages) also do a
-            # redirect, as is done by all such view functions in
-            # Django.
-            cookie = response.cookies[settings.SESSION_COOKIE_NAME]
-            csrf_token = _make_token(cookie.value)
-        except KeyError:
-            # Normal case - look for existing session cookie
-            try:
-                session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]
-                csrf_token = _make_token(session_id)
-            except KeyError:
-                # no incoming or outgoing cookie
-                pass
-
-        if csrf_token is not None and \
-                response['Content-Type'].split(';')[0] in _HTML_TYPES:
-
-            # ensure we don't add the 'id' attribute twice (HTML validity)
-            idattributes = itertools.chain(("id='csrfmiddlewaretoken'",),
-                                            itertools.repeat(''))
-            def add_csrf_field(match):
-                """Returns the matched <form> tag plus the added <input> element"""
-                return mark_safe(match.group() + "<div style='display:none;'>" + \
-                "<input type='hidden' " + idattributes.next() + \
-                " name='csrfmiddlewaretoken' value='" + csrf_token + \
-                "' /></div>")
-
-            # Modify any POST forms
-            response.content = _POST_FORM_RE.sub(add_csrf_field, response.content)
-        return response
-
-class CsrfMiddleware(CsrfViewMiddleware, CsrfResponseMiddleware):
-    """Django middleware that adds protection against Cross Site
-    Request Forgeries by adding hidden form fields to POST forms and
-    checking requests for the correct value.
-
-    In the list of middlewares, SessionMiddleware is required, and
-    must come after this middleware.  CsrfMiddleWare must come after
-    compression middleware.
-
-    If a session ID cookie is present, it is hashed with the
-    SECRET_KEY setting to create an authentication token.  This token
-    is added to all outgoing POST forms and is expected on all
-    incoming POST requests that have a session ID cookie.
-
-    If you are setting cookies directly, instead of using Django's
-    session framework, this middleware will not work.
-
-    CsrfMiddleWare is composed of two middleware, CsrfViewMiddleware
-    and CsrfResponseMiddleware which can be used independently.
-    """
-    pass
-
-def csrf_response_exempt(view_func):
-    """
-    Modifies a view function so that its response is exempt
-    from the post-processing of the CSRF middleware.
-    """
-    def wrapped_view(*args, **kwargs):
-        resp = view_func(*args, **kwargs)
-        resp.csrf_exempt = True
-        return resp
-    return wraps(view_func)(wrapped_view)
-
-def csrf_view_exempt(view_func):
-    """
-    Marks a view function as being exempt from CSRF view protection.
-    """
-    # We could just do view_func.csrf_exempt = True, but decorators
-    # are nicer if they don't have side-effects, so we return a new
-    # function.
-    def wrapped_view(*args, **kwargs):
-        return view_func(*args, **kwargs)
-    wrapped_view.csrf_exempt = True
-    return wraps(view_func)(wrapped_view)
-
-def csrf_exempt(view_func):
-    """
-    Marks a view function as being exempt from the CSRF checks
-    and post processing.
-
-    This is the same as using both the csrf_view_exempt and
-    csrf_response_exempt decorators.
-    """
-    return csrf_response_exempt(csrf_view_exempt(view_func))