├── InstallRelease ├── __init__.py ├── constants.py ├── state.py ├── data.py ├── cli.py ├── release_scorer.py ├── utils.py ├── cli_interact.py └── core.py ├── .github ├── images │ └── demo.png ├── dependabot.yml ├── workflows │ ├── publish-pypi.yml │ └── build-binary.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── cli └── __main__.py ├── .pre-commit-config.yaml ├── .editorconfig ├── Taskfile.yml ├── pyproject.toml ├── .gitignore ├── README.md └── LICENSE /InstallRelease/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/images/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishang/install-release/HEAD/.github/images/demo.png -------------------------------------------------------------------------------- /cli/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # This is the entry point for the install-release CLI 3 | 4 | from InstallRelease.cli import app 5 | 6 | if __name__ == "__main__": 7 | app() 8 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/astral-sh/ruff-pre-commit 3 | # Ruff version. 4 | rev: v0.14.3 5 | hooks: 6 | # Run the linter. 7 | - id: ruff-check 8 | # Run the formatter. 9 | - id: ruff-format 10 | 11 | - repo: https://github.com/abravalheri/validate-pyproject 12 | rev: v0.24.1 13 | hooks: 14 | - id: validate-pyproject 15 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/publish-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Publish to PyPI 2 | on: 3 | release: 4 | types: [published] 5 | 6 | permissions: 7 | id-token: write 8 | contents: read 9 | 10 | jobs: 11 | publish: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v4 16 | 17 | - name: Set up Python 18 | uses: actions/setup-python@v4 19 | with: 20 | python-version: "3.9" 21 | 22 | - name: Install uv 23 | uses: astral-sh/setup-uv@v4 24 | 25 | - name: Build and Publish to PyPI 26 | run: | 27 | uv build 28 | uv publish --token ${{ secrets.PYPI_TOKEN }} -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Version [e.g. 22] 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /InstallRelease/constants.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | HOME = os.path.expanduser("~") 4 | 5 | __bin_at__ = "bin" 6 | __dir_name__ = "install_release" 7 | 8 | __state_at__ = f"{__dir_name__}/state.json" 9 | __config_at__ = f"{__dir_name__}/config.json" 10 | 11 | _colors = { 12 | "green": "#8CC265", 13 | "light_green": "#D0FF5E bold", 14 | "blue": "#4AA5F0", 15 | "cyan": "#76F6FF", 16 | "yellow": "#F0A45D bold", 17 | "red": "#E8678A", 18 | "purple": "#8782E9 bold", 19 | } 20 | 21 | 22 | state_path = { 23 | "linux": f"{HOME}/.config/{__state_at__}", 24 | "darwin": f"{HOME}/Library/.config/{__state_at__}", 25 | } 26 | 27 | config_path = { 28 | "linux": f"{HOME}/.config/{__config_at__}", 29 | "darwin": f"{HOME}/Library/.config/{__config_at__}", 30 | } 31 | 32 | bin_path = { 33 | "linux": f"{HOME}/{__bin_at__}", 34 | "darwin": f"{HOME}/{__bin_at__}", 35 | } 36 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # docs 2 | 3 | [*.md] 4 | indent_style = space 5 | indent_size = 2 6 | 7 | 8 | # configs 9 | 10 | [*.tfvars] 11 | indent_style = space 12 | indent_size = 2 13 | 14 | [*.yml] 15 | indent_style = space 16 | indent_size = 2 17 | 18 | [*.toml] 19 | indent_style = space 20 | indent_size = 2 21 | 22 | [*.env] 23 | indent_style = space 24 | indent_size = 2 25 | 26 | [*.json] 27 | indent_style = space 28 | indent_size = 2 29 | 30 | [Makefile] 31 | indent_style = tab 32 | 33 | # lang 34 | 35 | [*.sh] 36 | indent_style = space 37 | indent_size = 2 38 | 39 | [*.rb] 40 | indent_style = space 41 | indent_size = 2 42 | 43 | [*.js] 44 | indent_style = space 45 | indent_size = 2 46 | 47 | [*.go] 48 | indent_style = space 49 | indent_size = 2 50 | 51 | [*.html] 52 | indent_style = space 53 | indent_size = 2 54 | 55 | [*.py] 56 | indent_style = space 57 | indent_size = 4 58 | 59 | [*.tf] 60 | indent_style = space 61 | indent_size = 2 62 | -------------------------------------------------------------------------------- /Taskfile.yml: -------------------------------------------------------------------------------- 1 | version: 3 2 | 3 | tasks: 4 | pkg:install: 5 | desc: Install dependencies with available package manager 6 | requires: 7 | vars: [NAMES] 8 | vars: 9 | MANAGERS: ["yum", "apt-get", "dnf", "apk", "brew", "pacman"] 10 | cmds: 11 | - | 12 | for PM in {{range .MANAGERS}}{{.}} {{end}}; do 13 | if command -v $PM >/dev/null 2>&1; then 14 | echo "Using $PM to install {{.NAMES}}" 15 | case $PM in 16 | yum) sudo yum install -y {{.NAMES}} ;; 17 | apt-get) sudo apt-get install -y {{.NAMES}} ;; 18 | dnf) sudo dnf install -y {{.NAMES}} ;; 19 | apk) sudo apk add {{.NAMES}} ;; 20 | brew) brew install {{.NAMES}} ;; 21 | pacman) sudo pacman -S {{.NAMES}} ;; 22 | esac 23 | exit 0 24 | fi 25 | done 26 | echo "No supported package manager found" >&2 27 | exit 1 28 | 29 | build:cli: 30 | dir: ./ 31 | desc: Build the CLI 32 | vars: 33 | FILENAME: '{{ .FILENAME | default "install-release" }}' 34 | ARGS: '{{ .ARGS | default "" }}' 35 | cmds: 36 | - mkdir -p dist 37 | - uv run python -m nuitka --standalone --onefile {{.ARGS}} --follow-imports cli/__main__.py --output-filename={{.FILENAME}} 38 | - rm -rf __main__.build __main__.onefile-build 39 | - mv {{.FILENAME}} dist/ 40 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "install-release" 3 | version = "0.5.8" 4 | readme = "README.md" 5 | description = "Simple package manager to easily install, update and manage any command-line(CLI) tool directly from github releases" 6 | authors = [ 7 | { name = "Rishang", email = "rishangbhavsarcs@gmail.com" } 8 | ] 9 | 10 | classifiers = [ 11 | "Intended Audience :: Information Technology", 12 | "Intended Audience :: System Administrators", 13 | "Operating System :: OS Independent", 14 | "Programming Language :: Python :: 3", 15 | "Programming Language :: Python", 16 | "Topic :: Software Development :: Libraries :: Python Modules", 17 | "Topic :: Software Development :: Libraries", 18 | "Topic :: Software Development :: Build Tools", 19 | "Topic :: Software Development", 20 | "Typing :: Typed", 21 | "Development Status :: 4 - Beta", 22 | "Intended Audience :: Developers", 23 | 24 | ] 25 | 26 | requires-python = ">=3.9" 27 | dependencies = [ 28 | "python-magic>=0.4.27", 29 | "requests>=2.32.5", 30 | "rich>=14.1.0", 31 | "typer>=0.17.3", 32 | "zstandard>=0.24.0", 33 | ] 34 | 35 | [project.urls] 36 | Homepage = "https://github.com/Rishang/install-release" 37 | Documentation = "https://github.com/Rishang/install-release" 38 | Repository = "https://github.com/Rishang/install-release" 39 | Issues = "https://github.com/Rishang/install-release/issues" 40 | Changelog = "https://github.com/Rishang/install-release/release" 41 | 42 | 43 | [dependency-groups] 44 | dev = [ 45 | "mypy>=1.17.1", 46 | "nuitka>=2.7.13", 47 | "pre-commit>=4.3.0", 48 | "ruff>=0.12.12", 49 | "setuptools", 50 | "types-requests>=2.32.4.20250809", 51 | ] 52 | 53 | [build-system] 54 | requires = ["setuptools>=42"] 55 | build-backend = "setuptools.build_meta" 56 | 57 | [tool.uv] 58 | package = true 59 | 60 | [tool.setuptools.packages.find] 61 | include = ["InstallRelease*"] 62 | 63 | [project.scripts] 64 | install-release = "InstallRelease.cli:app" 65 | ir = "InstallRelease.cli:app" 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # Nuitka 31 | # Usually these files are written by a python script from a template 32 | # before Nuitka builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | *.build 36 | *.onefile-build 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 97 | __pypackages__/ 98 | 99 | # Celery stuff 100 | celerybeat-schedule 101 | celerybeat.pid 102 | 103 | # SageMath parsed files 104 | *.sage.py 105 | 106 | # Environments 107 | .env 108 | .venv 109 | env/ 110 | venv/ 111 | ENV/ 112 | env.bak/ 113 | venv.bak/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | .dmypy.json 128 | dmypy.json 129 | 130 | # Pyre type checker 131 | .pyre/ 132 | .venv 133 | 134 | # temp 135 | tmp-* 136 | tmp 137 | temp 138 | temp-* 139 | __main__.* 140 | !__main__.py -------------------------------------------------------------------------------- /InstallRelease/state.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import platform 4 | from typing import Dict 5 | import dataclasses 6 | 7 | # locals 8 | from InstallRelease.utils import logger, EnhancedJSONEncoder, FilterDataclass 9 | 10 | 11 | def platform_path(paths: Dict[str, str], alt: str = "") -> str: 12 | """Provide path based on platform 13 | 14 | Args: 15 | paths: Dictionary mapping platform names to paths 16 | alt: Alternative path to use if provided 17 | 18 | Returns: 19 | The selected path for the current platform 20 | 21 | Raises: 22 | SystemExit: If no path is configured for the current platform 23 | """ 24 | system = platform.system().lower() 25 | 26 | if alt and alt != "null": 27 | return alt 28 | 29 | elif system in paths: 30 | p = paths[system] 31 | 32 | # Check and create directory if needed 33 | dir_path = os.path.dirname(p) 34 | if dir_path and not os.path.exists(dir_path): 35 | os.makedirs(dir_path) 36 | return p 37 | else: 38 | logger.error(f"No state dir path set for {system}") 39 | exit(1) 40 | 41 | 42 | class State: 43 | def __init__(self, file_path: str, obj): 44 | self.state: dict = {} 45 | self.cache: object 46 | self.state_file = file_path 47 | self.obj = obj 48 | self.load() 49 | 50 | def load(self): 51 | if os.path.exists(self.state_file): 52 | with open(self.state_file, "r") as f: 53 | _s = json.load(f) 54 | if len(_s) == 0: 55 | return 56 | for k in _s: 57 | if dataclasses.is_dataclass(self.obj): 58 | self.state[k] = FilterDataclass(_s[k], obj=self.obj) 59 | 60 | def save(self): 61 | with open(self.state_file, "w") as f: 62 | json.dump(self.state, f, cls=EnhancedJSONEncoder) 63 | 64 | def get(self, key: str) -> Dict: 65 | return self.state.get(key) # type: ignore 66 | 67 | def set(self, key: str, value): 68 | self.state[key] = value 69 | 70 | def items(self): 71 | return self.state.items() 72 | 73 | def keys(self): 74 | return self.state.keys() 75 | 76 | def pop(self, key: str): 77 | self.state.pop(key) 78 | 79 | def __getitem__(self, key: str) -> Dict: 80 | return self.state[key] 81 | 82 | def __setitem__(self, key: str, value: Dict): 83 | self.state[key] = value 84 | self.save() 85 | 86 | def __delitem__(self, key: str): 87 | del self.state[key] 88 | self.save() 89 | 90 | def __contains__(self, key: str) -> bool: 91 | return key in self.state 92 | 93 | def __len__(self) -> int: 94 | return len(self.state) 95 | 96 | def __repr__(self) -> str: 97 | return repr(self.state) 98 | 99 | def __eq__(self, other: object) -> bool: 100 | return self.state == other 101 | 102 | def __ne__(self, other: object) -> bool: 103 | return self.state != other 104 | -------------------------------------------------------------------------------- /.github/workflows/build-binary.yml: -------------------------------------------------------------------------------- 1 | name: Build Binary Executable 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | upload_to_release: 6 | description: "Upload to release (provide tag name, e.g., v1.0.0)" 7 | required: false 8 | type: string 9 | release: 10 | types: [published] 11 | 12 | permissions: 13 | id-token: write 14 | contents: write 15 | 16 | jobs: 17 | build: 18 | strategy: 19 | matrix: 20 | include: 21 | - os: ubuntu-latest 22 | executable: install-release-linux-x86_64 23 | pkg_deps: patchelf 24 | build_args: "" 25 | - os: ubuntu-24.04-arm 26 | executable: install-release-linux-aarch64 27 | pkg_deps: patchelf 28 | build_args: "" 29 | # - os: windows-latest 30 | # executable: install-release-windows.exe 31 | # pkg_deps: "" 32 | # build_args: "--windows-disable-console --assume-yes-for-downloads" 33 | - os: macos-latest 34 | executable: install-release-darwin 35 | pkg_deps: patchelf libmagic 36 | build_args: "--onefile-tempdir-spec=/tmp/nuitka-extract/install-release" 37 | runs-on: ${{ matrix.os }} 38 | steps: 39 | - name: Checkout code 40 | uses: actions/checkout@v4 41 | 42 | - name: Install Task 43 | uses: arduino/setup-task@v2 44 | with: 45 | repo-token: ${{ secrets.GITHUB_TOKEN }} 46 | 47 | - name: Set up Python 48 | uses: actions/setup-python@v4 49 | with: 50 | python-version: "3.13" 51 | 52 | - name: Install uv 53 | uses: astral-sh/setup-uv@v4 54 | 55 | - name: Install dependencies 56 | run: uv sync --all-groups --dev 57 | 58 | - name: Install system dependencies 59 | if: matrix.pkg_deps != '' 60 | run: task pkg:install NAMES="${{ matrix.pkg_deps }}" 61 | 62 | - name: Build CLI 63 | run: task build:cli FILENAME=${{ matrix.executable }} ARGS="${{ matrix.build_args }}" 64 | 65 | - name: Patch executable for macos 66 | if: matrix.os == 'macos-latest' 67 | run: | 68 | xattr -d com.apple.quarantine ./dist/${{ matrix.executable }} || echo "Failed to remove quarantine" 69 | 70 | - name: Test executable 71 | run: | 72 | chmod +x ./dist/${{ matrix.executable }} 73 | ./dist/${{ matrix.executable }} --help 74 | 75 | - name: Upload Artifact 76 | uses: actions/upload-artifact@v4 77 | with: 78 | name: install-release-${{ matrix.os }} 79 | path: dist/${{ matrix.executable }} 80 | 81 | - name: Get latest release tag 82 | if: github.event_name == 'workflow_dispatch' && inputs.upload_to_release == '' 83 | id: latest_release 84 | run: | 85 | LATEST_TAG=$(gh release list --limit 1 --json tagName --jq '.[0].tagName') 86 | echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT 87 | env: 88 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 89 | 90 | - name: Upload GitHub Release Assets 91 | if: github.event_name == 'release' || github.event_name == 'workflow_dispatch' 92 | uses: softprops/action-gh-release@v2 93 | with: 94 | tag_name: ${{ inputs.upload_to_release || steps.latest_release.outputs.tag || github.ref_name }} 95 | files: | 96 | dist/${{ matrix.executable }} 97 | env: 98 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /InstallRelease/data.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from typing import List, Dict, Optional 3 | from dataclasses import dataclass, fields, field 4 | 5 | 6 | exception_compressed_mime_type = [ 7 | "application/x-7z-compressed", 8 | ] 9 | 10 | 11 | @dataclass 12 | class OsInfo: 13 | architecture: List[str] 14 | platform: str 15 | platform_words: List[str] 16 | 17 | 18 | @dataclass 19 | class RepositoryInfo: 20 | name: str 21 | full_name: str 22 | html_url: str 23 | description: str 24 | language: str 25 | stargazers_count: int 26 | 27 | def __init__(self, **kwargs): 28 | names = set([f.name for f in fields(self)]) 29 | for k, v in kwargs.items(): 30 | if k in names: 31 | setattr(self, k, v) 32 | 33 | 34 | @dataclass 35 | class ReleaseAssets: 36 | browser_download_url: str 37 | content_type: str 38 | created_at: str 39 | download_count: int 40 | id: int 41 | name: str 42 | node_id: str 43 | size: int 44 | state: str 45 | updated_at: str 46 | 47 | def __init__(self, **kwargs): 48 | names = set([f.name for f in fields(self)]) 49 | for k, v in kwargs.items(): 50 | if k in names: 51 | setattr(self, k, v) 52 | 53 | def __post_init__(self): 54 | self.updated_at_dt = datetime.strptime(self.created_at, "%Y-%m-%dT%XZ") 55 | 56 | def size_mb(self) -> float: 57 | return float(str(self.size / 1000000)[:4]) 58 | 59 | 60 | @dataclass 61 | class Release: 62 | url: str 63 | name: str 64 | tag_name: str 65 | prerelease: bool 66 | published_at: str 67 | assets: List[ReleaseAssets] 68 | hold_update: Optional[bool] = field(default=False) 69 | custom_release_words: Optional[List[str]] = field(default=None) 70 | # author: dict 71 | # draft: bool 72 | # target_commitish: str 73 | 74 | def __post_init__(self): 75 | # Handle both dictionary and ReleaseAssets objects in the assets list 76 | processed_assets = [] 77 | for a in self.assets: 78 | if isinstance(a, ReleaseAssets): 79 | processed_assets.append(a) 80 | elif isinstance(a, dict): 81 | processed_assets.append(ReleaseAssets(**a)) 82 | else: 83 | raise TypeError(f"Unsupported asset type: {type(a)}") 84 | self.assets = processed_assets 85 | 86 | def published_dt(self): 87 | # Try different date formats commonly used by GitHub and GitLab 88 | for fmt in ["%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S.%fZ"]: 89 | try: 90 | return datetime.strptime(self.published_at, fmt) 91 | except ValueError: 92 | continue 93 | 94 | # If all formats fail, raise an exception with helpful message 95 | raise ValueError(f"Cannot parse date: {self.published_at}") 96 | 97 | 98 | @dataclass 99 | class ToolConfig: 100 | token: Optional[str] = field(default_factory=str) 101 | gitlab_token: Optional[str] = field(default_factory=str) 102 | path: Optional[str] = field(default_factory=str) 103 | pre_release: Optional[bool] = field(default=False) 104 | 105 | 106 | class irKey: 107 | def __init__(self, value): 108 | self.name = value.split("#")[-1] 109 | self.url = value.split("#")[0] 110 | 111 | 112 | # ---------- Type Aliases ----------- # 113 | 114 | TypeState = Dict[str, Release] 115 | -------------------------------------------------------------------------------- /InstallRelease/cli.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from typing import Optional 4 | 5 | # pipi 6 | import typer 7 | 8 | # locals 9 | from InstallRelease.utils import pprint, logger 10 | from InstallRelease.cli_interact import ( 11 | pull_state, 12 | get as _get, 13 | upgrade as _upgrade, 14 | remove, 15 | list_install, 16 | show_state, 17 | hold, 18 | cache_config, 19 | config, 20 | install_release_version, 21 | ) 22 | from InstallRelease.core import get_repo_info 23 | 24 | 25 | def see_help(arg: str = ""): 26 | pprint( 27 | f"This command required arguments, use [yellow]{arg} --help[reset] to see them" 28 | ) 29 | exit(1) 30 | 31 | 32 | # cli debug type alias 33 | __optionDebug = typer.Option(False, "-v", help="set verbose mode.") 34 | __optionQuite = typer.Option(False, "-q", help="set quite mode.") 35 | __optionForce = typer.Option(False, "-F", help="set force.") 36 | __optionSkipPrompt = typer.Option(False, "-y", help="skip confirmation (y/n) prompt.") 37 | 38 | 39 | def setLogger(quite: Optional[bool] = None, debug: Optional[bool] = None) -> None: 40 | """Set logger level based on verbosity options 41 | 42 | Args: 43 | quite: Enable quiet mode (fewer messages) 44 | debug: Enable debug mode (more messages) 45 | """ 46 | if debug: 47 | logger.setLevel(logging.DEBUG) 48 | elif quite: 49 | logger.setLevel(logging.ERROR) 50 | 51 | 52 | if os.environ.get("IR_DEBUG", "").lower() == "true": 53 | setLogger(debug=True) 54 | 55 | app = typer.Typer( 56 | help="GitHub / GitLab release installer based on your system (Linux/MacOS). Repo: https://github.com/Rishang/install-release", 57 | pretty_exceptions_enable=False, 58 | ) 59 | 60 | 61 | @app.command() 62 | def get( 63 | debug: bool = __optionDebug, 64 | quite: bool = __optionQuite, 65 | url: str = typer.Argument(None, help="[URL] of GitHub/GitLab repository"), 66 | tag_name: str = typer.Option("", "-t", help="get a specific tag version."), 67 | release_file: str = typer.Option("", "-r", help="get release by filename pattern."), 68 | name: str = typer.Option( 69 | "", 70 | "-n", 71 | help="tool name you want, Only for releases having different tools in releases", 72 | ), 73 | approve: bool = typer.Option(False, "-y", help="Approve without Prompt"), 74 | ): 75 | """ 76 | | Install GitHub/GitLab repository CLI tool from its releases 77 | """ 78 | 79 | setLogger(quite, debug) 80 | if url is None or url == "": 81 | see_help("get") 82 | 83 | _url = url 84 | url = "/".join(_url.split("/")[:5]) 85 | 86 | repo = get_repo_info(url, token=config.token, gitlab_token=config.gitlab_token) 87 | 88 | _get( 89 | repo, 90 | tag_name=tag_name, 91 | release_file=release_file, 92 | prompt=not approve, 93 | name=name, 94 | ) 95 | 96 | 97 | @app.command() 98 | def upgrade( 99 | debug: bool = __optionDebug, 100 | quite: bool = __optionQuite, 101 | force: bool = __optionForce, 102 | skip_prompt: bool = __optionSkipPrompt, 103 | ): 104 | """ 105 | | Upgrade all installed CLI tools from their repositories 106 | """ 107 | setLogger(quite, debug) 108 | local_version = install_release_version.local_version() 109 | latest_version = install_release_version.latest_version() 110 | logger.debug(f"local_version: {local_version}") 111 | logger.debug(f"latest_version: {latest_version}") 112 | # if local_version != latest_version: 113 | # pprint( 114 | # "[bold]***INFO: New version of install-release is available, " 115 | # "run [yellow]ir me --upgrade[reset] to update. ***\n" 116 | # ) 117 | _upgrade(force=force, skip_prompt=skip_prompt) 118 | 119 | 120 | @app.command() 121 | def ls( 122 | hold: bool = typer.Option( 123 | False, 124 | "--hold", 125 | help="list of tools which are kept on hold", 126 | ), 127 | ): 128 | """ 129 | | List all installed CLI tools 130 | """ 131 | list_install(hold_update=hold) 132 | 133 | 134 | @app.command() 135 | def rm( 136 | name: str = typer.Argument(None, help="name of installed tool to remove"), 137 | debug: bool = __optionDebug, 138 | ): 139 | """ 140 | | Remove any installed CLI tool 141 | """ 142 | setLogger(debug=debug) 143 | 144 | remove(name) 145 | 146 | 147 | @app.command(name="config") 148 | def _config( 149 | debug: bool = __optionDebug, 150 | token: str = typer.Option( 151 | "", 152 | "--token", 153 | help="set your GitHub token to solve API rate-limiting issue", 154 | ), 155 | gitlab_token: str = typer.Option( 156 | "", 157 | "--gitlab-token", 158 | help="set your GitLab token to solve API rate-limiting issue", 159 | ), 160 | path: str = typer.Option( 161 | "", 162 | "--path", 163 | help="set install path", 164 | ), 165 | pre_release: bool = typer.Option( 166 | False, "--pre-release", help="Also include pre-releases while checking updates." 167 | ), 168 | ): 169 | """ 170 | | Set configs for Install-Release 171 | """ 172 | 173 | setLogger(debug=debug) 174 | 175 | logger.info(f"Loading config: {cache_config.state_file}") 176 | 177 | if token != "": 178 | config.token = token 179 | logger.info("Updated GitHub token") 180 | if gitlab_token != "": 181 | config.gitlab_token = gitlab_token 182 | logger.info("Updated GitLab token") 183 | if path != "": 184 | config.path = path 185 | logger.info(f"Updated path to {path}") 186 | 187 | config.pre_release = pre_release 188 | 189 | cache_config.save() 190 | logger.info("Done.") 191 | 192 | 193 | @app.command() 194 | def state(debug: bool = __optionDebug): 195 | """ 196 | | Show the current stored state of Install-Release 197 | """ 198 | setLogger(debug=debug) 199 | show_state() 200 | 201 | 202 | @app.command() 203 | def pull( 204 | debug: bool = __optionDebug, 205 | url: str = typer.Option( 206 | "", 207 | "--url", 208 | help="Install tools from the remote state URL", 209 | ), 210 | override: bool = typer.Option( 211 | False, 212 | "-O", 213 | help="Enable Override local tool version with remote install-release state version.", 214 | ), 215 | ): 216 | """ 217 | | Install tools from the remote install-release state URL 218 | """ 219 | setLogger(debug=debug) 220 | 221 | if url is None or url == "": 222 | see_help("pull") 223 | 224 | pull_state(url, override) 225 | 226 | 227 | @app.command(name="hold") 228 | def _hold( 229 | name: str = typer.Argument( 230 | None, help="Name of CLI tool for which updates will be kept on hold" 231 | ), 232 | unset: bool = typer.Option(True, "--unset", help="unset from hold."), 233 | ): 234 | """ 235 | | Keep updates an installed CLI tool on hold. 236 | """ 237 | hold(name, hold_update=unset) 238 | 239 | 240 | @app.command(name="me") 241 | def me( 242 | update: bool = typer.Option( 243 | False, "--upgrade", "-U", help="Update Install-Release tool." 244 | ), 245 | version: bool = typer.Option( 246 | False, "--version", help="print version of Install-Release tool." 247 | ), 248 | ): 249 | """ 250 | | Update Install-Release tool. 251 | """ 252 | 253 | _v = install_release_version._local_version 254 | 255 | if update: 256 | _cmd = "ir get https://github.com/Rishang/install-release" 257 | pprint(f"Running: {_cmd}") 258 | 259 | os.system(_cmd) 260 | pprint( 261 | "\n\nNote: If update failed, with message `[red]error: externally-managed-environment[reset]` " 262 | "then try running below command,\n" 263 | f"command: [yellow]{_cmd} --break-system-packages[reset]" 264 | ) 265 | elif version: 266 | pprint(_v) 267 | else: 268 | pprint(f"Version: {_v}") 269 | pprint("Repo: https://github.com/Rishang/install-release") 270 | 271 | 272 | if __name__ == "__main__": 273 | app() 274 | -------------------------------------------------------------------------------- /InstallRelease/release_scorer.py: -------------------------------------------------------------------------------- 1 | import re 2 | import platform 3 | import subprocess 4 | from typing import List, Optional, Tuple, Dict, Any 5 | from InstallRelease.utils import logger, to_words 6 | 7 | platform_arch_aliases = { 8 | "x86_64": ["x86", "x64", "amd64", "amd", "x86_64"], 9 | "aarch64": ["arm64", "aarch64", "arm"], 10 | } 11 | 12 | 13 | class ReleaseScorer: 14 | """Simple class to score release names based on platform compatibility""" 15 | 16 | def __init__( 17 | self, extra_words: Optional[List[str]] = None, disable_penalties: bool = False 18 | ): 19 | """Initialize the scorer with platform words and extra matching words 20 | 21 | Args: 22 | platform_words: List of platform-specific words to match 23 | extra_words: Additional words to match against 24 | disable_penalties: Whether to disable penalties 25 | """ 26 | self.platform = platform.system().lower() 27 | self.architecture = platform.machine() 28 | self.is_glibc_system = self._detect_glibc() 29 | self.platform_words = self._platform_words() 30 | self.extra_words = extra_words or [] 31 | self.disable_penalties = disable_penalties 32 | 33 | # Combine all patterns for matching with weights 34 | self.pattern_weights = {} 35 | self.all_patterns = [] 36 | 37 | # Platform words get highest weight (5x for OS, 3x for arch) 38 | for word in self.platform_words: 39 | self.all_patterns.append(word) 40 | # Give OS platform higher weight than architecture 41 | if word == self.platform: 42 | self.pattern_weights[word] = 5.0 # OS gets highest priority 43 | elif any(word in aliases for aliases in platform_arch_aliases.values()): 44 | self.pattern_weights[word] = ( 45 | 3.0 # Architecture aliases get medium weight 46 | ) 47 | elif word in ["64bit", "32bit"] or "bit" in word: 48 | self.pattern_weights[word] = 1.0 # Architecture bits get lower weight 49 | else: 50 | self.pattern_weights[word] = 2.0 # Other platform words 51 | 52 | # Extra words get medium weight (2x) 53 | for word in self.extra_words: 54 | self.all_patterns.append(word) 55 | self.pattern_weights[word] = 2.0 56 | 57 | # Archive extensions get normal weight (1x) 58 | archive_pattern = r"\.(tar|zip|gz|bz2|xz|7z|rar)" 59 | self.all_patterns.append(archive_pattern) 60 | self.pattern_weights[archive_pattern] = 1.0 61 | 62 | logger.debug(f"ReleaseScorer initialized with patterns: {self.all_patterns}") 63 | logger.debug(f"Pattern weights: {self.pattern_weights}") 64 | logger.debug(f"Is glibc system: {self.is_glibc_system}") 65 | 66 | def _platform_words(self) -> list: 67 | words = [platform.system().lower(), platform.architecture()[0]] 68 | 69 | for alias in platform_arch_aliases: 70 | if platform.machine().lower() in platform_arch_aliases[alias]: 71 | words += platform_arch_aliases[alias] 72 | 73 | try: 74 | sys_alias = platform.platform().split("-")[0].lower() 75 | 76 | if platform.system().lower() != sys_alias: 77 | words.append(sys_alias) 78 | except Exception: 79 | pass 80 | 81 | if not self.is_glibc_system: 82 | words.append("musl") 83 | 84 | return words 85 | 86 | def _detect_glibc(self) -> bool: 87 | """Detect if the system is using glibc""" 88 | try: 89 | result = subprocess.run( 90 | ["ldd", "--version"], capture_output=True, text=True 91 | ) 92 | output = (result.stdout + result.stderr).lower() 93 | return "glibc" in output or "gnu" in output 94 | except Exception: 95 | return False 96 | 97 | def _calculate_pattern_match_score(self, release_name: str) -> float: 98 | """Calculate base score based on weighted pattern matching 99 | 100 | Args: 101 | release_name: Name of the release 102 | 103 | Returns: 104 | Weighted score based on pattern matches 105 | """ 106 | total_weight = 0.0 107 | matched_weight = 0.0 108 | release_name_lower = release_name.lower() 109 | 110 | for pattern in self.all_patterns: 111 | weight = self.pattern_weights.get(pattern, 1.0) 112 | total_weight += weight 113 | 114 | if re.search(pattern.lower(), release_name_lower): 115 | matched_weight += weight 116 | 117 | if total_weight == 0: 118 | return 0.0 119 | 120 | return matched_weight / total_weight 121 | 122 | def _apply_penalties_and_bonuses(self, score: float, release_name: str) -> float: 123 | """Apply penalties and bonuses to the base score 124 | 125 | Args: 126 | score: Base score from pattern matching 127 | release_name: Name of the release 128 | 129 | Returns: 130 | Adjusted score after applying penalties/bonuses 131 | """ 132 | adjusted_score = score 133 | release_name_lower = release_name.lower() 134 | penalty_words = [ 135 | "debug", 136 | "dbg", 137 | ".json", 138 | ".txt", 139 | ".yaml", 140 | ".yml", 141 | ".md", 142 | ".jsonl", 143 | ] 144 | 145 | # Apply penalty for musl releases on glibc systems 146 | if self.is_glibc_system and "musl" in release_name_lower: 147 | adjusted_score *= 0.8 # 20% penalty 148 | logger.debug( 149 | f"Applied musl penalty to '{release_name}': {score} -> {adjusted_score}" 150 | ) 151 | 152 | # Apply bonus for glibc releases on glibc systems 153 | elif self.is_glibc_system and any( 154 | word in release_name_lower for word in ["glibc", "gnu"] 155 | ): 156 | adjusted_score *= 1.05 # 5% bonus 157 | 158 | logger.debug( 159 | f"Applied glibc bonus to '{release_name}': {score} -> {adjusted_score}" 160 | ) 161 | 162 | # Apply penalty for debug releases or unwanted words 163 | if any(word in release_name_lower for word in penalty_words): 164 | adjusted_score *= 0.8 # 20% penalty 165 | 166 | logger.debug(f"Applied debug penalty to '{release_name}': {adjusted_score}") 167 | 168 | return adjusted_score 169 | 170 | def score(self, release_name: str) -> float: 171 | """Score a release name 172 | 173 | Args: 174 | release_name: Name of the release to score 175 | 176 | Returns: 177 | Score between 0 and 1, higher is better 178 | """ 179 | base_score = self._calculate_pattern_match_score(release_name) 180 | if not self.disable_penalties and self.extra_words != []: 181 | final_score = self._apply_penalties_and_bonuses(base_score, release_name) 182 | else: 183 | final_score = base_score 184 | 185 | logger.debug( 186 | f"name: '{release_name}', base_score: {base_score}, final_score: {final_score}" 187 | ) 188 | 189 | return final_score 190 | 191 | def score_multiple(self, release_names: List[str]) -> List[Tuple[str, float]]: 192 | """Score multiple release names 193 | 194 | Args: 195 | release_names: List of release names to score 196 | 197 | Returns: 198 | List of tuples (release_name, score) sorted by score descending 199 | """ 200 | scores = [(name, self.score(name)) for name in release_names] 201 | return sorted(scores, key=lambda x: x[1], reverse=True) 202 | 203 | def select_best( 204 | self, release_names: List[str], min_score: float = 0.2 205 | ) -> Optional[str]: 206 | """Select the best release name from a list 207 | 208 | Args: 209 | release_names: List of release names to choose from 210 | 211 | Returns: 212 | The best release name or None if no valid matches 213 | """ 214 | if not release_names: 215 | return None 216 | 217 | scored = self.score_multiple(release_names) 218 | logger.debug(f"Scored: {scored}") 219 | 220 | # Filter out releases with zero score 221 | valid_scores = [item for item in scored if item[1] > 0] 222 | 223 | if not valid_scores: 224 | return None 225 | 226 | best_name, best_score = valid_scores[0] 227 | 228 | # If penalties are disabled, check if the best match has the same number of words as the extra words 229 | # extra words will be the user manual input of release file name pattern 230 | if self.disable_penalties: 231 | for name, score in valid_scores: 232 | words = to_words(name) 233 | if len(words) == len(self.extra_words): 234 | logger.debug("Overwritten best name and score") 235 | best_name = name 236 | best_score = score 237 | break 238 | 239 | logger.debug(f"Selected: '{best_name}' with score: {best_score}") 240 | if best_score < min_score: 241 | logger.debug( 242 | f"Warning: Best match has low probability (score: {best_score})" 243 | ) 244 | 245 | return best_name 246 | 247 | def get_info(self) -> Dict[str, Any]: 248 | """Get information about the scorer configuration 249 | 250 | Returns: 251 | Dictionary with scorer configuration details 252 | """ 253 | return { 254 | "platform_words": self.platform_words, 255 | "extra_words": self.extra_words, 256 | "all_patterns": self.all_patterns, 257 | "pattern_weights": self.pattern_weights, 258 | "is_glibc_system": self.is_glibc_system, 259 | "platform": self.platform, 260 | "architecture": self.architecture, 261 | } 262 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 🚀 Install Release 3 |

