Skip to content

gitversioned.settings

Configuration management settings for GitVersioned.

This module resolves and manages configuration parameters loaded from CLI arguments, environment variables, and files like pyproject.toml or setup.cfg.

RegexStrategy

Bases: BaseModel

Output strategy using regex version replacement.

Updates the version string inline in an existing file by searching for a match with a regex pattern and replacing the target named 'version' group.

Example

::

strategy = RegexStrategy(pattern=r'version = "(?P<version>.*?)"')
Source code in src/gitversioned/settings.py
class RegexStrategy(BaseModel):
    """
    Output strategy using regex version replacement.

    Updates the version string inline in an existing file by searching for a match with
    a regex pattern and replacing the target named 'version' group.

    Example:
        ::

            strategy = RegexStrategy(pattern=r'version = "(?P<version>.*?)"')
    """

    type: Literal["regex"] = Field(
        default="regex",
        description=(
            "Discriminator type field identifying the regex-based replacement strategy."
        ),
    )
    pattern: str = Field(
        description=(
            "The regular expression containing a (?P<version>...) named group to "
            "locate and replace within the target file."
        )
    )

Settings

Bases: BaseSettings

Unified configuration settings for GitVersioned.

Manages settings loaded from environment variables, configuration files (such as pyproject.toml or setup.cfg), CLI flags, and constructor inputs. Governs how the dynamic version parser resolves git refs, matches tags, and generates target version files.

Example

::

settings = Settings(package_name="my_package")
src_path = settings.resolve_path_from_src("my_package/__init__.py")

:cvar model_config: Custom configuration dictionary settings for Pydantic.

