or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-interface.mdconfiguration.mdfile-management.mdindex.mdplugin-system.mdversion-detection.md
tile.json

tessl/pypi-poetry-dynamic-versioning

Plugin for Poetry to enable dynamic versioning based on VCS tags

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/poetry-dynamic-versioning@1.9.x

To install, run

npx @tessl/cli install tessl/pypi-poetry-dynamic-versioning@1.9.0

index.mddocs/

Poetry Dynamic Versioning

A Poetry plugin that enables dynamic versioning based on version control system tags. It automatically injects version information from VCS tags (like Git tags) into relevant project files during Poetry commands such as build, eliminating the need to manually edit and commit version changes.

Package Information

  • Package Name: poetry-dynamic-versioning
  • Language: Python
  • Installation: pip install "poetry-dynamic-versioning[plugin]"
  • Requirements: Python 3.7+, Poetry 1.2.0+

Core Imports

import poetry_dynamic_versioning

For programmatic usage (internal API functions):

from poetry_dynamic_versioning import (
    _get_version,
    _get_and_apply_version,
    _get_config_from_path,
    _validate_config
)

Note: These are internal functions (prefixed with _) and may change between versions. They are documented here as they provide the core functionality for programmatic usage.

Basic Usage

As Poetry Plugin

Configure in pyproject.toml:

[tool.poetry-dynamic-versioning]
enable = true

[build-system]
requires = ["poetry-core>=1.0.0", "poetry-dynamic-versioning>=1.0.0,<2.0.0"]
build-backend = "poetry_dynamic_versioning.backend"

Enable via CLI:

# Install plugin
poetry self add "poetry-dynamic-versioning[plugin]"

# Enable in project
poetry dynamic-versioning enable

# Apply versioning manually
poetry dynamic-versioning

# Show current version
poetry dynamic-versioning show

Programmatic Usage

from poetry_dynamic_versioning import _get_version, _get_config_from_path
from pathlib import Path

# Get configuration for current project
config = _get_config_from_path()

# Get dynamic version
version_string, version_obj = _get_version(config)
print(f"Dynamic version: {version_string}")

# Apply version to project files
from poetry_dynamic_versioning import _get_and_apply_version
project_name = _get_and_apply_version(retain=True, force=True)

Architecture

Poetry Dynamic Versioning operates through several key components:

  • Plugin System: Integrates with Poetry via ApplicationPlugin to hook into Poetry commands
  • Build Backend: Provides PEP 517 compliant build backend by wrapping poetry.core.masonry.api
  • Version Detection: Uses Dunamai library to extract version information from VCS tags
  • File Substitution: Automatically updates version placeholders in source files during builds
  • State Management: Tracks and reverts changes to maintain repository cleanliness

The plugin supports both Classic Poetry mode ([tool.poetry]) and PEP 621 mode ([project]), automatically detecting the appropriate configuration format.

Capabilities

Configuration Management

Load, validate, and merge configuration from pyproject.toml with comprehensive validation and default value handling. Supports complex configuration hierarchies including substitution patterns, file-specific settings, and VCS options.

def _get_config(local: Mapping) -> _Config: ...
def _get_config_from_path(start: Optional[Path] = None) -> Mapping: ...
def _validate_config(config: Optional[Mapping] = None) -> Sequence[str]: ...
def _default_config() -> Mapping: ...

Configuration

Version Detection and Processing

Extract version information from version control systems using Dunamai, with support for custom patterns, formatting, and override mechanisms. Handles Git, Mercurial, and other VCS systems with extensive customization options.

def _get_version(config: _Config, name: Optional[str] = None) -> Tuple[str, Version]: ...
def _get_version_from_file(config: _Config) -> Optional[str]: ...
def _get_override_version(name: Optional[str], env: Optional[Mapping] = None) -> Optional[str]: ...

Version Detection

File Management and Substitution

Apply dynamic versions to project files with automatic backup and restoration. Supports pattern-based substitution in multiple file types with configurable folder structures and file-specific behaviors.

def _get_and_apply_version(
    pyproject_path: Optional[Path] = None,
    retain: bool = False,
    force: bool = False,
    io: bool = True
) -> Optional[str]: ...
def _apply_version(
    name: str,
    version: str,
    instance: Version,
    config: _Config,
    pyproject_path: Path,
    mode: _Mode,
    retain: bool = False
) -> None: ...
def _revert_version(retain: bool = False) -> None: ...

File Management

Plugin Integration

Poetry plugin classes and command handlers that integrate dynamic versioning into Poetry's command lifecycle with event-driven activation and cleanup.

class DynamicVersioningPlugin(ApplicationPlugin):
    def activate(self, application: Application) -> None: ...

class DynamicVersioningCommand(Command):
    def handle(self) -> int: ...

def activate() -> None: ...
def deactivate() -> None: ...

Plugin System

CLI Interface

