feat: Initiate package

This commit is contained in:
Mr Finchum 2025-01-31 12:14:06 +01:00
parent 85fc80d778
commit 30ade13aae
12 changed files with 276 additions and 91 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
test/
dist/
.ropeproject/
__pycache__/

69
.gitlab-ci.yml Normal file
View file

@ -0,0 +1,69 @@
---
include:
- local: .gitlab-ci/versioning/gitversion.yml
- local: .gitlab-ci/git/create_tag.yml
stages:
- build
- release
gitversion:
extends: .versioning:gitversion
stage: .pre
tags:
- gitlab-org-docker
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run this job when commits are pushed or merged to the default branch
build:
stage: build
image: python:3.9.21
tags:
- gitlab-org-docker
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run this job when commits are pushed or merged to the default branch
needs:
- job: gitversion
artifacts: true
script:
- sed -i "s/^__version__ = .*/__version__ = \"${GitVersion_MajorMinorPatch}\"/" src/PyPiUpdateCheck/__init__.py
- cat src/PyPiUpdateCheck/__init__.py
- python3 -m pip install build
- python3 -m build
artifacts:
paths:
- dist/*
expire_in: 1 day
publish:
stage: release
image: python:3.9.21
tags:
- gitlab-org-docker
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run this job when commits are pushed or merged to the default branch
variables:
TWINE_USERNAME: "__token__"
TWINE_PASSWORD: $TWINE_API
needs:
- job: build
artifacts: true
script:
- python3 -m pip install twine
- python3 -m twine upload dist/*
create_tag:
extends: .git:create_tag
stage: release
tags:
- gitlab-org-docker
variables:
VERSION: $GitVersion_SemVer
TOKEN: $GITLAB_TOKEN
needs:
- job: gitversion
artifacts: true
rules:
- if: $CI_COMMIT_TAG
when: never # Do not run this job when a tag is created manually
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run this job when commits are pushed or merged to the default branch

View file

@ -0,0 +1,15 @@
---
.git:create_tag:
image: alpine:3.21
variables:
GIT_STRATEGY: clone
GIT_DEPTH: 0
GIT_LFS_SKIP_SMUDGE: 1
VERSION: ''
TOKEN: '' # Token with push privileges
script:
- apk add git
- git remote set-url origin https://oauth2:$TOKEN@$CI_SERVER_HOST/$CI_PROJECT_PATH
- git tag $VERSION
- git push origin tag $VERSION

View file

@ -0,0 +1,31 @@
---
.versioning:gitversion:
image:
name: mcr.microsoft.com/dotnet/sdk:9.0
variables:
GIT_STRATEGY: clone
GIT_DEPTH: 0 # force a deep/non-shallow fetch need by gitversion
GIT_LFS_SKIP_SMUDGE: 1
cache: [] # caches and before / after scripts can mess things up
script:
- |
dotnet tool install --global GitVersion.Tool --version 5.*
export PATH="$PATH:/root/.dotnet/tools"
dotnet-gitversion -output buildserver
# We could just collect the output file gitversion.properties (with artifacts:report:dotenv: gitversion.properties as it is already in DOTENV format,
# however it contains ~33 variables which unnecessarily consumes many of the 50 max DOTENV variables of the free GitLab version.
# Limits are higher for licensed editions, see https://docs.gitlab.com/ee/ci/yaml/artifacts_reports.html#artifactsreportsdotenv
grep 'GitVersion_LegacySemVer=' gitversion.properties >> gitversion.env
grep 'GitVersion_SemVer=' gitversion.properties >> gitversion.env
grep 'GitVersion_FullSemVer=' gitversion.properties >> gitversion.env
grep 'GitVersion_Major=' gitversion.properties >> gitversion.env
grep 'GitVersion_Minor=' gitversion.properties >> gitversion.env
grep 'GitVersion_Patch=' gitversion.properties >> gitversion.env
grep 'GitVersion_MajorMinorPatch=' gitversion.properties >> gitversion.env
grep 'GitVersion_BuildMetaData=' gitversion.properties >> gitversion.env
artifacts:
reports:
# propagates variables into the pipeline level
dotenv: gitversion.env

6
CHANGELOG.md Normal file
View file

@ -0,0 +1,6 @@
# Changelog
## 0.0.1: Project Initiation
- First working version
- ATM terminal promt to accept or deny update
- More to come soon

5
GitVersion.yml Normal file
View file

@ -0,0 +1,5 @@
---
mode: MainLine
major-version-bump-message: "^(build|chore|ci|docs|feat|fix|patch|refactor|revert|style|test)(\\([\\w\\s-,/\\\\]*\\))?(!:|:.*\\n\\n((.+\\n)+\\n)?BREAKING CHANGE:\\s.+)" # noqa yaml[line-length]
minor-version-bump-message: "^(build|chore|ci|docs|feat|refactor|revert|style|test)(\\([\\w\\s-,/\\\\]*\\))?:"
patch-version-bump-message: "^(fix|patch)(\\([\\w\\s-,/\\\\]*\\))?:"

20
LICENSE.md Normal file
View file

@ -0,0 +1,20 @@
# GNU Affero General Public License v3.0
Copyright (C) [2024] [Mr Finchum]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
---
## Additional Notes:
This program is licensed under the AGPL-3.0, which requires that any modifications or derivative works distributed or used over a network must also be licensed under the AGPL-3.0.

View file

@ -1,93 +1,3 @@
# PyPiUpdater
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.com/CodeByMrFinchum/PyPiUpdater.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.com/CodeByMrFinchum/PyPiUpdater/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
## More to come

3
pip_README.md Normal file
View file

@ -0,0 +1,3 @@
Simple program to update package from PyPi with pip.
For more info see [PyPiUpdater gitlab](https://gitlab.com/CodeByMrFinchum/PyPiUpdater#).

26
pyproject.toml Normal file
View file

@ -0,0 +1,26 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "PyPiUpdater"
dynamic = ["version"]
authors = [{ name = "Mr Finchum" }]
description = "Simple program to update package from PyPi with pip."
readme = "pip_README.md"
requires-python = ">=3.8"
dependencies = ["requests", "packaging"]
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Operating System :: OS Independent",
]
[project.urls]
Source = "https://gitlab.com/CodeByMrFinchum/PyPiUpdater"
[tool.hatch.build.targets.wheel]
packages = ["src/PyPiUpdater"]
[tool.hatch.version]
path = "src/PyPiUpdater/__init__.py"

View file

@ -0,0 +1,5 @@
from .pypi_updater import PyPiUpdater
__all__ = ["PyPiUpdater"]
__version__ = "0.0.1"

View file

@ -0,0 +1,91 @@
import requests
from packaging import version
import subprocess
import sys
class PyPiUpdater:
def _restart_program(self):
"""Restarts the current Python script."""
print("Restarting the application...")
python = sys.executable
subprocess.run([python] + sys.argv)
sys.exit() # Ensure the old process exits
def update_package(self, package_name):
"""Runs pip install -U <package_name>."""
print(f"Updating {package_name}...")
subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", package_name])
def check_and_update(self, package_name, local_version):
"""Checks for updates and installs if needed."""
checker = PyPiUpdateCheck()
is_newer, latest_version = checker.check_for_update(package_name, local_version)
if is_newer is None:
print(f"Error checking for updates: {latest_version}")
elif is_newer:
print(f"New version available: {latest_version}")
choice = input("Do you want to update (y/n)\n")
if choice == "y":
self.update_package(package_name)
self._restart_program() # Restart after updating
else:
print("packge not updated")
else:
print("You are up to date!")
class PyPiUpdateCheck:
def _get_latest_version_from_rss(self, package_name):
"""
Fetch the RSS feed from PyPI and extract the latest version number.
Returns the latest version or None if an error occurs.
"""
rss_url = f"https://pypi.org/rss/project/{package_name.lower()}/releases.xml"
try:
response = requests.get(rss_url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx, 5xx)
# Extract the latest version from the RSS XML
# The RSS feed is XML, so we just need to parse the version from the first entry
from xml.etree import ElementTree as ET
root = ET.fromstring(response.content)
# The version is in the <title> tag of the first <item> in the RSS feed
latest_version = root.find(".//item/title").text.strip()
return latest_version, None
except requests.exceptions.RequestException as e:
return None, f"Network error: {str(e)}"
except Exception as e:
return None, f"Error parsing feed: {str(e)}"
def _compare_versions(self, local_version, online_version):
"""
Compare the local and online version strings.
Returns (True, online_version) if online is newer, (False, online_version) if same or older.
"""
try:
local_ver = version.parse(local_version)
online_ver = version.parse(online_version)
if online_ver > local_ver:
return True, online_version # Online version is newer
else:
return False, online_version # Local version is the same or newer
except Exception as e:
return None, f"Error comparing versions: {str(e)}"
def check_for_update(self, package_name, local_version):
"""
Check if the given package has a newer version on PyPI compared to the local version.
Returns (True, online_version), (False, online_version), or (None, error_message).
"""
online_version, error_message = self._get_latest_version_from_rss(package_name)
if online_version is None:
return None, error_message # Error fetching or parsing feed
return self._compare_versions(local_version, online_version)