<commit_before>import json

from django_hstore_mixin.serializers import serializeItem, serializeDict

class JsonDict(dict):
    """ A dict-like object where all values are serialized to and from
    JSON upon setting and getting, allowing it to be stored in and
    retrieved from Hstore field while maintaining original type. """
    def __init__(self, data, modelInstance, *args, **kwargs):
        self._modelInstance = modelInstance
        data = data or {}  # Avoid data being NoneType
        super(JsonDict, self).__init__(data, *args, **kwargs)

    def __setitem__(self, k, v):
        # Serialize value being set
        super(JsonDict, self).__setitem__(k, serializeItem(v))

        # You can't use __setitem__ on a @property (ie. "e.data['foo'] = 1"
        # will return e._data as an object which then gets updated, but those
        # updates won't make their way back to the db).  As such, we must
        # update the db field hiding behind the property manually.
        self._modelInstance._data = self.copy()

    def __getitem__(self, key):
        # Deserialize on 'get'
        return json.loads(super(JsonDict, self).__getitem__(key))

    def __getattr__(self, key):
        # Deserialize on 'get'
        return json.loads(super(JsonDict, self).__getattr__(key))

    def __repr__(self):
        # Deserialize values for reproduction
        return repr({k: v for k, v in self.items()})

    def __lt__(self, other):
        return {k: v for k, v in self.items()} < other

    def __le__(self, other):
        return {k: v for k, v in self.items()} <= other

    def __eq__(self, other):
        return {k: v for k, v in self.items()} == other

    def __ne__(self, other):
        return {k: v for k, v in self.items()} != other

    def __gt__(self, other):
        return {k: v for k, v in self.items()} > other

    def __ge__(self, other):
        return {k: v for k, v in self.items()} <= other

    def get(self, key, default=None):
        value = super(JsonDict, self).get(key, default)

        # Only deserialize if value was pulled from dict
        if value and value != default:
            value = json.loads(value)
        return value

    def items(self):
        return [(k, json.loads(v)) for k, v in super(JsonDict, self).items()]

    def update(self, other):
        # This is pretty ugly.
        dict_self = dict(self)
        dict_self.update(serializeDict(other))
        self._modelInstance._data = dict_self
<commit_msg>Handle other field names<commit_after>import json

from django_hstore_mixin.serializers import serializeItem, serializeDict

class JsonDict(dict):
    """ A dict-like object where all values are serialized to and from
    JSON upon setting and getting, allowing it to be stored in and
    retrieved from Hstore field while maintaining original type. """
    def __init__(self, data, modelInstance, datafield='_data', *args, **kwargs):
        self._modelInstance = modelInstance
        self._datafield = datafield
        data = data or {}  # Avoid data being NoneType
        super(JsonDict, self).__init__(data, *args, **kwargs)

    def __setitem__(self, k, v):
        # Serialize value being set
        super(JsonDict, self).__setitem__(k, serializeItem(v))

        # You can't use __setitem__ on a @property (ie. "e.data['foo'] = 1"
        # will return e._data as an object which then gets updated, but those
        # updates won't make their way back to the db).  As such, we must
        # update the db field hiding behind the property manually.
        setattr(self._modelInstance, self._datafield, self.copy())

    def __getitem__(self, key):
        # Deserialize on 'get'
        return json.loads(super(JsonDict, self).__getitem__(key))

    def __getattr__(self, key):
        # Deserialize on 'get'
        return json.loads(super(JsonDict, self).__getattr__(key))

    def __repr__(self):
        # Deserialize values for reproduction
        return repr({k: v for k, v in self.items()})

    def __lt__(self, other):
        return {k: v for k, v in self.items()} < other

    def __le__(self, other):
        return {k: v for k, v in self.items()} <= other

    def __eq__(self, other):
        return {k: v for k, v in self.items()} == other

    def __ne__(self, other):
        return {k: v for k, v in self.items()} != other

    def __gt__(self, other):
        return {k: v for k, v in self.items()} > other

    def __ge__(self, other):
        return {k: v for k, v in self.items()} <= other

    def get(self, key, default=None):
        value = super(JsonDict, self).get(key, default)

        # Only deserialize if value was pulled from dict
        if value and value != default:
            value = json.loads(value)
        return value

    def items(self):
        return [(k, json.loads(v)) for k, v in super(JsonDict, self).items()]

    def update(self, other):
        # This is pretty ugly.
        dict_self = dict(self)
        dict_self.update(serializeDict(other))
        setattr(self._modelInstance, self._datafield, dict_self)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import ServerInfo
from enum import Enum

class TargetTypes(Enum):
    CHANNEL = 1
    USER = 2

class IRCChannel(object):
    def __init__(self, name):
        """
        @type name: str
        """
        self.Name = name
        self.Topic = ''
        self.TopicSetBy = ''
        self.Users = {}
        self.Ranks = {}
        self.Modes = {}

    def __str__(self):
        return self.Name

    def getHighestStatusOfUser(self, nickname):
        if not self.Ranks[nickname]:
            return None

        for mode in ServerInfo.StatusOrder:
            if mode in self.Ranks[nickname]:
                return mode

        return None

class IRCUser(object):
    def __init__(self, user):
        """
        @type user: str
        """
        self.User = None
        self.Hostmask = None

        if '!' in user:
            userArray = user.split('!')
            self.Name = userArray[0]
            if len(userArray) > 1:
                userArray = userArray[1].split('@')
                self.User = userArray[0]
                self.Hostmask = userArray[1]
            self.String = "{}!{}@{}".format(self.Name, self.User, self.Hostmask)
        else:
            self.Name = user
            self.String = "{}!{}@{}".format(self.Name, None, None)

class IRCMessage(object):

    def __init__(self, msgType, user, channel, message, bot):
        """
        @type msgType: str
        @type user: str
        @type channel: IRCChannel
        @type message: unicode
        @type bot: MoronBot
        """
        try:
            unicodeMessage = message.decode('utf-8', 'ignore')
        except UnicodeEncodeError:  # Already utf-8?
            unicodeMessage = message
        self.Type = msgType
        self.MessageList = unicodeMessage.strip().split(' ')
        self.MessageString = unicodeMessage
        self.User = IRCUser(user)

        self.Channel = None
        if channel is None:
            self.ReplyTo = self.User.Name
            self.TargetType = TargetTypes.USER
        else:
            self.Channel = channel
            # I would like to set this to the channel object but I would probably break functionality if I did :I
            self.ReplyTo = channel.Name
            self.TargetType = TargetTypes.CHANNEL

        self.Command = ''
        self.Parameters = ''
        self.ParameterList = []

        if self.MessageList[0].startswith(bot.commandChar):
            self.Command = self.MessageList[0][len(bot.commandChar):]
            if self.Command == '':
                self.Command = self.MessageList[1]
                self.Parameters = u' '.join(self.MessageList[2:])
            else:
                self.Parameters = u' '.join(self.MessageList[1:])
        elif self.MessageList[0].startswith(bot.nickname) and len(self.MessageList) > 1:
            self.Command = self.MessageList[1]
            self.Parameters = u' '.join(self.MessageList[2:])

        if self.Parameters.strip():
            self.ParameterList = self.Parameters.split(' ')

            self.ParameterList = [param for param in self.ParameterList if param != '']

            if len(self.ParameterList) == 1 and not self.ParameterList[0]:
                self.ParameterList = []
<commit_msg>How about don't trigger on startswith<commit_after># -*- coding: utf-8 -*-
import ServerInfo
from enum import Enum

class TargetTypes(Enum):
    CHANNEL = 1
    USER = 2

class IRCChannel(object):
    def __init__(self, name):
        """
        @type name: str
        """
        self.Name = name
        self.Topic = ''
        self.TopicSetBy = ''
        self.Users = {}
        self.Ranks = {}
        self.Modes = {}

    def __str__(self):
        return self.Name

    def getHighestStatusOfUser(self, nickname):
        if not self.Ranks[nickname]:
            return None

        for mode in ServerInfo.StatusOrder:
            if mode in self.Ranks[nickname]:
                return mode

        return None

