|
| 1 | +import json |
| 2 | +import os, sys |
| 3 | +import time |
| 4 | +from pathlib import Path |
| 5 | +from packaging.version import parse as parse_version, Version |
| 6 | +import inquirer |
| 7 | +from agentstack.utils import term_color, get_version, get_framework |
| 8 | +from agentstack import packaging |
| 9 | +from appdirs import user_data_dir |
| 10 | + |
| 11 | +AGENTSTACK_PACKAGE = 'agentstack' |
| 12 | + |
| 13 | + |
| 14 | +def _is_ci_environment(): |
| 15 | + """Detect if we're running in a CI environment""" |
| 16 | + ci_env_vars = [ |
| 17 | + 'CI', |
| 18 | + 'GITHUB_ACTIONS', |
| 19 | + 'GITLAB_CI', |
| 20 | + 'TRAVIS', |
| 21 | + 'CIRCLECI', |
| 22 | + 'JENKINS_URL', |
| 23 | + 'TEAMCITY_VERSION' |
| 24 | + ] |
| 25 | + return any(os.getenv(var) for var in ci_env_vars) |
| 26 | + |
| 27 | + |
| 28 | +# Try to get appropriate directory for storing update file |
| 29 | +try: |
| 30 | + base_dir = Path(user_data_dir("agentstack", "agency")) |
| 31 | + # Test if we can write to directory |
| 32 | + test_file = base_dir / '.test_write_permission' |
| 33 | + test_file.touch() |
| 34 | + test_file.unlink() |
| 35 | +except (RuntimeError, OSError, PermissionError): |
| 36 | + # In CI or when directory is not writable, use temp directory |
| 37 | + base_dir = Path(os.getenv('TEMP', '/tmp')) |
| 38 | + |
| 39 | +LAST_CHECK_FILE_PATH = base_dir / ".cli-last-update" |
| 40 | +INSTALL_PATH = Path(sys.executable).parent.parent |
| 41 | +ENDPOINT_URL = "https://pypi.org/simple" |
| 42 | +CHECK_EVERY = 3600 # hour |
| 43 | + |
| 44 | + |
| 45 | +def get_latest_version(package: str) -> Version: |
| 46 | + """Get version information from PyPi to save a full package manager invocation""" |
| 47 | + import requests # defer import until we know we need it |
| 48 | + response = requests.get(f"{ENDPOINT_URL}/{package}/", headers={"Accept": "application/vnd.pypi.simple.v1+json"}) |
| 49 | + if response.status_code != 200: |
| 50 | + raise Exception(f"Failed to fetch package data from pypi.") |
| 51 | + data = response.json() |
| 52 | + return parse_version(data['versions'][-1]) |
| 53 | + |
| 54 | + |
| 55 | +def load_update_data(): |
| 56 | + """Load existing update data or return empty dict if file doesn't exist""" |
| 57 | + if Path(LAST_CHECK_FILE_PATH).exists(): |
| 58 | + try: |
| 59 | + with open(LAST_CHECK_FILE_PATH, 'r') as f: |
| 60 | + return json.load(f) |
| 61 | + except (json.JSONDecodeError, PermissionError): |
| 62 | + return {} |
| 63 | + return {} |
| 64 | + |
| 65 | + |
| 66 | +def should_update() -> bool: |
| 67 | + """Has it been longer than CHECK_EVERY since the last update check?""" |
| 68 | + # Always check for updates in CI |
| 69 | + if _is_ci_environment(): |
| 70 | + return True |
| 71 | + |
| 72 | + data = load_update_data() |
| 73 | + last_check = data.get(str(INSTALL_PATH)) |
| 74 | + |
| 75 | + if not last_check: |
| 76 | + return True |
| 77 | + |
| 78 | + return time.time() - float(last_check) > CHECK_EVERY |
| 79 | + |
| 80 | + |
| 81 | +def record_update_check(): |
| 82 | + """Save current timestamp for this installation""" |
| 83 | + # Don't record updates in CI |
| 84 | + if _is_ci_environment(): |
| 85 | + return |
| 86 | + |
| 87 | + try: |
| 88 | + data = load_update_data() |
| 89 | + data[str(INSTALL_PATH)] = time.time() |
| 90 | + |
| 91 | + # Create directory if it doesn't exist |
| 92 | + LAST_CHECK_FILE_PATH.parent.mkdir(parents=True, exist_ok=True) |
| 93 | + |
| 94 | + with open(LAST_CHECK_FILE_PATH, 'w') as f: |
| 95 | + json.dump(data, f, indent=2) |
| 96 | + except (OSError, PermissionError): |
| 97 | + # Silently fail in CI or when we can't write |
| 98 | + pass |
| 99 | + |
| 100 | + |
| 101 | +def check_for_updates(update_requested: bool = False): |
| 102 | + """ |
| 103 | + `update_requested` indicates the user has explicitly requested an update. |
| 104 | + """ |
| 105 | + if not update_requested and not should_update(): |
| 106 | + return |
| 107 | + |
| 108 | + print("Checking for updates...\n") |
| 109 | + |
| 110 | + try: |
| 111 | + latest_version: Version = get_latest_version(AGENTSTACK_PACKAGE) |
| 112 | + except Exception as e: |
| 113 | + print(term_color("Failed to retrieve package index.", 'red')) |
| 114 | + return |
| 115 | + |
| 116 | + installed_version: Version = parse_version(get_version(AGENTSTACK_PACKAGE)) |
| 117 | + if latest_version > installed_version: |
| 118 | + print('') # newline |
| 119 | + if inquirer.confirm(f"New version of {AGENTSTACK_PACKAGE} available: {latest_version}! Do you want to install?"): |
| 120 | + packaging.upgrade(f'{AGENTSTACK_PACKAGE}[{get_framework()}]') |
| 121 | + print(term_color(f"{AGENTSTACK_PACKAGE} updated. Re-run your command to use the latest version.", 'green')) |
| 122 | + sys.exit(0) |
| 123 | + else: |
| 124 | + print(term_color("Skipping update. Run `agentstack update` to install the latest version.", 'blue')) |
| 125 | + else: |
| 126 | + print(f"{AGENTSTACK_PACKAGE} is up to date ({installed_version})") |
| 127 | + |
| 128 | + record_update_check() |
| 129 | + |
0 commit comments