Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/sugar/bundle/bundleversion.py
blob: e7632314dca5d0d0b4f349fef66b87e1dbdaba13 (plain)
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
# Copyright (C) 2010, OLPC
#
# This library 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 of the License, or (at your option) any later version.
#
# This library 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 library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

#
# Based on the implementation of PEP 386, but adapted to our
# numeration schema.
#

import re


class InvalidVersionError(Exception):
    """The passed activity version can not be normalized."""
    pass

VERSION_RE = re.compile(r'''
    ^
    (?P<version>\d+)               # minimum 'N'
    (?P<extraversion>(?:\.\d+)*)   # any number of extra '.N' segments
    (?:
    (?P<local>\-[a-zA-Z]*)         # ignore any string in the comparison
    )?
    $''', re.VERBOSE)


class NormalizedVersion(object):
    """A normalized version.

    Good:
        1
        1.2
        1.2.3
        1.2.3-peru

    Bad:
        1.2peru        # must be separated with -
        1.2.           # can't end with '.'
        1.02.5         # can't have a leading zero

    """

    def __init__(self, activity_version):
        """Create a NormalizedVersion instance from a version string.

        Keyword arguments:
        activity_version -- The version string

        """
        self._activity_version = activity_version
        self.parts = []
        self._local = None

        if not isinstance(self._activity_version, str):
            raise InvalidVersionError(self._activity_version)

        match = VERSION_RE.search(self._activity_version)
        if not match:
            raise InvalidVersionError(self._activity_version)

        groups = match.groupdict()

        version = self._parse_version(groups['version'])
        self.parts.append(version)

        if groups['extraversion'] not in ('', None):
            versions = self._parse_extraversions(groups['extraversion'][1:])
            self.parts.extend(versions)

        self._local = groups['local']

    def _parse_version(self, version_string):
        """Verify that there is no leading zero and convert to integer.

        Keyword arguments:
        version -- string to be parsed

        Return: Version

        """
        if len(version_string) > 1 and version_string[0] == '0':
            raise InvalidVersionError("Can not have leading zero in segment"
                                      " %s in %r" % (version_string,
                                      self._activity_version))

        return int(version_string)

    def _parse_extraversions(self, extraversion_string):
        """Split into N versions and convert them to integers, verify
        that there are no leading zeros and drop trailing zeros.

        Keyword arguments:
        extraversion -- 'N.N.N...' sequence to be parsed

        Return: List of extra versions

        """
        nums = []
        for n in extraversion_string.split("."):
            if len(n) > 1 and n[0] == '0':
                raise InvalidVersionError("Can not have leading zero in "
                                          "segment %s in %r" % (n,
                                          self._activity_version))
            nums.append(int(n))

        while nums and nums[-1] == 0:
            nums.pop()

        return nums

    def __str__(self):
        version_string = '.'.join(str(v) for v in self.parts)
        if self._local != None:
            version_string += self._local
        return version_string

    def __repr__(self):
        return "%s('%s')" % (self.__class__.__name__, self)

    def _cannot_compare(self, other):
        raise TypeError("Can not compare %s and %s"
                % (type(self).__name__, type(other).__name__))

    def __eq__(self, other):
        if not isinstance(other, NormalizedVersion):
            self._cannot_compare(other)
        return self.parts == other.parts

    def __lt__(self, other):
        if not isinstance(other, NormalizedVersion):
            self._cannot_compare(other)
        return self.parts < other.parts

    def __ne__(self, other):
        return not self.__eq__(other)

    def __gt__(self, other):
        return not (self.__lt__(other) or self.__eq__(other))

    def __le__(self, other):
        return self.__eq__(other) or self.__lt__(other)

    def __ge__(self, other):
        return self.__eq__(other) or self.__gt__(other)