Skip to content

gitversioned

Opinionated PEP 440 Python versioning for Git repos and submodules.

Provides an automated, deterministic system for generating rich version information from Git repository metadata. It enforces CI/User authority and creates version files with deep metadata for auditability, integrating natively with Hatch and Setuptools.

Example: :: from gitversioned import Settings, resolve_version from gitversioned.utils import BuildEnvironment, GitRepository

version, _, ref = resolve_version(
    Settings(), GitRepository(), BuildEnvironment()
)
print("Current version:", version)

BuildEnvironment

Bases: BaseModel

Structured metadata representing the current system and build execution context.

Captures environmental data such as OS details, hardware specs, and CI presence. Utilized to record the provenance of a build artifact for auditing and debugging.

Example

env = BuildEnvironment() print(env.os_system) 'Darwin'

Source code in src/gitversioned/utils/environment.py
class BuildEnvironment(BaseModel):
    """
    Structured metadata representing the current system and build execution context.

    Captures environmental data such as OS details, hardware specs, and CI presence.
    Utilized to record the provenance of a build artifact for auditing and debugging.

    Example:
        >>> env = BuildEnvironment()
        >>> print(env.os_system)
        'Darwin'
    """

    model_config = ConfigDict(frozen=True)

    # --- System & OS ---
    hostname: str = Field(
        default_factory=socket.gethostname,
        description="The network hostname of the build machine.",
    )
    user: str = Field(
        default_factory=get_user,
        description="The system username executing the build process.",
    )
    os_system: str = Field(
        default_factory=platform.system,
        description="The operating system name (e.g., 'Linux', 'Darwin', 'Windows').",
    )
    os_release: str = Field(
        default_factory=platform.release,
        description="The operating system release version.",
    )
    os_version: str = Field(
        default_factory=platform.version,
        description="The operating system build or release date string.",
    )

    # --- Hardware ---
    cpu_arch: str = Field(
        default_factory=platform.machine,
        description="Hardware architecture of the build machine (e.g., 'x86_64').",
    )
    cpu_cores: int = Field(
        default_factory=lambda: os.cpu_count() or 0,
        description="The number of logical CPU cores available.",
    )
    total_ram_gb: float = Field(
        default_factory=get_ram_gb,
        description="The total available system RAM in gigabytes.",
    )

    # --- Runtime ---
    python_version: str = Field(
        default_factory=platform.python_version,
        description="The version of the Python runtime executing the build.",
    )
    python_implementation: str = Field(
        default_factory=platform.python_implementation,
        description="The specific Python implementation (e.g., 'CPython', 'PyPy').",
    )
    python_compiler: str = Field(
        default_factory=platform.python_compiler,
        description="The compiler string used to build the Python runtime.",
    )
    timestamp: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc),
        description="UTC timestamp when this context was captured.",
    )

    # --- CI Context ---
    is_ci: bool = Field(
        default_factory=lambda: get_ci_info()[0],
        description="True if executing within a recognized CI environment.",
    )
    ci_provider: str | None = Field(
        default_factory=lambda: get_ci_info()[1],
        description="The name of the detected CI provider, or None if undetermined.",
    )

    # --- Path Context ---
    project_root: Path = Field(
        default_factory=Path.cwd,
        description="The root directory of the project where the build was initiated.",
    )

    build_id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        description="A unique identifier generated for this specific build execution.",
    )

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

        ci_str = f" [CI: {self.ci_provider}]" if self.is_ci else " [Local]"
        return (
            f"BuildEnvironment({self.os_system} {self.os_release} {self.cpu_arch}, "
            f"Python {self.python_version}, project={self.project_root.name}, "
            f"id={self.build_id}){ci_str}"
        )

    def __repr__(self) -> str:
        """Return a detailed string representation."""
        return (
            f"BuildEnvironment("
            f"hostname={self.hostname!r}, user={self.user!r}, "
            f"os_system={self.os_system!r}, os_release={self.os_release!r}, "
            f"os_version={self.os_version!r}, "
            f"cpu_arch={self.cpu_arch!r}, cpu_cores={self.cpu_cores!r}, "
            f"total_ram_gb={self.total_ram_gb!r}, "
            f"python_version={self.python_version!r}, "
            f"python_implementation={self.python_implementation!r}, "
            f"python_compiler={self.python_compiler!r}, timestamp={self.timestamp!r}, "
            f"is_ci={self.is_ci!r}, ci_provider={self.ci_provider!r}, "
            f"project_root={self.project_root!r}, build_id={self.build_id!r}"
            f")"
        )

__repr__()

Return a detailed string representation.

