Esta es una guia de como setear tu proyecto de python con herramientas para ayudarte al desarrollo y despliegue rapido de paquetes.
pipx install poetry
poetry config virtualenvs.in-project true
las opciones --src
y --name
para crear el proyecto con carpeta src y especificarle el nombre de la carpeta raiz por separado.
poetry new --src --name my-package my-package-folder
Nos creara una estructura de carpetas como esta:
.
├── README.md
├── pyproject.toml
├── src
│ └── my_package
│ └── __init__.py
└── tests
└── __init__.py
inicializamos git en la rama main
git init -b main
pusheamos a github
git remote add origin <your-repo-url>
y agregamos un .gitignore
de https://www.toptal.com/developers/gitignore
Creamos dos archivos:
src/my_package/operations.py
from time import sleep
import json,os
import yaml
from calculator.utils import get_cwd, get_admin_pass
import os
def add_two_numbers(a:int,b:int)->str:
return a+b
def multiply_two_numbers(a:str,b:str)->list[int]:
return a * b
def divide_two_numbers(a: float, b: str)->int:
return a / b
src/my_package/utils.py
import os
def get_cwd():
return os.getcwd()
Pasemos a la siguiente seccion antes de que nos caiga la ley por haber cometido estos delitos al codigo.
Estas son algunas herramientas que nos ayudaran a tener un codigo bonito, legible, liberarnos de algunos bugs y siguiendo las buenas practicas de formato de codigo.
Alguns de estas herramientas pueden incluirse como librerias en tu IDE favorito.
An extremely fast Python linter and code formatter, written in Rust.
Contiene isort, black y flake8
ruff check .
ruff check --fix .
ruff format .
Mypy is a static type checker for Python.
mypy .
Pero aun con todas estas herramientas los desarrolladores nos lincharian al agregarles un paso extra a su flujo de trabajo.
Asi que trataremos de automatizar las cosas aun más!
A framework for managing and maintaining multi-language pre-commit hooks.
poetry add pre-commit --group dev
creamos un archivo llamado .pre-commit-config.yaml
y agregamos la siguiente configuracion:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.7
hooks:
- id: ruff
args: [ --fix ]
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.7.1
hooks:
- id: mypy
args: [--disallow-untyped-calls]
e instalamos los hooks:
pre-commit install
git commit -m "first commit"
git push -u origin main
Ya tenemos nuestro primer release clean! Ahora que hacemos?? ?? ?? ??
Automatic Semantic Versioning for Python projects.
Esta herramienta nos resulve toodas las dudas de arriba automaticamente!
Esta basada en Angular Commit Style, hay formatos mas complejos pero lo podemos resumir en tipo y mensaje:
<tipo>: <mensaje>
Debe ser uno de los siguientes:
- feat: A new feature
- fix: A bug fix
- docs: Documentation only changes
- style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
- refactor: A code change that neither fixes a bug nor adds a feature
- perf: A code change that improves performance
- test: Adding missing or correcting existing tests
- chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
Agregamos las siguientes lineas a nuestro archivo pyproject.toml
[tool.semantic_release]
assets = []
commit_message = "{version}\n\nAutomatically generated by python-semantic-release"
commit_parser = "angular"
logging_use_named_masks = false
major_on_zero = true
tag_format = "v{version}"
version_toml = [
"pyproject.toml:tool.poetry.version",
]
build_command = "pip install poetry && poetry build"
[tool.semantic_release.branches.main]
match = "(main|master)"
prerelease_token = "rc"
prerelease = false
[tool.semantic_release.changelog]
template_dir = "templates"
changelog_file = "CHANGELOG.md"
exclude_commit_patterns = []
[tool.semantic_release.changelog.environment]
block_start_string = "{%"
block_end_string = "%}"
variable_start_string = "{{"
variable_end_string = "}}"
comment_start_string = "{#"
comment_end_string = "#}"
trim_blocks = false
lstrip_blocks = false
newline_sequence = "\n"
keep_trailing_newline = false
extensions = []
autoescape = true
[tool.semantic_release.commit_author]
env = "GIT_COMMIT_AUTHOR"
default = "semantic-release <semantic-release>"
[tool.semantic_release.commit_parser_options]
allowed_tags = ["chore", "feat", "fix", "style", "refactor", "test"]
minor_tags = ["feat"]
patch_tags = ["fix"]
[tool.semantic_release.remote]
name = "origin"
type = "github"
ignore_token_for_push = false
[tool.semantic_release.remote.token]
env = "GH_TOKEN"
[tool.semantic_release.publish]
dist_glob_patterns = ["dist/*"]
upload_to_vcs_release = true
Esta herramienta nos crea un CHANGELOG.md pero ademas tenemos la opcion de crear una plantilla personalizada.
en la ruta .github/workflows
agregamos el archivo main.yml
name: 'Semantic Release Versioning'
on:
push:
branches:
- main
jobs:
release:
runs-on: ubuntu-latest
concurrency: release
permissions:
id-token: write
contents: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Python Semantic Release
uses: python-semantic-release/python-semantic-release@master
with:
github_token: ${{ secrets.GH_TOKEN }}
git commit -m "chore: add semantic release and github actions"
git push -u origin main
git commit -m "feat: random function"
git push -u origin main