aboutsummaryrefslogtreecommitdiff
path: root/src/hydrilla/versions.py
blob: 93f395de3c25c145c8d716fe30928fc1a4c7b689 (about) (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
# SPDX-License-Identifier: GPL-3.0-or-later

# Functions to operate on version numbers.
#
# This file is part of Hydrilla&Haketilo.
#
# Copyright (C) 2021, 2022 Wojtek Kosior
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
#
# I, Wojtek Kosior, thereby promise not to sue for violation of this
# file's license. Although I request that you do not make use this code
# in a proprietary program, I am not going to enforce this in court.

"""
This module contains functions for deconstruction and construction of version
strings and version tuples.
"""

# Enable using with Python 3.7.
from __future__ import annotations

import typing as t

VerTuple = t.NewType('VerTuple', 'tuple[int, ...]')

def normalize_version(ver: t.Sequence[int]) -> VerTuple:
    """Strip rightmost zeroes from 'ver'."""
    new_len = 0
    for i, num in enumerate(ver):
        if num != 0:
            new_len = i + 1

    return VerTuple(tuple(ver[:new_len]))

def parse(ver_str: str) -> tuple[int, ...]:
    """
    Convert 'ver_str' into an array representation, e.g. for ver_str="4.6.13.0"
    return [4, 6, 13, 0].
    """
    return tuple(int(num) for num in ver_str.split('.'))

def parse_normalize(ver_str: str) -> VerTuple:
    """
    Convert 'ver_str' into a VerTuple representation, e.g. for
    ver_str="4.6.13.0" return (4, 6, 13).
    """
    return normalize_version(parse(ver_str))

def version_string(ver: VerTuple, rev: t.Optional[int] = None) -> str:
    """
    Produce version's string representation (optionally with revision), like:
        1.2.3-5
    """
    return '.'.join(str(n) for n in ver) + ('' if rev is None else f'-{rev}')