Рубрики
Без рубрики

Семантическое управление версиями в Python с Git Hooks

Я пишу контент для AWS, Kubernetes, Python, JavaScript и многое другое. Чтобы просмотреть весь последний контент, будьте … Tagged с Python, 100daysOfpython.

Я пишу контент для AWS, Kubernetes, Python, JavaScript и многое другое. Чтобы просмотреть весь последний контент, обязательно Посетите мой блог и подписаться на мою рассылку. Подпишись на меня в Твиттере .

Это день 22 года #100daysofpython Challenge.

Этот пост будет использовать Предварительный Коммит и коммитировщик Пакеты для автоматизации наших семантических версий для Python на основе наших коммитов.

Пост создаст работу, выполненную в посте “Ваш первый пакет PIP с Python” Анкет

Окончательный код можно найти Здесь Анкет

Предварительные условия

  1. Знакомство с Pipenv Анкет Смотрите здесь за мой пост на Pipenv.

Начиная

Мы собираемся клонировать и работать с Okeeffed/your-первое пип-пакель-в питоне Репозиторий и установите необходимые пакеты.

$ git clone https://github.com/okeeffed/your-first-pip-package-in-python semantic-versioning-in-python-with-git-hooks
$ cd semantic-versioning-in-python-with-git-hooks

# Init the virtual environment
$ pipenv install --dev pre-commit Commitizen toml

# Create some required files
$ touch .pre-commit-config.yaml

На этом этапе мы готовы настроить наш крюк перед набором.

Предварительная конфигурация

Нам нужно добавить следующее в .pre-commit-config.yaml :

---
repos:
  - repo: https://github.com/commitizen-tools/commitizen
    rev: master
    hooks:
      - id: commitizen
        stages: [commit-msg]

После этого мы можем настроить наш Коммиссия конфигурация.

Настройка коммитировщика

Мы можем настроить это, запустив Pipenv Run Cz init :

$ pipenv run cz init
? Please choose a supported config file: (default: pyproject.toml) pyproject.toml
? Please choose a cz (commit rule): (default: cz_conventional_commits) cz_conventional_commits
No Existing Tag. Set tag to v0.0.1
? Please enter the correct version format: (default: "$version")
? Do you want to install pre-commit hook? Yes
commitizen already in pre-commit config
commitizen pre-commit hook is now installed in your '.git'

You can bump the version and create changelog running:

cz bump --changelog
The configuration are all set.

Сейчас мы находимся на стадии, где наши коммиты могут повлиять на наши версии! Файл создан для нас pyproject.toml :

[tool]
[tool.commitizen]
name = "cz_conventional_commits"
version = "0.0.1"
tag_format = "$version"

Это будет содержать информацию о версии, которая поддерживается для нас Commerizen.

Автоматизированное семантическое управление версиями на работе

Прежде всего, нам нужно будет создать тег для версии 0,0,1 :

$ git tag -a 0.0.1 -m "Init version"

Наша версия изменится на основе именования, которые мы даем наши коммиты. Установленный Git Hook будет применять, что наши коммиты следуют за Обычные коммиты Наименование соглашений.

Посмотрим на это в действии. Во -первых, давайте добавим новую функцию в файл demo_pip_math/math.py :

def divide(x: int, y: int) -> float:
    """divide one number by another

    Args:
                    x (int): first number in the division
                    y (int): second number in the division

    Returns:
                    int: division of x and y
    """
    return x / y

Мы хотим добавить и совершить этот код. Посмотрим, что произойдет, когда мы установим неверную версию:

$ git add demo_pip_math/math.py
$ git commit -m "added new feature division"
commitizen check.........................................................Failed
- hook id: commitizen
- exit code: 14

commit validation: failed!
please enter a commit message in the commitizen format.
commit "": "not a valid commit name"
pattern: (build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert|bump)(\(\S+\))?!?:(\s.*)

Это говорит об использовании, что мы не соответствовали ожидаемому шаблону.