Source code in src/gitversioned/settings.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
class Settings(BaseSettings):
    """
    Unified configuration settings for GitVersioned.

    Manages settings loaded from environment variables, configuration files (such as
    pyproject.toml or setup.cfg), CLI flags, and constructor inputs. Governs how
    the dynamic version parser resolves git refs, matches tags, and generates target
    version files.

    Example:
        ::

            settings = Settings(package_name="my_package")
            src_path = settings.resolve_path_from_src("my_package/__init__.py")

    :cvar model_config: Custom configuration dictionary settings for Pydantic.
    """

    model_config = SettingsConfigDict(
        arbitrary_types_allowed=True,
        extra="allow",
        populate_by_name=True,
        validate_assignment=True,
        env_prefix="GITVERSIONED__",
        cli_prefix="gitversioned_",
        cli_parse_args=True,
        pyproject_toml_table_header=("tool", "gitversioned"),
    )

    # Project Configuration
    package_name: str = Field(
        default="auto",
        description=(
            "The package name being versioned. "
            "Enables automatic package name detection when set to 'auto'."
        ),
    )
    project_root: EnsurePath = Field(
        default_factory=Path.cwd,
        description="The absolute path to the root directory of the project.",
    )
    src_root: EnsurePath = Field(
        default_factory=Path.cwd,
        description=(
            "The path to the source root directory. "
            "Enables automatic source directory fallback detection "
            "when set to 'auto'."
        ),
    )
    build_is_editable: bool = Field(
        default=False,
        description=(
            "Flag indicating whether the package is built as an editable installation."
        ),
    )
    overrides: dict[str, dict[str, Any]] = Field(
        default_factory=dict,
        description="Override-based settings configurations.",
    )

    # Version Source Configuration
    version: str = Field(
        default="auto",
        description=(
            "Explicit version override string. "
            "Enables dynamic version resolution from git/files "
            "when set to 'auto'."
        ),
    )
    source_type: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: ["auto"],
        description="Priority order of sources to query for version information.",
    )
    version_source_file: str | None = Field(
        default="version.txt",
        description=(
            "Path to a file containing the version string. Set to None to disable."
        ),
    )
    version_source_archive: str | None = Field(
        default=".git_archival.txt",
        description=(
            "Path to a git-archive export info file used when "
            "Git is unavailable. Set to None to disable."
        ),
    )
    version_source_function: str | None = Field(
        default=None,
        description=(
            "A string pointing to a module and function (e.g. 'module:func') "
            "to resolve the version. Set to None to disable."
        ),
    )
    regex_version: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: [
            r"^(?:releases?/)?v?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)$"
        ],
        description=(
            "Regular expression patterns to parse and validate "
            "the explicit version string."
        ),
    )
    regex_tag: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: [
            r"^(?:releases?/)?v?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)$"
        ],
        description=(
            "Regular expression patterns to extract semantic versioning from Git tags."
        ),
    )
    regex_branch: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: [
            r"^(?:releases?/)?v?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"
        ],
        description=(
            "Regular expression patterns to extract semantic "
            "versioning from the current Git branch name."
        ),
    )
    regex_commit: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: [
            r"(?i)^(?:release\s+|bump(?:\s+\w+)*\s+)?"
            r"v?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"
        ],
        description=(
            "Regular expression patterns to extract semantic "
            "versioning from Git commit messages."
        ),
    )
    regex_file: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: [
            r"(?i)(?:version|__version__)\s*[:=]\s*['\"]?"
            r"(v?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:[a-zA-Z0-9.\-+]+)?)"
            r"['\"]?"
        ],
        description=(
            "Regular expression patterns to parse version strings "
            "from version source files."
        ),
    )
    regex_archive: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: [
            r"(?sm)"
            r"(?=.*^commit_sha:\s*(?P<commit_sha>[^\n]*))"
            r"(?=.*^short_sha:\s*(?P<short_sha>[^\n]*))"
            r"(?=.*^timestamp:\s*(?P<timestamp>[^\n]*))"
            r"(?=.*^author_name:\s*(?P<author_name>[^\n]*))"
            r"(?=.*^author_email:\s*(?P<author_email>[^\n]*))"
            r"(?=.*^ref_names:\s*(?P<ref_names>[^\n]*))"
            r"(?=.*^ref_names:.*?(?:v)?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+))"
            r"(?=.*^distance_from_head:\s*(?P<distance_from_head>[^\n]*))"
            r"(?=.*^is_head_commit:\s*(?P<is_head_commit>[^\n]*))"
            r"(?=.*^total_commits:\s*(?P<total_commits>[^\n]*))"
            r"(?=.*^is_current_branch:\s*(?P<is_current_branch>[^\n]*))"
            r"(?=.*^commit_message:\n(?P<commit_message>.*))"
        ],
        description=(
            "Regular expression patterns to parse Git metadata "
            "from git-archive export files."
        ),
    )

    # Generated Version Configuration
    version_type: VersionType = Field(
        default="auto",
        description=(
            "The type of version format to generate (e.g. 'release', 'dev', or 'auto')."
        ),
    )
    version_standard: VersionStandard = Field(
        default="pep440",
        description=(
            "The standard formatting layout (PEP 440 or SemVer 2) "
            "to use for version normalization."
        ),
    )
    auto_increment: (
        dict[
            Literal["release", "dev", "pre", "alpha", "nightly", "post"],
            IncrementLevel,
        ]
        | None
    ) = Field(
        default_factory=lambda: cast(
            "AutoIncrementDict",
            {
                "dev": "patch",
                "pre": "minor",
            },
        ),
        description=(
            "Target increment mapping to apply when ahead of the latest release tag."
        ),
    )
    format_main: str = Field(
        default="{version.major}.{version.minor}.{version.micro}",
        description="Format string for the main semantic version segment.",
    )
    format_dev: str = Field(
        default="dev{ref.timestamp:%Y%m%d}+{ref.short_sha}",
        description="Format string for development builds.",
    )
    format_pre: str = Field(
        default="a{ref.timestamp:%Y%m%d}",
        description="Format string for pre-release or alpha builds.",
    )
    format_post: str = Field(
        default="post{ref.distance_from_head}",
        description="Format string for post-release builds.",
    )
    dirty_ignore: Annotated[list[str], EnsureList()] = Field(
        default_factory=lambda: ["target", "build", "dist", "__pycache__"],
        description=(
            "List of file paths and directories to ignore when "
            "checking if the repository is dirty."
        ),
    )

    # Generated Version Outputs Configuration
    output: str = Field(
        default="version.py",
        description="The target output path to write the generated version file.",
    )
    output_strategies: dict[str, OutputStrategy] | OutputStrategy = Field(
        default_factory=lambda: cast(
            "dict[str, OutputStrategy]",
            {
                "release": TemplatePathStrategy(
                    path=Path(__file__).parent / "templates" / "release.py.template",
                ),
                "dev": TemplatePathStrategy(
                    path=Path(__file__).parent / "templates" / "dev.py.template",
                ),
            },
        ),
        description="Output strategies for formatting the version file.",
    )

    @classmethod
    def settings_customise_sources(
        cls,
        settings_cls: type[BaseSettings],
        init_settings: PydanticBaseSettingsSource,
        env_settings: PydanticBaseSettingsSource,
        dotenv_settings: PydanticBaseSettingsSource,
        file_secret_settings: PydanticBaseSettingsSource,
    ) -> tuple[PydanticBaseSettingsSource, ...]:
        """
        Customize configuration sources and priority for loading settings.

        This method overrides the default pydantic-settings loaders to resolve
        values in the following order: constructor kwargs, setup.cfg,
        pyproject.toml, dotenv files, environment variables, and CLI arguments.

        :param settings_cls: The BaseSettings subclass being initialized.
        :param init_settings: Source loading constructor keyword arguments.
        :param env_settings: Source loading environment variables.
        :param dotenv_settings: Source loading .env files.
        :param file_secret_settings: Source loading file secrets.
        :return: A tuple of settings sources in priority order.
        """
        _ = (file_secret_settings,)  # Allow unused variable to satisfy lint/format
        input_args = init_settings()
        project_root = Path(input_args.get("project_root") or Path.cwd())

        return (
            init_settings,
            SetupCfgSettingsSource(settings_cls, project_root=project_root),
            PyprojectTomlConfigSettingsSource(
                settings_cls, toml_file=project_root / "pyproject.toml"
            ),
            TomlConfigSettingsSource(
                settings_cls, toml_file=project_root / "gitversioned.toml"
            ),
            TomlConfigSettingsSource(
                settings_cls, toml_file=project_root / ".gitversioned.toml"
            ),
            JsonConfigSettingsSource(
                settings_cls, json_file=project_root / "gitversioned.json"
            ),
            JsonConfigSettingsSource(
                settings_cls, json_file=project_root / ".gitversioned.json"
            ),
            dotenv_settings,
            env_settings,
            CliSettingsSource(
                settings_cls,
                cli_ignore_unknown_args=True,
                cli_parse_args=True,
                cli_prefix=settings_cls.model_config.get("cli_prefix", ""),
            ),
        )

    def __str__(self) -> str:
        """
        Return a concise string representation of the settings.

        :return: Concise string representation.
        """
        return (
            f"{self.__class__.__name__}("
            f"package_name={self.package_name!r}, "
            f"version={self.version!r}, "
            f"version_type={self.version_type!r}, "
            f"project_root={self.project_root!r}, "
            f"src_root={self.src_root!r}, "
            f"source_type={self.source_type!r}, "
            f"auto_increment={self.auto_increment!r}, "
            f"output={self.output!r}, "
            f"dirty_ignore={self.dirty_ignore!r}"
            f")"
        )

    def __repr__(self) -> str:
        """
        Return a detailed string representation of the settings.

        :return: Detailed string representation of settings.
        """
        return (
            f"{self.__class__.__name__}("
            f"package_name={self.package_name!r}, "
            f"project_root={self.project_root!r}, "
            f"src_root={self.src_root!r}, "
            f"build_is_editable={self.build_is_editable!r}, "
            f"version={self.version!r}, "
            f"source_type={self.source_type!r}, "
            f"version_source_file={self.version_source_file!r}, "
            f"version_source_archive={self.version_source_archive!r}, "
            f"version_source_function={self.version_source_function!r}, "
            f"regex_version={self.regex_version!r}, "
            f"regex_tag={self.regex_tag!r}, "
            f"regex_branch={self.regex_branch!r}, "
            f"regex_commit={self.regex_commit!r}, "
            f"regex_file={self.regex_file!r}, "
            f"regex_archive={self.regex_archive!r}, "
            f"version_type={self.version_type!r}, "
            f"version_standard={self.version_standard!r}, "
            f"auto_increment={self.auto_increment!r}, "
            f"format_main={self.format_main!r}, "
            f"format_dev={self.format_dev!r}, "
            f"format_pre={self.format_pre!r}, "
            f"format_post={self.format_post!r}, "
            f"dirty_ignore={self.dirty_ignore!r}, "
            f"output={self.output!r}, "
            f"output_strategies={self.output_strategies!r}"
            f")"
        )

    @autolog
    def get_overridden_settings(self, override_name: str) -> Settings:
        """
        Get a new Settings instance with overrides for the given override name.

        This method dumps the root settings, pops the 'overrides' key to prevent
        infinite recursion, and updates the settings with override-specific config.

        :param override_name: Name of the override configuration to load settings for.
        :returns: A new Settings instance with the overrides applied.
        :raises ValueError: If the override name does not exist.
        """
        if override_name not in self.overrides:
            raise ValueError(f"Override '{override_name}' not found in configuration.")

        data = self.model_dump()
        if self.model_extra:
            data.update(self.model_extra)

        # Set overrides to an empty dict in data to prevent loading error or warnings
        # during Pydantic initialization.
        data["overrides"] = {}
        override_configs = self.overrides[override_name]
        data.update(override_configs)

        settings = Settings(**data)
        # Explicitly clear overrides on the returned instance to prevent
        # infinite recursion if dictionary fields merge during Pydantic
        # Settings loading from files (e.g. pyproject.toml).
        settings.overrides = {}
        return settings

    @autolog
    def resolve_path_from_root(
        self, path: str | Path | None, enforce_existence: bool = True
    ) -> Path | None:
        """
        Resolve a path relative to the project root or source root.

        This method attempts to resolve the given path first from the project root,
        falling back to the source root if it is not found.

        Example:
            ::

                path = settings.resolve_path_from_root("version.txt")

        :param path: The path to resolve.
        :param enforce_existence: Whether to enforce that the path exists.
        :return: The resolved absolute Path if it exists (or if not enforcing
            existence), otherwise None.
        """
        if enforce_existence:
            return self.resolve_path_from_project(
                path, enforce_existence=True
            ) or self.resolve_path_from_src(path, enforce_existence=True)
        else:
            resolved = self.resolve_path_from_project(
                path, enforce_existence=True
            ) or self.resolve_path_from_src(path, enforce_existence=True)
            if resolved is not None:
                return resolved
            if self.src_root != self.project_root:
                if path:
                    try:
                        rel_src = self.src_root.relative_to(self.project_root)
                        p_path = Path(path)
                        if p_path.parts[: len(rel_src.parts)] == rel_src.parts:
                            return self.resolve_path_from_project(
                                path, enforce_existence=False
                            )
                    except ValueError:
                        pass
                return self.resolve_path_from_src(path, enforce_existence=False)
            return self.resolve_path_from_project(path, enforce_existence=False)

    @autolog
    def resolve_path_from_project(
        self, path: str | Path | None, enforce_existence: bool = True
    ) -> Path | None:
        """
        Resolve a path relative to the project root directory.

        Example:
            ::

                path = settings.resolve_path_from_project("setup.cfg")

        :param path: The path to resolve.
        :param enforce_existence: Whether to enforce that the path exists.
        :return: The resolved absolute Path if it exists (or if not enforcing
            existence), otherwise None.
        """
        if not path:
            return None

        if isinstance(path, str):
            path = Path(path)
        if not path.is_absolute():
            path = self.project_root / path
        return path if (not enforce_existence or path.exists()) else None

    @autolog
    def resolve_path_from_src(
        self, path: str | Path | None, enforce_existence: bool = True
    ) -> Path | None:
        """
        Resolve a path relative to the source root directory.

        Example:
            ::

                path = settings.resolve_path_from_src("my_package/__init__.py")

        :param path: The path to resolve.
        :param enforce_existence: Whether to enforce that the path exists.
        :return: The resolved absolute Path if it exists (or if not enforcing
            existence), otherwise None.
        """
        if not path:
            return None

        if isinstance(path, str):
            path = Path(path)
        if not path.is_absolute():
            path = self.src_root / path
        return path if (not enforce_existence or path.exists()) else None

    @field_validator("auto_increment", mode="before")
    @classmethod
    def _coerce_auto_increment(cls, value: Any) -> Any:
        if isinstance(value, str):
            if value.lower().strip() == "none":
                return None
            with contextlib.suppress(json.JSONDecodeError):
                value = json.loads(value)
        return value

    @field_validator("output_strategies", mode="before")
    @classmethod
    def _coerce_output_strategies(cls, value: Any) -> Any:
        if isinstance(value, str):
            with contextlib.suppress(json.JSONDecodeError):
                return json.loads(value)
        return value

    @model_validator(mode="after")
    def _resolve_auto_fields(self) -> Settings:
        # Internal validator to resolve 'auto' fields after initialization.
        if not self.project_root.exists():
            raise ValueError(
                f"Project root directory does not exist: {self.project_root}"
            )
        if not self.project_root.is_dir():
            raise ValueError(f"Project root is not a directory: {self.project_root}")

        if self.package_name == "auto":
            new_pkg_name = _detect_package_name(self.project_root)
            if new_pkg_name != self.package_name:
                self.package_name = new_pkg_name

        if (
            self.src_root == self.project_root
            or self.src_root.resolve() == Path.cwd().resolve()
        ):
            new_src_root = _resolve_src_root(self.project_root, self.package_name)
            if new_src_root != self.src_root:
                self.src_root = new_src_root

        return self

