File: version.py

package info (click to toggle)
python-pyfunceble 4.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,144 kB
  • sloc: python: 27,918; sh: 142; makefile: 48
file content (375 lines) | stat: -rw-r--r-- 13,921 bytes parent folder | download
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""
The tool to check the availability or syntax of domain, IP or URL.

::


    ██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
    ██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
    ██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
    ██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
    ██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
    ╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

Provides the version comparison tool.

Author:
    Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom

Special thanks:
    https://pyfunceble.github.io/#/special-thanks

Contributors:
    https://pyfunceble.github.io/#/contributors

Project link:
    https://github.com/funilrys/PyFunceble

Project documentation:
    https://docs.pyfunceble.com

Project homepage:
    https://pyfunceble.github.io/

License:
::


    Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024, 2025 Nissar Chababy

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import os
import sys
from datetime import datetime, timezone

import colorama
from box import Box

import PyFunceble.cli.storage
import PyFunceble.facility
import PyFunceble.storage
from PyFunceble.cli.utils.stdout import print_single_line
from PyFunceble.converter.internal_url import InternalUrlConverter
from PyFunceble.helpers.dict import DictHelper
from PyFunceble.helpers.download import DownloadHelper
from PyFunceble.helpers.exceptions import UnableToDownload
from PyFunceble.utils.version import VersionUtility


def get_upstream_version() -> Box:
    """
    Provides the state of the upstream version.
    """

    try:
        response = DownloadHelper(
            InternalUrlConverter(
                PyFunceble.cli.storage.VERSION_DUMP_LINK,
            ).get_converted(),
            own_proxy_handler=True,
            proxies=PyFunceble.storage.PROXY,
            certificate_validation=(
                PyFunceble.storage.CONFIGURATION.verify_ssl_certificate
                if PyFunceble.storage.CONFIGURATION
                else True
            ),
        ).download_text()
    except UnableToDownload:
        response = "{}"

    return Box(
        DictHelper().from_yaml(response),
        frozen_box=True,
    )


def get_local_version() -> Box:
    """
    Provides the state of the local version file.
    """

    return Box(
        DictHelper().from_yaml_file(
            os.path.join(
                PyFunceble.storage.CONFIG_DIRECTORY,
                PyFunceble.cli.storage.DISTRIBUTED_VERSION_FILENAME,
            )
        ),
        frozen_box=True,
    )


def handle_force_update(upstream_version: Box) -> None:
    """
    Checks if we should force the end-user to update.
    """

    version_utility = VersionUtility(PyFunceble.storage.PROJECT_VERSION)

    if (
        PyFunceble.facility.ConfigLoader.is_already_loaded()
        and PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.colour
    ):
        message = (
            f"{colorama.Style.BRIGHT}{colorama.Fore.RED}A critical issue has "
            f"been fixed.{colorama.Style.RESET_ALL}\n"
            f"{colorama.Style.BRIGHT}{colorama.Fore.GREEN}Please take the time to"
            f"update {PyFunceble.storage.PROJECT_NAME}!{colorama.Style.RESET_ALL}"
        )
    else:
        message = (
            "A critical issue has been fixed.\nPlease take the time to "
            f"update {PyFunceble.storage.PROJECT_NAME}!"
        )

    if upstream_version.force_update.status:
        for minimal in upstream_version.force_update.minimal_version:
            if version_utility.is_older_than(minimal):
                print(message)

                sys.exit(1)


def handle_deprecated_version(upstream_version: Box) -> bool:
    """
    Checks if the current version (local) is deprecated and provides a message
    to the end-user.

    :return:
        :py:class:`True` if local is deprecated. :py:class:`False` otherwise.
    """

    version_utility = VersionUtility(PyFunceble.storage.PROJECT_VERSION)

    if PyFunceble.facility.ConfigLoader.is_already_loaded():
        if PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.quiet:
            message = "Version deprecated."
        elif PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.colour:
            message = (
                f"{colorama.Style.BRIGHT}{colorama.Fore.RED}Your current version "
                f"is considered as deprecated.{colorama.Style.RESET_ALL}\n"
                f"{colorama.Style.BRIGHT}{colorama.Fore.GREEN}Please take the "
                "time to "
                f"update {PyFunceble.storage.PROJECT_NAME}!{colorama.Style.RESET_ALL}"
            )
        else:
            message = (
                "Your current version is considered as deprecated.\nPlease take "
                "the time to "
                f"update {PyFunceble.storage.PROJECT_NAME}!"
            )
    else:
        message = (
            "Your current version is considered as deprecated.\nPlease take the "
            "time to "
            f"update {PyFunceble.storage.PROJECT_NAME}!"
        )

    for version in reversed(upstream_version.deprecated):
        if version_utility.is_older_than(version):
            print(message)
            return True

    return False


