File: types.py

package info (click to toggle)
debiancontributors 0.7.8-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 404 kB
  • sloc: python: 1,894; makefile: 18
file content (227 lines) | stat: -rw-r--r-- 8,010 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# coding: utf8
# Debian Contributors data source core data structures
#
# Copyright (C) 2013  Enrico Zini <enrico@debian.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 3 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, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from .parser import Fail
import six
import re

__all__ = ["Identifier", "Contribution"]


class Identifier(object):
    """
    Information about a user identifier
    """
    __slots__ = ("type", "id", "desc")

    # Validator regexps
    TYPE_VALIDATORS = {
        "login": re.compile(r"^[a-z0-9._-]+$"),
        # From http://www.regular-expressions.info/email.html
        "email": re.compile(r"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}", re.I),
        "fpr": re.compile(r"^[A-F0-9]{32,40}$"),
        "url": re.compile(r"^https?://"),
        # "wiki": re.compile("^[A-Za-z]+$"),
    }

    def __init__(self, type, id, desc=None):
        self.type = type
        self.id = id
        self.desc = desc

    def __hash__(self):
        return hash(self.type) + hash(self.id)

    def __eq__(self, other):
        return (self.type == other.type
                and self.id == other.id)

    def to_json(self):
        """
        Return a JSON-serializable structure for this identifier
        """
        if self.desc:
            return {
                "type": self.type,
                "id": self.id,
                "desc": self.desc,
            }
        else:
            return {
                "type": self.type,
                "id": self.id,
            }

    def validate(self):
        """
        Validate the contents of this Identifier, raising parser.Fail if
        anything fails.
        """
        # Validate member types
        if not isinstance(self.type, six.string_types):
            raise Fail(400, "Identifier type is '{}' instead of a string".format(type(self.type)))
        if not isinstance(self.id, six.string_types):
            raise Fail(400, "Identifier id is '{}' instead of a string".format(type(self.id)))
        if self.desc is not None and not isinstance(self.desc, six.string_types):
            raise Fail(400, "Identifier desc is '{}' instead of None or a string".format(type(self.desc)))

        # Validator for this type
        type_validator = self.TYPE_VALIDATORS.get(self.type, None)
        if type_validator is None:
            raise Fail(400, "Invalid identifier type '{}'".format(self.type))

        # Parse the ID and validate it
        if not type_validator.match(self.id):
            raise Fail(400, "{} '{}' is not a valid identifier".format(self.type, self.id))

    @classmethod
    def create_auto(cls, s, default_desc=None):
        """
        Autodetect identifier type and value from a string.

        'desc' is the default description to use if not inferred automatically.
        """
        from email.utils import getaddresses
        if "<" in s:
            # Use getaddresses instead of parseaddr because
            # parseaddr truncates the string at a stray command, instead of
            # declaring a failed parse:
            # parseaddr("a, <b>") gives ('', 'a')
            results = getaddresses((s,))
            if len(results) == 1:
                # Parsing was ok
                desc, ident = results[0]
            else:
                # Something went wrong, possibly a stray comma. Trying again
                # wtih a regexp
                mo = re.match(r"^\s*(?:(.+)\s+)?<([^>]+)>\s*$", s)
                if mo:
                    desc, ident = mo.group(1, 2)
                else:
                    desc, ident = default_desc, s
        else:
            desc, ident = default_desc, s
        ident = ident.replace(" ", "")
        for type, regexp in cls.TYPE_VALIDATORS.items():
            if regexp.match(ident):
                return cls(type, ident, desc)
        raise ValueError("cannot infer a valid Identifier from '{}'".format(s))


class Contribution(object):
    """
    Information about a contribution.
    """
    __slots__ = ("type", "begin", "end", "url")

    def __init__(self, type, begin=None, end=None, url=None):
        """
        type: contribution type (as configured in contrbutors.debian.org for a
              source)
        begin: start time of this contribution. None to reuse the last start time.
        end: end time of this contribution. None to mean 'now'.
        url: URL used to list all contributions of this type from this person,
             if available.
        """
        self.type = type
        self.begin = begin
        self.end = end
        self.url = url

    def __hash__(self):
        return hash(self.type) + hash(self.begin) + hash(self.end)

    def __eq__(self, other):
        return (self.type == other.type
                and self.begin == other.begin
                and self.end == other.end)

    def extend_by_date(self, date):
        """
        Extend the date range to include the given date

        "Extend" is a bit imprecise: if the current end date is None (meaning
        'today'), then it is set to 'date' (which could be before than today)
        """
        if self.begin is None:
            self.begin = date
        else:
            self.begin = min(self.begin, date)

        if self.end is None:
            self.end = date
        else:
            self.end = max(self.end, date)

    def to_json(self):
        """
        Return a JSON-serializable structure for this contribution
        """
        res = {"type": self.type}
        if self.begin:
            res["begin"] = self.begin.strftime("%Y-%m-%d")
        if self.end:
            res["end"] = self.end.strftime("%Y-%m-%d")
        if self.url:
            res["url"] = self.url
        return res

    @classmethod
    def merged(cls, first, second):
        """
        Build a Contribution with a merge of two existing ones
        """
        if second.begin is None:
            begin = first.begin
        elif first.begin is None:
            begin = second.begin
        else:
            begin = min(first.begin, second.begin)

        if second.end is None:
            end = first.end
        elif first.end is None:
            end = second.end
        else:
            end = max(first.end, second.end)

        if first.url is None:
            url = second.url
        else:
            url = first.url

        return cls(first.type, begin, end, url)

    def validate(self):
        """
        Validate the contents of this Identifier, raising parser.Fail if
        anything fails.
        """
        # Validate member types
        if not isinstance(self.type, six.string_types):
            raise Fail(400, "Contribution type is '{}' instead of a string".format(type(self.type)))
        if self.begin is not None and not hasattr(self.begin, "strftime"):
            raise Fail(400, "Contribution begin is '{}' and does not look like a date or datetime".format(
                type(self.begin)))
        if self.end is not None and not hasattr(self.end, "strftime"):
            raise Fail(400, "Contribution end is '{}' and does not look like a date or datetime".format(type(self.end)))
        if self.url is not None and not isinstance(self.url, six.string_types):
            raise Fail(400, "Contribution URL is '{}' instead of None or a string".format(type(self.url)))