Skip to content

Commit

Permalink
feat: initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pradishb committed Dec 12, 2023
0 parents commit 3b78d57
Show file tree
Hide file tree
Showing 10 changed files with 389 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
@@ -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 }}
131 changes: 131 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include LICENSE
include README.md
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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 [email protected].
Empty file added pkg_updater/__init__.py
Empty file.
Empty file added pkg_updater/py.typed
Empty file.
118 changes: 118 additions & 0 deletions pkg_updater/updater.py
Original file line number Diff line number Diff line change
@@ -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()
39 changes: 39 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 = "[email protected]" }]
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"
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
psutil

0 comments on commit 3b78d57

Please sign in to comment.