|
1 | 1 | """Store configuration options as a singleton.""" |
2 | 2 | from __future__ import annotations |
3 | 3 |
|
| 4 | +import json |
| 5 | +import logging |
4 | 6 | import os |
5 | 7 | import re |
| 8 | +import sys |
| 9 | +import time |
| 10 | +import urllib.request |
| 11 | +import warnings |
6 | 12 | from argparse import Namespace |
7 | 13 | from functools import lru_cache |
8 | 14 | from pathlib import Path |
9 | 15 | from typing import Any |
| 16 | +from urllib.error import HTTPError, URLError |
10 | 17 |
|
| 18 | +from packaging.version import Version |
| 19 | + |
| 20 | +from ansiblelint import __version__ |
11 | 21 | from ansiblelint.loaders import yaml_from_file |
12 | 22 |
|
| 23 | +_logger = logging.getLogger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +CACHE_DIR = ( |
| 27 | + os.path.expanduser(os.environ.get("XDG_CONFIG_CACHE", "~/.cache")) + "/ansible-lint" |
| 28 | +) |
| 29 | + |
13 | 30 | DEFAULT_WARN_LIST = [ |
14 | 31 | "avoid-implicit", |
15 | 32 | "experimental", |
@@ -171,3 +188,106 @@ def parse_ansible_version(stdout: str) -> tuple[str, str | None]: |
171 | 188 | if match: |
172 | 189 | return match.group(1), None |
173 | 190 | return "", f"FATAL: Unable parse ansible cli version: {stdout}" |
| 191 | + |
| 192 | + |
| 193 | +def in_venv() -> bool: |
| 194 | + """Determine whether Python is running from a venv.""" |
| 195 | + if hasattr(sys, "real_prefix"): |
| 196 | + return True |
| 197 | + pfx = getattr(sys, "base_prefix", sys.prefix) |
| 198 | + return pfx != sys.prefix |
| 199 | + |
| 200 | + |
| 201 | +def guess_install_method() -> str: |
| 202 | + """Guess if pip upgrade command should be used.""" |
| 203 | + pip = "" |
| 204 | + if in_venv(): |
| 205 | + _logger.debug("Found virtualenv, assuming `pip3 install` will work.") |
| 206 | + pip = f"pip install --upgrade {__package__}" |
| 207 | + elif __file__.startswith(os.path.expanduser("~/.local/lib")): |
| 208 | + _logger.debug( |
| 209 | + "Found --user installation, assuming `pip3 install --user` will work." |
| 210 | + ) |
| 211 | + pip = f"pip3 install --user --upgrade {__package__}" |
| 212 | + |
| 213 | + # By default we assume pip is not safe to be used |
| 214 | + use_pip = False |
| 215 | + package_name = "ansible-lint" |
| 216 | + try: |
| 217 | + # Use pip to detect if is safe to use it to upgrade the package. |
| 218 | + # We do imports here to for performance and reasons, and also in order |
| 219 | + # to avoid errors if pip internals change. Also we want to avoid having |
| 220 | + # to add pip as a dependency, so we make use of it only when present. |
| 221 | + |
| 222 | + # trick to avoid runtime warning from inside pip: _distutils_hack/__init__.py:33: UserWarning: Setuptools is replacing distutils. |
| 223 | + with warnings.catch_warnings(record=True): |
| 224 | + warnings.simplefilter("always") |
| 225 | + # pylint: disable=import-outside-toplevel |
| 226 | + from pip._internal.exceptions import UninstallationError |
| 227 | + from pip._internal.metadata import get_default_environment |
| 228 | + from pip._internal.req.req_uninstall import uninstallation_paths |
| 229 | + |
| 230 | + try: |
| 231 | + dist = get_default_environment().get_distribution(package_name) |
| 232 | + if dist: |
| 233 | + logging.debug("Found %s dist", dist) |
| 234 | + for _ in uninstallation_paths(dist): |
| 235 | + use_pip = True |
| 236 | + else: |
| 237 | + logging.debug("Skipping %s as it is not installed.", package_name) |
| 238 | + use_pip = False |
| 239 | + except UninstallationError as exc: |
| 240 | + logging.debug(exc) |
| 241 | + use_pip = False |
| 242 | + except ImportError: |
| 243 | + use_pip = False |
| 244 | + |
| 245 | + # We only want to recommend pip for upgrade if it looks safe to do so. |
| 246 | + return pip if use_pip else "" |
| 247 | + |
| 248 | + |
| 249 | +def get_version_warning() -> str: |
| 250 | + """Display warning if current version is outdated.""" |
| 251 | + msg = "" |
| 252 | + data = {} |
| 253 | + current_version = Version(__version__) |
| 254 | + if not os.path.exists(CACHE_DIR): |
| 255 | + os.makedirs(CACHE_DIR) |
| 256 | + cache_file = f"{CACHE_DIR}/latest.json" |
| 257 | + refresh = True |
| 258 | + if os.path.exists(cache_file): |
| 259 | + age = time.time() - os.path.getmtime(cache_file) |
| 260 | + if age < 24 * 60 * 60: |
| 261 | + refresh = False |
| 262 | + with open(cache_file, encoding="utf-8") as f: |
| 263 | + data = json.load(f) |
| 264 | + |
| 265 | + if refresh or not data: |
| 266 | + release_url = ( |
| 267 | + "https://api.github.com/repos/ansible/ansible-lint/releases/latest" |
| 268 | + ) |
| 269 | + try: |
| 270 | + with urllib.request.urlopen(release_url) as url: |
| 271 | + data = json.load(url) |
| 272 | + with open(cache_file, "w", encoding="utf-8") as f: |
| 273 | + json.dump(data, f) |
| 274 | + except (URLError, HTTPError) as exc: |
| 275 | + _logger.debug( |
| 276 | + "Unable to fetch latest version from %s due to: %s", release_url, exc |
| 277 | + ) |
| 278 | + return "" |
| 279 | + |
| 280 | + html_url = data["html_url"] |
| 281 | + new_version = Version(data["tag_name"][1:]) # removing v prefix from tag |
| 282 | + # breakpoint() |
| 283 | + |
| 284 | + if current_version > new_version: |
| 285 | + msg = "[dim]You are using a pre-release version of ansible-lint.[/]" |
| 286 | + elif current_version < new_version: |
| 287 | + msg = f"""[warning]A new release of ansible-lint is available: [red]{current_version}[/] → [green][link={html_url}]{new_version}[/][/][/]""" |
| 288 | + |
| 289 | + pip = guess_install_method() |
| 290 | + if pip: |
| 291 | + msg += f" Upgrade by running: [info]{pip}[/]" |
| 292 | + |
| 293 | + return msg |
0 commit comments