From 5471f75765bf2b48e171275cd3f57bbd3cfc3e2a Mon Sep 17 00:00:00 2001 From: Julien Danjou Date: Tue, 21 Jan 2025 14:07:45 +0100 Subject: [PATCH] feat: export head sha Change-Id: I4a0387baea6bc716cef978c0d2b1cef01d301faa --- pytest_mergify/__init__.py | 3 +-- pytest_mergify/resources/github_actions.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/pytest_mergify/__init__.py b/pytest_mergify/__init__.py index 6af9e66..486fce3 100644 --- a/pytest_mergify/__init__.py +++ b/pytest_mergify/__init__.py @@ -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)", ), ) diff --git a/pytest_mergify/resources/github_actions.py b/pytest_mergify/resources/github_actions.py index 90e62f8..104c17d 100644 --- a/pytest_mergify/resources/github_actions.py +++ b/pytest_mergify/resources/github_actions.py @@ -1,4 +1,6 @@ import os +import pathlib +import json from opentelemetry.sdk.resources import Resource, ResourceDetector @@ -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", @@ -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]