class IRCUser(object):
    def __init__(self, user):
        """
        @type user: str
        """
        self.User = None
        self.Hostmask = None

        if '!' in user:
            userArray = user.split('!')
            self.Name = userArray[0]
            if len(userArray) > 1:
                userArray = userArray[1].split('@')
                self.User = userArray[0]
                self.Hostmask = userArray[1]
            self.String = "{}!{}@{}".format(self.Name, self.User, self.Hostmask)
        else:
            self.Name = user
            self.String = "{}!{}@{}".format(self.Name, None, None)

class IRCMessage(object):

    def __init__(self, msgType, user, channel, message, bot):
        """
        @type msgType: str
        @type user: str
        @type channel: IRCChannel
        @type message: unicode
        @type bot: MoronBot
        """
        try:
            unicodeMessage = message.decode('utf-8', 'ignore')
        except UnicodeEncodeError:  # Already utf-8?
            unicodeMessage = message
        self.Type = msgType
        self.MessageList = unicodeMessage.strip().split(' ')
        self.MessageString = unicodeMessage
        self.User = IRCUser(user)

        self.Channel = None
        if channel is None:
            self.ReplyTo = self.User.Name
            self.TargetType = TargetTypes.USER
        else:
            self.Channel = channel
            # I would like to set this to the channel object but I would probably break functionality if I did :I
            self.ReplyTo = channel.Name
            self.TargetType = TargetTypes.CHANNEL

        self.Command = ''
        self.Parameters = ''
        self.ParameterList = []

        if self.MessageList[0].startswith(bot.commandChar):
            self.Command = self.MessageList[0][len(bot.commandChar):]
            if self.Command == '':
                self.Command = self.MessageList[1]
                self.Parameters = u' '.join(self.MessageList[2:])
            else:
                self.Parameters = u' '.join(self.MessageList[1:])
        elif self.MessageList[0] == bot.nickname and len(self.MessageList) > 1:
            self.Command = self.MessageList[1]
            self.Parameters = u' '.join(self.MessageList[2:])

        if self.Parameters.strip():
            self.ParameterList = self.Parameters.split(' ')

            self.ParameterList = [param for param in self.ParameterList if param != '']

            if len(self.ParameterList) == 1 and not self.ParameterList[0]:
                self.ParameterList = []
<|endoftext|>


<commit_before>from django_hstore_mixin.serializers import deserializeValue, serializeValue, serializeDict

class JsonDict(dict):
    """ A dict-like object where all values are serialized to and from
    JSON upon setting and getting, allowing it to be stored in and
    retrieved from Hstore field while maintaining original type. """
    def __init__(self, data, modelInstance, datafield='_data', *args, **kwargs):
        self._modelInstance = modelInstance
        self._datafield = datafield
        data = data or {}  # Avoid data being NoneType
        super(JsonDict, self).__init__(data, *args, **kwargs)

    def __setitem__(self, k, v):
        # Serialize value being set
        super(JsonDict, self).__setitem__(k, serializeValue(v))

        # You can't use __setitem__ on a @property (ie. "e.data['foo'] = 1"
        # will return e._data as an object which then gets updated, but those
        # updates won't make their way back to the db).  As such, we must
        # update the db field hiding behind the property manually.
        setattr(self._modelInstance, self._datafield, self.copy())

    def __getitem__(self, key):
        # Deserialize on 'get'
        return deserializeValue(super(JsonDict, self).__getitem__(key))

    def __getattr__(self, key):
        # Deserialize on 'get'
        return deserializeValue(super(JsonDict, self).__getattr__(key))

    def __repr__(self):
        # Deserialize values for reproduction
        return repr({k: v for k, v in self.items()})

    def __lt__(self, other):
        return {k: v for k, v in self.items()} < other

    def __le__(self, other):
        return {k: v for k, v in self.items()} <= other

    def __eq__(self, other):
        return {k: v for k, v in self.items()} == other

    def __ne__(self, other):
        return {k: v for k, v in self.items()} != other

    def __gt__(self, other):
        return {k: v for k, v in self.items()} > other

    def __ge__(self, other):
        return {k: v for k, v in self.items()} <= other

    def get(self, key, default=None):
        value = super(JsonDict, self).get(key, default)

        # Only deserialize if value was pulled from dict
        if value and value != default:
            value = deserializeValue(value)
        return value

    def items(self):
        return [(k, deserializeValue(v)) for k, v in super(JsonDict, self).items()]

    def update(self, other):
        # This is pretty ugly.
        dict_self = dict(self)
        dict_self.update(serializeDict(other))
        setattr(self._modelInstance, self._datafield, dict_self)

    @staticmethod
    def deserializeValue(value):
        """ Convenience method to provide interface to deserializeValue tooling """
        return deserializeValue(value)

    @staticmethod
    def serializeValue(value):
        """ Convenience method to provide interface to serializeValue tooling """
        return serializeValue(value)

    @staticmethod
    def serializeDict(dictionary):
        """ Convenience method to provide interface to serializeDict tooling """
        return serializeDict(dictionary)
<commit_msg>Abstract "apply_to_field" tooling. Use dict() to access deserialized data rather than self.copy()<commit_after>from django_hstore_mixin.serializers import deserializeValue, serializeValue, serializeDict

class JsonDict(dict):
    """ A dict-like object where all values are serialized to and from
    JSON upon setting and getting, allowing it to be stored in and
    retrieved from Hstore field while maintaining original type. """
    def __init__(self, data, modelInstance, datafield='_data', *args, **kwargs):
        self._modelInstance = modelInstance
        self._datafield = datafield
        data = data or {}  # Avoid data being NoneType
        super(JsonDict, self).__init__(data, *args, **kwargs)

    def __setitem__(self, k, v):
        # Serialize value being set
        super(JsonDict, self).__setitem__(k, serializeValue(v))

        # You can't use __setitem__ on a @property (ie. "e.data['foo'] = 1"
        # will return e._data as an object which then gets updated, but those
        # updates won't make their way back to the db).  As such, we must
        # update the db field hiding behind the property manually.
        self._apply_to_field(dict(self))

    def __getitem__(self, key):
        # Deserialize on 'get'
        return deserializeValue(super(JsonDict, self).__getitem__(key))

    def __getattr__(self, key):
        # Deserialize on 'get'
        return deserializeValue(super(JsonDict, self).__getattr__(key))

    def __repr__(self):
        # Deserialize values for reproduction
        return repr({k: v for k, v in self.items()})

    def __lt__(self, other):
        return {k: v for k, v in self.items()} < other

    def __le__(self, other):
        return {k: v for k, v in self.items()} <= other

    def __eq__(self, other):
        return {k: v for k, v in self.items()} == other

    def __ne__(self, other):
        return {k: v for k, v in self.items()} != other

    def __gt__(self, other):
        return {k: v for k, v in self.items()} > other

    def __ge__(self, other):
        return {k: v for k, v in self.items()} <= other

    def _apply_to_field(self, dictionary):
        """ Apply value to underlying hstore field """
        setattr(self._modelInstance, self._datafield, dictionary)

    def get(self, key, default=None):
        value = super(JsonDict, self).get(key, default)

        # Only deserialize if value was pulled from dict
        if value and value != default:
            value = deserializeValue(value)
        return value

    def items(self):
        return [(k, deserializeValue(v)) for k, v in super(JsonDict, self).items()]

    def update(self, other):
        # This is pretty ugly.
        dict_self = dict(self)
        dict_self.update(serializeDict(other))
        self._apply_to_field(dict_self)

    @staticmethod
    def deserializeValue(value):
        """ Convenience method to provide interface to deserializeValue tooling """
        return deserializeValue(value)

    @staticmethod
    def serializeValue(value):
        """ Convenience method to provide interface to serializeValue tooling """
        return serializeValue(value)

    @staticmethod
    def serializeDict(dictionary):
        """ Convenience method to provide interface to serializeDict tooling """
        return serializeDict(dictionary)