def handle_greater_version(upstream_version: Box) -> None:
    """
    Checks if the current version (local) is more recent than the upstream one
    and provides a message.

    :return:
        :py:class:`True` if local is greater. :py:class:`False` otherwise.
    """

    version_utility = VersionUtility(PyFunceble.storage.PROJECT_VERSION)

    if PyFunceble.facility.ConfigLoader.is_already_loaded():
        if PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.quiet:
            message = ""
        elif PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.colour:
            message = (
                f"{colorama.Style.BRIGHT}{colorama.Fore.CYAN}Your current version "
                f"is more recent!{colorama.Style.RESET_ALL}\n"
                f"{colorama.Style.BRIGHT}{colorama.Fore.GREEN}You should "
                "really consider to submit a Pull Request to "
                f"{PyFunceble.storage.PROJECT_NAME}!"
                f"{colorama.Style.RESET_ALL}\n"
                f"{colorama.Style.BRIGHT}Your version:{colorama.Style.RESET_ALL} "
                f"{PyFunceble.storage.PROJECT_VERSION}\n"
                f"{colorama.Style.BRIGHT}Upstream version:{colorama.Style.RESET_ALL} "
                f"{upstream_version.current_version}\n"
            )
        else:
            message = (
                "Your current version is more recent!\nYou should really "
                "consider to submit a Pull Request to  "
                f"{PyFunceble.storage.PROJECT_NAME}!\n"
                f"Your version: {PyFunceble.storage.PROJECT_VERSION}\n"
                f"Upstream version: {upstream_version.current_version}"
            )
    else:
        message = (
            "Your current version is more recent!\nYou should really "
            "consider to submit a Pull Request to  "
            f"{PyFunceble.storage.PROJECT_NAME}!\n"
            f"Your version: {PyFunceble.storage.PROJECT_VERSION}\n"
            f"Upstream version: {upstream_version.current_version}"
        )

    if version_utility.is_recent(upstream_version.current_version):
        print(message)
        return True

    return False


def handle_older_version(upstream_version: Box) -> bool:
    """
    Checks if the current version (local) is older than the upstream one
    and provides a message to the end-user.

    :return:
        :py:class:`True` if local is older. :py:class:`False` otherwise.
    """

    version_utility = VersionUtility(PyFunceble.storage.PROJECT_VERSION)

    if PyFunceble.facility.ConfigLoader.is_already_loaded():
        if PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.quiet:
            message = "New version available."
        elif PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.colour:
            message = (
                f"{colorama.Style.BRIGHT}{colorama.Fore.GREEN}Please take the "
                "time to "
                f"update {PyFunceble.storage.PROJECT_NAME}!"
                f"{colorama.Style.RESET_ALL}\n"
                f"{colorama.Style.BRIGHT}Your version:{colorama.Style.RESET_ALL} "
                f"{PyFunceble.storage.PROJECT_VERSION}\n"
                f"{colorama.Style.BRIGHT}Upstream version:{colorama.Style.RESET_ALL} "
                f"{upstream_version.current_version}\n"
            )
        else:
            message = (
                f"Please take the time to update "
                f"{PyFunceble.storage.PROJECT_NAME}!\n"
                f"Your version: {PyFunceble.storage.PROJECT_VERSION}\n"
                f"Upstream version: {upstream_version.current_version}"
            )
    else:
        message = (
            "Please take the time to "
            f"update {PyFunceble.storage.PROJECT_NAME}!\n"
            f"Your version: {PyFunceble.storage.PROJECT_VERSION}\n"
            f"Upstream version: {upstream_version.current_version}"
        )

    if version_utility.is_older_than(upstream_version.current_version):
        print(message)
        return True

    return False


def handle_messages(upstream_version: Box) -> None:
    """
    Handles and prints the upstream messages.
    """

    version_utility = VersionUtility(PyFunceble.storage.PROJECT_VERSION)
    iso_dateformat = "%Y-%m-%dT%H:%M:%S%z"

    if PyFunceble.facility.ConfigLoader.is_already_loaded():
        if (
            PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.quiet
            or PyFunceble.storage.CONFIGURATION.cli_testing.display_mode.simple
        ):
            authorized = False
        else:
            authorized = True
    else:
        authorized = True

    if authorized:
        local_timezone = datetime.now(timezone.utc).astimezone().tzinfo

        for minimal_version, data in upstream_version.messages.items():
            if not version_utility.is_equal_to(
                minimal_version
            ) and not version_utility.is_recent(minimal_version):
                continue

            remaining_days = None

            for single_message in data:
                if "until_date" in single_message:
                    try:
                        remaining_days = (
                            datetime.strptime(single_message.until_date, iso_dateformat)
                            - datetime.now(tz=local_timezone)
                        ).days
                    except ValueError:
                        remaining_days = 0

                if remaining_days is not None and remaining_days <= 0:
                    continue

                if "until" in single_message and (
                    version_utility.is_recent(single_message.until)
                    or version_utility.is_equal_to(single_message.until)
                ):
                    continue

                if "type" in single_message:
                    if single_message.type == "info":
                        coloration = colorama.Fore.YELLOW
                    elif single_message.type == "warning":
                        coloration = colorama.Fore.MAGENTA
                    else:
                        coloration = colorama.Fore.BLUE
                else:
                    coloration = colorama.Fore.CYAN

                coloration += colorama.Style.BRIGHT

                print(
                    f"{coloration}{single_message.message}"
                    f"{colorama.Style.RESET_ALL}\n"
                )


def print_central_messages(check_force_update: bool = False) -> None:
    """
    Collect all possible messages from upstream and downstream and print them.
    """

    upstream_version = get_upstream_version()

    if upstream_version:
        if check_force_update:
            handle_force_update(upstream_version)

        _ = (
            not handle_deprecated_version(upstream_version)
            and not handle_greater_version(upstream_version)
            and not handle_older_version(upstream_version)
        )

        handle_messages(upstream_version)

    prefix = " - " if len(PyFunceble.cli.storage.EXTRA_MESSAGES) > 1 else ""

    for extra_message in PyFunceble.cli.storage.EXTRA_MESSAGES:
        print_single_line(prefix + extra_message, force=True, end="\n")