From 3b78d5713328090f56bbe128adf83d337d91ca06 Mon Sep 17 00:00:00 2001 From: Pradish Bijukchhe Date: Tue, 12 Dec 2023 18:06:14 +0545 Subject: [PATCH] feat: initial commit --- .github/workflows/python-publish.yml | 27 ++++++ .gitignore | 131 +++++++++++++++++++++++++++ LICENSE | 19 ++++ MANIFEST.in | 2 + README.md | 52 +++++++++++ pkg_updater/__init__.py | 0 pkg_updater/py.typed | 0 pkg_updater/updater.py | 118 ++++++++++++++++++++++++ pyproject.toml | 39 ++++++++ requirements.txt | 1 + 10 files changed, 389 insertions(+) create mode 100644 .github/workflows/python-publish.yml create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 README.md create mode 100644 pkg_updater/__init__.py create mode 100644 pkg_updater/py.typed create mode 100644 pkg_updater/updater.py create mode 100644 pyproject.toml create mode 100644 requirements.txt diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..fdd604c --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,27 @@ +name: Upload Python Package +on: + push: + branches: + - master +permissions: + contents: read +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v3 + with: + python-version: "3.x" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build + - name: Build package + run: python -m build + - name: Publish package + uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..07a95d2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,131 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +.vscode + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ +dist diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..96f1555 --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018 The Python Packaging Authority + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..c1a7121 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include LICENSE +include README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..1675ceb --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ +# pkg-updater + +A python script to update packages + +``` +$ pkg-updater my-pkg +Next update in 899s, press enter to continue... +Checking for updates... +Gracefully shutting down running processes... +Installing updates... +... +... +... +Restarting closed processes... +Complete. +``` + +## Installation + +You can install the package via pip: + +```bash +pip install pkg-updater +``` + +## Usage + +``` +usage: pkg-updater [-h] [--extra-index-url EXTRA_INDEX_URL] [--interval INTERVAL] [--delay-first DELAY_FIRST] [--restart RESTART] package_name + +positional arguments: + package_name + +options: + -h, --help show this help message and exit + --extra-index-url EXTRA_INDEX_URL + --interval INTERVAL + --delay-first DELAY_FIRST + --restart RESTART +``` + +## License + +This project is licensed under the terms of the MIT license. + +## Contributing + +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. + +## Contact + +If you want to contact me you can reach me at pradishbijukchhe@gmail.com. diff --git a/pkg_updater/__init__.py b/pkg_updater/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pkg_updater/py.typed b/pkg_updater/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/pkg_updater/updater.py b/pkg_updater/updater.py new file mode 100644 index 0000000..23f2e93 --- /dev/null +++ b/pkg_updater/updater.py @@ -0,0 +1,118 @@ +import sys +import time +import traceback +from argparse import ArgumentParser +from msvcrt import getch +from msvcrt import kbhit +from subprocess import DEVNULL +from subprocess import PIPE +from subprocess import Popen +from subprocess import check_output + +import psutil + + +def sleep(timeout: int): + """ + Sleep for a given amount of time, + Can be canceled at any time + """ + start = time.time() + while True: + elapsed = int(time.time() - start) + remaining = timeout - elapsed + sys.stdout.write( + f"\rNext update in {remaining}s, press enter to continue..." + ) + sys.stdout.flush() + if remaining <= 0: + break + if kbhit(): + if getch() == b"\r": + break + time.sleep(0.1) + print() + + +def get_running_processes(text: str): + proc_iter = psutil.process_iter() + processes: list[psutil.Process] = [] + for i in proc_iter: + try: + for cmd in i.cmdline(): + if "--restart" in cmd: + # filter self + break + if text in cmd: + processes.append(i) + except psutil.Error: + pass + return processes + + +def get_is_up_to_date(pkg_name: str, extra_index_url: str = ""): + cmd = ["pip", "install", "--upgrade", pkg_name] + if extra_index_url: + cmd += ["--extra-index-url", extra_index_url] + cmd += ["--dry-run"] + print("Checking for updates...") + stdout = check_output(cmd, stderr=PIPE).decode() + return "Would install" not in stdout + + +def install_updates(pkg_name: str, extra_index_url: str = ""): + cmd = ["pip", "install", "--upgrade", pkg_name] + if extra_index_url: + cmd += ["--extra-index-url", extra_index_url] + + print("Installing updates...") + with Popen(cmd, stdout=PIPE, stderr=PIPE, text=True) as p: + if p.stdout: + for line in p.stdout: + print(line.strip()) + if p.stderr: + for line in p.stderr: + print(line.strip()) + + +def main(): + parser = ArgumentParser() + parser.add_argument("package_name") + parser.add_argument("--extra-index-url") + parser.add_argument("--interval", default=900, type=int) + parser.add_argument("--delay-first", default=900, type=int) + parser.add_argument("--restart") + args = parser.parse_args() + sleep(args.delay_first) + while True: + try: + if get_is_up_to_date(args.package_name, args.extra_index_url): + print("Already up to date.") + else: + if args.restart: + print("Gracefully shutting down running processes...") + processes = get_running_processes(args.restart) + data = [(i.cmdline(), i.cwd()) for i in processes] + for i in processes: + i.terminate() + else: + data = [] + install_updates(args.package_name, args.extra_index_url) + if args.restart: + print("Restarting closed processes...") + for cmd, cwd in data: + Popen( + cmd, + cwd=cwd, + stderr=DEVNULL, + stdout=DEVNULL, + start_new_session=True, + ) + print("Complete.") + except Exception: + traceback.print_exc() + sleep(args.interval) + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..908b63e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,39 @@ +[build-system] +requires = ["setuptools>=61.2"] +build-backend = "setuptools.build_meta" + +[project] +name = "pkg-updater" +version = "1.0.0" +dependencies = ["psutil"] +requires-python = ">=3" +authors = [{ name = "Pradish Bijukchhe", email = "pradishbijukchhe@gmail.com" }] +description = "A python script to update packages" +readme = "README.md" +license = { file = "LICENSE" } +keywords = [] +classifiers = ["Programming Language :: Python :: 3"] + +[project.urls] +Homepage = "https://github.com/sandbox-pokhara/pkg-updater" +Issues = "https://github.com/sandbox-pokhara/pkg-updater/issues" + +[project.scripts] +pkg-updater = "pkg_updater.updater:main" + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.package-dir] +"pkg_updater" = "pkg_updater" + +[tool.isort] +line_length = 79 +force_single_line = true + +[tool.black] +line-length = 79 +preview = true + +[tool.pyright] +typeCheckingMode = "strict" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a4d92cc --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +psutil