__repr__()

Return a detailed string representation of the settings.

:return: Detailed string representation of settings.

Source code in src/gitversioned/settings.py
def __repr__(self) -> str:
    """
    Return a detailed string representation of the settings.

    :return: Detailed string representation of settings.
    """
    return (
        f"{self.__class__.__name__}("
        f"package_name={self.package_name!r}, "
        f"project_root={self.project_root!r}, "
        f"src_root={self.src_root!r}, "
        f"build_is_editable={self.build_is_editable!r}, "
        f"version={self.version!r}, "
        f"source_type={self.source_type!r}, "
        f"version_source_file={self.version_source_file!r}, "
        f"version_source_archive={self.version_source_archive!r}, "
        f"version_source_function={self.version_source_function!r}, "
        f"regex_version={self.regex_version!r}, "
        f"regex_tag={self.regex_tag!r}, "
        f"regex_branch={self.regex_branch!r}, "
        f"regex_commit={self.regex_commit!r}, "
        f"regex_file={self.regex_file!r}, "
        f"regex_archive={self.regex_archive!r}, "
        f"version_type={self.version_type!r}, "
        f"version_standard={self.version_standard!r}, "
        f"auto_increment={self.auto_increment!r}, "
        f"format_main={self.format_main!r}, "
        f"format_dev={self.format_dev!r}, "
        f"format_pre={self.format_pre!r}, "
        f"format_post={self.format_post!r}, "
        f"dirty_ignore={self.dirty_ignore!r}, "
        f"output={self.output!r}, "
        f"output_strategies={self.output_strategies!r}"
        f")"
    )

