Skip to content

Commit

Permalink
Add warning message about outdated linter version
Browse files Browse the repository at this point in the history
Checks every 24h if current version is latest and prints warning
message if so. If HTTP requests fails, no error is displayed.
  • Loading branch information
ssbarnea committed Oct 24, 2022
1 parent aa1ed71 commit ec70ef6
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/ansiblelint/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from ansiblelint import formatters
from ansiblelint._mockings import _perform_mockings
from ansiblelint.color import console, console_stderr, render_yaml
from ansiblelint.config import PROFILES
from ansiblelint.config import PROFILES, get_version_warning
from ansiblelint.config import options as default_options
from ansiblelint.constants import RULE_DOC_URL, SUCCESS_RC, VIOLATIONS_FOUND_RC
from ansiblelint.errors import MatchError
Expand Down Expand Up @@ -290,6 +290,8 @@ def report_summary( # pylint: disable=too-many-branches,too-many-locals
msg += f", and fixed {summary.fixed} issue(s)"
msg += f" on {files_count} files."

msg += get_version_warning()

console_stderr.print(msg)


Expand Down
83 changes: 83 additions & 0 deletions src/ansiblelint/config.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
"""Store configuration options as a singleton."""
from __future__ import annotations

import json
import logging
import os
import re
import sys
import time
import urllib.request
from argparse import Namespace
from functools import lru_cache
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError

from packaging.version import Version

from ansiblelint import __version__
from ansiblelint.loaders import yaml_from_file

_logger = logging.getLogger(__name__)

DEFAULT_WARN_LIST = [
"avoid-implicit",
"experimental",
Expand Down Expand Up @@ -171,3 +182,75 @@ def parse_ansible_version(stdout: str) -> tuple[str, str | None]:
if match:
return match.group(1), None
return "", f"FATAL: Unable parse ansible cli version: {stdout}"


def in_venv() -> bool:
"""Determine whether Python is running from a venv."""
if hasattr(sys, "real_prefix"):
return True
pfx = getattr(sys, "base_prefix", sys.prefix)
return pfx != sys.prefix


def guess_install_method() -> str:
"""Guess if upgrade command installed."""
pip = ""
if in_venv():
# for k in ("VIRTUAL_ENV", "CONDA_PREFIX", "PYENV_VERSION"):
# if k in os.environ:
_logger.debug("Found virtualenv, assuming `pip3 install` will work.")
pip = f"pip install --upgrade {__package__}"
elif __file__.startswith(os.path.expanduser("~/.local/lib")):
_logger.debug(
"Found --user installation, assuming `pip3 install --user` will work."
)
pip = f"pip3 install --user --upgrade {__package__}"

return pip


def get_version_warning() -> str:
"""Display warning if current version is outdated."""
msg = ""
new_version = Version("9999.99.9")
data = {}
current_version = Version(__version__)
cache_dir = os.path.expanduser("~/.cache/ansible-lint")
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
cache_file = f"{cache_dir}/latest222.json"
refresh = True
if os.path.exists(cache_file):
age = time.time() - os.path.getmtime(cache_file)
if age < 24 * 60 * 60:
refresh = False
with open(cache_file, encoding="utf-8") as f:
data = json.load(f)

if refresh or not data:
release_url = (
"https://api.github.com/repos/ansible/ansible-lint/releases/latest"
)
try:
with urllib.request.urlopen(release_url) as url:
data = json.load(url)
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(data, f)
except (URLError, HTTPError) as exc:
_logger.debug(
"Unable to fetch latest version from %s due to: %s", release_url, exc
)
return ""

html_url = data["html_url"]
tag_name = data["tag_name"] # name

if current_version < new_version:
msg = f"""\n\n[warning]A new release of ansible-lint is available: [red]{current_version}[/] → [green][link={html_url}]{tag_name}[/][/][/]
Do not report bugs without trying the latest version."""

pip = guess_install_method()
if pip:
msg += f" Upgrade running: [info]{pip}[/]"

return msg

0 comments on commit ec70ef6

Please sign in to comment.