Version-bump your software with a single command
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Programmatic API for version parsing, manipulation, and bumping operations. This module provides the foundational functionality for understanding, modifying, and serializing version numbers across multiple versioning schemes including SemVer, CalVer, and custom formats.
Core functions for performing version bumps programmatically with full configuration support and SCM integration.
def do_bump(
version_part: Optional[str],
new_version: Optional[str],
config: Config,
config_file: Optional[Path] = None,
dry_run: bool = False
) -> None:
"""
Perform complete version bump operation.
Executes the full version bump workflow including version calculation,
file updates, SCM operations, and hook execution.
Args:
version_part: Component to increment ('major', 'minor', 'patch', etc.)
new_version: Explicit version to set (overrides version_part)
config: Configuration object with version settings and behavior
config_file: Path to configuration file to update
dry_run: Preview changes without modifying files
Raises:
ConfigurationError: Invalid configuration or missing required settings
VersionNotFoundError: Current version not found in files
DirtyWorkingDirectoryError: Repository has uncommitted changes
"""
def get_next_version(
current_version: "Version",
config: Config,
version_part: Optional[str] = None,
new_version: Optional[str] = None
) -> "Version":
"""
Calculate the next version based on current version and configuration.
Determines next version by incrementing specified component or parsing
explicit version string according to configuration rules.
Args:
current_version: Current Version object
config: Configuration containing version rules and formats
version_part: Component to increment (e.g., 'patch', 'minor')
new_version: Explicit version string to parse
Returns:
New Version object with updated components
Raises:
ConfigurationError: Cannot generate next version
InvalidVersionPartError: Invalid version component specified
"""
def commit_and_tag(
config: Config,
context: Dict[str, Any],
dry_run: bool = False
) -> None:
"""
Create SCM commit and tag after version changes.
Handles repository operations including staging changes, creating commits,
and applying tags with templated messages.
Args:
config: Configuration with SCM settings
context: Template context for commit/tag messages
dry_run: Preview operations without executing
"""Core class representing parsed versions with component manipulation capabilities.
class Version:
"""
Represents a parsed version with its components.
Provides methods for bumping version components and serializing
back to string format using configured patterns.
"""
def __init__(self, values: Dict[str, Any], spec: VersionSpec) -> None:
"""
Initialize Version with component values and specification.
Args:
values: Dictionary of version component values
spec: VersionSpec defining component behavior
"""
def bump(self, version_part: str) -> "Version":
"""
Create new Version with specified component incremented.
Args:
version_part: Name of component to increment
Returns:
New Version object with bumped component
Raises:
InvalidVersionPartError: Component doesn't exist or can't be bumped
"""
def serialize(
self,
serialize_patterns: List[str],
context: Dict[str, Any]
) -> str:
"""
Convert Version back to string using serialization patterns.
Args:
serialize_patterns: List of format patterns to try
context: Template context for formatting
Returns:
Formatted version string
Raises:
FormattingError: Cannot format version with given patterns
"""
@property
def values(self) -> Dict[str, Any]:
"""Dictionary of component names to values."""Individual version component management with customizable behavior and increment rules.
class VersionComponent:
"""
Represents a single version component with its behavior rules.
Handles component-specific increment logic, value validation,
and null/reset behavior for complex versioning schemes.
"""
def __init__(self, name: str, spec: VersionComponentSpec) -> None:
"""
Initialize component with name and specification.
Args:
name: Component name (e.g., 'major', 'minor', 'patch')
spec: Component specification defining behavior
"""
def bump(self, value: str) -> str:
"""
Increment component value according to its function.
Args:
value: Current component value
Returns:
Next component value
Raises:
FormattingError: Cannot increment value
"""
def null_value(self) -> str:
"""
Get null/reset value for this component.
Returns:
Value to use when resetting component (e.g., '0' for numeric)
"""
class VersionSpec:
"""
Specification of version components and their relationships.
Defines the complete structure of a version including component
order, dependencies, and increment behavior.
"""
def __init__(self, components: Dict[str, VersionComponent]) -> None:
"""
Initialize specification with component definitions.
Args:
components: Dictionary mapping component names to VersionComponent objects
"""
def create_version(self, values: Dict[str, Any]) -> Version:
"""
Create Version object from component values.
Args:
values: Dictionary of component values
Returns:
New Version object
"""Configuration management for version parsing, serialization, and component behavior.
class VersionConfig:
"""
Configuration for version parsing and serialization.
Contains regex patterns, serialization formats, and component
specifications for a complete versioning scheme.
"""
def __init__(
self,
parse: str,
serialize: List[str],
search: str,
replace: str,
part_configs: Dict[str, VersionComponentSpec]
) -> None:
"""
Initialize version configuration.
Args:
parse: Regex pattern for parsing version strings
serialize: List of serialization format patterns
search: Template for finding versions in files
replace: Template for replacing versions in files
part_configs: Component specifications
"""
def parse(self, version_string: str) -> Dict[str, str]:
"""
Parse version string into component dictionary.
Args:
version_string: Version string to parse
Returns:
Dictionary of component names to string values
Raises:
FormattingError: String doesn't match parse pattern
"""
def create_version_spec(self) -> VersionSpec:
"""
Create VersionSpec from component configurations.
Returns:
VersionSpec object for creating Version instances
"""Component increment functions supporting different versioning behaviors.
class NumericFunction:
"""Numeric increment function for integer components."""
def __init__(self, first_value: str = "0") -> None:
"""
Initialize numeric function.
Args:
first_value: Starting value for component
"""
def bump(self, value: str) -> str:
"""Increment numeric value by 1."""
class ValuesFunction:
"""List-based function for enumerated values like alpha, beta, rc."""
def __init__(
self,
values: List[str],
optional_value: Optional[str] = None,
first_value: Optional[str] = None
) -> None:
"""
Initialize values function.
Args:
values: List of valid values in increment order
optional_value: Value that can be skipped
first_value: Starting value
"""
def bump(self, value: str) -> str:
"""Move to next value in the list."""
class CalVerFunction:
"""Calendar versioning function for date-based components."""
def __init__(self, calver_format: str) -> None:
"""
Initialize CalVer function.
Args:
calver_format: CalVer format string (e.g., '%Y', '%m', '%d')
"""
def bump(self, value: str) -> str:
"""Update to current date value."""Version string parsing and formatting utilities.
def parse_version(
version_string: str,
parse_pattern: str
) -> Dict[str, str]:
"""
Parse version string using regex pattern.
Args:
version_string: Version string to parse
parse_pattern: Regex pattern with named groups
Returns:
Dictionary of component names to values
Raises:
FormattingError: String doesn't match pattern
"""
def serialize(
version: Version,
serialize_patterns: List[str],
context: Dict[str, Any]
) -> str:
"""
Serialize Version object to string using format patterns.
Args:
version: Version object to serialize
serialize_patterns: List of format strings to try
context: Template context for formatting
Returns:
Formatted version string
Raises:
FormattingError: Cannot format with any pattern
"""from bumpversion.config import get_configuration
from bumpversion.bump import do_bump, get_next_version
# Load project configuration
config = get_configuration()
# Perform complete version bump
do_bump(
version_part="patch",
new_version=None,
config=config,
config_file=None,
dry_run=False
)
# Or get next version without updating files
current_version = config.version_config.parse(config.current_version)
next_version = get_next_version(current_version, config, "minor")
print(f"Next version: {next_version.serialize(config.serialize, {})}")from bumpversion.versioning.models import Version, VersionSpec, VersionComponent
from bumpversion.versioning.functions import NumericFunction, ValuesFunction
# Create custom version components
major = VersionComponent("major", VersionComponentSpec(type="numeric"))
minor = VersionComponent("minor", VersionComponentSpec(type="numeric"))
pre = VersionComponent("pre", VersionComponentSpec(
type="values",
values=["alpha", "beta", "rc"],
optional_value="rc"
))
# Create version spec
spec = VersionSpec({"major": major, "minor": minor, "pre": pre})
# Create and manipulate version
version = spec.create_version({"major": "1", "minor": "2", "pre": "alpha"})
bumped = version.bump("pre") # 1.2.betafrom bumpversion.versioning.version_config import VersionConfig
from bumpversion.versioning.models import VersionComponentSpec
# Create custom version configuration
config = VersionConfig(
parse=r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<pre>\w+))?",
serialize=[
"{major}.{minor}.{patch}-{pre}",
"{major}.{minor}.{patch}"
],
search="{current_version}",
replace="{new_version}",
part_configs={
"major": VersionComponentSpec(type="numeric"),
"minor": VersionComponentSpec(type="numeric"),
"patch": VersionComponentSpec(type="numeric"),
"pre": VersionComponentSpec(
type="values",
values=["alpha", "beta", "rc"],
optional_value="rc"
)
}
)
# Parse and manipulate versions
components = config.parse("1.2.3-beta")
version = config.create_version_spec().create_version(components)Install with Tessl CLI
npx tessl i tessl/pypi-bump-my-version