__str__()

Return a concise string representation of the settings.

:return: Concise string representation.

Source code in src/gitversioned/settings.py
def __str__(self) -> str:
    """
    Return a concise string representation of the settings.

    :return: Concise string representation.
    """
    return (
        f"{self.__class__.__name__}("
        f"package_name={self.package_name!r}, "
        f"version={self.version!r}, "
        f"version_type={self.version_type!r}, "
        f"project_root={self.project_root!r}, "
        f"src_root={self.src_root!r}, "
        f"source_type={self.source_type!r}, "
        f"auto_increment={self.auto_increment!r}, "
        f"output={self.output!r}, "
        f"dirty_ignore={self.dirty_ignore!r}"
        f")"
    )

get_overridden_settings(override_name)

Get a new Settings instance with overrides for the given override name.

This method dumps the root settings, pops the 'overrides' key to prevent infinite recursion, and updates the settings with override-specific config.

:param override_name: Name of the override configuration to load settings for. :returns: A new Settings instance with the overrides applied. :raises ValueError: If the override name does not exist.

Source code in src/gitversioned/settings.py
@autolog
def get_overridden_settings(self, override_name: str) -> Settings:
    """
    Get a new Settings instance with overrides for the given override name.

    This method dumps the root settings, pops the 'overrides' key to prevent
    infinite recursion, and updates the settings with override-specific config.

    :param override_name: Name of the override configuration to load settings for.
    :returns: A new Settings instance with the overrides applied.
    :raises ValueError: If the override name does not exist.
    """
    if override_name not in self.overrides:
        raise ValueError(f"Override '{override_name}' not found in configuration.")

    data = self.model_dump()
    if self.model_extra:
        data.update(self.model_extra)

    # Set overrides to an empty dict in data to prevent loading error or warnings
    # during Pydantic initialization.
    data["overrides"] = {}
    override_configs = self.overrides[override_name]
    data.update(override_configs)

    settings = Settings(**data)
    # Explicitly clear overrides on the returned instance to prevent
    # infinite recursion if dictionary fields merge during Pydantic
    # Settings loading from files (e.g. pyproject.toml).
    settings.overrides = {}
    return settings

