Encapsulating package managers

This commit is contained in:
Jelmer Draaijer 2024-02-13 17:46:28 +01:00
parent de54e4fba3
commit 4470dc83f6
4 changed files with 60 additions and 4 deletions

View File

@ -1,4 +1,5 @@
{
"_extensions": ["dependencies.InstallExtension"],
"project_name": "My Awesome Project",
"project_slug": "{{ cookiecutter.project_name.lower()|replace(' ', '_')|replace('-', '_')|replace('.', '_')|trim() }}",
"description": "Behold My Awesome Project!",

55
dependencies.py Normal file
View File

@ -0,0 +1,55 @@
from typing import Any
from cookiecutter.environment import StrictEnvironment
from jinja2.ext import Extension
class PackageManager:
managers: dict[str, "PackageManager"] = {}
def __init_subclass__(cls, **kwargs):
cls.managers[cls.__name__.lower()] = cls()
def install(self, obj: str, context: dict[str, Any]) -> str:
raise NotImplementedError("Subclasses must implement the install method")
class PIP(PackageManager):
"""PIP package manager"""
def install(self, obj: str, context: dict[str, Any]) -> str:
if obj == "development":
return "pip install -r requirements/local.txt"
return f"pip install {obj}"
class Poetry(PackageManager):
"""Poetry package manager"""
def install(self, obj: str, context: dict[str, Any]) -> str:
if obj == "development":
return "poetry install --with dev"
return f"poetry add {obj}"
class UV(PackageManager):
"""Poetry package manager"""
class InstallExtension(Extension):
"""Jinja2 extension to convert a Python object to JSON."""
def __init__(self, environment: StrictEnvironment):
"""Initialize the extension with the given environment."""
super().__init__(environment)
def install(obj, context):
# TODO we need to retrieve the package manager from the context or in another way
# manager_name = context.package_manager
manager_name = "pip"
package_manager = PackageManager.managers[manager_name]
return package_manager.install(obj, context)
environment.filters["install"] = install

View File

@ -21,7 +21,7 @@ steps:
path: ${PRE_COMMIT_HOME}
commands:
- export PRE_COMMIT_HOME=$CI_PROJECT_DIR/.cache/pre-commit
- pip install -q pre-commit
- {{ "-q pre-commit"|install(cookiecutter)}}
- pre-commit run --show-diff-on-failure --color=always --all-files
- name: test
@ -38,7 +38,7 @@ steps:
{%- else %}
image: python:3.11
commands:
- pip install -r requirements/local.txt
- {{ "development"|install(cookiecutter)}}
- pytest
{%- endif%}

View File

@ -10,7 +10,7 @@ jobs:
include:
- name: "Linter"
before_script:
- pip install -q ruff
- {{ "ruff"|install(cookiecutter)}}
script:
- ruff check .
@ -39,7 +39,7 @@ jobs:
python:
- "3.11"
install:
- pip install -r requirements/local.txt
- {{ "development"|install(cookiecutter)}}
script:
- pytest
{%- endif %}