0
# Core Version Management
1
2
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.
3
4
## Capabilities
5
6
### Version Bumping Operations
7
8
Core functions for performing version bumps programmatically with full configuration support and SCM integration.
9
10
```python { .api }
11
def do_bump(
12
version_part: Optional[str],
13
new_version: Optional[str],
14
config: Config,
15
config_file: Optional[Path] = None,
16
dry_run: bool = False
17
) -> None:
18
"""
19
Perform complete version bump operation.
20
21
Executes the full version bump workflow including version calculation,
22
file updates, SCM operations, and hook execution.
23
24
Args:
25
version_part: Component to increment ('major', 'minor', 'patch', etc.)
26
new_version: Explicit version to set (overrides version_part)
27
config: Configuration object with version settings and behavior
28
config_file: Path to configuration file to update
29
dry_run: Preview changes without modifying files
30
31
Raises:
32
ConfigurationError: Invalid configuration or missing required settings
33
VersionNotFoundError: Current version not found in files
34
DirtyWorkingDirectoryError: Repository has uncommitted changes
35
"""
36
37
def get_next_version(
38
current_version: "Version",
39
config: Config,
40
version_part: Optional[str] = None,
41
new_version: Optional[str] = None
42
) -> "Version":
43
"""
44
Calculate the next version based on current version and configuration.
45
46
Determines next version by incrementing specified component or parsing
47
explicit version string according to configuration rules.
48
49
Args:
50
current_version: Current Version object
51
config: Configuration containing version rules and formats
52
version_part: Component to increment (e.g., 'patch', 'minor')
53
new_version: Explicit version string to parse
54
55
Returns:
56
New Version object with updated components
57
58
Raises:
59
ConfigurationError: Cannot generate next version
60
InvalidVersionPartError: Invalid version component specified
61
"""
62
63
def commit_and_tag(
64
config: Config,
65
context: Dict[str, Any],
66
dry_run: bool = False
67
) -> None:
68
"""
69
Create SCM commit and tag after version changes.
70
71
Handles repository operations including staging changes, creating commits,
72
and applying tags with templated messages.
73
74
Args:
75
config: Configuration with SCM settings
76
context: Template context for commit/tag messages
77
dry_run: Preview operations without executing
78
"""
79
```
80
81
### Version Object Model
82
83
Core class representing parsed versions with component manipulation capabilities.
84
85
```python { .api }
86
class Version:
87
"""
88
Represents a parsed version with its components.
89
90
Provides methods for bumping version components and serializing
91
back to string format using configured patterns.
92
"""
93
94
def __init__(self, values: Dict[str, Any], spec: VersionSpec) -> None:
95
"""
96
Initialize Version with component values and specification.
97
98
Args:
99
values: Dictionary of version component values
100
spec: VersionSpec defining component behavior
101
"""
102
103
def bump(self, version_part: str) -> "Version":
104
"""
105
Create new Version with specified component incremented.
106
107
Args:
108
version_part: Name of component to increment
109
110
Returns:
111
New Version object with bumped component
112
113
Raises:
114
InvalidVersionPartError: Component doesn't exist or can't be bumped
115
"""
116
117
def serialize(
118
self,
119
serialize_patterns: List[str],
120
context: Dict[str, Any]
121
) -> str:
122
"""
123
Convert Version back to string using serialization patterns.
124
125
Args:
126
serialize_patterns: List of format patterns to try
127
context: Template context for formatting
128
129
Returns:
130
Formatted version string
131
132
Raises:
133
FormattingError: Cannot format version with given patterns
134
"""
135
136
@property
137
def values(self) -> Dict[str, Any]:
138
"""Dictionary of component names to values."""
139
```
140
141
### Version Components
142
143
Individual version component management with customizable behavior and increment rules.
144
145
```python { .api }
146
class VersionComponent:
147
"""
148
Represents a single version component with its behavior rules.
149
150
Handles component-specific increment logic, value validation,
151
and null/reset behavior for complex versioning schemes.
152
"""
153
154
def __init__(self, name: str, spec: VersionComponentSpec) -> None:
155
"""
156
Initialize component with name and specification.
157
158
Args:
159
name: Component name (e.g., 'major', 'minor', 'patch')
160
spec: Component specification defining behavior
161
"""
162
163
def bump(self, value: str) -> str:
164
"""
165
Increment component value according to its function.
166
167
Args:
168
value: Current component value
169
170
Returns:
171
Next component value
172
173
Raises:
174
FormattingError: Cannot increment value
175
"""
176
177
def null_value(self) -> str:
178
"""
179
Get null/reset value for this component.
180
181
Returns:
182
Value to use when resetting component (e.g., '0' for numeric)
183
"""
184
185
class VersionSpec:
186
"""
187
Specification of version components and their relationships.
188
189
Defines the complete structure of a version including component
190
order, dependencies, and increment behavior.
191
"""
192
193
def __init__(self, components: Dict[str, VersionComponent]) -> None:
194
"""
195
Initialize specification with component definitions.
196
197
Args:
198
components: Dictionary mapping component names to VersionComponent objects
199
"""
200
201
def create_version(self, values: Dict[str, Any]) -> Version:
202
"""
203
Create Version object from component values.
204
205
Args:
206
values: Dictionary of component values
207
208
Returns:
209
New Version object
210
"""
211
```
212
213
### Version Configuration
214
215
Configuration management for version parsing, serialization, and component behavior.
216
217
```python { .api }
218
class VersionConfig:
219
"""
220
Configuration for version parsing and serialization.
221
222
Contains regex patterns, serialization formats, and component
223
specifications for a complete versioning scheme.
224
"""
225
226
def __init__(
227
self,
228
parse: str,
229
serialize: List[str],
230
search: str,
231
replace: str,
232
part_configs: Dict[str, VersionComponentSpec]
233
) -> None:
234
"""
235
Initialize version configuration.
236
237
Args:
238
parse: Regex pattern for parsing version strings
239
serialize: List of serialization format patterns
240
search: Template for finding versions in files
241
replace: Template for replacing versions in files
242
part_configs: Component specifications
243
"""
244
245
def parse(self, version_string: str) -> Dict[str, str]:
246
"""
247
Parse version string into component dictionary.
248
249
Args:
250
version_string: Version string to parse
251
252
Returns:
253
Dictionary of component names to string values
254
255
Raises:
256
FormattingError: String doesn't match parse pattern
257
"""
258
259
def create_version_spec(self) -> VersionSpec:
260
"""
261
Create VersionSpec from component configurations.
262
263
Returns:
264
VersionSpec object for creating Version instances
265
"""
266
```
267
268
### Version Functions
269
270
Component increment functions supporting different versioning behaviors.
271
272
```python { .api }
273
class NumericFunction:
274
"""Numeric increment function for integer components."""
275
276
def __init__(self, first_value: str = "0") -> None:
277
"""
278
Initialize numeric function.
279
280
Args:
281
first_value: Starting value for component
282
"""
283
284
def bump(self, value: str) -> str:
285
"""Increment numeric value by 1."""
286
287
class ValuesFunction:
288
"""List-based function for enumerated values like alpha, beta, rc."""
289
290
def __init__(
291
self,
292
values: List[str],
293
optional_value: Optional[str] = None,
294
first_value: Optional[str] = None
295
) -> None:
296
"""
297
Initialize values function.
298
299
Args:
300
values: List of valid values in increment order
301
optional_value: Value that can be skipped
302
first_value: Starting value
303
"""
304
305
def bump(self, value: str) -> str:
306
"""Move to next value in the list."""
307
308
class CalVerFunction:
309
"""Calendar versioning function for date-based components."""
310
311
def __init__(self, calver_format: str) -> None:
312
"""
313
Initialize CalVer function.
314
315
Args:
316
calver_format: CalVer format string (e.g., '%Y', '%m', '%d')
317
"""
318
319
def bump(self, value: str) -> str:
320
"""Update to current date value."""
321
```
322
323
### Serialization Functions
324
325
Version string parsing and formatting utilities.
326
327
```python { .api }
328
def parse_version(
329
version_string: str,
330
parse_pattern: str
331
) -> Dict[str, str]:
332
"""
333
Parse version string using regex pattern.
334
335
Args:
336
version_string: Version string to parse
337
parse_pattern: Regex pattern with named groups
338
339
Returns:
340
Dictionary of component names to values
341
342
Raises:
343
FormattingError: String doesn't match pattern
344
"""
345
346
def serialize(
347
version: Version,
348
serialize_patterns: List[str],
349
context: Dict[str, Any]
350
) -> str:
351
"""
352
Serialize Version object to string using format patterns.
353
354
Args:
355
version: Version object to serialize
356
serialize_patterns: List of format strings to try
357
context: Template context for formatting
358
359
Returns:
360
Formatted version string
361
362
Raises:
363
FormattingError: Cannot format with any pattern
364
"""
365
```
366
367
## Usage Examples
368
369
### Basic Version Bumping
370
371
```python
372
from bumpversion.config import get_configuration
373
from bumpversion.bump import do_bump, get_next_version
374
375
# Load project configuration
376
config = get_configuration()
377
378
# Perform complete version bump
379
do_bump(
380
version_part="patch",
381
new_version=None,
382
config=config,
383
config_file=None,
384
dry_run=False
385
)
386
387
# Or get next version without updating files
388
current_version = config.version_config.parse(config.current_version)
389
next_version = get_next_version(current_version, config, "minor")
390
print(f"Next version: {next_version.serialize(config.serialize, {})}")
391
```
392
393
### Custom Version Manipulation
394
395
```python
396
from bumpversion.versioning.models import Version, VersionSpec, VersionComponent
397
from bumpversion.versioning.functions import NumericFunction, ValuesFunction
398
399
# Create custom version components
400
major = VersionComponent("major", VersionComponentSpec(type="numeric"))
401
minor = VersionComponent("minor", VersionComponentSpec(type="numeric"))
402
pre = VersionComponent("pre", VersionComponentSpec(
403
type="values",
404
values=["alpha", "beta", "rc"],
405
optional_value="rc"
406
))
407
408
# Create version spec
409
spec = VersionSpec({"major": major, "minor": minor, "pre": pre})
410
411
# Create and manipulate version
412
version = spec.create_version({"major": "1", "minor": "2", "pre": "alpha"})
413
bumped = version.bump("pre") # 1.2.beta
414
```
415
416
### Version Configuration
417
418
```python
419
from bumpversion.versioning.version_config import VersionConfig
420
from bumpversion.versioning.models import VersionComponentSpec
421
422
# Create custom version configuration
423
config = VersionConfig(
424
parse=r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<pre>\w+))?",
425
serialize=[
426
"{major}.{minor}.{patch}-{pre}",
427
"{major}.{minor}.{patch}"
428
],
429
search="{current_version}",
430
replace="{new_version}",
431
part_configs={
432
"major": VersionComponentSpec(type="numeric"),
433
"minor": VersionComponentSpec(type="numeric"),
434
"patch": VersionComponentSpec(type="numeric"),
435
"pre": VersionComponentSpec(
436
type="values",
437
values=["alpha", "beta", "rc"],
438
optional_value="rc"
439
)
440
}
441
)
442
443
# Parse and manipulate versions
444
components = config.parse("1.2.3-beta")
445
version = config.create_version_spec().create_version(components)
446
```