|
3 | 3 | import pathlib |
4 | 4 | import random |
5 | 5 | import sys |
| 6 | +import threading |
6 | 7 | import uuid |
7 | 8 | import warnings |
| 9 | +from distutils.version import LooseVersion |
8 | 10 | from typing import Any, Dict, Optional, Sequence, Tuple |
| 11 | +from urllib.request import Request, urlopen |
| 12 | + |
| 13 | +import pkg_resources |
| 14 | +from rich import print |
| 15 | +from rich.panel import Panel |
9 | 16 |
|
10 | 17 | ALLOWED_PROTOCOLS = {'pickle', 'protobuf', 'protobuf-array', 'pickle-array'} |
11 | 18 | ALLOWED_COMPRESSIONS = {'lz4', 'bz2', 'lzma', 'zlib', 'gzip'} |
@@ -443,3 +450,49 @@ def filter_dict(d: Dict) -> Dict: |
443 | 450 | :return: filtered dict |
444 | 451 | """ |
445 | 452 | return dict(filter(lambda item: item[1], d.items())) |
| 453 | + |
| 454 | + |
| 455 | +def _version_check(package: str = None, github_repo: str = None): |
| 456 | + try: |
| 457 | + if not package: |
| 458 | + package = vars(sys.modules[__name__])['__package__'] |
| 459 | + if not github_repo: |
| 460 | + github_repo = package |
| 461 | + |
| 462 | + cur_ver = LooseVersion(pkg_resources.get_distribution(package).version) |
| 463 | + req = Request( |
| 464 | + f'https://pypi.python.org/pypi/{package}/json', |
| 465 | + headers={'User-Agent': 'Mozilla/5.0'}, |
| 466 | + ) |
| 467 | + with urlopen( |
| 468 | + req, timeout=5 |
| 469 | + ) as resp: # 'with' is important to close the resource after use |
| 470 | + j = json.load(resp) |
| 471 | + releases = j.get('releases', {}) |
| 472 | + latest_release_ver = list( |
| 473 | + sorted(LooseVersion(v) for v in releases.keys() if '.dev' not in v) |
| 474 | + )[-1] |
| 475 | + if cur_ver < latest_release_ver: |
| 476 | + print( |
| 477 | + Panel( |
| 478 | + f'You are using [b]{package} {cur_ver}[/b], but [bold green]{latest_release_ver}[/] is available. ' |
| 479 | + f'You may upgrade it via [b]pip install -U {package}[/b]. [link=https://github.com/jina-ai/{github_repo}/blob/main/CHANGELOG.md]Read Changelog here[/link].', |
| 480 | + title=':new: New version available!', |
| 481 | + width=50, |
| 482 | + ) |
| 483 | + ) |
| 484 | + except Exception: |
| 485 | + # no network, too slow, PyPi is down |
| 486 | + pass |
| 487 | + |
| 488 | + |
| 489 | +def is_latest_version(package: str = None, github_repo: str = None) -> None: |
| 490 | + """Check if there is a latest version from Pypi, set env `NO_VERSION_CHECK` to disable it. |
| 491 | +
|
| 492 | + :param package: package name if none auto-detected |
| 493 | + :param github_repo: repo name that contains CHANGELOG if none then the same as package name |
| 494 | + """ |
| 495 | + |
| 496 | + threading.Thread( |
| 497 | + target=_version_check, daemon=True, args=(package, github_repo) |
| 498 | + ).start() |
0 commit comments