<|endoftext|>


<commit_before># Time:  O(n)
# Space: O(1)

class Solution:
    # @param {integer[]} preorder
    # @return {boolean}
    def verifyPreorder(self, preorder):
        low, i = float("-inf"), -1
        for p in preorder:
            if p < low:
                return False
            while i >= 0 and p > preorder[i]:
                low = preorder[i]
                i -= 1
            i += 1
            preorder[i] = p
        return True

# Time:  O(n)
# Space: O(n)
class Solution2:
    # @param {integer[]} preorder
    # @return {boolean}
    def verifyPreorder(self, preorder):
        low = float("-inf")
        path = []
        for p in preorder:
            if p < low:
                return False
            while path and p > path[-1]:
                low = path[-1]
                path.pop()
            path.append(p)
        return True
<commit_msg>Update verify-preorder-sequence-in-binary-search-tree.py<commit_after># Time:  O(n)
# Space: O(1)

class Solution:
    # @param {integer[]} preorder
    # @return {boolean}
    def verifyPreorder(self, preorder):
        low, i = float("-inf"), -1
        for p in preorder:
            if p < low:
                return False
            while i >= 0 and p > preorder[i]:
                low = preorder[i]
                i -= 1
            i += 1
            preorder[i] = p
        return True

# Time:  O(n)
# Space: O(h)
class Solution2:
    # @param {integer[]} preorder
    # @return {boolean}
    def verifyPreorder(self, preorder):
        low = float("-inf")
        path = []
        for p in preorder:
            if p < low:
                return False
            while path and p > path[-1]:
                low = path[-1]
                path.pop()
            path.append(p)
        return True
<|endoftext|>


<commit_before>__version__ = '0.0.7'<commit_msg>version bump<commit_after>__version__ = '0.0.8'<|endoftext|>


<commit_before># Copyright 2013 Globo.com. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

import wtforms
from flask.ext import wtf
from wtforms import validators
from countries import country_choices
from flaskext.babel import gettext

class SignupForm(wtf.Form):
    first_name = wtforms.TextField(gettext(u"First name"),
                                   validators=[validators.DataRequired()])
    last_name = wtforms.TextField(gettext(u"Last name"),
                                  validators=[validators.DataRequired()])
    email = wtforms.TextField(
        gettext(u"Email"),
        validators=[validators.DataRequired(), validators.Email()]
    )

class SurveyForm(wtf.Form):
    email = wtforms.HiddenField(u"email",
                                validators=[validators.DataRequired(),
                                            validators.Email()])
    signature = wtforms.HiddenField(u"signature",
                                    validators=[validators.DataRequired()])
    choices = [
        ("cio", "CIO"),
        ("cto", "CTO"),
        ("dba", "DBA"),
        ("developer", gettext("Developer")),
        ("manager", gettext("Project Manager")),
        ("researcher", gettext("Researcher")),
        ("student", gettext("Student")),
        ("teacher", gettext("Teacher")),
        ("ops", gettext("Ops")),
        ("", gettext("Other"))
    ]
    work = wtforms.SelectField(gettext(u"What do you do for a living?"),
                               choices=choices,
                               validators=[validators.DataRequired()])
    country = wtforms.SelectField(gettext(u"Where do you live?"),
                                  choices=country_choices,
                                  validators=[validators.DataRequired()])
    organization = wtforms.TextField(gettext(u"What is your company name?"),
                                     validators=[validators.DataRequired()])
    choices = [("build", gettext("Build my own PaaS")),
               ("compare", gettext("Compare to other PaaS")),
               ("deploy", gettext("Deploy my apps")),
               ("curious", gettext("I'm just curious")),
               ("", gettext("Other"))]
    why = wtforms.SelectField(gettext(u"Why do you want to try tsuru?"),
                              choices=choices,
                              validators=[validators.DataRequired()])
<commit_msg>forms: removing validation from survey fields.<commit_after># Copyright 2013 Globo.com. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

import wtforms
from flask.ext import wtf
from wtforms import validators
from countries import country_choices
from flaskext.babel import gettext

class SignupForm(wtf.Form):
    first_name = wtforms.TextField(gettext(u"First name"),
                                   validators=[validators.DataRequired()])
    last_name = wtforms.TextField(gettext(u"Last name"),
                                  validators=[validators.DataRequired()])
    email = wtforms.TextField(
        gettext(u"Email"),
        validators=[validators.DataRequired(), validators.Email()]
    )

class SurveyForm(wtf.Form):
    email = wtforms.HiddenField(u"email",
                                validators=[validators.DataRequired(),
                                            validators.Email()])
    signature = wtforms.HiddenField(u"signature",
                                    validators=[validators.DataRequired()])
    choices = [
        ("cio", "CIO"),
        ("cto", "CTO"),
        ("dba", "DBA"),
        ("developer", gettext("Developer")),
        ("manager", gettext("Project Manager")),
        ("researcher", gettext("Researcher")),
        ("student", gettext("Student")),
        ("teacher", gettext("Teacher")),
        ("ops", gettext("Ops")),
        ("", gettext("Other"))
    ]
    work = wtforms.SelectField(gettext(u"What do you do for a living?"),
                               choices=choices)
    country = wtforms.SelectField(gettext(u"Where do you live?"),
                                  choices=country_choices)
    organization = wtforms.TextField(gettext(u"What is your company name?"))
    choices = [("build", gettext("Build my own PaaS")),
               ("compare", gettext("Compare to other PaaS")),
               ("deploy", gettext("Deploy my apps")),
               ("curious", gettext("I'm just curious")),
               ("", gettext("Other"))]
    why = wtforms.SelectField(gettext(u"Why do you want to try tsuru?"),
                              choices=choices)
<|endoftext|>


<commit_before>import ast

from .base import BaseAnalyzer, Result, DeprecatedCodeVisitor

class GenericViewsVisitor(DeprecatedCodeVisitor):

    interesting = {
        'django.views.generic.simple': ['direct_to_template', 'redirect_to'],
        'django.views.generic.simple.direct_to_template': None,
        'django.views.generic.simple.redirect_to': None,

        'django.views.generic.date_based': [
            'archive_index', 'archive_year', 'archive_month', 'archive_week',
            'archive_day', 'archive_today', 'archive_detail'],
        'django.views.generic.date_based.archive_index': None,
        'django.views.generic.date_based.archive_year': None,
        'django.views.generic.date_based.archive_month': None,
        'django.views.generic.date_based.archive_week': None,
        'django.views.generic.date_based.archive_day': None,
        'django.views.generic.date_based.archive_today': None,
        'django.views.generic.date_based.archive_detail': None,

        'django.views.generic.list_detail': ['object_list', 'object_detail'],
        'django.views.generic.list_detail.object_list': None,
        'django.views.generic.list_detail.object_detail': None,

        'django.views.generic.create_update': [
            'create_object', 'update_object', 'delete_object'],
        'django.views.generic.create_update.create_object': None,
        'django.views.generic.create_update.update_object': None,
        'django.views.generic.create_update.delete_object': None,
    }

class GenericViewsAnalyzer(BaseAnalyzer):

    def analyze_file(self, filepath, code):
        if not isinstance(code, ast.AST):
            return
        visitor = GenericViewsVisitor()
        visitor.visit(code)
        for name, node, start, stop in visitor.get_found():
            result = Result(
                description = '%r function is deprecated' % name,
                path = filepath,
                line = start)
            lines = self.get_file_lines(filepath, start, stop)
            for lineno, important, text in lines:
                result.source.add_line(lineno, text, important)
            yield result
<commit_msg>Update generic views analyzer to target Django 1.5<commit_after>import ast

