- Comece configurando a ferramenta de versionamento de código (VCS).
Para inicializar um repositório, utilizando o GitHub,
execute o comando
git
, na linha de comando:
cd python-template && git init
Onde:
cd
: comando é a abreviação de "change directory". Você pode usar esse comando para mudar o diretório da linha de comando.git init
: inicializa um novo repositório no GitHub. Vale ressaltar que este comando apenas cria os arquivos necessários para inicializar o repositório, mas não realiza upload dos arquivos para o GitHub. De certo modo, estamos apenas "preparando o terreno" neste momento.&&
: permite a execução de mais de um comando, de uma só vez. No caso acima, mudamos o diretório do nosso terminal e criamos os arquivos que o GitHub precisa.
- Em seguida, instale o Poetry, executando o seguinte comando:
Ignorar esta etapa, caso você já tenha o Poetry instalado na sua maquina.
make poetry-download
Nunca ouviu falar do Poetry? Clique aqui para uma breve contextualização.
- Depois de instalar o Poetry, execute o comando abaixo, para instalar as dependências
necessárias do pacote:Initialize poetry and install
pre-commit
hooks:
make install
Opcional: você também pode habilitar uma feature chamada pre-commit
hooks, executando o seguinte comando:
make pre-commit-install
pre-commit
hooks são basicamente verificações, que são executadas automaticamente, toda vez que você realiza um
commit no seu repositório. Essas verificações variam desde formatar o código fonte, usando ferramentas, como o
Black, até execuções de testes unitários. Estes hooks são normalmente utilizados,
de modo que o commit só é realizado, quando o seu código passa por todas as verificações sem erros. Caso você não
tenha muita familiaridade com ferramentas, como MyPy,
Pytest, Isort e Black,
recomendo que não habilite essa opção.
- Executando codestyle:
O comando a seguir formatando o seu código fonte, conforme as configurações especificadas dentro do arquivo pyproject.toml.
make codestyle
- Fazendo upload do repositório para o GitHub:
git add .
git commit -m ":tada: Initial commit"
git branch -M main
git remote add origin https://github.com/ingwersen-erik/python-template.git
git push -u origin main
Os comandos acima realizam as seguintes operações:
git add .
: Adiciona quaisquer arquivos que você tenha criado/adicionado na pasta do repositório, para serem enviados para o repositório no GitHub.git commit -m ":tada: Initial commit"
: cria o commit destes arquivos adicionados. Basicamente, um commit especifica as mudanças que pretendemos subir no repositório. A flag-m
é utilizada para especificar a mensagem do commit e, é obrigatória. Caso você não especifique uma mensagem, o commit nao será feito.git branch -M main
: cria a branch que iremos utilizar para subir os arquivos. Como estamos criando agora o repositório e, subindo os arquivos do projeto pela primeira vez, estamos criando/utilizando a branch "padrão", que é a branch "main" (alguns projetos preferem utilizar o nome "master", ao invés de "main", muito embora não seja o mais usual).git remote add origin https://github.com/ingwersen-erik/python-template.git
: esse comando especifica a URL do repositório no Github.git push -u origin main
: realiza o upload dos arquivos especificados pelo comandogit add .
, utilizando o commit que criamos utilizando o segundo comando (git commit -m ":tada: Initial commit"
).
Acesse os links abaixo, para instruções de como habilitar o GitHub Dependabot e o Stale bot.
- Set up Dependabot verifica as dependências do seu projeto e, sugere a atualização de pacotes identificados que possuem algum problema de segurança.
- Set up Stale bot realiza o fechamento automático de GitHub issues estagnados.
Want to know more about Poetry? Check its documentation.
Details about Poetry
Poetry's commands are very intuitive and easy to learn, like:
poetry add numpy@latest
poetry run pytest
poetry publish --build
etc
Building a new version of the application contains steps:
- Bump the version of your package
poetry version <version>
. You can pass the new version explicitly, or a rule such asmajor
,minor
, orpatch
. For more details, refer to the Semantic Versions standard. - Make a commit to
GitHub
. - Create a
GitHub release
. - And... publish 🙂
poetry publish --build
Helpful packages and articles:
Typer
is great for creating CLI applications.Rich
makes it easy to add beautiful formatting in the terminal.Pydantic
– data validation and settings management using Python type hinting.Loguru
makes logging (stupidly) simple.tqdm
– fast, extensible progress bar for Python and CLI.IceCream
is a little library for sweet and creamy debugging.orjson
– ultra fast JSON parsing library.Returns
makes you function's output meaningful, typed, and safe!Hydra
is a framework for elegantly configuring complex applications.FastAPI
is a type-driven asynchronous web framework.
- Open Source Guides.
- A handy guide to financial support for open source
- GitHub Actions Documentation.
- Maybe you would like to add gitmoji to commit names. This is really funny. 😄
- Supports for
Python 3.9
and higher. Poetry
as the dependencies manager. See configuration inpyproject.toml
andsetup.cfg
.- Automatic codestyle with
black
,isort
andpyupgrade
. - Ready-to-use
pre-commit
hooks with code-formatting. - Type checks with
mypy
; docstring checks withdarglint
; security checks withsafety
andbandit
- Testing with
pytest
. - Ready-to-use
.editorconfig
,.dockerignore
, and.gitignore
. You don't have to worry about those things.
GitHub
integration: issue and pr templates.Github Actions
with predefined build workflow as the default CI/CD.- Everything is already set up for security checks, codestyle checks, code formatting, testing, linting, docker builds, etc with
Makefile
. More details in makefile-usage. - Dockerfile for your package.
- Always up-to-date dependencies with
@dependabot
. You will only enable it. - Automatic drafts of new releases with
Release Drafter
. You may see the list of labels inrelease-drafter.yml
. Works perfectly with Semantic Versions specification.
- Ready-to-use Pull Requests templates and several Issue templates.
- Files such as:
LICENSE
,CONTRIBUTING.md
,CODE_OF_CONDUCT.md
, andSECURITY.md
are generated automatically. Stale bot
that closes abandoned issues after a period of inactivity. (You will only need to setup free plan). Configuration is here.- Semantic Versions specification with
Release Drafter
.
pip install -U python-template
or install with Poetry
poetry add python-template
Makefile
contains a lot of functions for faster development.
1. Download and remove Poetry
To download and install Poetry run:
make poetry-download
To uninstall
make poetry-remove
2. Install all dependencies and pre-commit hooks
Install requirements:
make install
Pre-commit hooks could be installed after git init
via:
make pre-commit-install
3. Codestyle
Automatic formatting uses pyupgrade
, isort
and black
.
make codestyle
# ou use o sinônimo do comando acima
make formatting
Codestyle checks only, without rewriting files:
make check-codestyle
Observação:
check-codestyle
utiliza as seguintes ferramentas:isort
,black
edarglint
.
Executando o próximo comando, o Poetry atualiza as dependência do seu projeto, buscando a versão mais atualizada de cada biblioteca, caso não existam erros de compatibilidade entre os requerimentos de cada biblioteca.
make update-dev-deps
4. Code security
make check-safety
This command launches Poetry
integrity checks as well as identifies security issues with Safety
and Bandit
.
make check-safety
5. Type checks
Run mypy
static type checker
make mypy
6. Tests with coverage badges
Run pytest
make test
7. All linters
Of course there is a command to rule run all linters in one:
make lint
the same as:
make test && make check-codestyle && make mypy && make check-safety
8. Docker
make docker-build
which is equivalent to:
make docker-build VERSION=latest
Remove docker image with
make docker-remove
More information about docker.
9. Cleanup
Delete pycache files
make pycache-remove
Remove package build
make build-remove
Delete .DS_STORE files
make dsstore-remove
Remove .mypycache
make mypycache-remove
Or to remove all above run:
make cleanup
You can see the list of available releases on the GitHub Releases page.
We follow Semantic Versions specification.
We use Release Drafter
. As pull requests are merged, a draft release is kept up-to-date listing the changes, ready to publish when you’re ready. With the categories option, you can categorize pull requests in release notes using labels.
Label | Title in Releases |
---|---|
enhancement , feature |
🚀 Features |
bug , refactoring , bugfix , fix |
🔧 Fixes & Refactoring |
build , ci , testing |
📦 Build System & CI/CD |
breaking |
💥 Breaking Changes |
documentation |
📝 Documentation |
dependencies |
⬆️ Dependencies updates |
You can update it in release-drafter.yml
.
GitHub creates the bug
, enhancement
, and documentation
labels for you. Dependabot creates the dependencies
label. Create the remaining labels on the Issues tab of your GitHub repository, when you need them.
This project is licensed under the terms of the MIT
license. See LICENSE for more details.
@misc{python-template,
author = {ingwersen-erik},
title = {Repositorio template para criacao de projetos em Python.},
year = {2022},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {\url{https://github.com/ingwersen-erik/python-template}}
}