Source code in src/gitversioned/utils/environment.py
def __repr__(self) -> str:
    """Return a detailed string representation."""
    return (
        f"BuildEnvironment("
        f"hostname={self.hostname!r}, user={self.user!r}, "
        f"os_system={self.os_system!r}, os_release={self.os_release!r}, "
        f"os_version={self.os_version!r}, "
        f"cpu_arch={self.cpu_arch!r}, cpu_cores={self.cpu_cores!r}, "
        f"total_ram_gb={self.total_ram_gb!r}, "
        f"python_version={self.python_version!r}, "
        f"python_implementation={self.python_implementation!r}, "
        f"python_compiler={self.python_compiler!r}, timestamp={self.timestamp!r}, "
        f"is_ci={self.is_ci!r}, ci_provider={self.ci_provider!r}, "
        f"project_root={self.project_root!r}, build_id={self.build_id!r}"
        f")"
    )

__str__()

Return a concise string representation.

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

    ci_str = f" [CI: {self.ci_provider}]" if self.is_ci else " [Local]"
    return (
        f"BuildEnvironment({self.os_system} {self.os_release} {self.cpu_arch}, "
        f"Python {self.python_version}, project={self.project_root.name}, "
        f"id={self.build_id}){ci_str}"
    )

GitRepository

Interface for querying Git repository status and references.

Provides properties and methods to interact with a Git repository using typed Pydantic models for commits, tags, and branches.

Example

.. code-block:: python

from gitversioned.utils.git import GitRepository

repo = GitRepository()
if repo.is_available:
    print(repo.head_name)
