0
# Version Detection
1
2
Version extraction and processing functionality that interfaces with version control systems through the Dunamai library. Supports multiple VCS types, custom formatting, and various override mechanisms for flexible version determination.
3
4
## Capabilities
5
6
### Primary Version Detection
7
8
Extract version information from version control systems with comprehensive configuration support, pattern matching, and style validation. Handles shallow repositories, custom patterns, and multiple VCS types.
9
10
```python { .api }
11
def _get_version(config: _Config, name: Optional[str] = None) -> Tuple[str, Version]:
12
"""
13
Get version from VCS or override sources based on configuration.
14
15
Parameters:
16
- config: Configuration object containing VCS and formatting settings
17
- name: Optional project name for override lookup
18
19
Returns:
20
Tuple[str, Version]: (formatted_version_string, dunamai_version_object)
21
22
Raises:
23
- ValueError: Invalid VCS type or style configuration
24
- RuntimeError: VCS operation failures or shallow repository issues
25
"""
26
```
27
28
### Dunamai VCS Integration
29
30
Interface with Dunamai library for VCS version extraction with comprehensive parameter support including tag patterns, branch specifications, and commit handling options.
31
32
```python { .api }
33
def _get_version_from_dunamai(
34
vcs: Vcs,
35
pattern: Union[str, Pattern],
36
config: _Config,
37
*,
38
strict: Optional[bool] = None
39
) -> Version:
40
"""
41
Extract version from VCS using Dunamai with configuration options.
42
43
Parameters:
44
- vcs: Version control system type from Dunamai
45
- pattern: Tag pattern (string regex or Dunamai Pattern object)
46
- config: Configuration containing VCS-specific options
47
- strict: Override strict mode for version validation
48
49
Returns:
50
Version: Dunamai Version object with extracted version information
51
"""
52
```
53
54
### File-Based Version Sources
55
56
Read version information from files as an alternative to VCS-based detection, with optional pattern extraction for parsing complex file formats.
57
58
```python { .api }
59
def _get_version_from_file(config: _Config) -> Optional[str]:
60
"""
61
Read version from a file specified in configuration.
62
63
Parameters:
64
- config: Configuration containing from-file settings
65
66
Returns:
67
Optional[str]: Version string from file or None if not configured
68
69
Raises:
70
- RuntimeError: Unable to find pyproject.toml for relative path resolution
71
- ValueError: File doesn't match specified pattern
72
"""
73
```
74
75
### Version Override System
76
77
Environment-based version override system supporting both global bypass and per-package overrides for build system flexibility and distro packaging support.
78
79
```python { .api }
80
def _get_override_version(name: Optional[str], env: Optional[Mapping] = None) -> Optional[str]:
81
"""
82
Get version override from environment variables.
83
84
Parameters:
85
- name: Package name for specific override lookup
86
- env: Environment variables mapping (defaults to os.environ)
87
88
Returns:
89
Optional[str]: Override version string or None if not set
90
"""
91
```
92
93
### Jinja Template Rendering
94
95
Render Jinja2 templates with comprehensive version context including VCS information, environment variables, and formatting functions for advanced version string customization.
96
97
```python { .api }
98
def _render_jinja(
99
version: Version,
100
template: str,
101
config: _Config,
102
extra: Optional[Mapping] = None
103
) -> str:
104
"""
105
Render Jinja2 template with version context and configuration imports.
106
107
Parameters:
108
- version: Dunamai Version object with VCS information
109
- template: Jinja2 template string
110
- config: Configuration including format-jinja-imports
111
- extra: Additional template variables
112
113
Returns:
114
str: Rendered version string from template
115
"""
116
```
117
118
## Version Context Variables
119
120
The Jinja rendering system provides extensive context variables:
121
122
### Core Version Information
123
124
```python { .api }
125
# Basic version components
126
base: str # Base version (e.g., "1.2.3")
127
stage: Optional[str] # Pre-release stage (e.g., "alpha", "beta", "rc")
128
revision: Optional[int] # Pre-release revision number
129
distance: int # Commits since last tag
130
commit: str # Commit hash (short or full based on config)
131
dirty: bool # Whether working directory has uncommitted changes
132
133
# Branch and metadata
134
branch: Optional[str] # Current branch name
135
branch_escaped: Optional[str] # Branch name with non-alphanumeric chars removed
136
tagged_metadata: Optional[str] # Tagged metadata from version pattern
137
timestamp: Optional[str] # Commit timestamp as YYYYmmddHHMMSS UTC
138
139
# Semantic version components
140
major: int # First part of base version
141
minor: int # Second part of base version
142
patch: int # Third part of base version
143
144
# Additional context
145
version: Version # Full Dunamai Version object
146
env: dict # Environment variables dictionary
147
```
148
149
### Template Functions
150
151
```python { .api }
152
# Dunamai serialization functions
153
bump_version(version: str, index: int = -1) -> str
154
serialize_pep440(base: str, stage: str = None, revision: int = None, **kwargs) -> str
155
serialize_semver(base: str, stage: str = None, revision: int = None, **kwargs) -> str
156
serialize_pvp(base: str, stage: str = None, revision: int = None, **kwargs) -> str
157
```
158
159
## Usage Examples
160
161
### Basic Version Detection
162
163
```python
164
from poetry_dynamic_versioning import _get_version, _get_config_from_path
165
166
# Get configuration and version
167
config = _get_config_from_path()
168
version_str, version_obj = _get_version(config)
169
170
print(f"Version: {version_str}")
171
print(f"Base: {version_obj.base}")
172
print(f"Distance: {version_obj.distance}")
173
print(f"Commit: {version_obj.commit}")
174
```
175
176
### Environment Override Usage
177
178
```python
179
import os
180
from poetry_dynamic_versioning import _get_override_version
181
182
# Set environment override
183
os.environ["POETRY_DYNAMIC_VERSIONING_OVERRIDE"] = "my-package=1.0.0,other-pkg=2.0.0"
184
185
# Check for override
186
override = _get_override_version("my-package")
187
if override:
188
print(f"Using override version: {override}")
189
```
190
191
### Custom Jinja Template
192
193
```python
194
from dunamai import Version
195
from poetry_dynamic_versioning import _render_jinja
196
197
# Create version object
198
version = Version("1.2.3", distance=5, commit="abc123", dirty=True)
199
200
# Custom template
201
template = """
202
{%- if distance == 0 -%}
203
{{ base }}
204
{%- else -%}
205
{{ base }}.dev{{ distance }}+{{ commit }}{% if dirty %}.dirty{% endif %}
206
{%- endif -%}
207
"""
208
209
config = {
210
"format-jinja-imports": [],
211
"bump": False
212
}
213
214
result = _render_jinja(version, template, config)
215
print(f"Formatted version: {result}") # "1.2.3.dev5+abc123.dirty"
216
```
217
218
### File-Based Version Reading
219
220
```python
221
from poetry_dynamic_versioning import _get_version_from_file
222
223
# Configuration for reading from VERSION file
224
config = {
225
"from-file": {
226
"source": "VERSION",
227
"pattern": r"v(\d+\.\d+\.\d+)" # Extract version from "v1.2.3" format
228
}
229
}
230
231
version = _get_version_from_file(config)
232
if version:
233
print(f"Version from file: {version}")
234
```
235
236
### VCS Pattern Customization
237
238
```python
239
from dunamai import Vcs, Pattern
240
from poetry_dynamic_versioning import _get_version_from_dunamai
241
242
# Custom configuration for Git with specific pattern
243
config = {
244
"latest-tag": False,
245
"tag-dir": "tags",
246
"tag-branch": None,
247
"full-commit": True,
248
"strict": True,
249
"pattern-prefix": "release-",
250
"ignore-untracked": True,
251
"commit-length": 8
252
}
253
254
# Use custom pattern for release tags
255
pattern = r"release-(?P<base>\d+\.\d+\.\d+)"
256
version = _get_version_from_dunamai(Vcs.Git, pattern, config)
257
258
print(f"Version from Git: {version.serialize()}")
259
```