1# Copyright 2017 Linaro Limited
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Semi Semantic Versioning
19
20Implements a subset of semantic versioning that is supportable by the image
21header.
22"""
23
24from collections import namedtuple
25import re
26
27SemiSemVersion = namedtuple('SemiSemVersion', ['major', 'minor', 'revision',
28                                               'build'])
29
30version_re = re.compile(
31    r"""^([1-9]\d*|0)(\.([1-9]\d*|0)(\.([1-9]\d*|0)(\+([1-9]\d*|0))?)?)?$""")
32
33
34def decode_version(text):
35    """Decode the version string, which should be of the form maj.min.rev+build
36    """
37    m = version_re.match(text)
38    if m:
39        result = SemiSemVersion(
40                int(m.group(1)) if m.group(1) else 0,
41                int(m.group(3)) if m.group(3) else 0,
42                int(m.group(5)) if m.group(5) else 0,
43                int(m.group(7)) if m.group(7) else 0)
44        return result
45    else:
46        msg = "Invalid version number, should be maj.min.rev+build with later "
47        msg += "parts optional"
48        raise ValueError(msg)
49
50
51if __name__ == '__main__':
52    print(decode_version("1.2"))
53    print(decode_version("1.0"))
54    print(decode_version("0.0.2+75"))
55    print(decode_version("0.0.0+00"))
56