Source code in src/gitversioned/utils/git.py
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
566
567
568
569
570
571
572
573
574
575
576
577
class GitRepository:
    """Interface for querying Git repository status and references.

    Provides properties and methods to interact with a Git repository using typed
    Pydantic models for commits, tags, and branches.

    Example
    -------
    .. code-block:: python

        from gitversioned.utils.git import GitRepository

        repo = GitRepository()
        if repo.is_available:
            print(repo.head_name)
    """

    def __init__(
        self,
        repository_path: Path | str | None = None,
    ) -> None:
        """Initialize the GitRepository instance.

        :param repository_path: Base directory of the repository,
            defaults to Path.cwd().
        """
        self.base_path = Path(repository_path or Path.cwd()).resolve()

    def __str__(self) -> str:
        """Return a concise string representation."""
        if not self.is_available:
            return f"GitRepository({self.base_path}) - Unavailable"

        dirty_files = self.dirty_files
        current = self.current_commit
        tag = self.last_tag
        branch = self.current_branch

        head = "detached"
        if branch:
            head = branch.branch_name
        elif current:
            head = current.short_sha

        return (
            f"GitRepository(path={self.base_path!r}, is_available=True, "
            f"commit_count={self.commit_count}, is_dirty={bool(dirty_files)}, "
            f"dirty_files={dirty_files}, "
            f"current_commit={current.short_sha if current else None}, "
            f"last_tag={tag.tag_name if tag else None}, "
            f"current_branch={branch.branch_name if branch else None}"
            f") - {head}{'*' if dirty_files else ''}"
        )

    def __repr__(self) -> str:
        """Return a detailed string representation."""
        return f"GitRepository(base_path={self.base_path!r})"

    @property
    def is_available(self) -> bool:
        """Check if the base path is within a valid Git work tree.

        :return: True if the repository path is a valid Git work tree, False otherwise.
        """
        if self._execute_command(["rev-parse", "--is-inside-work-tree"]) != "true":
            return False

        show_toplevel = self._execute_command(["rev-parse", "--show-toplevel"])
        if not show_toplevel:
            return False

        try:
            root_dir = Path(show_toplevel).resolve()
            return self.base_path.resolve().is_relative_to(root_dir)
        except Exception:  # noqa: BLE001
            return False

    @property
    def root_directory(self) -> Path:
        """Get the root directory of the Git repository.

        :return: Absolute path to the Git repository root.
        :raises NotAGitRepositoryError: If the path is not a valid Git repository.
        """
        self._ensure_valid_repository()
        return Path(self._execute_command(["rev-parse", "--show-toplevel"]))

    @property
    def repository_name(self) -> str:
        """Get the name of the Git repository.

        Attempts to parse the name from the remote origin URL, falling back
        to the root directory name.

        :return: The repository name.
        """
        if remote_url := self.remote_origin_url:
            name = remote_url.split("/")[-1]
            return name[:-4] if name.endswith(".git") else name
        return self.root_directory.name

    @property
    def remote_origin_url(self) -> str:
        """Get the remote origin URL.

        :return: Remote origin URL, or empty string if not set.
        """
        if not self.is_available:
            return ""
        return self._execute_command(["config", "--get", "remote.origin.url"])

    @property
    def commit_count(self) -> int:
        """Get the total commit count on the current branch.

        :return: Total number of commits, or 0 if unavailable.
        """
        if not self.is_available:
            return 0
        try:
            return int(self._execute_command(["rev-list", "--count", "HEAD"]) or 0)
        except ValueError:
            return 0

    @property
    def is_dirty(self) -> bool:
        """Check if the repository has uncommitted modifications.

        :return: True if dirty changes exist, False otherwise.
        """
        return bool(self.dirty_files)

    @property
    def dirty_files(self) -> list[Path]:
        """Get a list of all modified and untracked file paths.

        :return: List of paths with uncommitted changes.
        """
        if not self.is_available:
            return []
        output = self._execute_command(["status", "--porcelain"])
        dirty = []
        for line in output.splitlines():
            if line:
                path = line[3:]
                if " -> " in path:
                    path = path.split(" -> ")[-1]
                dirty.append((self.base_path / path).resolve())
        return dirty

    @property
    def current_commit(self) -> GitReference | None:
        """Get the most recent commit.

        :return: Most recent commit reference, or None if empty.
        """
        return next(self.commits, None)

    @property
    def current_commit_or_fallback(self) -> GitReference:
        """Get the most recent commit or a generated fallback reference.

        :return: Current commit reference, or a dummy reference if unavailable.
        """
        return (
            self.current_commit
            if self.is_available and self.current_commit
            else GitReference(
                timestamp=datetime.now(timezone.utc),
                distance_from_head=0,
                is_head_commit=True,
            )
        )

    @property
    def last_tag(self) -> GitReference | None:
        """Get the most recent tag.

        :return: Most recent tag reference, or None if no tags exist.
        """
        return next(self.tags, None)

    @property
    def current_branch(self) -> GitReference | None:
        """Get the currently checked-out branch.

        :return: Current branch reference, or None if in detached HEAD.
        """
        return next(
            (branch for branch in self.branches if branch.is_current_branch),
            None,
        )

    @property
    def head_name(self) -> str:
        """Get the branch name or the short commit SHA of HEAD.

        :return: Current branch name, or short SHA if detached.
        """
        if branch := self.current_branch:
            return branch.branch_name
        if current := self.current_commit:
            return current.short_sha
        return ""

    @property
    def commits(self) -> Iterator[GitReference]:
        """Yield all commits in the repository history.

        :return: Iterator of commit reference objects.
        :raises NotAGitRepositoryError: If the path is not a valid Git repository.
        """
        self._ensure_valid_repository()
        total_commits = self.commit_count
        format_string = "%H|%h|%cI|%an|%ae|%s|%D"
        lines = self._stream_command(["log", f"--format={format_string}"])

        for index, line in enumerate(lines):
            parts = line.split("|", 6)
            if len(parts) == _EXPECTED_LOG_PARTS_COUNT:
                tag_name = ""
                branch_name = ""
                is_current_branch = False

                refs = parts[6].split(", ") if parts[6] else []
                for ref in refs:
                    if ref.startswith("tag: "):
                        tag_name = ref[5:]
                    elif "->" in ref:
                        branch_name = ref.split(" -> ")[1]
                        is_current_branch = True
                    elif (
                        ref
                        and not ref.startswith("origin/")
                        and ref != "HEAD"
                        and not branch_name
                    ):
                        branch_name = ref

                yield GitReference(
                    commit_sha=parts[0],
                    short_sha=parts[1],
                    timestamp=datetime.fromisoformat(parts[2].replace("Z", "+00:00")),
                    author_name=parts[3],
                    author_email=parts[4],
                    commit_message=parts[5],
                    tag_name=tag_name,
                    branch_name=branch_name,
                    is_current_branch=is_current_branch,
                    distance_from_head=index,
                    is_head_commit=(index == 0),
                    total_commits=total_commits,
                )

    @property
    def tags(self) -> Iterator[GitReference]:
        """Yield all tags in the repository sorted by creation date.

        :return: Iterator of tag reference objects.
        :raises NotAGitRepositoryError: If the path is not a valid Git repository.
        """
        self._ensure_valid_repository()
        current = self.current_commit
        head_sha = current.commit_sha if current else ""
        total_commits = self.commit_count
        format_string = "%(refname:short)|%(creatordate:iso-strict)|%(objectname)"

        lines = self._stream_command(
            [
                "for-each-ref",
                "--sort=-creatordate",
                f"--format={format_string}",
                "refs/tags/",
            ]
        )

        for line in lines:
            name, date_str, sha = line.split("|")
            distance_str = self._execute_command(
                ["rev-list", "--count", f"{sha}..HEAD"]
            )
            yield GitReference(
                tag_name=name,
                commit_sha=sha,
                short_sha=sha[:7],
                timestamp=datetime.fromisoformat(date_str.replace("Z", "+00:00")),
                distance_from_head=int(distance_str or 0),
                is_head_commit=(sha == head_sha),
                total_commits=total_commits,
            )

    @property
    def branches(self) -> Iterator[GitReference]:
        """Yield all branches in the repository.

        :return: Iterator of branch reference objects.
        :raises NotAGitRepositoryError: If the path is not a valid Git repository.
        """
        self._ensure_valid_repository()
        current = self.current_commit
        head_sha = current.commit_sha if current else ""
        total_commits = self.commit_count
        format_string = (
            "%(refname:short)|%(objectname)|%(HEAD)|%(committerdate:iso-strict)"
        )

        lines = self._stream_command(
            [
                "for-each-ref",
                f"--format={format_string}",
                "refs/heads/",
                "refs/remotes/",
            ]
        )

        for line in lines:
            name, sha, current_marker, date_str = line.split("|")
            yield GitReference(
                branch_name=name,
                commit_sha=sha,
                short_sha=sha[:7],
                timestamp=datetime.fromisoformat(date_str.replace("Z", "+00:00")),
                distance_from_head=0,
                is_head_commit=(sha == head_sha),
                is_current_branch=(current_marker == "*"),
                total_commits=total_commits,
            )

    def filtered_dirty_files(
        self, ignore_paths: list[Path] | None = None, fail_on_unavailable: bool = False
    ) -> list[str]:
        """Filter modified files excluding the specified ignore paths.

        Example
        -------
        .. code-block:: python

            dirty = repo.filtered_dirty_files(ignore_paths=[Path("tmp")])

        :param ignore_paths: List of file/directory paths to exclude from results.
        :param fail_on_unavailable: If True, raise exception if Git is missing.
        :return: List of filtered dirty file paths as strings.
        :raises NotAGitRepositoryError: If repository is missing and
            fail_on_unavailable is True.
        """
        if not self.is_available:
            if fail_on_unavailable:
                raise NotAGitRepositoryError(
                    f"Path '{self.base_path}' is not a Git repository."
                )
            return []

        unfiltered_files = []
        ignore_paths_abs = [
            path.resolve() if path.is_absolute() else (self.base_path / path).resolve()
            for path in ignore_paths or []
        ]

        for dirty_file in self.dirty_files:
            if not any(
                dirty_file == ignored or ignored in dirty_file.parents
                for ignored in ignore_paths_abs
            ):
                unfiltered_files.append(str(dirty_file))

        return unfiltered_files

    def _stream_command(self, arguments: list[str]) -> Iterator[str]:
        # Stream the output of a Git command line by line.
        full_command = ["git", *arguments]
        try:
            with subprocess.Popen(  # noqa: S603
                full_command,
                cwd=self.base_path,
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL,
                text=True,
            ) as process:
                if process.stdout:
                    for line in process.stdout:
                        if clean_line := line.strip():
                            yield clean_line
        except (subprocess.CalledProcessError, FileNotFoundError, OSError) as error:
            logger.debug(f"Command '{shlex.join(full_command)}' failed: {error}")

    def _execute_command(self, arguments: list[str]) -> str:
        # Execute a Git command and return stdout as a stripped string.
        full_command = ["git", *arguments]
        try:
            return subprocess.run(  # noqa: S603
                full_command,
                cwd=self.base_path,
                capture_output=True,
                text=True,
                check=True,
            ).stdout.rstrip()
        except (subprocess.CalledProcessError, FileNotFoundError, OSError) as error:
            logger.debug(f"Command '{shlex.join(full_command)}' failed: {error}")
            return ""

    def _ensure_valid_repository(self) -> None:
        # Ensure the repository is available, raising NotAGitRepositoryError if not.
        if not self.is_available:
            raise NotAGitRepositoryError(
                f"Path '{self.base_path}' is not a Git repository."
            )