from .base import BaseAnalyzer, Result, DeprecatedCodeVisitor

class GenericViewsVisitor(DeprecatedCodeVisitor):

    interesting = {
        'django.views.generic.simple': ['direct_to_template', 'redirect_to'],
        'django.views.generic.simple.direct_to_template': None,
        'django.views.generic.simple.redirect_to': None,

        'django.views.generic.date_based': [
            'archive_index', 'archive_year', 'archive_month', 'archive_week',
            'archive_day', 'archive_today', 'archive_detail'],
        'django.views.generic.date_based.archive_index': None,
        'django.views.generic.date_based.archive_year': None,
        'django.views.generic.date_based.archive_month': None,
        'django.views.generic.date_based.archive_week': None,
        'django.views.generic.date_based.archive_day': None,
        'django.views.generic.date_based.archive_today': None,
        'django.views.generic.date_based.archive_detail': None,

        'django.views.generic.list_detail': ['object_list', 'object_detail'],
        'django.views.generic.list_detail.object_list': None,
        'django.views.generic.list_detail.object_detail': None,

        'django.views.generic.create_update': [
            'create_object', 'update_object', 'delete_object'],
        'django.views.generic.create_update.create_object': None,
        'django.views.generic.create_update.update_object': None,
        'django.views.generic.create_update.delete_object': None,
    }

class GenericViewsAnalyzer(BaseAnalyzer):

    def analyze_file(self, filepath, code):
        if not isinstance(code, ast.AST):
            return
        visitor = GenericViewsVisitor()
        visitor.visit(code)
        for name, node, start, stop in visitor.get_found():
            result = Result(
                description = (
                    '%r function has been deprecated in Django 1.3 and will '
                    'be removed in 1.5.' % name
                ),
                path = filepath,
                line = start)
            lines = self.get_file_lines(filepath, start, stop)
            for lineno, important, text in lines:
                result.source.add_line(lineno, text, important)
            yield result
<|endoftext|>


<commit_before>"""
Form and validation code for user registration.

"""

from django import newforms as forms
from django.contrib.auth.models import User

# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "required"
# in the HTML. Your mileage may vary.
attrs_dict = { 'class': 'required' }

class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.

    Validates that the password is entered twice and matches,
    and that the username is not already taken.

    """
    username = forms.CharField(max_length=30,
                               widget=forms.TextInput(attrs=attrs_dict),
                               label=u'Username')
    email = forms.EmailField(max_length=200,
                             widget=forms.TextInput(attrs=dict(attrs_dict,
                                                               maxlength=200)),
                             label=u'Email address')
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
                                label=u'Password')
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
                                label=u'Password (again, to catch typos)')
    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
                             label=u'I have read and agree to the Terms of Service')

    def clean_username(self):
        """
        Validates that the username is not already in use.

        """
        if self.clean_data.get('username', None):
            try:
                user = User.objects.get(username__exact=self.clean_data['username'])
            except User.DoesNotExist:
                return self.clean_data['username']
            raise forms.ValidationError(u'The username "%s" is already taken. Please choose another.' % self.clean_data['username'])

    def clean_password2(self):
        """
        Validates that the two password inputs match.

        """
        if self.clean_data.get('password1', None) and self.clean_data.get('password2', None) and \
           self.clean_data['password1'] == self.clean_data['password2']:
            return self.clean_data['password2']
        raise forms.ValidationError(u'You must type the same password each time')

    def clean_tos(self):
        """
        Validates that the user accepted the Terms of Service.

        """
        if self.clean_data.get('tos', False):
            return self.clean_data['tos']
        raise forms.ValidationError(u'You must agree to the terms to register')
<commit_msg>One more tweak<commit_after>"""
Form and validation code for user registration.

"""

from django import newforms as forms
from django.contrib.auth.models import User

# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "required"
# in the HTML. Your mileage may vary.
attrs_dict = { 'class': 'required' }

class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.

    Validates that the password is entered twice and matches,
    and that the username is not already taken.

    """
    username = forms.CharField(max_length=30,
                               widget=forms.TextInput(attrs=attrs_dict),
                               label=u'Username')
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
                                                               maxlength=200)),
                             label=u'Email address')
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
                                label=u'Password')
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
                                label=u'Password (again, to catch typos)')
    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
                             label=u'I have read and agree to the Terms of Service')

    def clean_username(self):
        """
        Validates that the username is not already in use.

        """
        if self.clean_data.get('username', None):
            try:
                user = User.objects.get(username__exact=self.clean_data['username'])
            except User.DoesNotExist:
                return self.clean_data['username']
            raise forms.ValidationError(u'The username "%s" is already taken. Please choose another.' % self.clean_data['username'])

    def clean_password2(self):
        """
        Validates that the two password inputs match.

        """
        if self.clean_data.get('password1', None) and self.clean_data.get('password2', None) and \
           self.clean_data['password1'] == self.clean_data['password2']:
            return self.clean_data['password2']
        raise forms.ValidationError(u'You must type the same password each time')

    def clean_tos(self):
        """
        Validates that the user accepted the Terms of Service.

        """
        if self.clean_data.get('tos', False):
            return self.clean_data['tos']
        raise forms.ValidationError(u'You must agree to the terms to register')
<|endoftext|>


<commit_before>"""
cmd is a framework to manage command lines.

cmd.py some-command --long-arg=value1 -s <othervalue> <nooptvalue1> <nooptvalue2>

to a call to :
some_command('nooptvalue1','nooptvalue2',long_arg='value1',s='othervalue')

to do this this function should be registerd :

@cmd.reg
some_command(_arg1,_arg2,long_arg,s='defaultvalue', *args):
 "Command docuemntation"

"""
import argparse
import sys

parser=argparse.ArgumentParser(prog='jcd')
subparsers = parser.add_subparsers()

class Command:
    def __init__(self, name, callable, args=[], opts=[], whatis="", doc="", argparser=None):
        """
        name the name of comamnd
        callabel the method to execute
        args : the list of names of argumetns to pass in
        opts : the list of names of available options
        whatis: one line summary of the command
        doc : a full  documentation of the command
        argparser : the argument parser : if set args/opts are ignored
        """
        self.name = name
        self.callable = callable
        if argparser != None:
            self.parser = argparser
            return

        self.parser=subparsers.add_parser(name,help=whatis)
        for opt in opts:
            if len(opt) == 1: self.parser.add_argument('-'+opt)
            else: self.parser.add_argument('--'+opt.replace('_','-'))
        for arg in args:
            self.parser.add_argument(arg.replace('_','-'),type=str)
        self.parser.set_defaults(cmd=self)

        self.args=args
        self.opts = opts
        self.doc = doc
        self.whatis = whatis

    def invoke(self,args):
        self.callable(**args)

cmdindex={}

def usage(name):
    print "Usage: %s <command> [command arguments...]" % name
    print "Available commands:"
    for cmd in cmdindex.values():
        print " %s\t%s" % (cmd.name,cmd.whatis)

def printall(**kwargs):
    print kwargs

def registercommand(cmd):
    cmdindex[cmd.name]=cmd

if __name__ == '__main__':
    registercommand(Command('hello',printall,whatis='Say hallow',args=['message']))
    args = parser.parse_args()
    par=dict(vars(args))
    del par['cmd']
    args.cmd.invoke(par)

    <commit_msg>Working commands with extra metadata<commit_after>"""
cmd is a framework to manage command lines.

cmd.py some-command --long-arg=value1 -s <othervalue> <nooptvalue1> <nooptvalue2>

to a call to :
some_command('nooptvalue1','nooptvalue2',long_arg='value1',s='othervalue')

to do this this function should be registerd :

@cmd.reg
some_command(_arg1,_arg2,long_arg,s='defaultvalue', *args):
 "Command docuemntation"

"""
import argparse
import sys
import inspect

parser=argparse.ArgumentParser(prog='jcd')
subparsers = parser.add_subparsers()

