Plugin for Poetry to enable dynamic versioning based on VCS tags
—
Command-line interface functionality for standalone usage of poetry-dynamic-versioning. Provides subcommands for configuration management, version display, and manual version application with comprehensive error handling and reporting.
Primary entry point for the command-line script that handles argument parsing, command dispatch, and error management for standalone usage.
def main() -> None:
"""
Main entry point for poetry-dynamic-versioning command-line script.
Handles CLI argument parsing, command dispatch, and error reporting.
Sets CLI mode and executes appropriate subcommand or default action.
Exits with code 1 on errors, 0 on success.
"""Enable dynamic versioning in project configuration by updating pyproject.toml with appropriate settings for both Classic Poetry and PEP 621 modes.
def enable() -> None:
"""
Enable dynamic versioning in project's pyproject.toml.
Updates configuration to enable the plugin, sets up build system
requirements, and configures appropriate project format settings.
Raises:
- RuntimeError: Unable to find pyproject.toml in current directory tree
"""
def _enable_in_doc(doc: tomlkit.TOMLDocument, env: Optional[Mapping] = None) -> tomlkit.TOMLDocument:
"""
Enable dynamic versioning configuration in a TOML document.
Parameters:
- doc: TOML document to modify
- env: Environment variables for override detection
Returns:
tomlkit.TOMLDocument: Modified document with dynamic versioning enabled
"""Display current dynamic version without modifying any files, useful for testing configuration and debugging version detection.
def show() -> None:
"""
Display the current dynamic version without modifying files.
Loads configuration from pyproject.toml and prints the computed
version string to stdout.
Raises:
- RuntimeError: Unable to find pyproject.toml or compute version
"""Apply dynamic versioning manually with validation and comprehensive reporting of changes made to project files.
def apply(*, standalone: bool) -> None:
"""
Apply dynamic versioning to project files with validation.
Parameters:
- standalone: Whether running in standalone mode (affects reporting)
Validates configuration, applies version to files, and reports results.
Raises:
- RuntimeError: Unable to determine dynamic version or apply changes
"""
def report_apply(name: str) -> None:
"""
Report the results of version application.
Parameters:
- name: Project name that was processed
Prints version information and list of modified files to stderr.
"""Comprehensive configuration validation with detailed error reporting for troubleshooting configuration issues.
def validate(*, standalone: bool, config: Optional[Mapping] = None) -> None:
"""
Validate configuration and print any errors found.
Parameters:
- standalone: Whether running in standalone mode (affects error formatting)
- config: Configuration to validate (auto-detects if None)
Prints validation errors to stderr if any are found.
"""Command-line argument parsing system with subcommand support and help text generation.
def get_parser() -> argparse.ArgumentParser:
"""
Create and configure argument parser for CLI interface.
Returns:
argparse.ArgumentParser: Configured parser with subcommands
"""
def parse_args(argv=None) -> argparse.Namespace:
"""
Parse command-line arguments.
Parameters:
- argv: Argument list (defaults to sys.argv)
Returns:
argparse.Namespace: Parsed arguments with command and options
"""poetry-dynamic-versioningApplies dynamic versioning to the current project, modifying files and leaving changes in place for inspection. Equivalent to poetry dynamic-versioning when used as a plugin.
poetry-dynamic-versioning enableUpdates pyproject.toml to enable dynamic versioning with standard configuration. Creates or modifies:
[tool.poetry-dynamic-versioning] section with enable = true[build-system] section with appropriate requirements and backend[project] dynamic version configuration if applicablepoetry-dynamic-versioning showDisplays the current dynamic version without modifying any files. Useful for:
class Key:
"""Configuration key constants."""
tool = "tool"
pdv = "poetry-dynamic-versioning"
enable = "enable"
build_system = "build-system"
requires = "requires"
build_backend = "build-backend"
project = "project"
poetry = "poetry"
dynamic = "dynamic"
version = "version"
name = "name"
class Command:
"""CLI command name constants."""
dv = "dynamic-versioning"
enable = "enable"
show = "show"
dv_enable = "dynamic-versioning enable"
dv_show = "dynamic-versioning show"
class Help:
"""Help text constants."""
main = "Apply the dynamic version to all relevant files and leave the changes in-place..."
enable = "Update pyproject.toml to enable the plugin using a typical configuration..."
show = "Print the version without changing any files."_DEFAULT_REQUIRES = ["poetry-core>=1.0.0", "poetry-dynamic-versioning>=1.0.0,<2.0.0"]
_DEFAULT_BUILD_BACKEND = "poetry_dynamic_versioning.backend"# Apply dynamic versioning to current project
poetry-dynamic-versioning
# Enable dynamic versioning in project configuration
poetry-dynamic-versioning enable
# Show current version without changes
poetry-dynamic-versioning showfrom poetry_dynamic_versioning.cli import main, enable, show, apply
from poetry_dynamic_versioning import _state
# Set CLI mode
_state.cli_mode = True
# Enable dynamic versioning
try:
enable()
print("Dynamic versioning enabled successfully")
except RuntimeError as e:
print(f"Failed to enable: {e}")
# Show current version
try:
show() # Prints version to stdout
except RuntimeError as e:
print(f"Failed to show version: {e}")
# Apply versioning manually
try:
apply(standalone=True)
except RuntimeError as e:
print(f"Failed to apply version: {e}")from poetry_dynamic_versioning.cli import validate
import tomlkit
# Load and validate current project configuration
validate(standalone=True)
# Validate specific configuration
with open("pyproject.toml", "rb") as f:
config = tomlkit.parse(f.read().decode("utf-8"))
validate(standalone=True, config=config)from poetry_dynamic_versioning.cli import _enable_in_doc
import tomlkit
# Load existing pyproject.toml
with open("pyproject.toml", "rb") as f:
doc = tomlkit.parse(f.read().decode("utf-8"))
# Enable dynamic versioning
updated_doc = _enable_in_doc(doc)
# Save updated configuration
with open("pyproject.toml", "wb") as f:
f.write(tomlkit.dumps(updated_doc).encode("utf-8"))
print("Dynamic versioning configuration added")from poetry_dynamic_versioning.cli import get_parser, parse_args
# Get configured parser
parser = get_parser()
# Parse custom arguments
args = parse_args(["enable"])
print(f"Command: {args.cmd}") # "enable"
# Parse with show command
args = parse_args(["show"])
print(f"Command: {args.cmd}") # "show"
# Parse default (no subcommand)
args = parse_args([])
print(f"Command: {args.cmd}") # None (default action)The CLI can be used in build scripts and CI/CD pipelines:
#!/bin/bash
# Build script example
# Show version for logging
echo "Building version: $(poetry-dynamic-versioning show)"
# Enable if not already configured
poetry-dynamic-versioning enable
# Build with Poetry
poetry build
# Version is automatically handled during buildimport sys
from poetry_dynamic_versioning.cli import main
# The main function handles all errors and exits appropriately
try:
main()
except SystemExit as e:
if e.code != 0:
print("Command failed")
else:
print("Command succeeded")The CLI respects the same environment variables as the plugin:
# Override version globally
export POETRY_DYNAMIC_VERSIONING_BYPASS="1.0.0-custom"
poetry-dynamic-versioning show # Outputs: 1.0.0-custom
# Enable debug output
export POETRY_DYNAMIC_VERSIONING_DEBUG="1"
poetry-dynamic-versioning # Shows debug information
# Override specific project
export POETRY_DYNAMIC_VERSIONING_OVERRIDE="my-project=2.0.0"
poetry-dynamic-versioning show # Uses override if project name matchesInstall with Tessl CLI
npx tessl i tessl/pypi-poetry-dynamic-versioning