branches property

Yield all branches in the repository.

:return: Iterator of branch reference objects. :raises NotAGitRepositoryError: If the path is not a valid Git repository.

commit_count property

Get the total commit count on the current branch.

:return: Total number of commits, or 0 if unavailable.

commits property

Yield all commits in the repository history.

:return: Iterator of commit reference objects. :raises NotAGitRepositoryError: If the path is not a valid Git repository.

current_branch property

Get the currently checked-out branch.

:return: Current branch reference, or None if in detached HEAD.

current_commit property

Get the most recent commit.

:return: Most recent commit reference, or None if empty.

current_commit_or_fallback property

Get the most recent commit or a generated fallback reference.

:return: Current commit reference, or a dummy reference if unavailable.

dirty_files property

Get a list of all modified and untracked file paths.

:return: List of paths with uncommitted changes.

head_name property

Get the branch name or the short commit SHA of HEAD.

:return: Current branch name, or short SHA if detached.

is_available property

Check if the base path is within a valid Git work tree.

:return: True if the repository path is a valid Git work tree, False otherwise.

is_dirty property

Check if the repository has uncommitted modifications.

:return: True if dirty changes exist, False otherwise.

last_tag property

Get the most recent tag.

:return: Most recent tag reference, or None if no tags exist.

remote_origin_url property

Get the remote origin URL.

:return: Remote origin URL, or empty string if not set.

repository_name property

Get the name of the Git repository.

Attempts to parse the name from the remote origin URL, falling back to the root directory name.