resolve_path_from_project(path, enforce_existence=True)

Resolve a path relative to the project root directory.

Example

::

path = settings.resolve_path_from_project("setup.cfg")

:param path: The path to resolve. :param enforce_existence: Whether to enforce that the path exists. :return: The resolved absolute Path if it exists (or if not enforcing existence), otherwise None.

Source code in src/gitversioned/settings.py
@autolog
def resolve_path_from_project(
    self, path: str | Path | None, enforce_existence: bool = True
) -> Path | None:
    """
    Resolve a path relative to the project root directory.

    Example:
        ::

            path = settings.resolve_path_from_project("setup.cfg")

    :param path: The path to resolve.
    :param enforce_existence: Whether to enforce that the path exists.
    :return: The resolved absolute Path if it exists (or if not enforcing
        existence), otherwise None.
    """
    if not path:
        return None

    if isinstance(path, str):
        path = Path(path)
    if not path.is_absolute():
        path = self.project_root / path
    return path if (not enforce_existence or path.exists()) else None

resolve_path_from_root(path, enforce_existence=True)

Resolve a path relative to the project root or source root.

This method attempts to resolve the given path first from the project root, falling back to the source root if it is not found.

Example

::

path = settings.resolve_path_from_root("version.txt")

:param path: The path to resolve. :param enforce_existence: Whether to enforce that the path exists. :return: The resolved absolute Path if it exists (or if not enforcing existence), otherwise None.

