git_utils.py
1 import logging 2 import os 3 4 _logger = logging.getLogger(__name__) 5 6 7 def get_git_repo_url(path: str) -> str | None: 8 """ 9 Obtains the url of the git repository associated with the specified path, 10 returning ``None`` if the path does not correspond to a git repository. 11 """ 12 try: 13 from git import Repo 14 except ImportError as e: 15 _logger.warning( 16 "Failed to import Git (the Git executable is probably not on your PATH)," 17 " so Git SHA is not available. Error: %s", 18 e, 19 ) 20 return None 21 22 try: 23 repo = Repo(path, search_parent_directories=True) 24 return next((remote.url for remote in repo.remotes), None) 25 except Exception: 26 return None 27 28 29 def get_git_commit(path: str) -> str | None: 30 """ 31 Obtains the hash of the latest commit on the current branch of the git repository associated 32 with the specified path, returning ``None`` if the path does not correspond to a git 33 repository. 34 """ 35 try: 36 from git import Repo 37 except ImportError as e: 38 _logger.warning( 39 "Failed to import Git (the Git executable is probably not on your PATH)," 40 " so Git SHA is not available. Error: %s", 41 e, 42 ) 43 return None 44 try: 45 if os.path.isfile(path): 46 path = os.path.dirname(os.path.abspath(path)) 47 repo = Repo(path, search_parent_directories=True) 48 if path in repo.ignored(path): 49 return None 50 return repo.head.commit.hexsha 51 except Exception: 52 return None 53 54 55 def get_git_branch(path: str) -> str | None: 56 """ 57 Obtains the name of the current branch of the git repository associated with the specified 58 path, returning ``None`` if the path does not correspond to a git repository. 59 """ 60 try: 61 from git import Repo 62 except ImportError as e: 63 _logger.warning( 64 "Failed to import Git (the Git executable is probably not on your PATH)," 65 " so Git SHA is not available. Error: %s", 66 e, 67 ) 68 return None 69 70 try: 71 if os.path.isfile(path): 72 path = os.path.dirname(path) 73 repo = Repo(path, search_parent_directories=True) 74 return repo.active_branch.name 75 except Exception: 76 return None