def _name2opt(name):
    if name.startswith('-'): return name
    if len(name) == 1: return '-%s'% name
    return '--%s' % name

class Command:
    def __init__(self, name, callable, args=[], opts=[], help="", argparser=None):
        """
        name the name of comamnd
        callabel the method to execute
        args : the list of arguments to pass in. Each item is either :
            - A simple string
            - A dictionnary with ArgumentParser.add_argument() kw params. A special entry "name" contains the name of the argument
        opts : the list of names of available options. Each item is either :
            - A simple string
            - A dictionnary with ArgumentParser.add_argument() kw params. A special entry "name" contains the name of the option (with or without -)
        help: Quick help of the command
        argparser : the argument parser : if set args/opts are ignored
        """
        self.name = name
        self.callable = callable

        self.parser=subparsers.add_parser(name,help=help)
        for opt in opts:
            if not isinstance(opt,str): #not a string : expecting kv
                nopt = dict(opt)
                del nopt['name']
                self.parser.add_argument(_name2opt(opt['name']), **nopt)
            else:
                self.parser.add_argument(_name2opt(opt))
        for arg in args:
            if not isinstance(arg,str): #not a string : expecting kv
                nopt = dict(arg)
                del nopt['name']
                self.parser.add_argument(arg['name'], **nopt)
            else:
                self.parser.add_argument(arg,type=str)
        self.parser.set_defaults(cmd=self)

    def invoke(self,args):
        self.callable(**args)

def printall(**kwargs):
    print kwargs

def reg(f):
    Command(f.__name__,f,help=f.__doc__,
        args=list(arg.lstrip('_') for arg in inspect.getargspec(f).args if arg.startswith('_')),
        opts=list(arg.lstrip('_') for arg in inspect.getargspec(f).args if not arg.startswith('_')) )
    return f

@reg
def setup(_p1,_p2,truc,truac):
    pass
if __name__ == '__main__':
    Command('hello',printall,help='Say hallow',args=['message',{'name':'label','help':'The display label of my stuff'}])
    Command('bye',printall,help='Say bye',args=['message'], opts=['s','--k',{'name':'smook','help':'do some spoopic stuff'}])
    args = parser.parse_args()
    par=dict(vars(args))
    del par['cmd']
    args.cmd.invoke(par)

    <|endoftext|>


<commit_before>from urlparse import urlparse
import cStringIO
import mimetypes
import os
import datetime

__version__ = '1.0'

def s3open(*args, **kwargs):
    """ Convenience method for creating S3File object.
    """
    return S3File(*args, **kwargs)

class S3File(object):

    def __init__(self, url, key=None, secret=None, expiration_days=0, private=False, content_type=None, create=True):
        from boto.s3.connection import S3Connection
        from boto.s3.key import Key

        self.url = urlparse(url)
        self.expiration_days = expiration_days
        self.buffer = cStringIO.StringIO()
        self.private = private
        self.content_type = content_type or mimetypes.guess_type(self.url.path)[0]

        bucket = self.url.netloc
        if bucket.endswith('.s3.amazonaws.com'):
            bucket = bucket[:-17]

        self.client = S3Connection(key, secret)

        if create:
            self.bucket = self.client.create_bucket(bucket)
        else:
            self.bucket = self.client.get_bucket(bucket, validate=False)

        self.key = Key(self.bucket)
        self.key.key = self.url.path.lstrip("/")

        self._remote_read()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def _remote_read(self):
        """ Read S3 contents into internal file buffer.
        """
        self.buffer.truncate(0)
        if self.key.exists():
            self.key.get_contents_to_file(self.buffer)
        self.buffer.seek(0)

    def _remote_write(self):
        """ Write file contents to S3 from internal buffer.
        """
        self.truncate(self.tell())

        headers = {
            "x-amz-acl":  "private" if self.private else "public-read"
        }

        if self.content_type:
            headers["Content-Type"] = self.content_type

        if self.expiration_days:
            now = datetime.datetime.utcnow()
            then = now + datetime.timedelta(self.expiration_days)
            headers["Expires"] = then.strftime("%a, %d %b %Y %H:%M:%S GMT")
            headers["Cache-Control"] = 'max-age=%d' % (self.expiration_days * 24 * 3600),

        self.key.set_contents_from_file(self.buffer, headers=headers, rewind=True)

    def close(self):
        """ Close the file and write contents to S3.
        """
        value = self.buffer.getvalue()
        self._remote_write()
        self.buffer.close()

    # pass-through methods

    def flush(self):
        self._remote_write()

    def next(self):
        return self.buffer.next()

    def read(self, size=-1):
        return self.buffer.read(size)

    def readline(self, size=-1):
        return self.buffer.readline(size)

    def readlines(self, sizehint=-1):
        return self.buffer.readlines(sizehint)

    def xreadlines(self):
        return self.buffer.xreadlines()

    def seek(self, offset, whence=os.SEEK_SET):
        self.buffer.seek(offset, whence)

    def tell(self):
        return self.buffer.tell()

    def truncate(self, size=None):
        self.buffer.truncate(size or self.tell())

    def write(self, s):
        self.buffer.write(s)

    def writelines(self, sequence):
        self.buffer.writelines(sequence)
<commit_msg>Fix a misplaced comma causing Cache-Control to be a tuple<commit_after>from urlparse import urlparse
import cStringIO
import mimetypes
import os
import datetime

__version__ = '1.0'

def s3open(*args, **kwargs):
    """ Convenience method for creating S3File object.
    """
    return S3File(*args, **kwargs)

class S3File(object):

    def __init__(self, url, key=None, secret=None, expiration_days=0, private=False, content_type=None, create=True):
        from boto.s3.connection import S3Connection
        from boto.s3.key import Key

        self.url = urlparse(url)
        self.expiration_days = expiration_days
        self.buffer = cStringIO.StringIO()
        self.private = private
        self.content_type = content_type or mimetypes.guess_type(self.url.path)[0]

        bucket = self.url.netloc
        if bucket.endswith('.s3.amazonaws.com'):
            bucket = bucket[:-17]

        self.client = S3Connection(key, secret)

        if create:
            self.bucket = self.client.create_bucket(bucket)
        else:
            self.bucket = self.client.get_bucket(bucket, validate=False)

        self.key = Key(self.bucket)
        self.key.key = self.url.path.lstrip("/")

        self._remote_read()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def _remote_read(self):
        """ Read S3 contents into internal file buffer.
        """
        self.buffer.truncate(0)
        if self.key.exists():
            self.key.get_contents_to_file(self.buffer)
        self.buffer.seek(0)

    def _remote_write(self):
        """ Write file contents to S3 from internal buffer.
        """
        self.truncate(self.tell())

        headers = {
            "x-amz-acl":  "private" if self.private else "public-read"
        }

        if self.content_type:
            headers["Content-Type"] = self.content_type

        if self.expiration_days:
            now = datetime.datetime.utcnow()
            then = now + datetime.timedelta(self.expiration_days)
            headers["Expires"] = then.strftime("%a, %d %b %Y %H:%M:%S GMT")
            headers["Cache-Control"] = 'max-age=%d' % (self.expiration_days * 24 * 3600,)

        self.key.set_contents_from_file(self.buffer, headers=headers, rewind=True)

    def close(self):
        """ Close the file and write contents to S3.
        """
        value = self.buffer.getvalue()
        self._remote_write()
        self.buffer.close()

    # pass-through methods

    def flush(self):
        self._remote_write()

    def next(self):
        return self.buffer.next()

    def read(self, size=-1):
        return self.buffer.read(size)

    def readline(self, size=-1):
        return self.buffer.readline(size)

    def readlines(self, sizehint=-1):
        return self.buffer.readlines(sizehint)

    def xreadlines(self):
        return self.buffer.xreadlines()

    def seek(self, offset, whence=os.SEEK_SET):
        self.buffer.seek(offset, whence)

    def tell(self):
        return self.buffer.tell()

    def truncate(self, size=None):
        self.buffer.truncate(size or self.tell())

    def write(self, s):
        self.buffer.write(s)

    def writelines(self, sequence):
        self.buffer.writelines(sequence)
