Skip to content

Commit 0ec5743

Browse files
Merge pull request #65 from ModusCreate-Perdigao-GHAS-Playground/feature/fix-sha-sarif
Refactor get_git_info method to use consistent commit SHA fetching
2 parents 3cc3826 + 393b7e1 commit 0ec5743

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/codeql_wrapper/infrastructure/git_utils.py

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,16 @@ def get_git_info(
3737
) -> GitInfo:
3838
self.logger.debug(f"Getting Git info for repository: {self.repository_path}")
3939

40+
# Get consistent commit SHA using the fetch approach
41+
current_ref_resolved = self.get_git_ref(current_ref)
42+
commit_sha = self._get_consistent_commit_sha(current_ref_resolved)
43+
4044
git_info = GitInfo(
4145
repository=self.repo.remotes.origin.url.split("/")[-2]
4246
+ "/"
4347
+ self.repo.remotes.origin.url.split("/")[-1].replace(".git", ""),
44-
commit_sha=self.repo.head.commit.hexsha,
45-
current_ref=self.get_git_ref(current_ref),
48+
commit_sha=commit_sha,
49+
current_ref=current_ref_resolved,
4650
base_ref=self.get_base_ref(base_ref),
4751
remote_url=self.repo.remotes.origin.url,
4852
is_git_repository=True,
@@ -60,6 +64,38 @@ def get_git_info(
6064

6165
return git_info
6266

67+
def _get_consistent_commit_sha(self, current_ref: str) -> str:
68+
"""
69+
Get a consistent commit SHA by fetching the ref and using FETCH_HEAD.
70+
71+
Equivalent to:
72+
git fetch origin refs/pull/xx/merge
73+
git rev-parse FETCH_HEAD
74+
"""
75+
try:
76+
# For PR merge refs, fetch the specific ref and use FETCH_HEAD
77+
if current_ref.startswith("refs/pull/"):
78+
self.logger.debug(f"Fetching specific ref: {current_ref}")
79+
80+
# Equivalent to: git fetch origin refs/pull/31/merge
81+
origin = self.repo.remotes.origin
82+
origin.fetch(current_ref)
83+
84+
# Equivalent to: git rev-parse FETCH_HEAD
85+
fetch_head_commit = self.repo.commit("FETCH_HEAD")
86+
commit_sha = fetch_head_commit.hexsha
87+
88+
self.logger.debug(f"Using FETCH_HEAD commit: {commit_sha}")
89+
return commit_sha
90+
91+
except Exception as e:
92+
self.logger.debug(f"Failed to fetch specific ref {current_ref}: {e}")
93+
94+
# Fallback to HEAD commit for non-PR refs or if fetch fails
95+
commit_sha = self.repo.head.commit.hexsha
96+
self.logger.debug(f"Using HEAD commit: {commit_sha}")
97+
return commit_sha
98+
6399
def get_diff_files(self, git_info: GitInfo) -> List[str]:
64100

65101
try:

0 commit comments

Comments
 (0)