Coverage for src / project_meta / git_info.py: 0%
22 statements
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-11 21:45 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-11 21:45 +0000
1"""Module to retrieve git metadata for the project."""
2from __future__ import annotations
4from dataclasses import dataclass
5from pathlib import Path
7import git
10@dataclass
11class GitInfo:
12 """Dataclass to hold git information.
14 :param branch: Current git branch name.
15 :param commit: Current git commit SHA.
16 :param dirty: Boolean indicating if there are uncommitted changes.
17 """
19 @staticmethod
20 def create(repo_path: Path) -> GitInfo:
21 """Get the project git metadata.
23 :param repo_path: Path to the git repository.
24 :return: GitInfo dataclass.
25 """
26 try:
27 repo = git.Repo(repo_path)
28 sha = repo.head.object.hexsha[:7]
29 branch_name = repo.active_branch.name
30 return GitInfo(branch=branch_name, commit=sha, dirty=repo.is_dirty())
31 except git.exc.InvalidGitRepositoryError:
32 # Fallback for when the project is not a git repo (e.g., in a CI/CD build)
33 return GitInfo(branch="NA", commit="", dirty=True)
35 branch: str
36 commit: str
37 dirty: bool
39 def __str__(self) -> str:
40 """Return a string representation of the git information.
42 :return: String with branch name and short commit SHA, e.g., 'main-abc1234-dirty'
43 """
44 if not self.commit:
45 return "unknown-version"
46 return f"{self.branch}-{self.commit[:7]}{'-dirty' if self.dirty else ''}"