<|endoftext|>


<commit_before># Copyright (C) 2006-2008 Jelmer Vernooij <jelmer@samba.org>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Tests for subvertpy."""

__author__ = 'Jelmer Vernooij <jelmer@samba.org>'
__docformat__ = 'restructuredText'

from cStringIO import StringIO
import os
import shutil
import sys
import tempfile
import unittest
try:
    from unittest import SkipTest
except ImportError:
    try:
        from unittest2 import SkipTest
    except ImportError:
        from testtools.testcase import TestSkipped as SkipTest
import urllib2
import urlparse

from subvertpy import (
    client,
    delta,
    properties,
    ra,
    repos,
    )
from subvertpy.ra import (
    Auth,
    RemoteAccess,
    )

class TestCase(unittest.TestCase):
    """Base test case.

    :note: Adds assertIsInstance and assertIs.
    """

    def assertIsInstance(self, obj, kls, msg=None):
        """Fail if obj is not an instance of kls"""
        if not isinstance(obj, kls):
            if msg is None: msg = "%r is an instance of %s rather than %s" % (
                obj, obj.__class__, kls)
            self.fail(msg)

    def assertIs(self, left, right, message=None):
        if not (left is right):
            if message is not None:
                raise AssertionError(message)
            else:
                raise AssertionError("%r is not %r." % (left, right))

class TestCaseInTempDir(TestCase):
    """Test case that runs in a temporary directory."""

    def setUp(self):
        TestCase.setUp(self)
        self._oldcwd = os.getcwd()
        self.test_dir = tempfile.mkdtemp()
        os.chdir(self.test_dir)

    def tearDown(self):
        TestCase.tearDown(self)
        os.chdir(self._oldcwd)
        shutil.rmtree(self.test_dir)

class TestFileEditor(object):
    """Simple file editor wrapper that doesn't require closing."""

    def __init__(self, file):
        self.file = file
        self.is_closed = False

    def change_prop(self, name, value):
        self.file.change_prop(name, value)

    def modify(self, contents=None):
        if contents is None:
            contents = urllib2.randombytes(100)
        txdelta = self.file.apply_textdelta()
        delta.send_stream(StringIO(contents), txdelta)

    def close(self):
        assert not self.is_closed
        self.is_closed = True
        self.file.close()

class TestDirEditor(object):
    """Simple dir editor wrapper that doesn't require closing."""

    def __init__(self, dir, baseurl, revnum):
        self.dir = dir
        self.baseurl = baseurl
        self.revnum = revnum
        self.is_closed = False
        self.children = []

    def close_children(self):
        for c in reversed(self.children):
            if not c.is_closed:
                c.close()

    def close(self):
        assert not self.is_closed
        self.is_closed = True
        self.close_children()
        self.dir.close()

    def change_prop(self, name, value):
        self.close_children()
        self.dir.change_prop(name, value)

    def open_dir(self, path):
        self.close_children()
        child = TestDirEditor(self.dir.open_directory(path, -1), self.baseurl, self.revnum)
        self.children.append(child)
        return child

    def open_file(self, path):
        self.close_children()
        child = TestFileEditor(self.dir.open_file(path, -1))
        self.children.append(child)
        return child

    def add_dir(self, path, copyfrom_path=None, copyfrom_rev=-1):
        self.close_children()
        if copyfrom_path is not None:
            copyfrom_path = urlparse.urljoin(self.baseurl+"/", copyfrom_path)
        if copyfrom_path is not None and copyfrom_rev == -1:
            copyfrom_rev = self.revnum
        assert (copyfrom_path is None and copyfrom_rev == -1) or \
               (copyfrom_path is not None and copyfrom_rev > -1)
        child = TestDirEditor(self.dir.add_directory(path, copyfrom_path,
            copyfrom_rev), self.baseurl, self.revnum)
        self.children.append(child)
        return child

    def add_file(self, path, copyfrom_path=None, copyfrom_rev=-1):
        self.close_children()
        if copyfrom_path is not None:
            copyfrom_path = urlparse.urljoin(self.baseurl+"/", copyfrom_path)
        if copyfrom_path is not None and copyfrom_rev == -1:
            copyfrom_rev = self.revnum
        child = TestFileEditor(self.dir.add_file(path, copyfrom_path,
            copyfrom_rev))
        self.children.append(child)
        return child

    def delete(self, path):
        self.close_children()
        self.dir.delete_entry(path)

class TestCommitEditor(TestDirEditor):
    """Simple commit editor wrapper."""

    def __init__(self, editor, baseurl, revnum):
        self.editor = editor
        TestDirEditor.__init__(self, self.editor.open_root(), baseurl, revnum)

    def close(self):
        TestDirEditor.close(self)
        self.editor.close()