:return: The repository name.

root_directory property

Get the root directory of the Git repository.

:return: Absolute path to the Git repository root. :raises NotAGitRepositoryError: If the path is not a valid Git repository.

tags property

Yield all tags in the repository sorted by creation date.

:return: Iterator of tag reference objects. :raises NotAGitRepositoryError: If the path is not a valid Git repository.

__init__(repository_path=None)

Initialize the GitRepository instance.

:param repository_path: Base directory of the repository, defaults to Path.cwd().

Source code in src/gitversioned/utils/git.py
def __init__(
    self,
    repository_path: Path | str | None = None,
) -> None:
    """Initialize the GitRepository instance.

    :param repository_path: Base directory of the repository,
        defaults to Path.cwd().
    """
    self.base_path = Path(repository_path or Path.cwd()).resolve()

__repr__()

Return a detailed string representation.

Source code in src/gitversioned/utils/git.py
def __repr__(self) -> str:
    """Return a detailed string representation."""
    return f"GitRepository(base_path={self.base_path!r})"

__str__()

Return a concise string representation.

Source code in src/gitversioned/utils/git.py
def __str__(self) -> str:
    """Return a concise string representation."""
    if not self.is_available:
        return f"GitRepository({self.base_path}) - Unavailable"

    dirty_files = self.dirty_files
    current = self.current_commit
    tag = self.last_tag
    branch = self.current_branch

    head = "detached"
    if branch:
        head = branch.branch_name
    elif current:
        head = current.short_sha

    return (
        f"GitRepository(path={self.base_path!r}, is_available=True, "
        f"commit_count={self.commit_count}, is_dirty={bool(dirty_files)}, "
        f"dirty_files={dirty_files}, "
        f"current_commit={current.short_sha if current else None}, "
        f"last_tag={tag.tag_name if tag else None}, "
        f"current_branch={branch.branch_name if branch else None}"
        f") - {head}{'*' if dirty_files else ''}"
    )

filtered_dirty_files(ignore_paths=None, fail_on_unavailable=False)

Filter modified files excluding the specified ignore paths.

Example

.. code-block:: python

dirty = repo.filtered_dirty_files(ignore_paths=[Path("tmp")])

:param ignore_paths: List of file/directory paths to exclude from results. :param fail_on_unavailable: If True, raise exception if Git is missing. :return: List of filtered dirty file paths as strings. :raises NotAGitRepositoryError: If repository is missing and fail_on_unavailable is True.

Source code in src/gitversioned/utils/git.py
def filtered_dirty_files(
    self, ignore_paths: list[Path] | None = None, fail_on_unavailable: bool = False
) -> list[str]:
    """Filter modified files excluding the specified ignore paths.

    Example
    -------
    .. code-block:: python

        dirty = repo.filtered_dirty_files(ignore_paths=[Path("tmp")])

    :param ignore_paths: List of file/directory paths to exclude from results.
    :param fail_on_unavailable: If True, raise exception if Git is missing.
    :return: List of filtered dirty file paths as strings.
    :raises NotAGitRepositoryError: If repository is missing and
        fail_on_unavailable is True.
    """
    if not self.is_available:
        if fail_on_unavailable:
            raise NotAGitRepositoryError(
                f"Path '{self.base_path}' is not a Git repository."
            )
        return []

    unfiltered_files = []
    ignore_paths_abs = [
        path.resolve() if path.is_absolute() else (self.base_path / path).resolve()
        for path in ignore_paths or []
    ]

    for dirty_file in self.dirty_files:
        if not any(
            dirty_file == ignored or ignored in dirty_file.parents
            for ignored in ignore_paths_abs
        ):
            unfiltered_files.append(str(dirty_file))

    return unfiltered_files

LoggingSettings

Bases: BaseSettings

Settings configuration for the GitVersioned logging subsystem.

This class defines the configuration schema for logging, loading parameters from environment variables prefixed with GITVERSIONED__LOGGING__ or via direct instantiation. It allows customizing the output sink, log level, format template, OpenTelemetry integration, and thread-safe queueing.

Example

.. code-block:: python

from gitversioned.logging import LoggingSettings, configure_logger

settings = LoggingSettings(
    enabled=True,
    level="DEBUG",
    sink="stdout"
)
configure_logger(settings)

:cvar model_config: Configuration dictionary dictating environment variable prefixes and nested delimiters.