Учитывая, что мы добавляем новую функцию, давайте попробуем с подвиг: префикс:

$ git commit -m "feat: added new divide functionality"
commitizen check.........................................................Passed
[main 333d291] feat: added new divide functionality
 1 file changed, 13 insertions(+)

Мы прошли!

Теперь, когда мы внесли изменения, мы можем использовать Коммиссия Чтобы помочь нам обновить нашу версию, создать изменение изменений и обновить версию:

$ pipenv run cz bump
bump: version 0.0.1 → 0.1.0
tag to create: 0.1.0
increment detected: MINOR

Done!

Если мы сейчас проверим pyproject.toml , мы видим, что это изменение отражено для нас:

[tool]
[tool.commitizen]
name = "cz_conventional_commits"
version = "0.1.0"
tag_format = "$version"

Создание изменчивости

Чтобы создать изменение, запустить Pipenv Run CZ Changelog :

$ pipenv run cz changelog
# ... no output

Это создаст ChangeLog.md Файл в наш проект Root Directory, теперь со следующей информацией:

## 0.1.0 (2021-08-10)

### Feat

- added new divide functionality

## 0.0.1 (2021-08-10)

### Feat

- add in division function
- init commit

Успех!

Поддерживать setup.py в синхронизации

Наконец, мы хотим убедиться, что наш setup.py синхронизируется с тем, что отражено в pyproject.toml Анкет

Мы можем сделать это с Toml упаковка.

Внутри setup.py , измените файл на следующее:

import setuptools
import toml
from os.path import join, dirname, abspath

pyproject_path = join(dirname(abspath("__file__")),
                      '../pyproject.toml')
file = open(pyproject_path, "r")
toml_str = file.read()

parsed_toml = toml.loads(toml_str)

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="demo_pip_math",
    version=parsed_toml['tool']['commitizen']['version'],
    author="Dennis O'Keeffe",
    author_email="hello@dennisokeeffe.com",
    description="Demo your first Pip package.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/okeeffed/your-first-pip-package-in-python",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
    keywords='pip-demo math',
    project_urls={
        'Homepage': 'https://github.com/okeeffed/your-first-pip-package-in-python',
    },

)

Мы читаем в TOML и находим ссылку на текущую версию.

Мы можем проверить, что это все еще работает, как и ожидалось, с сборка Сценарий, который уже был добавлен в репо:

$ pipenv run build
running sdist
running egg_info
creating demo_pip_math.egg-info
writing demo_pip_math.egg-info/PKG-INFO
writing dependency_links to demo_pip_math.egg-info/dependency_links.txt
writing top-level names to demo_pip_math.egg-info/top_level.txt
writing manifest file 'demo_pip_math.egg-info/SOURCES.txt'
reading manifest file 'demo_pip_math.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
adding license file 'LICENSE'
writing manifest file 'demo_pip_math.egg-info/SOURCES.txt'
running check
creating demo_pip_math-0.1.0
creating demo_pip_math-0.1.0/demo_pip_math
creating demo_pip_math-0.1.0/demo_pip_math.egg-info
creating demo_pip_math-0.1.0/tests
copying files to demo_pip_math-0.1.0...
copying LICENSE -> demo_pip_math-0.1.0
copying MANIFEST.in -> demo_pip_math-0.1.0
copying README.md -> demo_pip_math-0.1.0
copying pyproject.toml -> demo_pip_math-0.1.0
copying setup.py -> demo_pip_math-0.1.0
copying demo_pip_math/__init__.py -> demo_pip_math-0.1.0/demo_pip_math
copying demo_pip_math/math.py -> demo_pip_math-0.1.0/demo_pip_math
copying demo_pip_math.egg-info/PKG-INFO -> demo_pip_math-0.1.0/demo_pip_math.egg-info
copying demo_pip_math.egg-info/SOURCES.txt -> demo_pip_math-0.1.0/demo_pip_math.egg-info
copying demo_pip_math.egg-info/dependency_links.txt -> demo_pip_math-0.1.0/demo_pip_math.egg-info
copying demo_pip_math.egg-info/top_level.txt -> demo_pip_math-0.1.0/demo_pip_math.egg-info
copying tests/__init__.py -> demo_pip_math-0.1.0/tests
copying tests/test_math.py -> demo_pip_math-0.1.0/tests
Writing demo_pip_math-0.1.0/setup.cfg
creating dist
Creating tar archive
removing 'demo_pip_math-0.1.0' (and everything under it)
running bdist_wheel
running build
running build_py
creating build
creating build/lib
creating build/lib/demo_pip_math
copying demo_pip_math/__init__.py -> build/lib/demo_pip_math
copying demo_pip_math/math.py -> build/lib/demo_pip_math
creating build/lib/tests
copying tests/__init__.py -> build/lib/tests
copying tests/test_math.py -> build/lib/tests
warning: build_py: byte-compiling is disabled, skipping.