Source code in src/gitversioned/settings.py
@autolog
def resolve_path_from_root(
    self, path: str | Path | None, enforce_existence: bool = True
) -> Path | None:
    """
    Resolve a path relative to the project root or source root.

    This method attempts to resolve the given path first from the project root,
    falling back to the source root if it is not found.

    Example:
        ::

            path = settings.resolve_path_from_root("version.txt")

    :param path: The path to resolve.
    :param enforce_existence: Whether to enforce that the path exists.
    :return: The resolved absolute Path if it exists (or if not enforcing
        existence), otherwise None.
    """
    if enforce_existence:
        return self.resolve_path_from_project(
            path, enforce_existence=True
        ) or self.resolve_path_from_src(path, enforce_existence=True)
    else:
        resolved = self.resolve_path_from_project(
            path, enforce_existence=True
        ) or self.resolve_path_from_src(path, enforce_existence=True)
        if resolved is not None:
            return resolved
        if self.src_root != self.project_root:
            if path:
                try:
                    rel_src = self.src_root.relative_to(self.project_root)
                    p_path = Path(path)
                    if p_path.parts[: len(rel_src.parts)] == rel_src.parts:
                        return self.resolve_path_from_project(
                            path, enforce_existence=False
                        )
                except ValueError:
                    pass
            return self.resolve_path_from_src(path, enforce_existence=False)
        return self.resolve_path_from_project(path, enforce_existence=False)

resolve_path_from_src(path, enforce_existence=True)

Resolve a path relative to the source root directory.

Example

::

path = settings.resolve_path_from_src("my_package/__init__.py")

:param path: The path to resolve. :param enforce_existence: Whether to enforce that the path exists. :return: The resolved absolute Path if it exists (or if not enforcing existence), otherwise None.

Source code in src/gitversioned/settings.py
@autolog
def resolve_path_from_src(
    self, path: str | Path | None, enforce_existence: bool = True
) -> Path | None:
    """
    Resolve a path relative to the source root directory.

    Example:
        ::

            path = settings.resolve_path_from_src("my_package/__init__.py")

    :param path: The path to resolve.
    :param enforce_existence: Whether to enforce that the path exists.
    :return: The resolved absolute Path if it exists (or if not enforcing
        existence), otherwise None.
    """
    if not path:
        return None

    if isinstance(path, str):
        path = Path(path)
    if not path.is_absolute():
        path = self.src_root / path
    return path if (not enforce_existence or path.exists()) else None

settings_customise_sources(settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings) classmethod

Customize configuration sources and priority for loading settings.

This method overrides the default pydantic-settings loaders to resolve values in the following order: constructor kwargs, setup.cfg, pyproject.toml, dotenv files, environment variables, and CLI arguments.