Source code in src/gitversioned/logging.py
class LoggingSettings(BaseSettings):
    """
    Settings configuration for the GitVersioned logging subsystem.

    This class defines the configuration schema for logging, loading parameters
    from environment variables prefixed with `GITVERSIONED__LOGGING__` or via
    direct instantiation. It allows customizing the output sink, log level,
    format template, OpenTelemetry integration, and thread-safe queueing.

    Example:
        .. code-block:: python

            from gitversioned.logging import LoggingSettings, configure_logger

            settings = LoggingSettings(
                enabled=True,
                level="DEBUG",
                sink="stdout"
            )
            configure_logger(settings)

    :cvar model_config: Configuration dictionary dictating environment variable
                        prefixes and nested delimiters.
    """

    enabled: bool = Field(
        default=False,
        description=(
            "Enables or disables logging output across the gitversioned package."
        ),
    )
    clear_loggers: bool = Field(
        default=False,
        description=(
            "Configures whether all existing active logger sinks "
            "are removed prior to setup."
        ),
    )
    sink: str | Any = Field(
        default=sys.stderr,
        description=(
            "Specifies and maps the output target, such as standard streams "
            "(stdout, stderr) or a file path, for log messages."
        ),
    )
    level: str = Field(
        default="WARNING",
        description=(
            "Configures the minimum severity level required for log messages "
            "to be emitted."
        ),
    )
    otel_formatting: Literal["auto", "enable", "disable"] = Field(
        default="auto",
        description=(
            "Configures the OpenTelemetry-compliant JSON formatting option "
            "(auto, enable, or disable)."
        ),
    )
    format: str | Callable[..., Any] | None = Field(
        default="<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>\n",
        description=(
            "Configures the standard text template layout for emitted log lines."
        ),
    )
    filter: Any = Field(
        default=True,
        description=(
            "Configures the filtering criteria, using a prefix string, "
            "list of prefixes, or a filter function."
        ),
    )
    enqueue: bool = Field(
        default=True,
        description="Enables or disables asynchronous, thread-safe message queueing.",
    )
    kwargs: dict[str, Any] = Field(
        default_factory=dict,
        description=(
            "Maps additional custom arguments passed directly "
            "to the loguru add handler."
        ),
    )

    model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(
        env_prefix="GITVERSIONED__LOGGING__",
        env_nested_delimiter="__",
    )

    @field_validator("sink", mode="before")
    @classmethod
    def _parse_sink(cls, value: Any) -> Any:
        # Convert string aliases for standard output/error streams to stream objects.
        if isinstance(value, str):
            mapping = {
                "stdout": sys.stdout,
                "sys.stdout": sys.stdout,
                "stderr": sys.stderr,
                "sys.stderr": sys.stderr,
            }
            return mapping.get(value.lower(), value)
        return value

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", ""),
        ),
    )

configure_logger(settings=None, **default_overrides)

Configure the global Loguru logger based on settings.

This function initializes or updates the active logger handler. If no settings are provided, it loads settings from environment variables. It enables interception of standard library log statements and configures formatting, sinks, filtering, and queue options.

Example

.. code-block:: python

from gitversioned.logging import LoggingSettings, configure_logger

configure_logger(
    settings=LoggingSettings(level="INFO"),
    clear_loggers=True
)

:param settings: Logging configurations, defaults to None (loads from environment). :param default_overrides: Parameter overrides merged into env settings if settings is None. :returns: None. :raises ImportError: Raised if OpenTelemetry formatting is enabled but the package is not installed.

Source code in src/gitversioned/logging.py
def configure_logger(  # noqa: C901, PLR0912, PLR0915
    settings: LoggingSettings | None = None,
    **default_overrides: Any,
) -> None:
    """
    Configure the global Loguru logger based on settings.

    This function initializes or updates the active logger handler. If no
    settings are provided, it loads settings from environment variables.
    It enables interception of standard library log statements and configures
    formatting, sinks, filtering, and queue options.

    Example:
        .. code-block:: python

            from gitversioned.logging import LoggingSettings, configure_logger

            configure_logger(
                settings=LoggingSettings(level="INFO"),
                clear_loggers=True
            )

    :param settings: Logging configurations, defaults to None (loads from environment).
    :param default_overrides: Parameter overrides merged into env settings if
                              settings is None.
    :returns: None.
    :raises ImportError: Raised if OpenTelemetry formatting is enabled but the
                         package is not installed.
    """
    if settings is None:
        env_settings = LoggingSettings()
        merged = default_overrides.copy()
        for field in env_settings.model_fields_set:
            merged[field] = getattr(env_settings, field)
        settings = LoggingSettings(**merged)

    if not settings.enabled:
        logger.disable("gitversioned")
        intercept_standard_logging(False)
        if isinstance(_state["handler_id"], int):
            with contextlib.suppress(ValueError):
                logger.remove(_state["handler_id"])
            _state["handler_id"] = None
        return

    logger.enable("gitversioned")
    intercept_standard_logging(True)

    if settings.clear_loggers:
        if hasattr(logger, "_mock_name") or type(logger).__name__ in (
            "MagicMock",
            "Mock",
        ):
            logger.remove()
        else:
            for handler_id, handler in list(cast("Any", logger)._core.handlers.items()):  # noqa: SLF001
                sink = getattr(handler, "_sink", None)
                handler_obj = getattr(sink, "_handler", None)
                if handler_obj and type(handler_obj).__name__ == "PropagateHandler":
                    continue
                with contextlib.suppress(ValueError):
                    logger.remove(handler_id)
        _state["handler_id"] = None
    elif isinstance(_state["handler_id"], int):
        with contextlib.suppress(ValueError):
            logger.remove(_state["handler_id"])
        _state["handler_id"] = None

    use_otel = settings.otel_formatting == "enable" or (
        settings.otel_formatting == "auto" and opentelemetry_trace is not None
    )
    if settings.otel_formatting == "enable" and opentelemetry_trace is None:
        raise ImportError(
            "OpenTelemetry is not installed but 'otel_formatting' was set to 'enable'."
        )

    if use_otel:
        sink_val = OtelSink(settings.sink)
        log_format = "{message}\n"
    else:
        sink_val = settings.sink
        log_format = settings.format

    filter_val = "gitversioned" if settings.filter is True else settings.filter

    if isinstance(filter_val, str):
        final_filter: Any = filter_val
    elif isinstance(filter_val, (list, tuple)):
        prefixes = tuple(filter_val)

        def final_filter(record: dict[str, Any]) -> bool:
            return bool(record["name"] and record["name"].startswith(prefixes))

    else:
        final_filter = None if filter_val is False else filter_val

    # Resolve "auto" log level
    level_val = settings.level
    if level_val == "auto":
        level_val = "WARNING"

    _state["handler_id"] = logger.add(
        sink=cast("Any", sink_val),
        level=level_val,
        filter=cast("Any", final_filter),
        format=cast("Any", log_format),
        enqueue=settings.enqueue,
        **settings.kwargs,
    )

