1# Copyright 2018 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15import time 16import pathlib 17 18import pkg_resources 19import packaging.version 20import requests 21 22 23def _get_pypi_version(package_name: str) -> str: 24 r = requests.get(f"https://pypi.org/pypi/{package_name}/json") 25 r.raise_for_status() 26 27 return r.json()["info"]["version"] 28 29 30def _only_once_pls(package_name: str) -> bool: 31 flag = pathlib.Path.home() / ".cache" / f"update-check-{package_name}" 32 33 if not flag.exists(): 34 flag.parent.mkdir(parents=True, exist_ok=True) 35 flag.touch() 36 return True 37 38 last_check = flag.stat().st_mtime 39 one_day_in_seconds = 60 * 60 * 24 40 41 if last_check < time.time() - one_day_in_seconds: 42 flag.touch() 43 return True 44 else: 45 return False 46 47 48def check_for_updates(package_name: str, print=print) -> None: 49 if not _only_once_pls(package_name): 50 return 51 52 current_version = packaging.version.Version( 53 pkg_resources.get_distribution(package_name).version 54 ) 55 56 pypi_version = packaging.version.Version(_get_pypi_version(package_name)) 57 58 if current_version >= pypi_version: 59 return 60 61 print( 62 f"{package_name} has a newer version available. Current version is " 63 f"{current_version}, newest is {pypi_version}. Run `python3 -m pip " 64 f"install --upgrade {package_name}` to update." 65 ) 66