:param settings_cls: The BaseSettings subclass being initialized. :param init_settings: Source loading constructor keyword arguments. :param env_settings: Source loading environment variables. :param dotenv_settings: Source loading .env files. :param file_secret_settings: Source loading file secrets. :return: A tuple of settings sources in priority order.

Source code in src/gitversioned/settings.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
    """
    Customize configuration sources and priority for loading settings.

    This method overrides the default pydantic-settings loaders to resolve
    values in the following order: constructor kwargs, setup.cfg,
    pyproject.toml, dotenv files, environment variables, and CLI arguments.

    :param settings_cls: The BaseSettings subclass being initialized.
    :param init_settings: Source loading constructor keyword arguments.
    :param env_settings: Source loading environment variables.
    :param dotenv_settings: Source loading .env files.
    :param file_secret_settings: Source loading file secrets.
    :return: A tuple of settings sources in priority order.
    """
    _ = (file_secret_settings,)  # Allow unused variable to satisfy lint/format
    input_args = init_settings()
    project_root = Path(input_args.get("project_root") or Path.cwd())

    return (
        init_settings,
        SetupCfgSettingsSource(settings_cls, project_root=project_root),
        PyprojectTomlConfigSettingsSource(
            settings_cls, toml_file=project_root / "pyproject.toml"
        ),
        TomlConfigSettingsSource(
            settings_cls, toml_file=project_root / "gitversioned.toml"
        ),
        TomlConfigSettingsSource(
            settings_cls, toml_file=project_root / ".gitversioned.toml"
        ),
        JsonConfigSettingsSource(
            settings_cls, json_file=project_root / "gitversioned.json"
        ),
        JsonConfigSettingsSource(
            settings_cls, json_file=project_root / ".gitversioned.json"
        ),
        dotenv_settings,
        env_settings,
        CliSettingsSource(
            settings_cls,
            cli_ignore_unknown_args=True,
            cli_parse_args=True,
            cli_prefix=settings_cls.model_config.get("cli_prefix", ""),
        ),
    )

SetupCfgSettingsSource

Bases: PydanticBaseSettingsSource

Settings source for loading configurations from setup.cfg files.

Extracts configuration parameters nested under the 'tool:gitversioned' sections of a project's setup.cfg file. Integrates as a custom source in the Pydantic settings management pipeline.

Example

::

source = SetupCfgSettingsSource(Settings, project_root=Path.cwd())
config = source()

:ivar project_root: The root directory containing the setup.cfg file.

Source code in src/gitversioned/settings.py
class SetupCfgSettingsSource(PydanticBaseSettingsSource):
    """
    Settings source for loading configurations from setup.cfg files.

    Extracts configuration parameters nested under the 'tool:gitversioned'
    sections of a project's setup.cfg file. Integrates as a custom source in
    the Pydantic settings management pipeline.

    Example:
        ::

            source = SetupCfgSettingsSource(Settings, project_root=Path.cwd())
            config = source()

    :ivar project_root: The root directory containing the setup.cfg file.
    """

    def __init__(self, settings_cls: type[BaseSettings], project_root: Path) -> None:
        """
        Initialize the setup.cfg settings source.

        :param settings_cls: The Settings class being configured.
        :param project_root: The root directory containing setup.cfg.
        """
        super().__init__(settings_cls)
        self.project_root = project_root

    def __call__(self) -> dict[str, Any]:
        """
        Retrieve loaded settings from setup.cfg.

        :return: Loaded configuration settings dict.
        """
        return self._config

    def get_field_value(self, field: Any, field_name: str) -> tuple[Any, str, bool]:
        """
        Get value for a configuration field from setup.cfg.

        :param field: The Pydantic Field object.
        :param field_name: The name of the field to fetch.
        :return: A tuple containing the field's value, name, and if it was found.
        :raises KeyError: If the field is not present in the settings source.
        """
        _ = (field,)  # Allow unused variable to satisfy lint/format
        config = self._config
        if field_name in config:
            return config[field_name], field_name, False
        raise KeyError(field_name)

    @functools.cached_property
    def _config(self) -> dict[str, Any]:
        # Load and parse configuration from setup.cfg and cache the result.
        path = self.project_root / "setup.cfg"
        if not path.exists():
            return {}

        config_parser = configparser.ConfigParser()
        config_parser.read(path)
        base_section = "tool:gitversioned"

        result: dict[str, Any] = {}
        if base_section in config_parser:
            result.update(config_parser.items(base_section))

        prefix = f"{base_section}:"
        for section in config_parser.sections():
            if section.startswith(prefix):
                key = section[len(prefix) :]
                if key.startswith("overrides:"):
                    override_name = key[10:]
                    overrides_dict = result.setdefault("overrides", {})
                    if not isinstance(overrides_dict, dict):
                        overrides_dict = {}
                        result["overrides"] = overrides_dict
                    override_val = overrides_dict.setdefault(override_name, {})
                    override_val.update(config_parser.items(section))
                else:
                    val = result.get(key, {})
                    if not isinstance(val, dict):
                        val = {"_": val}
                    val.update(config_parser.items(section))
                    result[key] = val

        return result