resolve_version(settings, repository=None, environment=None)

Resolve the dynamic version from configured sources and apply formatting.

Queries the repository sources to obtain a base version, determines the build type (e.g., release or dev), applies auto-increment increments if configured, and formats the final PEP 440 version.

Example

from gitversioned.settings import Settings version, v_type, ref = resolve_version(Settings())

:param settings: Configuration settings governing version resolution. :param repository: Optional Git repository instance to query. :param environment: Optional build environment parameters. :return: A tuple containing the final normalized Version, the version type, and the GitReference used for resolution.

Source code in src/gitversioned/versioning/entrypoints.py
@autolog
def resolve_version(
    settings: Settings,
    repository: GitRepository | None = None,
    environment: BuildEnvironment | None = None,
) -> tuple[Version, VersionType, GitReference]:
    """
    Resolve the dynamic version from configured sources and apply formatting.

    Queries the repository sources to obtain a base version, determines the build
    type (e.g., release or dev), applies auto-increment increments if configured,
    and formats the final PEP 440 version.

    Example:
        >>> from gitversioned.settings import Settings
        >>> version, v_type, ref = resolve_version(Settings())

    :param settings: Configuration settings governing version resolution.
    :param repository: Optional Git repository instance to query.
    :param environment: Optional build environment parameters.
    :return: A tuple containing the final normalized Version, the version type,
        and the GitReference used for resolution.
    """
    repository, environment = _resolve_repo_and_env(settings, repository, environment)

    try:
        version, reference = resolve_sources(settings.source_type, settings, repository)
        logger.info(f"Resolved version from sources: {version} for git ref {reference}")

    except VersionResolutionError as ver_err:
        logger.info(f"Could not resolve version from sources: {ver_err}")
        version = Version("0.1.0")
        reference = repository.current_commit_or_fallback
        logger.warning(
            "No version could be resolved from the configured sources, "
            f"defaulting to base version: {version} and git reference {reference}"
        )

    version_type = _determine_version_type(settings, repository, reference)
    logger.info(f"Using version type: '{version_type}' for git reference {reference}")

    target_key = cast("VersionType", version_type)
    auto_increment_level = ""
    val = (
        settings.auto_increment.get(cast("Any", target_key))
        if settings.auto_increment is not None
        else None
    )
    if (
        val is None
        and target_key in ("alpha", "nightly")
        and settings.auto_increment is not None
    ):
        val = settings.auto_increment.get("pre")
    if val is not None:
        auto_increment_level = val.lower().strip()
    if (
        target_idx := {"major": 0, "minor": 1, "micro": 2, "patch": 2, "bug": 2}.get(
            auto_increment_level
        )
    ) is not None:
        base_version = version
        parts = [version.major, version.minor, version.micro]
        parts[target_idx] += 1
        for index in range(target_idx + 1, len(parts)):
            parts[index] = 0
        version = Version(".".join(map(str, parts)))
        logger.info(
            f"Auto-incremented version from {base_version} to {version} "
            f"(target='{auto_increment_level}')"
        )

    # Generate and validate new semantic version
    version_base = generate_from_template(
        settings.format_main, version, reference, settings, repository, environment
    )
    version_segment = generate_from_template(
        {
            "release": "",
            "dev": settings.format_dev,
            "pre": settings.format_pre,
            "alpha": settings.format_pre,
            "nightly": settings.format_pre,
            "post": settings.format_post,
        }.get(version_type),
        version,
        reference,
        settings,
        repository,
        environment,
    )
    version_final = Version(f"{version_base}.{version_segment}".rstrip("+."))
    logger.info(f"Resolved final version: {version_final}")

    return version_final, cast("VersionType", version_type), reference