class SubversionTestCase(TestCaseInTempDir):
    """A test case that provides the ability to build Subversion
    repositories."""

    def _init_client(self):
        self.client_ctx = client.Client()
        self.client_ctx.auth = Auth([ra.get_simple_provider(),
                                     ra.get_username_provider(),
                                     ra.get_ssl_client_cert_file_provider(),
                                     ra.get_ssl_client_cert_pw_file_provider(),
                                     ra.get_ssl_server_trust_file_provider()])
        self.client_ctx.log_msg_func = self.log_message_func
        #self.client_ctx.notify_func = lambda err: mutter("Error: %s" % err)

    def setUp(self):
        super(SubversionTestCase, self).setUp()
        self._init_client()

    def tearDown(self):
        del self.client_ctx
        super(SubversionTestCase, self).tearDown()

    def log_message_func(self, items):
        return self.next_message

    def make_repository(self, relpath, allow_revprop_changes=True):
        """Create a repository.

        :return: Handle to the repository.
        """
        abspath = os.path.join(self.test_dir, relpath)

        repos.create(abspath)

        if allow_revprop_changes:
            if sys.platform == 'win32':
                revprop_hook = os.path.join(abspath, "hooks",
                        "pre-revprop-change.bat")
                open(revprop_hook, 'w').write("exit 0\n")
            else:
                revprop_hook = os.path.join(abspath, "hooks",
                        "pre-revprop-change")
                open(revprop_hook, 'w').write("#!/bin/sh\n")
                os.chmod(revprop_hook, os.stat(revprop_hook).st_mode | 0111)

        if sys.platform == 'win32':
            return "file://%s" % abspath.replace("\\", "/")
        else:
            return "file://%s" % abspath

    def make_checkout(self, repos_url, relpath):
        """Create a new checkout."""
        self.client_ctx.checkout(repos_url, relpath, "HEAD")

    def client_set_prop(self, path, name, value):
        """Set a property on a local file or directory."""
        if value is None:
            value = ""
        self.client_ctx.propset(name, value, path, False, True)

    def client_get_prop(self, path, name, revnum=None, recursive=False):
        """Retrieve a property from a local or remote file or directory."""
        if revnum is None:
            rev = "WORKING"
        else:
            rev = revnum
        ret = self.client_ctx.propget(name, path, rev, rev, recursive)
        if recursive:
            return ret
        else:
            return ret.values()[0]

    def client_get_revprop(self, url, revnum, name):
        """Get the revision property.

        :param url: URL of the repository
        :param revnum: Revision number
        :param name: Property name
        :return: Revision property value
        """
        r = ra.RemoteAccess(url)
        return r.rev_proplist(revnum)[name]

    def client_set_revprop(self, url, revnum, name, value):
        """Set a revision property on a repository.

        :param url: URL of the repository
        :param revnum: Revision number of the revision
        :param name: Name of the property
        :param value: Value of the property, None to remove
        """
        r = ra.RemoteAccess(url, auth=Auth([ra.get_username_provider()]))
        r.change_rev_prop(revnum, name, value)

    def client_resolve(self, path, choice, depth=0):
        """Resolve a conflict set on a local path."""
        self.client_ctx.resolve(path, depth, choice)

    def client_commit(self, dir, message=None, recursive=True):
        """Commit current changes in specified working copy.

        :param dir: List of paths to commit.
        """
        olddir = os.path.abspath('.')
        self.next_message = message
        os.chdir(dir)
        info = self.client_ctx.commit(["."], recursive, False)
        os.chdir(olddir)
        assert info is not None
        return info

    def client_add(self, relpath, recursive=True):
        """Add specified files to working copy.

        :param relpath: Path to the files to add.
        """
        self.client_ctx.add(relpath, recursive, False, False)

    def client_log(self, url, start_revnum, stop_revnum):
        """Fetch the log

        :param url: URL to log
        :param start_revnum: Start revision of the range to log over
        :param start_revnum: Stop revision of the range to log over
        :return: Dictionary
        """
        r = ra.RemoteAccess(url)
        assert isinstance(url, str)
        ret = {}
        def rcvr(orig_paths, rev, revprops, has_children=None):
            ret[rev] = (orig_paths,
                    revprops.get(properties.PROP_REVISION_AUTHOR),
                    revprops.get(properties.PROP_REVISION_DATE),
                    revprops.get(properties.PROP_REVISION_LOG))
        r.get_log(rcvr, [""], start_revnum, stop_revnum, 0, True, True,
                  revprops=[properties.PROP_REVISION_AUTHOR,
                      properties.PROP_REVISION_DATE,
                      properties.PROP_REVISION_LOG])
        return ret

    def client_delete(self, relpath):
        """Remove specified files from working copy.

        :param relpath: Path to the files to remove.
        """
        self.client_ctx.delete([relpath], True)

    def client_copy(self, oldpath, newpath, revnum=None):
        """Copy file in working copy.

        :param oldpath: Relative path to original file.
        :param newpath: Relative path to new file.
        """
        if revnum is None:
            rev = "HEAD"
        else:
            rev = revnum
        self.client_ctx.copy(oldpath, newpath, rev)

    def client_update(self, path):
        """Update path.

        :param path: Path
        """
        self.client_ctx.update([path], "HEAD", True)

    def build_tree(self, files):
        """Create a directory tree.

        :param files: Dictionary with filenames as keys, contents as
            values. None as value indicates a directory.
        """
        for f in files:
            if files[f] is None:
                try:
                    os.makedirs(f)
                except OSError:
                    pass
            else:
                try:
                    os.makedirs(os.path.dirname(f))
                except OSError:
                    pass
                open(f, 'w').write(files[f])

    def make_client(self, repospath, clientpath, allow_revprop_changes=True):
        """Create a repository and a checkout. Return the checkout.

        :param repospath: Optional relpath to check out if not the full
            repository.
        :param clientpath: Path to checkout
        :return: Repository URL.
        """
        repos_url = self.make_repository(repospath,
            allow_revprop_changes=allow_revprop_changes)
        self.make_checkout(repos_url, clientpath)
        return repos_url

    def open_fs(self, relpath):
        """Open a fs.

        :return: FS.
        """
        return repos.Repository(relpath).fs()

    def get_commit_editor(self, url, message="Test commit"):
        """Obtain a commit editor.

        :param url: URL to connect to
        :param message: Commit message
        :return: Commit editor object
        """
        ra_ctx = RemoteAccess(url.encode("utf-8"),
            auth=Auth([ra.get_username_provider()]))
        revnum = ra_ctx.get_latest_revnum()
        return TestCommitEditor(ra_ctx.get_commit_editor({"svn:log": message}),
            ra_ctx.url, revnum)

def test_suite():
    names = [
        'client',
        'core',
        'delta',
        'marshall',
        'properties',
        'ra',
        'repos',
        'server',
        'wc',
        ]
    module_names = ['subvertpy.tests.test_' + name for name in names]
    result = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite = loader.loadTestsFromNames(module_names)
    result.addTests(suite)
    return result
<commit_msg>Under windows, local file system url should be file:///<commit_after># Copyright (C) 2006-2008 Jelmer Vernooij <jelmer@samba.org>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Tests for subvertpy."""

__author__ = 'Jelmer Vernooij <jelmer@samba.org>'
__docformat__ = 'restructuredText'

from cStringIO import StringIO
import os
import shutil
import sys
import tempfile
import unittest
try:
    from unittest import SkipTest
except ImportError:
    try:
        from unittest2 import SkipTest
    except ImportError:
        from testtools.testcase import TestSkipped as SkipTest
import urllib2
import urlparse

from subvertpy import (
    client,
    delta,
    properties,
    ra,
    repos,
    )
from subvertpy.ra import (
    Auth,
    RemoteAccess,
    )

class TestCase(unittest.TestCase):
    """Base test case.

    :note: Adds assertIsInstance and assertIs.
    """

    def assertIsInstance(self, obj, kls, msg=None):
        """Fail if obj is not an instance of kls"""
        if not isinstance(obj, kls):
            if msg is None: msg = "%r is an instance of %s rather than %s" % (
                obj, obj.__class__, kls)
            self.fail(msg)

    def assertIs(self, left, right, message=None):
        if not (left is right):
            if message is not None:
                raise AssertionError(message)
            else:
                raise AssertionError("%r is not %r." % (left, right))

class TestCaseInTempDir(TestCase):
    """Test case that runs in a temporary directory."""

    def setUp(self):
        TestCase.setUp(self)
        self._oldcwd = os.getcwd()
        self.test_dir = tempfile.mkdtemp()
        os.chdir(self.test_dir)

    def tearDown(self):
        TestCase.tearDown(self)
        os.chdir(self._oldcwd)
        shutil.rmtree(self.test_dir)

class TestFileEditor(object):
    """Simple file editor wrapper that doesn't require closing."""

    def __init__(self, file):
        self.file = file
        self.is_closed = False

    def change_prop(self, name, value):
        self.file.change_prop(name, value)

    def modify(self, contents=None):
        if contents is None:
            contents = urllib2.randombytes(100)
        txdelta = self.file.apply_textdelta()
        delta.send_stream(StringIO(contents), txdelta)

    def close(self):
        assert not self.is_closed
        self.is_closed = True
        self.file.close()

class TestDirEditor(object):
    """Simple dir editor wrapper that doesn't require closing."""

    def __init__(self, dir, baseurl, revnum):
        self.dir = dir
        self.baseurl = baseurl
        self.revnum = revnum
        self.is_closed = False
        self.children = []

    def close_children(self):
        for c in reversed(self.children):
            if not c.is_closed:
                c.close()

    def close(self):
        assert not self.is_closed
        self.is_closed = True
        self.close_children()
        self.dir.close()

    def change_prop(self, name, value):
        self.close_children()
        self.dir.change_prop(name, value)

    def open_dir(self, path):
        self.close_children()
        child = TestDirEditor(self.dir.open_directory(path, -1), self.baseurl, self.revnum)
        self.children.append(child)
        return child

    def open_file(self, path):
        self.close_children()
        child = TestFileEditor(self.dir.open_file(path, -1))
        self.children.append(child)
        return child

    def add_dir(self, path, copyfrom_path=None, copyfrom_rev=-1):
        self.close_children()
        if copyfrom_path is not None:
            copyfrom_path = urlparse.urljoin(self.baseurl+"/", copyfrom_path)
        if copyfrom_path is not None and copyfrom_rev == -1:
            copyfrom_rev = self.revnum
        assert (copyfrom_path is None and copyfrom_rev == -1) or \
               (copyfrom_path is not None and copyfrom_rev > -1)
        child = TestDirEditor(self.dir.add_directory(path, copyfrom_path,
            copyfrom_rev), self.baseurl, self.revnum)
        self.children.append(child)
        return child

    def add_file(self, path, copyfrom_path=None, copyfrom_rev=-1):
        self.close_children()
        if copyfrom_path is not None:
            copyfrom_path = urlparse.urljoin(self.baseurl+"/", copyfrom_path)
        if copyfrom_path is not None and copyfrom_rev == -1:
            copyfrom_rev = self.revnum
        child = TestFileEditor(self.dir.add_file(path, copyfrom_path,
            copyfrom_rev))
        self.children.append(child)
        return child

    def delete(self, path):
        self.close_children()
        self.dir.delete_entry(path)

