Skip to content

Commit

Permalink
feat: export head sha
Browse files Browse the repository at this point in the history
Change-Id: I4a0387baea6bc716cef978c0d2b1cef01d301faa
  • Loading branch information
jd committed Jan 21, 2025
1 parent af231f9 commit 5471f75
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
3 changes: 1 addition & 2 deletions pytest_mergify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,7 @@ def pytest_addoption(parser: _pytest.config.argparsing.Parser) -> None:
group.addoption(
"--mergify-api-url",
help=(
"URL of the Mergify API "
"(or set via MERGIFY_API_URL environment variable)",
"URL of the Mergify API (or set via MERGIFY_API_URL environment variable)",
),
)

Expand Down
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(leo): we want the head sha of 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 5471f75

Please sign in to comment.