resolve_version_output(settings, repository=None, environment=None)

Resolve the version and format the target output content.

Runs version resolution and then applies the configured output strategies to format the final string (e.g., for writing to a version file).

Example

from gitversioned.settings import Settings content, version, v_type, ref = resolve_version_output(Settings())

:param settings: Configuration settings governing output generation. :param repository: Optional Git repository instance to query. :param environment: Optional build environment parameters. :return: A tuple containing the formatted output content string, the resolved Version, the version type, and the GitReference.

Source code in src/gitversioned/versioning/entrypoints.py
@autolog
def resolve_version_output(
    settings: Settings,
    repository: GitRepository | None = None,
    environment: BuildEnvironment | None = None,
) -> tuple[
    str,
    Version,
    VersionType,
    GitReference,
]:
    """
    Resolve the version and format the target output content.

    Runs version resolution and then applies the configured output strategies
    to format the final string (e.g., for writing to a version file).

    Example:
        >>> from gitversioned.settings import Settings
        >>> content, version, v_type, ref = resolve_version_output(Settings())

    :param settings: Configuration settings governing output generation.
    :param repository: Optional Git repository instance to query.
    :param environment: Optional build environment parameters.
    :return: A tuple containing the formatted output content string, the resolved
        Version, the version type, and the GitReference.
    """
    repository, environment = _resolve_repo_and_env(settings, repository, environment)
    version, version_type, reference = resolve_version(
        settings, repository, environment
    )
    output = generate_output_from_strategies(
        version, version_type, reference, settings, repository, environment
    )
    logger.info(f"Resolved version output: {output} for git reference {reference}")

    return output, version, version_type, reference

resolve_version_output_to_stream(settings, repository=None, environment=None)

Resolve the version and write formatted content to the configured output file path.

Resolves the dynamic version, formats it using the configured strategy, and writes the formatted content to the specified output file path. Creates parent directories for files if needed.

Example

from gitversioned.settings import Settings settings = Settings() res = resolve_version_output_to_stream(settings)

:param settings: Configuration settings governing output path and formatting. :param repository: Optional Git repository instance to query. :param environment: Optional build environment parameters. :return: A tuple containing the resolved output Path (or None if disabled), the formatted content, the Version, the version type, and the GitReference. :raises ValueError: If the configured output target cannot be written to.

Source code in src/gitversioned/versioning/entrypoints.py
@autolog
def resolve_version_output_to_stream(
    settings: Settings,
    repository: GitRepository | None = None,
    environment: BuildEnvironment | None = None,
) -> tuple[Path | None, str, Version, VersionType, GitReference]:
    """
    Resolve the version and write formatted content to the configured output file path.

    Resolves the dynamic version, formats it using the configured strategy, and writes
    the formatted content to the specified output file path. Creates parent directories
    for files if needed.

    Example:
        >>> from gitversioned.settings import Settings
        >>> settings = Settings()
        >>> res = resolve_version_output_to_stream(settings)

    :param settings: Configuration settings governing output path and formatting.
    :param repository: Optional Git repository instance to query.
    :param environment: Optional build environment parameters.
    :return: A tuple containing the resolved output Path (or None if disabled),
        the formatted content, the Version, the version type, and the GitReference.
    :raises ValueError: If the configured output target cannot be written to.
    """
    repository, environment = _resolve_repo_and_env(settings, repository, environment)
    output_content, version, version_type, reference = resolve_version_output(
        settings, repository, environment
    )

    output_path = None
    if not settings.output:
        logger.debug("No output target configured, skipping writing to output path.")
    else:
        output_path = settings.resolve_path_from_root(
            settings.output, enforce_existence=False
        )
        if output_path is None:
            raise ValueError(
                f"Could not resolve output path for target: {settings.output}"
            )
        try:
            output_path.parent.mkdir(parents=True, exist_ok=True)
            output_path.write_text(output_content, encoding="utf-8")
        except OSError as err:
            raise ValueError(f"Invalid output target: {settings.output}") from err

    if hasattr(settings, "overrides") and settings.overrides:
        for override_name in settings.overrides:
            override_settings = settings.get_overridden_settings(override_name)
            override_settings.version = str(version)
            override_settings.auto_increment = None
            override_settings.version_type = version_type
            resolve_version_output_to_stream(
                settings=override_settings,
                repository=repository,
                environment=environment,
            )

    return output_path, output_content, version, version_type, reference