|
| 1 | +import tarfile |
| 2 | +import zipfile |
| 3 | +from pathlib import Path |
| 4 | +from platform import machine, system |
| 5 | +from stat import S_IXGRP, S_IXOTH, S_IXUSR |
| 6 | +from subprocess import PIPE, Popen |
| 7 | +from typing import Callable |
| 8 | + |
| 9 | +import py7zr |
| 10 | +import requests |
| 11 | + |
| 12 | +SYSTEM_CACHE_DIR = { |
| 13 | + "linux": Path().home() / ".cache" / "cachebin", |
| 14 | + "darwin": Path().home() / "Library" / "Caches" / "cachebin", |
| 15 | + "windows": Path().home() / "AppData" / "Local" / "cachebin", |
| 16 | +} |
| 17 | + |
| 18 | + |
| 19 | +def download_file(url: str, directory_path: Path | str, force: bool = False) -> Path: |
| 20 | + """ |
| 21 | + Downloads a file from the given URL and saves it to the specified directory. |
| 22 | +
|
| 23 | + Args: |
| 24 | + url (str): The URL of the file to download. |
| 25 | + directory_path (Path): The directory where the file will be saved. |
| 26 | +
|
| 27 | + Returns: |
| 28 | + Path of the downloaded file. |
| 29 | + """ |
| 30 | + directory_path = Path(directory_path) # Ensure directory_path is a Path object |
| 31 | + response = requests.get(url, stream=True) |
| 32 | + response.raise_for_status() # Raise an error for bad responses |
| 33 | + |
| 34 | + directory_path.mkdir(parents=True, exist_ok=True) |
| 35 | + |
| 36 | + filename = url.split("/")[-1] # Extract the filename from the URL |
| 37 | + file_path = directory_path / filename |
| 38 | + |
| 39 | + if not file_path.exists() or force: |
| 40 | + print(f"Downloading {url} to {file_path}...") |
| 41 | + with open(file_path, "wb") as file: |
| 42 | + for chunk in response.iter_content(chunk_size=8192): |
| 43 | + file.write(chunk) |
| 44 | + |
| 45 | + return file_path |
| 46 | + |
| 47 | + |
| 48 | +def extract_archive(archive_path: Path | str, extract_path: Path | str) -> Path: # noqa: PLR0912 |
| 49 | + """ |
| 50 | + Extracts a compressed archive to the specified directory. |
| 51 | +
|
| 52 | + Args: |
| 53 | + archive_path (Path): The path to the archive file. |
| 54 | + extract_to (Path): The directory where the archive will be extracted. |
| 55 | + """ |
| 56 | + archive_path = Path(archive_path) |
| 57 | + extract_path = Path(extract_path) |
| 58 | + if not archive_path.exists(): |
| 59 | + raise FileNotFoundError(f"Archive {archive_path} does not exist.") |
| 60 | + |
| 61 | + extract_path.mkdir(parents=True, exist_ok=True) |
| 62 | + |
| 63 | + archive: zipfile.ZipFile | tarfile.TarFile | py7zr.SevenZipFile |
| 64 | + if archive_path.name.endswith(("tar.gz", "tgz")): |
| 65 | + archive = tarfile.open(archive_path, "r:gz") |
| 66 | + elif archive_path.name.endswith("tar.bz2"): |
| 67 | + archive = tarfile.open(archive_path, "r:bz2") |
| 68 | + elif archive_path.name.endswith("tar.xz"): |
| 69 | + archive = tarfile.open(archive_path, "r:xz") |
| 70 | + elif archive_path.name.endswith("tar"): |
| 71 | + archive = tarfile.open(archive_path, "r:") |
| 72 | + elif archive_path.name.endswith("zip"): |
| 73 | + archive = zipfile.ZipFile(archive_path, "r") |
| 74 | + elif archive_path.name.endswith("7z"): |
| 75 | + archive = py7zr.SevenZipFile(archive_path, "r") |
| 76 | + else: |
| 77 | + raise RuntimeError(f"Unsupported archive format: {archive_path}") |
| 78 | + |
| 79 | + extracted_parent_directory = extract_path |
| 80 | + |
| 81 | + top_item: zipfile.ZipInfo | tarfile.TarInfo | py7zr.FileInfo |
| 82 | + if isinstance(archive, zipfile.ZipFile): |
| 83 | + top_item = archive.infolist()[0] |
| 84 | + if top_item.is_dir(): |
| 85 | + extracted_parent_directory = extract_path / top_item.filename |
| 86 | + |
| 87 | + elif isinstance(archive, tarfile.TarFile): |
| 88 | + top_item = archive.getmembers()[0] |
| 89 | + if top_item.isdir(): |
| 90 | + extracted_parent_directory = extract_path / top_item.name |
| 91 | + |
| 92 | + elif isinstance(archive, py7zr.SevenZipFile): |
| 93 | + top_item = archive.list()[0] |
| 94 | + if top_item.is_directory: |
| 95 | + extracted_parent_directory = extract_path / top_item.filename |
| 96 | + |
| 97 | + if not extracted_parent_directory.exists(): |
| 98 | + print(f"Extracting {archive_path} to {extract_path}...") |
| 99 | + archive.extractall(path=extract_path) |
| 100 | + return extracted_parent_directory |
| 101 | + |
| 102 | + |
| 103 | +def make_executable(file_path: str | Path) -> None: |
| 104 | + file_path = Path(file_path) |
| 105 | + current_permissions = file_path.stat().st_mode |
| 106 | + # Add the executable bit for the owner, group, and others |
| 107 | + file_path.chmod(current_permissions | S_IXUSR | S_IXGRP | S_IXOTH) |
| 108 | + |
| 109 | + |
| 110 | +class BinaryVersion: |
| 111 | + def __init__(self, version: str, parent: "BinaryManager"): |
| 112 | + self.parent = parent |
| 113 | + self.version = version |
| 114 | + self.url = self.parent.url_pattern.format( |
| 115 | + version=self.version, |
| 116 | + platform=self.parent._platform_string, |
| 117 | + extension=self.parent._extension, |
| 118 | + package_name=self.parent.package_name, |
| 119 | + ) |
| 120 | + self.archive_name = self.url.split("/")[-1] |
| 121 | + self.archive_path = download_file(self.url, self.parent._downloads_directory) |
| 122 | + self.binary_directory_path = ( |
| 123 | + extract_archive(self.archive_path, self.parent._package_directory / self.version) |
| 124 | + / self.parent._extracted_bin_path |
| 125 | + ) |
| 126 | + |
| 127 | + def call(self, command: str, *args: str) -> str: |
| 128 | + """ |
| 129 | + Calls the binary with the specified command and arguments. |
| 130 | +
|
| 131 | + Args: |
| 132 | + command (str): The command to execute. |
| 133 | + *args (str): Additional arguments for the command. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + str: The output of the command. |
| 137 | + """ |
| 138 | + binary_path = self.binary_directory_path / command |
| 139 | + if not binary_path.exists(): |
| 140 | + raise FileNotFoundError(f"Binary {binary_path} does not exist.") |
| 141 | + |
| 142 | + make_executable(binary_path) |
| 143 | + |
| 144 | + creation_flag = ( |
| 145 | + 0x08000000 if self.parent._system == "windows" else 0 |
| 146 | + ) # set creation flag to not open in new console on windows |
| 147 | + process = Popen([str(binary_path), *args], stdout=PIPE, stderr=PIPE, creationflags=creation_flag) |
| 148 | + stdout, stderr = process.communicate() |
| 149 | + if process.returncode != 0: |
| 150 | + raise RuntimeError(f"Command failed with error: {stderr.decode('utf-8')}") |
| 151 | + return stdout.decode("utf-8") |
| 152 | + |
| 153 | + |
| 154 | +class BinaryManager: |
| 155 | + def __init__( |
| 156 | + self, |
| 157 | + package_name: str, |
| 158 | + url_pattern: str, |
| 159 | + get_archive_extension: Callable[[str], str], # returns archive extension based on system |
| 160 | + get_platform_string: Callable[[str, str], str] = lambda system, |
| 161 | + architecture: f"{system}-{architecture}", # returns platform string used in url_pattern |
| 162 | + get_extracted_bin_path: Callable[[str], str] = lambda _: "bin", # returns extracted bin path based on system |
| 163 | + cache_directory: Path | str | None = None, |
| 164 | + ): |
| 165 | + self.package_name = package_name |
| 166 | + self.url_pattern = url_pattern |
| 167 | + self._system = system().lower() |
| 168 | + self._architecture = machine().lower() |
| 169 | + self._platform_string = get_platform_string(self._system, self._architecture) |
| 170 | + self._extension = get_archive_extension(self._system) |
| 171 | + self._extracted_bin_path = get_extracted_bin_path(self._system) |
| 172 | + |
| 173 | + self._cache_directory: Path |
| 174 | + if cache_directory is None: |
| 175 | + cache_directory = SYSTEM_CACHE_DIR.get(self._system) |
| 176 | + if cache_directory is None: |
| 177 | + raise ValueError(f"Unsupported system: {self._system}") |
| 178 | + self._cache_directory = cache_directory |
| 179 | + else: |
| 180 | + self._cache_directory = Path(cache_directory) |
| 181 | + self._downloads_directory = self._cache_directory / "downloads" |
| 182 | + self._archive_directory = self._cache_directory / self.package_name |
| 183 | + self._packages_directory = self._cache_directory / "packages" |
| 184 | + self._package_directory = self._packages_directory / self.package_name |
| 185 | + self._versions: dict[str, BinaryVersion] = {} |
| 186 | + |
| 187 | + def get_version(self, version: str) -> BinaryVersion: |
| 188 | + """ |
| 189 | + Adds a version to the manager. |
| 190 | +
|
| 191 | + Args: |
| 192 | + version (str): The version to add. |
| 193 | +
|
| 194 | + Returns: |
| 195 | + BinaryVersion object for the added version. |
| 196 | + """ |
| 197 | + if version not in self._versions: |
| 198 | + self._versions[version] = BinaryVersion(version, self) |
| 199 | + return self._versions[version] |
0 commit comments