4 | 5 |

6 | 7 | Python Version 8 | 9 | 10 | Downloads 11 | 12 |

13 | 14 | **Install Release** is a CLI tool by name `ir` to install any single-binary executable package for your device(Linux/MacOS/WSL) directly from their GitHub or GitLab releases and keep them updated. Consider it as a small package manager to install single binary tools from GitHub/GitLab releases. 15 | 16 | This can be any tool you want to install, which is pre-compiled for your device and present on GitHub or GitLab releases. 17 | 18 | > INFO: It's mainly for installing tools that are not directly available officially by package managers like `apt, yum, pacman, brew` etc. 19 | 20 | 21 | 22 | ## Table of Contents 📚 23 | 24 | - [Table of Contents 📚](#table-of-contents-) 25 | - [Getting started ⚡](#getting-started-) 26 | - [Prerequisites 📋](#prerequisites-) 27 | - [Install `install-release` package 📦](#install-install-release-package-) 28 | - [Updating `install-release` 🔄](#updating-install-release-) 29 | - [Example usage `ir --help` 💡](#example-usage-ir---help-) 30 | - [Install completion for cli 🎠](#install-completion-for-cli-) 31 | - [Install tool from GitHub/GitLab releases 🌈](#install-tool-from-githubgitlab-releases-) 32 | - [List installed tools 📋](#list-installed-tools-) 33 | - [Remove installed release ❌](#remove-installed-release-) 34 | - [Update all previously installed tools to the latest version 🕶️](#update-all-previously-installed-tools-to-the-latest-version-️) 35 | - [Pull state templates for installing tools 📄](#pull-state-templates-for-installing-tools-) 36 | - [Hold Update to specific installed tool ✋](#hold-update-to-specific-installed-tool-) 37 | - [Config tool installation path 🗂️](#config-tool-installation-path-️) 38 | - [Config updates for pre-release versions 🔌](#config-updates-for-pre-release-versions-) 39 | - [Configure GitHub/GitLab tokens for higher rate limit 🔑](#configure-githubgitlab-tokens-for-higher-rate-limit-) 40 | - [Configure custom release file 🔦](#configure-custom-release-file-) 41 | 42 | ## Getting started ⚡ 43 | 44 | ```bash 45 | # Install ir 46 | pip install -U install-release 47 | ``` 48 | 49 | Example Installation a tool named [deno](https://github.com/denoland/deno)(A modern runtime for JavaScript and TypeScript) directly from its GitHub releases. 50 | 51 | ```bash 52 | # ir get [GITHUB-URL or GITLAB-URL] 53 | 54 | # Example install deno tool from github 55 | ❯ ir get https://github.com/denoland/deno 56 | 57 | # Or for GitLab repositories 58 | 59 | # Example: Install gitlab cli tool from gitlab as binary name `glab` 60 | ❯ ir get https://gitlab.com/gitlab-org/cli -n glab 61 | ``` 62 | 63 | ![demo](https://raw.githubusercontent.com/Rishang/install-release/main/.github/images/demo.png) 64 | 65 | Checking for deno is installed by `install-release`: 66 | 67 | ``` 68 | ❯ which deno 69 | ~/bin/deno 70 | 71 | ❯ deno --version 72 | deno 1.46.3 (stable, release, x86_64-unknown-linux-gnu) 73 | v8 12.9.202.5-rusty 74 | typescript 5.5.2 75 | ``` 76 | 77 | ## Prerequisites 📋 78 | 79 | - python3.8 or higher 80 | 81 | - [libmagic](https://github.com/ahupp/python-magic#installation) 82 | - Default releases Installation Path is: `~/bin/`, 83 | This is the path where installed tools will get stored. 84 | 85 | - In order to run installed tools, you need to add the following line to your `~/.bashrc` or `~/.zshrc` file: 86 | 87 | ```bash 88 | export PATH=$HOME/bin:$PATH 89 | ``` 90 | 91 | ## Install `install-release` package 📦 92 | 93 | ```bash 94 | pip install -U install-release 95 | ``` 96 | 97 | ## Updating `install-release` 🔄 98 | 99 | For seeing version: 100 | 101 | ```bash 102 | ir me --version 103 | ``` 104 | 105 | For updating: 106 | 107 | ```bash 108 | ir me --upgrade 109 | ``` 110 | 111 | ## Example usage `ir --help` 💡 112 | 113 | ``` 114 | # Help page 115 | 116 | ❯ ir --help 117 | Usage: ir [OPTIONS] COMMAND [ARGS]... 118 | 119 | GitHub Release Installer, based on your system 120 | 121 | Commands: 122 | get | Install GitHub/GitLab release, cli tool 123 | ls | list all installed releases, cli tools 124 | rm | remove any installed release, cli tools 125 | upgrade | Upgrade all installed releases, cli tools 126 | state | show currently stored state 127 | config | Set configs for tool 128 | pull | Install tools from a remote state 129 | hold | Keep updates a tool on hold. 130 | me | Update ir tool. 131 | ``` 132 | 133 | For sub-command help use: `ir --help` 134 | 135 | Example: `ir get --help` 136 | 137 | #### Install completion for cli 🎠 138 | 139 | ```bash 140 | # ir --install-completion [SHELL: bash|zsh|fish|powershell] 141 | # Example for zsh: 142 | ir --install-completion zsh 143 | ``` 144 | 145 | #### Install tool from GitHub/GitLab releases 🌈 146 | 147 | ```bash 148 | ❯ ir get "https://github.com/ahmetb/kubectx" 149 | 150 | 📑 Repo : ahmetb/kubectx 151 | 🌟 Stars : 13295 152 | ✨ Language : Go 153 | 🔥 Title : Faster way to switch between clusters and namespaces in kubectl 154 | 155 | 🚀 Install: kubectx 156 | ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━┓ 157 | ┃ Name ┃ Selected Item ┃ Version ┃ Size Mb ┃ Downloads ┃ 158 | ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━┩ 159 | │ kubectx │ kubectx_v0.9.4_linux_x86_64.tar.gz │ v0.9.4 │ 1.0 │ 43811 │ 160 | └─────────┴────────────────────────────────────┴─────────┴─────────┴───────────┘ 161 | Install this tool (Y/n): y 162 | INFO Downloaded: 'kubectx_v0.9.4_linux_x86_64.tar.gz' at /tmp/dn_kubectx_ph6i7dmk utils.py:159 163 | INFO install /tmp/dn_kubectx_ph6i7dmk/kubectx /home/noobi/bin/kubectx core.py:132 164 | INFO Installed: kubectx 165 | ``` 166 | 167 | ``` 168 | # checking if kubectx is installed 169 | ❯ which kubectx 170 | /home/noobi/bin/kubectx 171 | 172 | ❯ kubectx --version 173 | 0.9.4 174 | ``` 175 | 176 | #### List installed tools 📋 177 | 178 | ```bash 179 | ❯ ir ls 180 | 181 | Installed tools 182 | ┏━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ 183 | ┃ Name ┃ Version ┃ Url ┃ 184 | ┡━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ 185 | │ terrascan │ v1.15.2 │ https://github.com/tenable/terrascan │ 186 | │ gron │ v0.7.1 │ https://github.com/tomnomnom/gron │ 187 | │ kubectx │ v0.9.4 │ https://github.com/ahmetb/kubectx │ 188 | └───────────┴─────────┴──────────────────────────────────────┘ 189 | ``` 190 | 191 | #### Remove installed release ❌ 192 | 193 | ```bash 194 | # Remove installed release 195 | 196 | ❯ ir rm gron 197 | 198 | INFO Removed: gron 199 | ``` 200 | 201 | #### Update all previously installed tools to the latest version 🕶️ 202 | 203 | ```bash 204 | ❯ ir upgrade 205 | 206 | Fetching: https://github.com/tenable/terrascan#terrascan 207 | Fetching: https://github.com/ahmetb/kubectx#kubectx 208 | 209 | Following tools will be upgraded: 210 | 211 | terrascan 212 | 213 | Upgrade these tools, (Y/n): y 214 | 215 | Updating: terrascan, v1.15.0 => v1.15.2 216 | INFO Downloaded: 'terrascan_1.15.2_Linux_x86_64.tar.gz' at /tmp/dn_terrascan_0as71a6v 217 | INFO install /tmp/dn_terrascan_0as71a6v/terrascan ~/bin/terrascan 218 | INFO Installed: terrascan 219 | 220 | Progress... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00 221 | ``` 222 | 223 | #### Pull state templates for installing tools 📄 224 | 225 | You can push your state to somewhere like GitHub and use it for any other device, to make a sync for tools installed via ir 226 | 227 | ```bash 228 | ❯ ir pull --url https://raw.githubusercontent.com/Rishang/dotFiles/main/templates/install-release/state.json 229 | ``` 230 | 231 | #### Hold Update to specific installed tool ✋ 232 | 233 | In case you want to hold an update to the specific tool, you can use `hold {tool-name}` command which will pause update for that tool. 234 | 235 | Example: keep tool named [k9s](https://github.com/derailed/k9s) update on hold 236 | 237 | ```bash 238 | ❯ ir hold k9s 239 | INFO Update on hold for, k9s to True 240 | ``` 241 | 242 | You can list tools on hold updates by `ls --hold` command 243 | 244 | ```bash 245 | ❯ ir ls --hold 246 | Installed tools kept on hold 247 | ┏━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ 248 | ┃ Name ┃ Version ┃ Url ┃ 249 | ┡━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ 250 | │ k9s │ v0.26.7 │ https://github.com/derailed/k9s │ 251 | └──────┴─────────┴───────────────────────────────────┘ 252 | ``` 253 | 254 | In case you want to unhold update to the specific tool, you can use `hold --unset {tool-name}` command by which it will pause update for that tool. 255 | 256 | ``` 257 | ❯ ir hold --unset k9s 258 | INFO Update on hold for, k9s to False 259 | ``` 260 | 261 | #### Config tool installation path 🗂️ 262 | 263 | ```bash 264 | ❯ ir config --path ~/.local/bin 265 | 266 | INFO updated path to: ~/.local/bin 267 | INFO Done 268 | ``` 269 | 270 | #### Config updates for pre-release versions 🔌 271 | 272 | This is useful when you want to install pre-release versions of tools like beta or alpha releases. By default, it is set to `False` in which case it will only check for latest release. 273 | 274 | ```bash 275 | ❯ ir config --pre-release 276 | ``` 277 | 278 | #### Configure GitHub/GitLab tokens for higher rate limit 🔑 279 | 280 | > For GitHub: 281 | ```bash 282 | ❯ ir config --token [your github token] 283 | 284 | INFO: Updated GitHub token 285 | INFO: Done. 286 | ``` 287 | 288 | > For GitLab: 289 | ```bash 290 | ❯ ir config --gitlab-token [your gitlab token] 291 | 292 | INFO: Updated GitLab token 293 | INFO: Done. 294 | ``` 295 | 296 | #### Configure custom release file 🔦 297 | 298 | In rare cases where install-release does not automatically find the correct release file for your system, you can manually specify the release file name from the GitHub or GitLab release page. 299 | 300 | - The tool will parse the release file name into keywords (removing version numbers and file extensions), then store these keywords in the state file to match the release file name during future tool upgrades. 301 | 302 | > Note: Even though this fixes the issue where `install release` fails to identify correct release package for your system, It will be helpful if you raise Github Issue in this case to make this tool better over the time. 303 | 304 | Usage: 305 | ```bash 306 | ❯ ir get [GITHUB-URL or GITLAB-URL] -r [release file] 307 | ``` 308 | 309 | Example: Installing the bore tool from GitHub with the release file name `bore-v0.4.0-arm-unknown-linux-musleabi.tar.gz`. Here, the keywords generated are: `bore, v0.4.0, arm, linux, musleabi` 310 | 311 | ```bash 312 | ❯ ir get https://github.com/ekzhang/bore -r bore-v0.4.0-arm-unknown-linux-musleabi.tar.gz 313 | ``` 314 | -------------------------------------------------------------------------------- /InstallRelease/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import sys 4 | import json 5 | import bz2 6 | import tarfile 7 | import gzip 8 | import shutil 9 | import logging 10 | import platform 11 | import subprocess 12 | import dataclasses 13 | from pathlib import Path 14 | from typing import List, Dict 15 | from dataclasses import dataclass 16 | from concurrent.futures import ThreadPoolExecutor 17 | from importlib.metadata import version, PackageNotFoundError 18 | 19 | # pipi 20 | import requests 21 | import zstandard as zstd 22 | from rich import print as pprint 23 | from rich.console import Console 24 | from rich.logging import RichHandler 25 | from rich.text import Text 26 | from rich.table import Table 27 | 28 | try: 29 | from magic.compat import detect_from_filename 30 | except ImportError: 31 | pprint( 32 | "[red]Failed to find libmagic. Check your installation\n" 33 | "refer this url to install libmagic first: https://github.com/ahupp/python-magic#installation [/]" 34 | ) 35 | sys.exit(1) 36 | 37 | # logging.basicConfig(level=logging.INFO) 38 | 39 | 40 | # locals 41 | from InstallRelease.constants import _colors 42 | 43 | requests_session = requests.Session() 44 | 45 | console = Console() 46 | 47 | 48 | def _logger(flag: str = "", format: str = ""): 49 | if format == "" or format is None: 50 | format = "%(levelname)s|%(name)s| %(message)s" 51 | 52 | # message 53 | logger = logging.getLogger(__name__) 54 | 55 | if os.environ.get(flag) is not None: 56 | logger.setLevel(logging.DEBUG) 57 | else: 58 | logger.setLevel(logging.INFO) 59 | 60 | # create console handler and set level to debug 61 | # ch = logging.StreamHandler() 62 | # ch.setLevel(logging.DEBUG) 63 | # # create formatter 64 | # # add formatter to ch 65 | # formatter = logging.Formatter(format) 66 | # ch.setFormatter(formatter) 67 | 68 | # # add ch to logger 69 | # logger.addHandler(ch) 70 | handler = RichHandler(log_time_format="") 71 | logger.addHandler(handler) 72 | return logger 73 | 74 | 75 | # message 76 | # export LOG_LEVEL=true 77 | logger = _logger("LOG_LEVEL") 78 | 79 | 80 | class EnhancedJSONEncoder(json.JSONEncoder): 81 | def default(self, o): 82 | if dataclasses.is_dataclass(o): 83 | return dataclasses.asdict(o) 84 | return super().default(o) 85 | 86 | 87 | class PackageVersion: 88 | def __init__(self, package_name: str): 89 | self.package_name = package_name 90 | self.url = f"https://pypi.org/pypi/{package_name}/json" 91 | self._local_version = self.local_version() 92 | self._latest_version = None 93 | 94 | def local_version(self): 95 | try: 96 | _version = version(self.package_name) 97 | return _version 98 | except PackageNotFoundError: 99 | return None 100 | 101 | def latest_version(self): 102 | try: 103 | if self._latest_version is not None: 104 | return self._latest_version 105 | 106 | response = requests_session.get(self.url) 107 | logger.debug( 108 | f"pipi response for package '{self.package_name}': " + str(response) 109 | ) 110 | data = response.json() 111 | version = data["info"]["version"] 112 | self._latest_version = version 113 | 114 | return version 115 | 116 | except requests.RequestException: 117 | print(f"Failed to fetch data for {self.package_name}") 118 | return None 119 | 120 | 121 | def FilterDataclass(data: dict, obj): 122 | """""" 123 | 124 | out: dict = dict() 125 | names = set([f.name for f in dataclasses.fields(obj)]) 126 | for k, v in data.items(): 127 | if k in names: 128 | out[k] = v 129 | return obj(**out) 130 | 131 | 132 | def is_none(val): 133 | if val is None: 134 | return True 135 | elif isinstance(val, str) and val != "": 136 | return False 137 | elif isinstance(val, dict) and val != {}: 138 | return False 139 | elif isinstance(val, list) and val != []: 140 | return False 141 | return True 142 | 143 | 144 | @dataclass 145 | class ShellOutputs: 146 | stdout: List[str] 147 | stderr: List[str] 148 | returncode: int 149 | 150 | 151 | class Shell: 152 | line_breaks = "\n" 153 | popen_args = {"shell": True, "stdout": subprocess.PIPE, "stderr": subprocess.PIPE} 154 | 155 | def console_to_str(self, s): 156 | console_encoding = sys.__stdout__.encoding 157 | 158 | """ From pypa/pip project, pip.backwardwardcompat. License MIT. """ 159 | if s is None: 160 | return 161 | try: 162 | return s.decode(console_encoding, "ignore") 163 | except UnicodeDecodeError: 164 | return s.decode("utf_8", "ignore") 165 | 166 | def str_from_console(self, s): 167 | text_type = str 168 | 169 | try: 170 | return text_type(s) 171 | except UnicodeDecodeError: 172 | return text_type(s, encoding="utf_8") 173 | 174 | def cmd(self, cmd) -> ShellOutputs: 175 | try: 176 | process = subprocess.Popen(cmd, **self.popen_args) # type: ignore 177 | stdout, stderr = process.communicate() 178 | returncode = process.returncode 179 | 180 | except Exception as e: 181 | logger.error("Exception for %s: \n%s" % (subprocess.list2cmdline(cmd), e)) 182 | 183 | returncode = returncode 184 | 185 | stdout = self.console_to_str(stdout) 186 | stdout = stdout.split(self.line_breaks) 187 | stdout = list(filter(None, stdout)) # filter empty values 188 | 189 | stderr = self.console_to_str(stderr) 190 | stderr = stderr.split(self.line_breaks) 191 | stderr = list(filter(None, stderr)) # filter empty values 192 | 193 | if "has-session" in cmd and len(stderr): 194 | if not stdout: 195 | stdout = stderr[0] 196 | logger.debug(f"stdout for {cmd}:\n{stdout}") 197 | 198 | return ShellOutputs(stdout=stdout, stderr=stderr, returncode=returncode) 199 | 200 | 201 | def sh(command: str): 202 | s = Shell() 203 | return s.cmd(command) 204 | 205 | 206 | def mkdir(path: str): 207 | file_path = Path(path) 208 | file_path = file_path.expanduser() 209 | 210 | if not file_path.is_dir(): 211 | logger.debug(f"creating dir: {file_path.absolute()}") 212 | os.makedirs(name=file_path.absolute()) 213 | else: 214 | ... 215 | 216 | 217 | def download(url: str, at: str): 218 | """Download a file""" 219 | 220 | file = requests_session.get(url, stream=True) 221 | if not os.path.exists(at): 222 | os.makedirs(at) 223 | 224 | file_name: str = url.split("/")[-1] 225 | if file.status_code == 200: 226 | with open(f"{at}/{file_name}", "wb") as fw: 227 | fw.write(file.content) 228 | logger.info(f"""Downloaded: \'{file_name}\' at {at}""") 229 | return f"{at}/{file_name}" 230 | else: 231 | logger.info(f"url: {url}, status_code: {file.status_code}") 232 | exit() 233 | 234 | 235 | def extract(path: str, at: str): 236 | """Extract tar/archived files, including .pkg.tar.zst""" 237 | 238 | try: 239 | system = platform.system().lower() 240 | file_info = detect_from_filename(path) 241 | 242 | if file_info.mime_type == "application/x-7z-compressed": 243 | if system in ["linux"]: 244 | cmd = f"7z x {path} -o{at}" 245 | logger.debug("command: " + cmd) 246 | sh(cmd) 247 | elif system == "windows": 248 | # 'C:\\Program Files\\7-zip\\7z.exe' 249 | pass 250 | elif file_info.mime_type == "application/x-bzip2" or path.endswith( 251 | (".bz2", ".tbz") 252 | ): 253 | logger.debug(f"Extracting bzip2 file: {path}") 254 | if path.endswith(".bz2") and not path.endswith(".tar.bz2"): 255 | # Single file compressed with bz2 256 | with bz2.open(path, "rb") as f_in: 257 | output_file = os.path.join(at, os.path.basename(path)[:-4]) 258 | with open(output_file, "wb") as f_out: 259 | f_out.write(f_in.read()) 260 | else: 261 | # Tar archive compressed with bz2 262 | with tarfile.open(path, "r:bz2") as tar: 263 | tar.extractall(path=at) 264 | 265 | elif path.endswith(".gz") and not path.endswith((".tar.gz", ".tgz")): 266 | # Single file compressed with gzip 267 | logger.debug(f"Extracting gzip file: {path}") 268 | # Single file compressed with gzip 269 | with gzip.open(path, "rb") as f_in: 270 | # Remove .gz extension for output filename 271 | output_file = os.path.join(at, os.path.basename(path)[:-3]) 272 | with open(output_file, "wb") as f_out: 273 | shutil.copyfileobj(f_in, f_out) 274 | logger.debug(f"Extracted to: {output_file}") 275 | 276 | elif path.endswith((".pkg.tar.zst", ".tar.zst")): 277 | logger.debug(f"Extracting zstd tar file: {path}") 278 | dctx = zstd.ZstdDecompressor() 279 | with open(path, "rb") as compressed: 280 | with dctx.stream_reader(compressed) as reader: 281 | # Wrap the stream in tarfile 282 | with tarfile.open(fileobj=reader, mode="r|") as tar: 283 | tar.extractall(path=at) 284 | logger.debug(f"Extracted to: {at}") 285 | 286 | else: 287 | shutil.unpack_archive(path, at) 288 | 289 | return True 290 | except Exception as e: 291 | logger.error(f"can't extract: {path}, error: {e}") 292 | raise Exception("Invalid file") 293 | 294 | 295 | def listItemsMatcher(patterns: List[str], word: str) -> float: 296 | """ 297 | eg: listItemsMatcher(patterns=['a','b'], word='a-cc') --> 0.5 298 | """ 299 | 300 | count = 0 301 | 302 | for pattern in patterns: 303 | if re.search(pattern.lower(), word.lower()): 304 | count += 1 305 | 306 | if count == 0: 307 | return 0 308 | 309 | return count / len(patterns) 310 | 311 | 312 | def threads(funct, data, max_workers=5, return_result: bool = True): 313 | results = [] 314 | with ThreadPoolExecutor(max_workers=max_workers) as executor: 315 | future = executor.map(funct, data) 316 | if return_result is True: 317 | for i in future: 318 | results.append(i) 319 | return results 320 | 321 | 322 | def show_table( 323 | data: List[Dict], ignore_keys: List = [], title: str = "", border_style="" 324 | ): 325 | """rich table""" 326 | 327 | def dict_list_tbl(items=List[dict], ignore_keys: list = []): 328 | keys = [] 329 | data = [] 330 | 331 | for item in items: 332 | _tmp: tuple = () 333 | for key in [i for i in item.keys() if i not in ignore_keys]: 334 | if key not in keys: 335 | keys.append(key) 336 | _tmp += (str(item[key]),) 337 | data.append(_tmp) 338 | 339 | return keys, data 340 | 341 | text = Text(title, style=_colors["light_green"]) 342 | 343 | print() 344 | 345 | table = Table(title=text, style=_colors["purple"], border_style=border_style) 346 | columns, rows = dict_list_tbl(data, ignore_keys) 347 | 348 | colors = { 349 | 0: _colors["yellow"], 350 | 1: _colors["red"], 351 | 2: _colors["green"], 352 | 3: _colors["cyan"], 353 | 4: _colors["blue"], 354 | } 355 | 356 | for count, col in enumerate(columns): 357 | color = colors[count % len(colors)] 358 | table.add_column(col, justify="left", style=color, no_wrap=True) 359 | for row in rows: 360 | table.add_row(*row) 361 | 362 | console = Console() 363 | console.print(table) 364 | 365 | 366 | def to_words(text: str, ignore_words: List[str] = []) -> List[str]: 367 | text = text.lower().replace("_", "-").split("-") 368 | words = [] 369 | for w in text: 370 | if w not in ignore_words: 371 | w = re.sub(r"\d", "", w) 372 | if w != "": 373 | words.append(w) 374 | return words 375 | -------------------------------------------------------------------------------- /InstallRelease/cli_interact.py: -------------------------------------------------------------------------------- 1 | import os 2 | from typing import Dict, Optional, cast 3 | from tempfile import TemporaryDirectory 4 | import platform 5 | 6 | # pipi 7 | from rich.progress import track 8 | from rich.console import Console 9 | 10 | # locals 11 | from InstallRelease.state import State, platform_path 12 | from InstallRelease.data import Release, ToolConfig, irKey, TypeState, ReleaseAssets 13 | 14 | from InstallRelease.constants import state_path, bin_path, config_path 15 | from InstallRelease.utils import ( 16 | mkdir, 17 | pprint, 18 | logger, 19 | show_table, 20 | is_none, 21 | threads, 22 | PackageVersion, 23 | requests_session, 24 | to_words, 25 | ) 26 | 27 | from InstallRelease.core import ( 28 | get_release, 29 | extract_release, 30 | install_bin, 31 | get_repo_info, 32 | RepoInfo, 33 | ) 34 | 35 | 36 | console = Console(width=40) 37 | 38 | install_release_version = PackageVersion("install-release") 39 | 40 | if os.environ.get("installState", "") == "test": 41 | temp_dir = "../temp" 42 | __spath = { 43 | "state_path": f"{temp_dir}/temp-state.json", 44 | "config_path": f"{temp_dir}/temp-config.json", 45 | } 46 | logger.info(f"installState={os.environ.get('installState')}") 47 | else: 48 | __spath = {"state_path": "", "config_path": ""} 49 | 50 | cache = State( 51 | file_path=platform_path(paths=state_path, alt=__spath["state_path"]), 52 | obj=Release, 53 | ) 54 | 55 | cache_config = State( 56 | file_path=platform_path(paths=config_path, alt=__spath["config_path"]), 57 | obj=ToolConfig, 58 | ) 59 | 60 | 61 | def load_config() -> ToolConfig: 62 | """Load config from cache_config 63 | 64 | Returns: 65 | The loaded configuration object or a new one if not found 66 | """ 67 | config = cache_config.state.get("config") 68 | 69 | if config is not None and isinstance(config, ToolConfig): 70 | return config 71 | else: 72 | new_config = ToolConfig() 73 | cache_config.set("config", new_config) 74 | cache_config.save() 75 | return new_config 76 | 77 | 78 | config: ToolConfig = load_config() 79 | 80 | # Handle the path, ensuring it's a string 81 | config_path_str = str(config.path) if config.path is not None else "" 82 | dest = platform_path(paths=bin_path, alt=config_path_str) 83 | 84 | # ------- cli ---------- 85 | 86 | 87 | def state_info(): 88 | logger.debug(cache.state_file) 89 | logger.debug(cache_config.state_file) 90 | logger.debug(dest) 91 | 92 | 93 | def get( 94 | repo: RepoInfo, 95 | tag_name: str = "", 96 | release_file: str = "", 97 | local: bool = True, 98 | prompt: bool = False, 99 | name: Optional[str] = None, 100 | ) -> None: 101 | """Get a release from a GitHub/GitLab repository 102 | 103 | Args: 104 | repo: Repository information handler 105 | tag_name: Specific tag to fetch 106 | release_file: Filename pattern to extract words from 107 | local: Whether to install locally 108 | prompt: Whether to prompt for confirmation 109 | name: Optional name to give the installed tool 110 | """ 111 | state_info() 112 | 113 | logger.debug(f"Python version: {platform.python_version()}") 114 | logger.debug(f"Platform: {platform.platform()}") 115 | try: 116 | logger.debug(f"Platform version: {platform.version()}") 117 | logger.debug(f"Platform release: {platform.release()}") 118 | except Exception as e: 119 | logger.error(f"Error getting platform info: {e}") 120 | 121 | # Extract words from release filename if provided 122 | custom_release_words = None 123 | if not is_none(release_file): 124 | filename = release_file.rsplit(".", 1)[0] 125 | custom_release_words = to_words( 126 | filename.replace(".", "-"), ignore_words=["v", "unknown"] 127 | ) 128 | 129 | pre_release = bool(config.pre_release) if hasattr(config, "pre_release") else False 130 | releases = repo.release(tag_name=tag_name, pre_release=pre_release) 131 | 132 | if not releases: 133 | logger.error(f"No releases found: {repo.repo_url}") 134 | return 135 | 136 | toolname = repo.repo_name.lower() if is_none(name) else name.lower() 137 | at = TemporaryDirectory(prefix=f"dn_{repo.repo_name}_") 138 | 139 | # Use extracted words or cached words or toolname 140 | extra_words = custom_release_words or [toolname] 141 | cached_release = cache.get(f"{repo.repo_url}#{toolname}") 142 | 143 | if ( 144 | not extra_words 145 | and cached_release 146 | and hasattr(cached_release, "custom_release_words") 147 | ): 148 | extra_words = cached_release.custom_release_words 149 | 150 | is_user_pattern = False 151 | if custom_release_words: 152 | is_user_pattern = True 153 | 154 | logger.debug(f"custom_release_words: {custom_release_words}") 155 | logger.debug(f"cached_release: {cached_release}") 156 | 157 | result = get_release( 158 | releases=releases, 159 | repo_url=repo.repo_url, 160 | extra_words=extra_words, 161 | is_user_pattern=is_user_pattern, 162 | ) 163 | 164 | logger.debug(result) 165 | 166 | # Handle the case where get_release returns False 167 | if result is False: 168 | logger.error("No suitable release assets found") 169 | return 170 | 171 | # At this point, result must be a ReleaseAssets object 172 | # Using cast to tell mypy that we've already checked the type 173 | asset = cast(ReleaseAssets, result) 174 | 175 | if prompt is not False: 176 | pprint( 177 | f"\n[green bold]📑 Repo : {repo.info.full_name}" 178 | f"\n[blue]🌟 Stars : {repo.info.stargazers_count}" 179 | f"\n[magenta]🔮 Language : {repo.info.language if repo.info.language else 'N/A'}" 180 | f"\n[yellow]🔥 Title : {repo.info.description}" 181 | ) 182 | show_table( 183 | data=[ 184 | { 185 | "Name": toolname, 186 | "Selected Item": asset.name, 187 | "Version": releases[0].tag_name, 188 | "Size Mb": asset.size_mb() if hasattr(asset, "size_mb") else "N/A", 189 | "Downloads": asset.download_count 190 | if hasattr(asset, "download_count") 191 | else "N/A", 192 | } 193 | ], 194 | title=f"🚀 Install: {toolname}", 195 | ) 196 | pprint(f"[color(6)]\nPath: {dest}") 197 | pprint("[color(34)]Install this tool (Y/n): ", end="") 198 | yn = input() 199 | if yn.lower() != "y": 200 | return 201 | else: 202 | pprint("\n[magenta]Downloading...[/magenta]") 203 | 204 | extract_release(item=asset, at=at.name) 205 | 206 | # Update the releases with the selected asset 207 | releases[0].assets = [asset] 208 | 209 | # Lock to specific version if tag was provided, unlock if release_file was used 210 | if tag_name: 211 | releases[0].hold_update = True 212 | else: 213 | releases[0].hold_update = False 214 | 215 | # Store extracted or cached words 216 | if custom_release_words: 217 | releases[0].custom_release_words = custom_release_words 218 | elif cached_release and hasattr(cached_release, "custom_release_words"): 219 | releases[0].custom_release_words = cached_release.custom_release_words 220 | 221 | mkdir(dest) 222 | install_bin(src=at.name, dest=dest, local=local, name=toolname) 223 | 224 | # """For ignoring holds in get too""" 225 | # check_key = cache.get(f"{repo.repo_url}#{toolname}") 226 | 227 | # if isinstance(check_key, GithubRelease) and check_key.hold_update == True: 228 | # logger.debug(f"hold_update={check_key.hold_update}") 229 | # releases[0].hold_update = True 230 | 231 | cache.set(f"{repo.repo_url}#{toolname}", value=releases[0]) 232 | cache.save() 233 | 234 | 235 | def upgrade(force: bool = False, skip_prompt: bool = False) -> None: 236 | """Upgrade all installed tools 237 | 238 | Args: 239 | force: Whether to force upgrade even if not newer 240 | skip_prompt: Whether to skip confirmation prompt 241 | """ 242 | state_info() 243 | 244 | state: TypeState = cache.state 245 | 246 | upgrades: Dict[str, RepoInfo] = {} 247 | 248 | def task(k: str) -> None: 249 | i = irKey(k) 250 | 251 | try: 252 | if state[k].hold_update is True: 253 | return 254 | except AttributeError: 255 | pass 256 | 257 | repo = get_repo_info( 258 | i.url, token=config.token, gitlab_token=config.gitlab_token 259 | ) 260 | pprint(f"Fetching: {k}") 261 | # Ensure pre_release is boolean 262 | pre_release = ( 263 | bool(config.pre_release) if hasattr(config, "pre_release") else False 264 | ) 265 | releases = repo.release(pre_release=pre_release) 266 | 267 | if releases[0].published_dt() > state[k].published_dt() or force is True: 268 | upgrades[i.name] = repo 269 | 270 | threads(task, data=[k for k in state], max_workers=20, return_result=False) 271 | 272 | # ask prompt to upgrade listed tools 273 | if len(upgrades) > 0: 274 | pprint("\n[bold magenta]Following tool will get upgraded.\n") 275 | console.print("[bold yellow]" + " ".join(upgrades.keys())) 276 | pprint("[bold blue]Upgrade these tools, (Y/n):", end=" ") 277 | 278 | if skip_prompt is False: 279 | r = input() 280 | if r.lower() != "y": 281 | return 282 | else: 283 | pprint("[bold green]All tools are onto latest version") 284 | return 285 | 286 | for name in track(upgrades, description="Upgrading..."): 287 | repo = upgrades[name] 288 | releases = repo.release() 289 | k = f"{repo.repo_url}#{name}" 290 | 291 | pprint( 292 | "[bold yellow]" 293 | f"Updating: {name}, {state[k].tag_name} => {releases[0].tag_name}" 294 | "[/]" 295 | ) 296 | get(repo, prompt=False, name=name) 297 | 298 | 299 | def show_state(): 300 | """ 301 | | Show state of all tools 302 | """ 303 | state_info() 304 | if os.path.exists(cache.state_file) and os.path.isfile(cache.state_file): 305 | with open(cache.state_file) as f: 306 | print(f.read()) 307 | 308 | 309 | def list_install( 310 | state: Optional[TypeState] = None, 311 | title: str = "Installed tools", 312 | hold_update: bool = False, 313 | ) -> None: 314 | """List all installed tools 315 | 316 | Args: 317 | state: Optional state data to list, defaults to global state 318 | title: Title to display for the list 319 | hold_update: Whether to show only tools with updates on hold 320 | """ 321 | if state is None: 322 | state_info() 323 | state = cache.state 324 | 325 | _table = [] 326 | _hold_table = [] 327 | for key in state: 328 | i = irKey(key) 329 | if hold_update: 330 | if state[key].hold_update is True: 331 | _hold_table.append( 332 | { 333 | "Name": i.name, 334 | "Version": f"[dim]{state[key].tag_name}", 335 | "Url": f"[dim]{state[key].url}", 336 | } 337 | ) 338 | continue 339 | 340 | _table.append( 341 | { 342 | "Name": i.name, 343 | "Version": ( 344 | state[key].tag_name + "[yellow] *HOLD_UPDATE*[/yellow]" 345 | if state[key].hold_update is True 346 | else state[key].tag_name 347 | ), 348 | "Url": state[key].url, 349 | } 350 | ) 351 | 352 | if hold_update: 353 | show_table(_hold_table, title=f"{title} kept on hold") 354 | else: 355 | show_table(_table, title=title) 356 | 357 | 358 | def remove(name: str): 359 | """ 360 | | Remove any cli tool. 361 | 362 | Args: 363 | name: The name of the tool to remove 364 | 365 | Returns: 366 | None 367 | """ 368 | state_info() 369 | state: TypeState = cache.state 370 | popKey = "" 371 | 372 | # Find the tool in the state 373 | for key in state: 374 | i = irKey(key) 375 | if i.name == name: 376 | popKey = key 377 | try: 378 | # Remove the executable 379 | tool_path = f"{dest}/{name}" 380 | if os.path.exists(tool_path): 381 | os.remove(tool_path) 382 | logger.debug(f"Removed file: {tool_path}") 383 | except OSError as e: 384 | logger.error(f"Failed to remove file: {e}") 385 | break 386 | 387 | # Remove from state if found 388 | if popKey: 389 | try: 390 | del state[popKey] 391 | cache.save() 392 | logger.info(f"Removed: {name}") 393 | except Exception as e: 394 | logger.error(f"Failed to update state: {e}") 395 | else: 396 | logger.warning(f"Tool not found: {name}") 397 | 398 | 399 | def hold(name: str, hold_update: bool): 400 | """ 401 | | Holds updates of any cli tool. 402 | """ 403 | state_info() 404 | state: TypeState = cache.state 405 | 406 | for _k in state: 407 | key = irKey(_k) 408 | if key.name == name: 409 | state[_k].hold_update = hold_update 410 | logger.info(f"Update on hold for, {name} to {hold_update}") 411 | break 412 | cache.save() 413 | 414 | 415 | def pull_state(url: str = "", override: bool = False): 416 | """ 417 | | Install tools from remote state 418 | """ 419 | logger.debug(url) 420 | 421 | if is_none(url): 422 | return 423 | 424 | r: dict = requests_session.get(url=url).json() 425 | 426 | data: dict = {k: Release(**r[k]) for k in r} 427 | state: TypeState = cache.state 428 | 429 | temp: Dict[str, Release] = {} 430 | 431 | for key in data: 432 | try: 433 | i = irKey(key) 434 | except Exception: 435 | logger.warning(f"Invalid input: {key}") 436 | continue 437 | 438 | if state.get(key) is not None: 439 | if state[key].tag_name == data[key].tag_name or override is False: 440 | logger.debug(f"Skipping: {key}") 441 | continue 442 | else: 443 | temp[key] = data[key] 444 | else: 445 | temp[key] = data[key] 446 | 447 | logger.debug(temp) 448 | 449 | if len(temp) == 0: 450 | return 451 | 452 | list_install(state=temp, title="Tools to be installed") 453 | pprint("\n[bold magenta]Following tool will get Installed.\n") 454 | pprint("[bold blue]Install these tools, (Y/n):", end=" ") 455 | 456 | _i = input() 457 | if _i.lower() != "y": 458 | return 459 | 460 | for key in temp: 461 | try: 462 | i = irKey(key) 463 | except Exception: 464 | logger.warning(f"Invalid input: {key}") 465 | continue 466 | get( 467 | get_repo_info(i.url, token=config.token, gitlab_token=config.gitlab_token), 468 | tag_name=temp[key].tag_name, 469 | prompt=False, 470 | name=i.name, 471 | ) 472 | -------------------------------------------------------------------------------- /InstallRelease/core.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import re 3 | import glob 4 | import platform 5 | from typing import List, Dict, Any, Optional, Union 6 | from datetime import datetime 7 | from abc import ABC, abstractmethod 8 | 9 | # pipi 10 | import requests 11 | from requests.auth import HTTPBasicAuth 12 | from magic.compat import detect_from_filename 13 | 14 | # locals 15 | from InstallRelease.utils import ( 16 | logger, 17 | extract, 18 | download, 19 | sh, 20 | ) 21 | from InstallRelease.data import ( 22 | Release, 23 | ReleaseAssets, 24 | RepositoryInfo, 25 | ) 26 | from InstallRelease.release_scorer import ReleaseScorer 27 | from InstallRelease.constants import HOME 28 | 29 | # --------------- CODE ------------------ 30 | 31 | __exec_pattern = r"application\/x-(\w+-)?(executable|binary)" 32 | 33 | 34 | class RepositoryError(Exception): 35 | """Base exception for repository operations""" 36 | 37 | pass 38 | 39 | 40 | class UnsupportedRepositoryError(RepositoryError): 41 | """Exception raised for unsupported repository types""" 42 | 43 | pass 44 | 45 | 46 | class ApiError(RepositoryError): 47 | """Exception raised for API errors""" 48 | 49 | pass 50 | 51 | 52 | class RepoInfo(ABC): 53 | """Abstract base class for repository information""" 54 | 55 | owner: str = "" 56 | repo_name: str = "" 57 | headers: Dict[str, str] = {} 58 | response: Optional[List[Release]] = None 59 | repo_url: str = "" 60 | api: str = "" 61 | token: str = "" 62 | data: Dict[str, Any] = {} 63 | info: RepositoryInfo = RepositoryInfo() 64 | 65 | def _validate_url(self, repo_url: str, domain: str) -> str: 66 | """Validate and normalize repository URL""" 67 | if domain not in repo_url: 68 | raise UnsupportedRepositoryError(f"Repository URL must contain '{domain}'") 69 | 70 | # Remove trailing slash if present 71 | if repo_url.endswith("/"): 72 | return repo_url[:-1] 73 | 74 | return repo_url 75 | 76 | @abstractmethod 77 | def _req(self, url: str) -> Dict[str, Any]: 78 | """Make a request to the repository API""" 79 | pass 80 | 81 | @abstractmethod 82 | def repository(self) -> Dict[str, Any]: 83 | """Get repository information""" 84 | pass 85 | 86 | @abstractmethod 87 | def release(self, tag_name: str = "", pre_release: bool = False) -> List[Release]: 88 | """Get release information""" 89 | pass 90 | 91 | 92 | class GitHubInfo(RepoInfo): 93 | """GitHub repository information handler""" 94 | 95 | headers: Dict[str, str] = {"Accept": "application/vnd.github.v3+json"} 96 | response: Optional[List[Release]] = None 97 | 98 | # https://api.github.com/repos/OWNER/REPO/releases/tags/TAG 99 | # https://api.github.com/repos/OWNER/REPO/releases/latest 100 | 101 | def __init__( 102 | self, 103 | repo_url: str, 104 | data: Optional[Dict[str, Any]] = None, 105 | token: Optional[str] = None, 106 | ) -> None: 107 | """Initialize a GitHub repository handler 108 | 109 | Args: 110 | repo_url: The URL of the GitHub repository 111 | data: Additional data to send with API requests 112 | token: GitHub API token for authentication 113 | 114 | Raises: 115 | UnsupportedRepositoryError: If the URL is not a valid GitHub repository URL 116 | """ 117 | # Initialize data to empty dict if None 118 | data = data or {} 119 | 120 | # Validate and normalize the URL 121 | repo_url = self._validate_url(repo_url, "github.com") 122 | 123 | # Parse repository information from URL 124 | repo_url_attr = repo_url.split("/") 125 | 126 | self.repo_url = repo_url 127 | self.owner, self.repo_name = repo_url_attr[-2], repo_url_attr[-1] 128 | self.api = f"https://api.github.com/repos/{self.owner}/{self.repo_name}" 129 | self.token = token or "" # Convert None to empty string 130 | 131 | self.data = data 132 | 133 | # Initialize repository info 134 | try: 135 | self.info = RepositoryInfo(**self._req(self.api)) 136 | except Exception as e: 137 | logger.error(f"Failed to fetch repository information: {str(e)}") 138 | raise ApiError(f"Failed to fetch repository information: {str(e)}") 139 | 140 | def _req(self, url: str) -> Dict[str, Any]: 141 | """Make a request to the GitHub API 142 | 143 | Args: 144 | url: The API URL to request 145 | 146 | Returns: 147 | The JSON response as a dictionary 148 | 149 | Raises: 150 | ApiError: If the API request fails 151 | """ 152 | auth = None 153 | if self.token: 154 | auth = HTTPBasicAuth("user", self.token) 155 | else: 156 | logger.debug("GitHub token not set") 157 | 158 | try: 159 | response = requests.get( 160 | url, 161 | headers=self.headers, 162 | auth=auth, 163 | json=self.data, 164 | ) 165 | response.raise_for_status() # Raise exception for HTTP errors 166 | data = response.json() 167 | 168 | # Check for API error messages 169 | if isinstance(data, dict) and data.get("message"): 170 | error_msg = data.get("message", "Unknown API error") 171 | logger.error(f"GitHub API error: {error_msg}") 172 | raise ApiError(f"GitHub API error: {error_msg}") 173 | 174 | return data 175 | except requests.RequestException as e: 176 | logger.error(f"Request failed: {str(e)}") 177 | raise ApiError(f"Request failed: {str(e)}") 178 | 179 | def repository(self) -> Dict[str, Any]: 180 | """Get repository information 181 | 182 | Returns: 183 | Dictionary containing repository information 184 | """ 185 | return self._req(self.api) 186 | 187 | def release(self, tag_name: str = "", pre_release: bool = False) -> List[Release]: 188 | """Get release information 189 | 190 | Args: 191 | tag_name: The specific tag name to fetch, or empty for latest 192 | pre_release: Whether to include pre-releases 193 | 194 | Returns: 195 | List of Release objects 196 | """ 197 | # Build the API URL based on tag name and pre-release flag 198 | if tag_name: 199 | api = f"{self.api}/releases/tags/{tag_name}" 200 | else: 201 | api = f"{self.api}/releases{'/latest' if not pre_release else ''}" 202 | 203 | # Fetch releases if not already cached 204 | if not self.response: 205 | logger.debug(f"Fetching GitHub release from: {api}") 206 | 207 | try: 208 | req = self._req(api) 209 | 210 | # Ensure we have a list of releases 211 | if not isinstance(req, list): 212 | req_dict: List[Dict[str, Any]] = ( 213 | [req] if isinstance(req, dict) else [] 214 | ) 215 | else: 216 | req_dict = req 217 | 218 | # Convert API response to Release objects 219 | self.response = [] 220 | for r in req_dict: 221 | # Process assets to convert them to ReleaseAssets objects 222 | assets_list: List[ReleaseAssets] = [] 223 | if ( 224 | isinstance(r, dict) 225 | and "assets" in r 226 | and isinstance(r["assets"], list) 227 | ): 228 | for asset_data in r["assets"]: 229 | if isinstance(asset_data, dict): 230 | assets_list.append(ReleaseAssets(**asset_data)) 231 | 232 | # Create Release object with properly typed assets 233 | if isinstance(r, dict): 234 | release = Release( 235 | url=self.repo_url, 236 | assets=assets_list, 237 | tag_name=r.get("tag_name", ""), 238 | prerelease=bool(r.get("prerelease", False)), 239 | published_at=r.get("published_at", ""), 240 | name=self.repo_name, 241 | ) 242 | if self.response is None: 243 | self.response = [] 244 | self.response.append(release) 245 | except Exception as e: 246 | logger.error(f"Failed to fetch releases: {str(e)}") 247 | return [] 248 | 249 | return self.response 250 | 251 | 252 | class GitlabInfo(RepoInfo): 253 | """GitLab repository information handler""" 254 | 255 | headers: Dict[str, str] = {"Accept": "application/json"} 256 | response: Optional[List[Release]] = None 257 | 258 | def __init__( 259 | self, 260 | repo_url: str, 261 | data: Optional[Dict[str, Any]] = None, 262 | token: Optional[str] = None, 263 | gitlab_token: Optional[str] = None, 264 | ) -> None: 265 | """Initialize a GitLab repository handler 266 | 267 | Args: 268 | repo_url: The URL of the GitLab repository 269 | data: Additional data to send with API requests 270 | token: Generic token for authentication 271 | gitlab_token: GitLab-specific token for authentication (preferred) 272 | 273 | Raises: 274 | UnsupportedRepositoryError: If the URL is not a valid GitLab repository URL 275 | """ 276 | # Initialize data to empty dict if None 277 | data = data or {} 278 | 279 | # Validate and normalize the URL 280 | repo_url = self._validate_url(repo_url, "gitlab.com") 281 | 282 | # Parse repository information from URL 283 | repo_url_attr = repo_url.split("/") 284 | 285 | self.repo_url = repo_url 286 | self.owner, self.repo_name = repo_url_attr[-2], repo_url_attr[-1] 287 | self.response = None 288 | 289 | # URL encode the project path (owner/repo_name) for GitLab API 290 | from urllib.parse import quote 291 | 292 | project_path = f"{self.owner}/{self.repo_name}" 293 | encoded_path = quote(project_path, safe="") 294 | 295 | self.api = f"https://gitlab.com/api/v4/projects/{encoded_path}" 296 | 297 | # Prefer gitlab_token if provided, otherwise fall back to token 298 | self.token = gitlab_token or token or "" 299 | 300 | self.data = data 301 | 302 | try: 303 | repo_info = self._req(self.api) 304 | 305 | # Convert GitLab API response to format compatible with GitHub format 306 | github_compatible_info = { 307 | "name": repo_info.get("name", ""), 308 | "full_name": repo_info.get("path_with_namespace", ""), 309 | "html_url": repo_info.get("web_url", ""), 310 | "description": repo_info.get("description", ""), 311 | "language": repo_info.get("predominant_language", ""), 312 | "stargazers_count": repo_info.get("star_count", 0), 313 | } 314 | 315 | self.info = RepositoryInfo(**github_compatible_info) 316 | except Exception as e: 317 | logger.error(f"Failed to fetch GitLab repository information: {str(e)}") 318 | raise ApiError(f"Failed to fetch GitLab repository information: {str(e)}") 319 | 320 | def _req(self, url: str) -> Dict[str, Any]: 321 | """Make a request to the GitLab API 322 | 323 | Args: 324 | url: The API URL to request 325 | 326 | Returns: 327 | The JSON response as a dictionary 328 | 329 | Raises: 330 | ApiError: If the API request fails 331 | """ 332 | headers = self.headers.copy() 333 | 334 | if self.token: 335 | headers["PRIVATE-TOKEN"] = self.token 336 | 337 | try: 338 | response = requests.get( 339 | url, 340 | headers=headers, 341 | json=self.data, 342 | ) 343 | response.raise_for_status() # Raise exception for HTTP errors 344 | data = response.json() 345 | 346 | # Check for API error messages 347 | if isinstance(data, dict) and data.get("message"): 348 | error_msg = data.get("message", "Unknown API error") 349 | logger.error(f"GitLab API error: {error_msg}") 350 | raise ApiError(f"GitLab API error: {error_msg}") 351 | 352 | return data 353 | except requests.RequestException as e: 354 | logger.error(f"Request failed: {str(e)}") 355 | raise ApiError(f"Request failed: {str(e)}") 356 | 357 | def repository(self) -> Dict[str, Any]: 358 | """Get repository information 359 | 360 | Returns: 361 | Dictionary containing repository information 362 | """ 363 | return self._req(self.api) 364 | 365 | def release(self, tag_name: str = "", pre_release: bool = False) -> List[Release]: 366 | """Get release information 367 | 368 | Args: 369 | tag_name: The specific tag name to fetch, or empty for latest 370 | pre_release: Whether to include pre-releases 371 | 372 | Returns: 373 | List of Release objects 374 | """ 375 | # Skip if we already have the releases cached 376 | if self.response: 377 | return self.response 378 | 379 | self.response = [] # Initialize empty list 380 | releases_api = f"{self.api}/releases" 381 | 382 | try: 383 | logger.debug(f"Fetching GitLab releases from: {releases_api}") 384 | 385 | # Fetch all releases 386 | releases_data = self._req(releases_api) 387 | 388 | # Ensure we have a list of dictionaries 389 | if not isinstance(releases_data, list): 390 | req_dict: List[Dict[str, Any]] = ( 391 | [releases_data] if isinstance(releases_data, dict) else [] 392 | ) 393 | else: 394 | req_dict = releases_data 395 | 396 | # Make sure we're working with dictionaries 397 | req_list: List[Dict[str, Any]] = [] 398 | for item in req_dict: 399 | if isinstance(item, dict): 400 | req_list.append(item) 401 | else: 402 | logger.warning(f"Unexpected response type: {type(item)}") 403 | 404 | # Filter by tag name if specified 405 | if tag_name: 406 | logger.debug(f"Filtering for tag: {tag_name}") 407 | req_list = [r for r in req_list if r.get("tag_name") == tag_name] 408 | 409 | # Filter out pre-releases if needed 410 | if not pre_release and len(req_list) > 0: 411 | req_list = [r for r in req_list if not r.get("upcoming_release", False)] 412 | 413 | # Sort by created_at to get latest first and take the latest if no tag specified 414 | if not tag_name and len(req_list) > 0: 415 | req_list.sort(key=lambda x: x.get("created_at", ""), reverse=True) 416 | if req_list: 417 | req_list = [req_list[0]] 418 | 419 | # Process releases 420 | for r in req_list: 421 | # Process release assets 422 | assets = [] 423 | if "assets" in r and "links" in r["assets"]: 424 | for link in r["assets"]["links"]: 425 | # In GitLab, the "url" is an API URL, but we need a direct download URL 426 | direct_url = link.get("direct_asset_url", "") 427 | if not direct_url: 428 | # Try to construct a direct URL from the name 429 | tag = r.get("tag_name", "") 430 | asset_name = link.get("name", "") 431 | if tag and asset_name: 432 | direct_url = f"https://gitlab.com/{self.owner}/{self.repo_name}/-/releases/{tag}/downloads/{asset_name}" 433 | 434 | asset = ReleaseAssets( 435 | browser_download_url=direct_url or link.get("url", ""), 436 | content_type=link.get("link_type", ""), 437 | created_at=r.get("created_at", ""), 438 | download_count=link.get("count", 0), 439 | id=link.get("id", 0), 440 | name=link.get("name", ""), 441 | node_id="", 442 | size=link.get("size", 0), 443 | state="uploaded", 444 | updated_at=r.get("created_at", ""), 445 | ) 446 | assets.append(asset) 447 | 448 | # Standardize datetime format 449 | published_at = r.get("created_at", "") 450 | try: 451 | if published_at: 452 | dt = datetime.strptime(published_at, "%Y-%m-%dT%H:%M:%S.%fZ") 453 | published_at = dt.strftime("%Y-%m-%dT%H:%M:%SZ") 454 | except ValueError: 455 | # Try alternative format 456 | try: 457 | dt = datetime.strptime(published_at, "%Y-%m-%dT%H:%M:%SZ") 458 | published_at = dt.strftime("%Y-%m-%dT%H:%M:%SZ") 459 | except ValueError: 460 | # Keep original if parsing fails 461 | pass 462 | 463 | release = Release( 464 | url=self.repo_url, 465 | assets=assets, 466 | tag_name=r.get("tag_name", ""), 467 | prerelease=r.get("upcoming_release", False), 468 | published_at=published_at, 469 | name=self.repo_name, 470 | ) 471 | 472 | self.response.append(release) 473 | 474 | except Exception as e: 475 | logger.error(f"Failed to fetch GitLab releases: {str(e)}") 476 | return [] 477 | 478 | return self.response 479 | 480 | 481 | def get_repo_info( 482 | repo_url: str, 483 | data: Optional[Dict[str, Any]] = None, 484 | token: Optional[str] = None, 485 | gitlab_token: Optional[str] = None, 486 | ) -> RepoInfo: 487 | """Factory method to get the appropriate repo info handler based on URL 488 | 489 | Args: 490 | repo_url: The repository URL (GitHub or GitLab) 491 | data: Additional data to send with API requests 492 | token: Generic API token for authentication 493 | gitlab_token: GitLab-specific token (used only for GitLab URLs) 494 | 495 | Returns: 496 | An instance of the appropriate RepoInfo subclass 497 | 498 | Raises: 499 | UnsupportedRepositoryError: If the URL is not supported 500 | """ 501 | # Initialize data to empty dict if None 502 | data = data or {} 503 | 504 | try: 505 | if "github.com" in repo_url: 506 | return GitHubInfo(repo_url, data, token) 507 | elif "gitlab.com" in repo_url: 508 | return GitlabInfo(repo_url, data, token, gitlab_token) 509 | else: 510 | error_msg = ( 511 | "Unsupported repository URL. Only GitHub and GitLab URLs are supported." 512 | ) 513 | logger.error(error_msg) 514 | raise UnsupportedRepositoryError(error_msg) 515 | except UnsupportedRepositoryError as e: 516 | logger.error(str(e)) 517 | sys.exit(1) 518 | except ApiError as e: 519 | logger.error(str(e)) 520 | sys.exit(1) 521 | except Exception as e: 522 | logger.error(f"Unexpected error: {str(e)}") 523 | sys.exit(1) 524 | 525 | 526 | class InstallRelease: 527 | """ 528 | Install a release from GitHub/GitLab 529 | """ 530 | 531 | USER: str 532 | SUDO_USER: str 533 | 534 | bin_path = { 535 | "linux": {"local": f"{HOME}/.local/bin", "global": "/usr/local/bin"}, 536 | "darwin": {"local": f"{HOME}/.local/bin", "global": "/usr/local/bin"}, 537 | } 538 | 539 | def __init__(self, source: str, name: str = "") -> None: 540 | """Initialize the InstallRelease object 541 | 542 | Args: 543 | source: Path to the source binary to install 544 | name: Name to give the installed binary 545 | """ 546 | pl = platform.system() 547 | self.paths = self.bin_path[pl.lower()] 548 | self.pl = pl 549 | self.source = source 550 | self.name = name 551 | 552 | def install(self, local: bool, at: Optional[str] = None) -> bool: 553 | """Install the release binary 554 | 555 | Args: 556 | local: Whether to install to local user bin or system bin 557 | at: Optional path to install to, overrides default paths 558 | 559 | Returns: 560 | True if installation succeeded, False otherwise 561 | """ 562 | system = platform.system().lower() 563 | 564 | if system == "linux": 565 | return self._install_linux(local, at) 566 | elif system == "darwin": 567 | return self._install_darwin(local, at) 568 | else: 569 | logger.error(f"Unsupported platform: {system}") 570 | return False 571 | 572 | def _install_linux(self, local: bool, at: Optional[str] = None) -> bool: 573 | """Install on Linux platforms 574 | 575 | Args: 576 | local: Whether to install to local user bin or system bin 577 | at: Optional path to install to, overrides default paths 578 | 579 | Returns: 580 | True if installation succeeded, False otherwise 581 | """ 582 | if local: 583 | cmd = f"install {self.source} {at or self.paths['local']}" 584 | else: 585 | cmd = f"sudo install {self.source} {at or self.paths['global']}" 586 | 587 | if self.name: 588 | cmd += f"/{self.name}" 589 | 590 | logger.info(cmd) 591 | out = sh(cmd) 592 | 593 | if out.returncode != 0: 594 | logger.error(out.stderr) 595 | return False 596 | else: 597 | logger.info( 598 | f"[bold yellow]Installed: {self.name}[/]", extra={"markup": True} 599 | ) 600 | return True 601 | 602 | def _install_darwin(self, local: bool, at: Optional[str] = None) -> bool: 603 | """Install on macOS platforms 604 | 605 | Args: 606 | local: Whether to install to local user bin or system bin 607 | at: Optional path to install to, overrides default paths 608 | 609 | Returns: 610 | True if installation succeeded, False otherwise 611 | """ 612 | return self._install_linux(local, at) 613 | 614 | def _install_windows(self, local: bool, at: Optional[str] = None) -> None: 615 | """Install on Windows platforms (not implemented) 616 | 617 | Args: 618 | local: Whether to install to local user bin or system bin 619 | at: Optional path to install to, overrides default paths 620 | """ 621 | ... 622 | 623 | 624 | def get_release( 625 | releases: List[Release], 626 | repo_url: str, 627 | extra_words: Optional[List[str]] = None, 628 | is_user_pattern: bool = False, 629 | ) -> Union[ReleaseAssets, bool]: 630 | """Get the release with the highest priority 631 | 632 | Args: 633 | releases: List of releases to choose from 634 | repo_url: The repository URL 635 | extra_words: Additional keywords to match against 636 | is_user_pattern: Whether to use user pattern mode 637 | Returns: 638 | The best matching ReleaseAssets or False if no match found 639 | """ 640 | # Initialize empty list if None 641 | extra_words = extra_words or [] 642 | logger.debug(f"extra_words: {extra_words}") 643 | logger.debug(f"is_user_pattern: {is_user_pattern}") 644 | 645 | # Create scorer with platform words and extra words 646 | scorer = ReleaseScorer(extra_words=extra_words, disable_penalties=is_user_pattern) 647 | 648 | # Log scorer information 649 | scorer_info = scorer.get_info() 650 | logger.debug("=== USING NEW RELEASE SCORER ===") 651 | logger.debug(f"platform_words: {scorer_info['all_patterns']}") 652 | logger.debug(f"glibc_system: {scorer_info['is_glibc_system']}") 653 | 654 | if len(releases) == 0: 655 | logger.warning(f"No releases found for: {repo_url}") 656 | return False 657 | 658 | # Find the first release with assets that is not a prerelease 659 | target_release = None 660 | for release in releases: 661 | if len(release.assets) > 0 and not release.prerelease: 662 | target_release = release 663 | break 664 | 665 | if not target_release: 666 | logger.warning("No suitable release found (non-prerelease with assets)") 667 | return False 668 | 669 | if not target_release.assets: 670 | logger.warning("No release assets found") 671 | return False 672 | 673 | # Extract asset names and score them 674 | asset_names = [asset.name for asset in target_release.assets] 675 | best_name = scorer.select_best(asset_names) 676 | 677 | if not best_name: 678 | logger.warning(f"No matching release found for {repo_url}") 679 | return False 680 | 681 | # Find the asset with the best name 682 | for asset in target_release.assets: 683 | if asset.name == best_name: 684 | logger.debug( 685 | f"Selected file: \n" 686 | f"File: '{asset.name}', content_type: '{asset.content_type}'" 687 | ) 688 | return asset 689 | 690 | return False 691 | 692 | 693 | def extract_release(item: ReleaseAssets, at: str) -> bool: 694 | """Download and extract release 695 | 696 | Args: 697 | item: The release asset to download and extract 698 | at: The directory to extract to 699 | 700 | Returns: 701 | True if extraction succeeded 702 | """ 703 | logger.debug(f"Download path: {at}") 704 | 705 | path = download(item.browser_download_url, at) 706 | logger.debug(f"path: {path}") 707 | 708 | logger.debug(f"Extracting: {path}") 709 | if not re.match( 710 | pattern=__exec_pattern, string=detect_from_filename(path).mime_type 711 | ): 712 | extract(path=path, at=at) 713 | logger.debug("Extracting done.") 714 | 715 | return True 716 | 717 | 718 | def install_bin(src: str, dest: str, local: bool, name: Optional[str] = None) -> bool: 719 | """Install single binary executable file from source to destination 720 | 721 | Args: 722 | src: Source directory to search for binaries 723 | dest: Destination directory to install to 724 | local: Whether to install locally or system-wide 725 | name: Optional name for the binary 726 | 727 | Returns: 728 | True if installation succeeded, False otherwise 729 | """ 730 | bin_files = [] 731 | 732 | for file in glob.iglob(f"{src}/**", recursive=True): 733 | f = detect_from_filename(file) 734 | if f.name == "directory": 735 | continue 736 | elif not re.match(pattern=__exec_pattern, string=f.mime_type): 737 | continue 738 | 739 | bin_files.append(file) 740 | 741 | if len(bin_files) > 1 or len(bin_files) == 0: 742 | logger.error(f"Expect single binary file got more or less:\n{bin_files}") 743 | return False 744 | 745 | irelease = InstallRelease(source=bin_files[0], name=name or "") 746 | return irelease.install(local, at=dest) 747 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------