class TestCommitEditor(TestDirEditor):
    """Simple commit editor wrapper."""

    def __init__(self, editor, baseurl, revnum):
        self.editor = editor
        TestDirEditor.__init__(self, self.editor.open_root(), baseurl, revnum)

    def close(self):
        TestDirEditor.close(self)
        self.editor.close()

class SubversionTestCase(TestCaseInTempDir):
    """A test case that provides the ability to build Subversion
    repositories."""

    def _init_client(self):
        self.client_ctx = client.Client()
        self.client_ctx.auth = Auth([ra.get_simple_provider(),
                                     ra.get_username_provider(),
                                     ra.get_ssl_client_cert_file_provider(),
                                     ra.get_ssl_client_cert_pw_file_provider(),
                                     ra.get_ssl_server_trust_file_provider()])
        self.client_ctx.log_msg_func = self.log_message_func
        #self.client_ctx.notify_func = lambda err: mutter("Error: %s" % err)

    def setUp(self):
        super(SubversionTestCase, self).setUp()
        self._init_client()

    def tearDown(self):
        del self.client_ctx
        super(SubversionTestCase, self).tearDown()

    def log_message_func(self, items):
        return self.next_message

    def make_repository(self, relpath, allow_revprop_changes=True):
        """Create a repository.

        :return: Handle to the repository.
        """
        abspath = os.path.join(self.test_dir, relpath)

        repos.create(abspath)

        if allow_revprop_changes:
            if sys.platform == 'win32':
                revprop_hook = os.path.join(abspath, "hooks",
                        "pre-revprop-change.bat")
                open(revprop_hook, 'w').write("exit 0\n")
            else:
                revprop_hook = os.path.join(abspath, "hooks",
                        "pre-revprop-change")
                open(revprop_hook, 'w').write("#!/bin/sh\n")
                os.chmod(revprop_hook, os.stat(revprop_hook).st_mode | 0111)

        if sys.platform == 'win32':
            return "file:///%s" % abspath.replace("\\", "/")
        else:
            return "file://%s" % abspath

    def make_checkout(self, repos_url, relpath):
        """Create a new checkout."""
        self.client_ctx.checkout(repos_url, relpath, "HEAD")

    def client_set_prop(self, path, name, value):
        """Set a property on a local file or directory."""
        if value is None:
            value = ""
        self.client_ctx.propset(name, value, path, False, True)

    def client_get_prop(self, path, name, revnum=None, recursive=False):
        """Retrieve a property from a local or remote file or directory."""
        if revnum is None:
            rev = "WORKING"
        else:
            rev = revnum
        ret = self.client_ctx.propget(name, path, rev, rev, recursive)
        if recursive:
            return ret
        else:
            return ret.values()[0]

    def client_get_revprop(self, url, revnum, name):
        """Get the revision property.

        :param url: URL of the repository
        :param revnum: Revision number
        :param name: Property name
        :return: Revision property value
        """
        r = ra.RemoteAccess(url)
        return r.rev_proplist(revnum)[name]

    def client_set_revprop(self, url, revnum, name, value):
        """Set a revision property on a repository.

        :param url: URL of the repository
        :param revnum: Revision number of the revision
        :param name: Name of the property
        :param value: Value of the property, None to remove
        """
        r = ra.RemoteAccess(url, auth=Auth([ra.get_username_provider()]))
        r.change_rev_prop(revnum, name, value)

    def client_resolve(self, path, choice, depth=0):
        """Resolve a conflict set on a local path."""
        self.client_ctx.resolve(path, depth, choice)

    def client_commit(self, dir, message=None, recursive=True):
        """Commit current changes in specified working copy.

        :param dir: List of paths to commit.
        """
        olddir = os.path.abspath('.')
        self.next_message = message
        os.chdir(dir)
        info = self.client_ctx.commit(["."], recursive, False)
        os.chdir(olddir)
        assert info is not None
        return info

    def client_add(self, relpath, recursive=True):
        """Add specified files to working copy.

        :param relpath: Path to the files to add.
        """
        self.client_ctx.add(relpath, recursive, False, False)

    def client_log(self, url, start_revnum, stop_revnum):
        """Fetch the log

        :param url: URL to log
        :param start_revnum: Start revision of the range to log over
        :param start_revnum: Stop revision of the range to log over
        :return: Dictionary
        """
        r = ra.RemoteAccess(url)
        assert isinstance(url, str)
        ret = {}
        def rcvr(orig_paths, rev, revprops, has_children=None):
            ret[rev] = (orig_paths,
                    revprops.get(properties.PROP_REVISION_AUTHOR),
                    revprops.get(properties.PROP_REVISION_DATE),
                    revprops.get(properties.PROP_REVISION_LOG))
        r.get_log(rcvr, [""], start_revnum, stop_revnum, 0, True, True,
                  revprops=[properties.PROP_REVISION_AUTHOR,
                      properties.PROP_REVISION_DATE,
                      properties.PROP_REVISION_LOG])
        return ret

    def client_delete(self, relpath):
        """Remove specified files from working copy.

        :param relpath: Path to the files to remove.
        """
        self.client_ctx.delete([relpath], True)

    def client_copy(self, oldpath, newpath, revnum=None):
        """Copy file in working copy.

        :param oldpath: Relative path to original file.
        :param newpath: Relative path to new file.
        """
        if revnum is None:
            rev = "HEAD"
        else:
            rev = revnum
        self.client_ctx.copy(oldpath, newpath, rev)

    def client_update(self, path):
        """Update path.

        :param path: Path
        """
        self.client_ctx.update([path], "HEAD", True)

    def build_tree(self, files):
        """Create a directory tree.

        :param files: Dictionary with filenames as keys, contents as
            values. None as value indicates a directory.
        """
        for f in files:
            if files[f] is None:
                try:
                    os.makedirs(f)
                except OSError:
                    pass
            else:
                try:
                    os.makedirs(os.path.dirname(f))
                except OSError:
                    pass
                open(f, 'w').write(files[f])

    def make_client(self, repospath, clientpath, allow_revprop_changes=True):
        """Create a repository and a checkout. Return the checkout.

        :param repospath: Optional relpath to check out if not the full
            repository.
        :param clientpath: Path to checkout
        :return: Repository URL.
        """
        repos_url = self.make_repository(repospath,
            allow_revprop_changes=allow_revprop_changes)
        self.make_checkout(repos_url, clientpath)
        return repos_url

    def open_fs(self, relpath):
        """Open a fs.

        :return: FS.
        """
        return repos.Repository(relpath).fs()

    def get_commit_editor(self, url, message="Test commit"):
        """Obtain a commit editor.

        :param url: URL to connect to
        :param message: Commit message
        :return: Commit editor object
        """
        ra_ctx = RemoteAccess(url.encode("utf-8"),
            auth=Auth([ra.get_username_provider()]))
        revnum = ra_ctx.get_latest_revnum()
        return TestCommitEditor(ra_ctx.get_commit_editor({"svn:log": message}),
            ra_ctx.url, revnum)

def test_suite():
    names = [
        'client',
        'core',
        'delta',
        'marshall',
        'properties',
        'ra',
        'repos',
        'server',
        'wc',
        ]
    module_names = ['subvertpy.tests.test_' + name for name in names]
    result = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite = loader.loadTestsFromNames(module_names)
    result.addTests(suite)
    return result
<|endoftext|>