Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MRG] Add self version check #61

Merged
merged 2 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion conrad/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from .utils import conrad_self_version_check


__all__ = ("main",)
Expand All @@ -9,6 +9,7 @@
def main():
from conrad.cli import cli

conrad_self_version_check()
cli()


Expand Down
100 changes: 98 additions & 2 deletions conrad/utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,107 @@
# -*- coding: utf-8 -*-

from .db import engine

import os
import sys
import json
import logging
import datetime as dt
from setuptools.version import pkg_resources

import requests
import geopy.exc as geopyexceptions
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter

from .db import engine
from . import __version__, CONRAD_HOME


SELFCHECK_DATE_FMT = "%Y-%m-%dT%H:%M:%SZ"


logger = logging.getLogger(__name__)


# https://github.com/pypa/pip/blob/master/src/pip/_internal/self_outdated_check.py
class SelfCheckState(object):
def __init__(self, cache_dir):
self.state = {}
self.statefile_path = os.path.join(cache_dir, "selfcheck.json")

# Try to load the existing state
try:
with open(self.statefile_path, "r") as f:
self.state = json.load(f)
except (IOError, ValueError, KeyError, FileNotFoundError):
# Explicitly suppressing exceptions, since we don't want to
# error out if the cache file is invalid.
pass

def save(self, pypi_version, current_time):
# If we do not have a path to cache in, don't bother saving.
if not self.statefile_path:
return

state = {
"last_check": current_time.strftime(SELFCHECK_DATE_FMT),
"pypi_version": pypi_version,
}

text = json.dumps(state, sort_keys=True, separators=(",", ":"))

with open(self.statefile_path, "w") as f:
f.write(text)


def get_pypi_version():
url = "https://pypi.org/pypi/conference-radar/json"
response = requests.get(url)
if response:
data = response.json()
pypi_version = data["info"]["version"]
return pypi_version


def conrad_self_version_check():
pypi_version = None

try:
state = SelfCheckState(cache_dir=CONRAD_HOME)

current_time = dt.datetime.utcnow()
# Determine if we need to refresh the state
if "last_check" in state.state and "pypi_version" in state.state:
last_check = dt.datetime.strptime(
state.state["last_check"],
SELFCHECK_DATE_FMT
)
if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60:
pypi_version = state.state["pypi_version"]

# Refresh the version if we need to or just see if we need to warn
if pypi_version is None:
pypi_version = get_pypi_version()

# Save that we've performed a check
state.save(pypi_version, current_time)

conrad_version = pkg_resources.parse_version(__version__)
remote_version = pkg_resources.parse_version(pypi_version)

if conrad_version < remote_version:
pip_cmd = "{} -m pip".format(sys.executable)
logger.warning(
f"You are using conrad version {__version__}; however,"
f" version {pypi_version} is available.\n"
"You should consider upgrading with"
f" '{pip_cmd} install --upgrade conference-radar'."
)
except Exception:
logger.debug(
"There was an error checking the latest version of conrad",
exc_info=True,
)


def initialize_database():
from .models import Base
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def setup_package():
packages=find_packages(exclude=("tests",)),
install_requires=requires,
extras_require={"dev": dev_requires},
entry_points={"console_scripts": ["conrad = conrad.cli:cli"]},
entry_points={"console_scripts": ["conrad = conrad.__main__:main"]},
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
Expand Down