Command-line interface for standalone usage with subcommands for enabling configuration, showing versions, and applying dynamic versioning outside of Poetry command contexts.

def main() -> None: ...
def enable() -> None: ...
def show() -> None: ...
def apply(*, standalone: bool) -> None: ...

Main Script Entry Point:

# From poetry_dynamic_versioning.__main__ module
def main() -> None:
    """
    Main entry point for the poetry-dynamic-versioning console script.
    
    Parses command-line arguments, sets CLI mode, and dispatches to
    appropriate CLI functions. Handles exceptions and exits with
    appropriate error codes.
    
    Used when package is executed as: python -m poetry_dynamic_versioning
    """

CLI Interface

Build Backend Integration

PEP 517 build backend that wraps poetry-core's masonry API with automatic dynamic versioning activation and cleanup for seamless integration with build tools.

# From poetry_dynamic_versioning.backend module
# Re-exports all poetry.core.masonry.api functionality with patching

def activate() -> None:
    """
    Activate build backend patching system.
    
    Automatically called when backend is loaded. Checks configuration,
    applies patches if enabled, and registers cleanup handlers.
    """

def deactivate() -> None:
    """
    Deactivate patches and restore original state.
    
    Called automatically on exit to ensure repository cleanliness
    after build operations complete.
    """

The backend module automatically re-exports all functions from poetry.core.masonry.api while adding dynamic versioning capabilities through the patch system.

Utility Functions

Internal utility functions that provide debugging, command execution, and project file discovery capabilities for advanced programmatic usage.

def _debug(message: str) -> None:
    """
    Print debug message to stderr if debug mode is enabled.
    
    Parameters:
    - message: Debug message to print
    
    Debug mode is controlled by POETRY_DYNAMIC_VERSIONING_DEBUG environment variable.
    """

def _run_cmd(command: str, codes: Sequence[int] = (0,)) -> Tuple[int, str]:
    """
    Execute shell command and return result.
    
    Parameters:
    - command: Shell command to execute
    - codes: Acceptable exit codes (defaults to [0])
    
    Returns:
    Tuple[int, str]: Exit code and combined stdout/stderr output
    
    Raises:
    - RuntimeError: If command exits with unacceptable code
    """

def _escape_branch(value: Optional[str]) -> Optional[str]:
    """
    Escape branch name for safe usage in version strings.
    
    Parameters:
    - value: Branch name to escape
    
    Returns:
    Optional[str]: Escaped branch name with non-alphanumeric characters removed
    """

def _format_timestamp(value: Optional[dt.datetime]) -> Optional[str]:
    """
    Format datetime as timestamp string.
    
    Parameters:
    - value: Datetime to format
    
    Returns:
    Optional[str]: Formatted timestamp string (YYYYMMDDHHMMSS)
    """

def _find_higher_file(*names: str, start: Optional[Path] = None) -> Optional[Path]:
    """
    Find file in current directory or parent directories.
    
    Parameters:
    - names: File names to search for
    - start: Starting directory (defaults to current directory)
    
    Returns:
    Optional[Path]: Path to first found file, or None if not found
    """

def _get_pyproject_path(start: Optional[Path] = None) -> Optional[Path]:
    """
    Find pyproject.toml file in directory tree.
    
    Parameters:
    - start: Starting directory (defaults to current directory)
    
    Returns:
    Optional[Path]: Path to pyproject.toml file, or None if not found
    """

def _get_pyproject_path_from_poetry(pyproject) -> Path:
    """
    Extract pyproject.toml path from Poetry instance.
    
    Parameters:
    - pyproject: Poetry pyproject instance
    
    Returns:
    Path: Path to pyproject.toml file
    
    Raises:
    - RuntimeError: Unable to determine path from Poetry instance
    """

Types

class _Mode(Enum):
    Classic = "classic"
    Pep621 = "pep621"

class _ProjectState:
    def __init__(
        self,
        path: Path,
        original_version: Optional[str],
        version: str,
        mode: _Mode,
        dynamic_array: Optional[tomlkit.items.Array],
        substitutions: Optional[MutableMapping[Path, str]] = None,
    ) -> None: ...

class _State:
    def __init__(self) -> None: ...
    patched_core_poetry_create: bool
    cli_mode: bool
    projects: MutableMapping[str, _ProjectState]

Environment Variables

  • POETRY_DYNAMIC_VERSIONING_BYPASS: Override version globally
  • POETRY_DYNAMIC_VERSIONING_OVERRIDE: Override specific packages (format: pkg1=0.1.0,pkg2=0.2.0)
  • POETRY_DYNAMIC_VERSIONING_DEBUG: Enable debug output (set to 1)
  • POETRY_DYNAMIC_VERSIONING_COMMANDS: Comma-separated list of Poetry commands to activate on
  • POETRY_DYNAMIC_VERSIONING_COMMANDS_NO_IO: Commands that shouldn't modify files (default: version)