0
# Core API
1
2
The core API provides the fundamental functions and classes for extracting version information from SCM repositories. These components form the foundation of setuptools-scm's functionality.
3
4
```python
5
from re import Pattern
6
from datetime import date, datetime
7
from typing import Any, Callable, Sequence
8
from os import PathLike
9
10
# Type Aliases (from setuptools_scm)
11
PathT = PathLike[str] | str
12
CMD_TYPE = Sequence[PathT] | str
13
VERSION_SCHEME = str | Callable[["ScmVersion"], str]
14
```
15
16
## Capabilities
17
18
### Version Retrieval Functions
19
20
Primary entry points for getting version information from SCM repositories with extensive configuration options.
21
22
```python { .api }
23
def get_version(
24
root: PathT = ".",
25
version_scheme: VERSION_SCHEME = "guess-next-dev",
26
local_scheme: VERSION_SCHEME = "node-and-date",
27
write_to: PathT | None = None,
28
write_to_template: str | None = None,
29
version_file: PathT | None = None,
30
version_file_template: str | None = None,
31
relative_to: PathT | None = None,
32
tag_regex: str | Pattern[str] = DEFAULT_TAG_REGEX,
33
parentdir_prefix_version: str | None = None,
34
fallback_version: str | None = None,
35
fallback_root: PathT = ".",
36
parse: Any | None = None,
37
git_describe_command: CMD_TYPE | None = None,
38
dist_name: str | None = None,
39
version_cls: Any | None = None,
40
normalize: bool = True,
41
search_parent_directories: bool = False
42
) -> str:
43
"""
44
Get version from SCM metadata.
45
46
Parameters:
47
- root: Directory to search for SCM repository
48
- version_scheme: Strategy for version calculation (default: "guess-next-dev")
49
- local_scheme: Strategy for local version part (default: "node-and-date")
50
- write_to: Path to write version file
51
- write_to_template: Template for version file content
52
- version_file: Path for version file relative to project
53
- version_file_template: Template for version file
54
- relative_to: File path to resolve root relatively from (typically __file__)
55
- tag_regex: Regex for parsing version tags
56
- parentdir_prefix_version: Prefix to strip from parent directory name
57
- fallback_version: Version to use if SCM detection fails
58
- fallback_root: Root directory for fallback parsing
59
- parse: Custom parse function
60
- git_describe_command: Custom git describe command
61
- dist_name: Distribution name for version file generation
62
- version_cls: Custom version class
63
- normalize: Whether to normalize version strings
64
- search_parent_directories: Whether to search parent directories for SCM
65
66
Returns:
67
Version string extracted from SCM
68
"""
69
```
70
71
```python { .api }
72
def _get_version(
73
config: Configuration,
74
force_write_version_files: bool | None = None
75
) -> str | None:
76
"""
77
Internal version retrieval using Configuration object.
78
79
Parameters:
80
- config: Configuration object with all settings
81
- force_write_version_files: Whether to force writing version files
82
83
Returns:
84
Version string or None if no version could be determined
85
"""
86
```
87
88
### Configuration Management
89
90
Configuration class that encapsulates all setuptools-scm settings and provides methods for loading from files.
91
92
```python { .api }
93
@dataclasses.dataclass
94
class Configuration:
95
"""Global configuration model for setuptools-scm"""
96
97
relative_to: PathT | None = None
98
root: PathT = "."
99
version_scheme: VERSION_SCHEME = "guess-next-dev"
100
local_scheme: VERSION_SCHEME = "node-and-date"
101
tag_regex: Pattern[str] = DEFAULT_TAG_REGEX
102
parentdir_prefix_version: str | None = None
103
fallback_version: str | None = None
104
fallback_root: PathT = "."
105
write_to: PathT | None = None
106
write_to_template: str | None = None
107
version_file: PathT | None = None
108
version_file_template: str | None = None
109
git_describe_command: CMD_TYPE | None = None
110
dist_name: str | None = None
111
version_cls: type = Version
112
parse: Any | None = None
113
search_parent_directories: bool = False
114
115
@property
116
def absolute_root(self) -> str:
117
"""Returns the absolute path to the repository root"""
118
119
@classmethod
120
def from_file(
121
cls,
122
name: PathT = "pyproject.toml",
123
dist_name: str | None = None,
124
**kwargs
125
) -> "Configuration":
126
"""
127
Read configuration from pyproject.toml file.
128
129
Parameters:
130
- name: Path to pyproject.toml file
131
- dist_name: Distribution name for file generation
132
- **kwargs: Additional configuration overrides
133
134
Returns:
135
Configuration object loaded from file
136
"""
137
138
@classmethod
139
def from_data(cls, relative_to: PathT, data: dict[str, Any]) -> "Configuration":
140
"""
141
Create configuration from data dictionary.
142
143
Parameters:
144
- relative_to: File path to resolve root from
145
- data: Configuration data as dictionary
146
147
Returns:
148
Configuration object created from data
149
"""
150
```
151
152
### SCM Version Representation
153
154
Data class representing a parsed version from SCM with formatting capabilities.
155
156
```python { .api }
157
@dataclasses.dataclass
158
class ScmVersion:
159
"""Represents a parsed version from SCM metadata"""
160
161
tag: Version | NonNormalizedVersion | str
162
"""The related tag or preformatted version string"""
163
164
config: Configuration
165
"""The configuration used to parse the version"""
166
167
distance: int = 0
168
"""The number of commits since the tag"""
169
170
node: str | None = None
171
"""The shortened node/commit ID"""
172
173
dirty: bool = False
174
"""Whether the working copy had uncommitted changes"""
175
176
preformatted: bool = False
177
"""Whether the version string was preformatted"""
178
179
branch: str | None = None
180
"""The branch name if any"""
181
182
node_date: date | None = None
183
"""The date of the commit if available"""
184
185
time: datetime = dataclasses.field(default_factory=_source_epoch_or_utc_now)
186
"""The current time or source epoch time"""
187
188
@property
189
def exact(self) -> bool:
190
"""Returns True if checked out exactly on a tag with no local changes"""
191
return self.distance == 0 and not self.dirty
192
193
def format_with(self, fmt: str, **kw: object) -> str:
194
"""
195
Format a given format string with attributes of this object.
196
197
Parameters:
198
- fmt: Format string with placeholders like {tag}, {distance}, {node}
199
- **kw: Additional keyword arguments for formatting
200
201
Returns:
202
Formatted version string
203
"""
204
205
def format_choice(self, clean_format: str, dirty_format: str, **kw: object) -> str:
206
"""
207
Choose format based on dirty state and format using format_with.
208
209
Parameters:
210
- clean_format: Format string for clean repository state
211
- dirty_format: Format string for dirty repository state
212
- **kw: Additional keyword arguments for formatting
213
214
Returns:
215
Formatted version string based on repository state
216
"""
217
218
def format_next_version(
219
self,
220
guess_next: Callable,
221
fmt: str = "{guessed}.dev{distance}",
222
*args,
223
**kwargs
224
) -> str:
225
"""
226
Format next version using a guess function.
227
228
Parameters:
229
- guess_next: Function that guesses the next version
230
- fmt: Format string for the result
231
- *args, **kwargs: Arguments passed to guess function
232
233
Returns:
234
Formatted next version string
235
"""
236
```
237
238
### Version Classes
239
240
Version handling classes that control normalization and string representation.
241
242
```python { .api }
243
class Version:
244
"""Standard packaging Version class (from packaging.version)"""
245
246
class NonNormalizedVersion(Version):
247
"""
248
A non-normalizing version handler that preserves original version strings.
249
250
Use this class to preserve version verification but skip normalization.
251
For example, to avoid git release candidate version tags ("1.0.0-rc1")
252
being normalized to "1.0.0rc1". Only use if you fully trust version tags.
253
"""
254
255
def __init__(self, version: str) -> None:
256
"""
257
Initialize with version string.
258
259
Parameters:
260
- version: Version string to preserve
261
"""
262
263
def __str__(self) -> str:
264
"""Return the non-normalized version string"""
265
266
def __repr__(self) -> str:
267
"""Return representation showing non-normalized version"""
268
```
269
270
## Usage Examples
271
272
### Basic Version Retrieval
273
274
```python
275
from setuptools_scm import get_version
276
277
# Simple case - get version from current directory
278
version = get_version()
279
print(f"Current version: {version}")
280
281
# Specify repository location
282
version = get_version(root="/path/to/my/repo")
283
print(f"Repo version: {version}")
284
```
285
286
### Advanced Configuration
287
288
```python
289
from setuptools_scm import get_version, Configuration
290
import re
291
292
# Custom tag regex for non-standard tag formats
293
custom_regex = re.compile(r"^release-(?P<version>.+)$")
294
version = get_version(
295
tag_regex=custom_regex,
296
version_scheme="only-version",
297
local_scheme="no-local-version"
298
)
299
300
# Configuration object approach
301
config = Configuration(
302
root=".",
303
version_scheme="simplified-semver",
304
local_scheme="node-and-date",
305
fallback_version="0.0.0.dev0",
306
write_to="src/mypackage/_version.py"
307
)
308
309
from setuptools_scm import _get_version
310
version = _get_version(config)
311
```
312
313
### Working with ScmVersion Objects
314
315
```python
316
from setuptools_scm import Configuration, _get_version
317
318
config = Configuration()
319
# This would typically be called internally, but shown for illustration
320
version_obj = setuptools_scm._get_version_impl.parse_version(config)
321
322
if version_obj:
323
print(f"Tag: {version_obj.tag}")
324
print(f"Distance: {version_obj.distance}")
325
print(f"Node: {version_obj.node}")
326
print(f"Dirty: {version_obj.dirty}")
327
print(f"Exact: {version_obj.exact}")
328
329
# Custom formatting
330
custom_format = version_obj.format_with("{tag}.post{distance}")
331
print(f"Custom format: {custom_format}")
332
```