Skip to content

Commit

Permalink
feat: export head sha (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
jd authored Jan 21, 2025
1 parent f200353 commit b3c0cf0
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions pytest_mergify/resources/github_actions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import os
import pathlib
import json

from opentelemetry.sdk.resources import Resource, ResourceDetector

Expand All @@ -11,6 +13,18 @@
class GitHubActionsResourceDetector(ResourceDetector):
"""Detects OpenTelemetry Resource attributes for GitHub Actions."""

@staticmethod
def get_github_actions_head_sha() -> str | None:
if os.getenv("GITHUB_EVENT_NAME") == "pull_request":
# NOTE: we want the head sha of the pull request
event_raw_path = os.getenv("GITHUB_EVENT_PATH")
if event_raw_path and (
(event_path := pathlib.Path(event_raw_path)).is_file()
):
event = json.loads(event_path.read_bytes())
return str(event["pull_request"]["head"]["sha"])
return os.getenv("GITHUB_SHA")

OPENTELEMETRY_GHA_MAPPING = {
cicd_attributes.CICD_PIPELINE_NAME: "GITHUB_JOB",
cicd_attributes.CICD_PIPELINE_RUN_ID: "GITHUB_RUN_ID",
Expand All @@ -33,6 +47,10 @@ def detect(self) -> Resource:
os.environ["GITHUB_SERVER_URL"] + "/" + os.environ["GITHUB_REPOSITORY"]
)

head_sha = self.get_github_actions_head_sha()
if head_sha is not None:
attributes[vcs_attributes.VCS_REF_HEAD_REVISION] = head_sha

for attribute_name, envvar in self.OPENTELEMETRY_GHA_MAPPING.items():
if envvar in os.environ:
attributes[attribute_name] = os.environ[envvar]
Expand Down

0 comments on commit b3c0cf0

Please sign in to comment.