__call__()

Retrieve loaded settings from setup.cfg.

:return: Loaded configuration settings dict.

Source code in src/gitversioned/settings.py
def __call__(self) -> dict[str, Any]:
    """
    Retrieve loaded settings from setup.cfg.

    :return: Loaded configuration settings dict.
    """
    return self._config

__init__(settings_cls, project_root)

Initialize the setup.cfg settings source.

:param settings_cls: The Settings class being configured. :param project_root: The root directory containing setup.cfg.

Source code in src/gitversioned/settings.py
def __init__(self, settings_cls: type[BaseSettings], project_root: Path) -> None:
    """
    Initialize the setup.cfg settings source.

    :param settings_cls: The Settings class being configured.
    :param project_root: The root directory containing setup.cfg.
    """
    super().__init__(settings_cls)
    self.project_root = project_root

get_field_value(field, field_name)

Get value for a configuration field from setup.cfg.

:param field: The Pydantic Field object. :param field_name: The name of the field to fetch. :return: A tuple containing the field's value, name, and if it was found. :raises KeyError: If the field is not present in the settings source.

Source code in src/gitversioned/settings.py
def get_field_value(self, field: Any, field_name: str) -> tuple[Any, str, bool]:
    """
    Get value for a configuration field from setup.cfg.

    :param field: The Pydantic Field object.
    :param field_name: The name of the field to fetch.
    :return: A tuple containing the field's value, name, and if it was found.
    :raises KeyError: If the field is not present in the settings source.
    """
    _ = (field,)  # Allow unused variable to satisfy lint/format
    config = self._config
    if field_name in config:
        return config[field_name], field_name, False
    raise KeyError(field_name)

TemplatePathStrategy

Bases: BaseModel

Output strategy using a template file path.

Resolves version files by reading a template file containing placeholder variables, replacing them with resolved version metadata, and writing to the output path.

Example

::

strategy = TemplatePathStrategy(path=Path("templates/release.py.template"))
Source code in src/gitversioned/settings.py
class TemplatePathStrategy(BaseModel):
    """
    Output strategy using a template file path.

    Resolves version files by reading a template file containing placeholder variables,
    replacing them with resolved version metadata, and writing to the output path.

    Example:
        ::

            strategy = TemplatePathStrategy(path=Path("templates/release.py.template"))
    """

    type: Literal["template_path"] = Field(
        default="template_path",
        description=(
            "Discriminator type field identifying the template path "
            "resolution strategy."
        ),
    )
    path: Path = Field(
        description=(
            "The file path containing the template text to format with "
            "version metadata."
        )
    )

TemplateStrStrategy

Bases: BaseModel

Output strategy using a raw template string.

Formats the target version file utilizing an inline template string pattern defined directly in the configuration, rather than reading from a file.

Example

::

strategy = TemplateStrStrategy(content="__version__ = '{version}'")
Source code in src/gitversioned/settings.py
class TemplateStrStrategy(BaseModel):
    """
    Output strategy using a raw template string.

    Formats the target version file utilizing an inline template string pattern
    defined directly in the configuration, rather than reading from a file.

    Example:
        ::

            strategy = TemplateStrStrategy(content="__version__ = '{version}'")
    """

    type: Literal["template_str"] = Field(
        default="template_str",
        description=(
            "Discriminator type field identifying the template string "
            "resolution strategy."
        ),
    )
    content: str = Field(
        description="The inline template string used to format the version file output."
    )