installing to build/bdist.macosx-11-x86_64/wheel
running install
running install_lib
creating build/bdist.macosx-11-x86_64
creating build/bdist.macosx-11-x86_64/wheel
creating build/bdist.macosx-11-x86_64/wheel/demo_pip_math
copying build/lib/demo_pip_math/__init__.py -> build/bdist.macosx-11-x86_64/wheel/demo_pip_math
copying build/lib/demo_pip_math/math.py -> build/bdist.macosx-11-x86_64/wheel/demo_pip_math
creating build/bdist.macosx-11-x86_64/wheel/tests
copying build/lib/tests/__init__.py -> build/bdist.macosx-11-x86_64/wheel/tests
copying build/lib/tests/test_math.py -> build/bdist.macosx-11-x86_64/wheel/tests
warning: install_lib: byte-compiling is disabled, skipping.

running install_egg_info
Copying demo_pip_math.egg-info to build/bdist.macosx-11-x86_64/wheel/demo_pip_math-0.1.0-py3.9.egg-info
running install_scripts
adding license file "LICENSE" (matched pattern "LICEN[CS]E*")
creating build/bdist.macosx-11-x86_64/wheel/demo_pip_math-0.1.0.dist-info/WHEEL
creating 'dist/demo_pip_math-0.1.0-py3-none-any.whl' and adding 'build/bdist.macosx-11-x86_64/wheel' to it
adding 'demo_pip_math/__init__.py'
adding 'demo_pip_math/math.py'
adding 'tests/__init__.py'
adding 'tests/test_math.py'
adding 'demo_pip_math-0.1.0.dist-info/LICENSE'
adding 'demo_pip_math-0.1.0.dist-info/METADATA'
adding 'demo_pip_math-0.1.0.dist-info/WHEEL'
adding 'demo_pip_math-0.1.0.dist-info/top_level.txt'
adding 'demo_pip_math-0.1.0.dist-info/RECORD'
removing build/bdist.macosx-11-x86_64/wheel

Мы можем увидеть эту версию 0,1,0 используется в этой сборке.

Резюме

Сегодняшний пост продемонстрировал, как использовать коммитировщик , Предварительный Коммит и Toml Пакеты, чтобы помочь автоматизировать наш процесс управления версиями на основе традиционных коммитов.

Это помогает более крупным командам сохранять свои пакеты семантически правильными, с небольшим количеством усилий, добавленных к их работе.

Ресурсы и дальнейшее чтение

  1. ABCS Pipenv
  2. Код проекта
  3. предварительная коммитация
  4. коммитировщик
  5. Ваш первый пакет PIP с Python

Кредит фото: Snapsbyclark

Первоначально опубликовано на моем блог . Чтобы увидеть новые сообщения без промедления, прочитайте сообщения там и подпишитесь на мою рассылку.

Оригинал: “https://dev.to/okeeffed/semantic-versioning-in-python-with-git-hooks-5c5a”