Skip to content

Commit

Permalink
Use rev-parse is-inside-work-tree to check if in git repo (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
martin-pil authored Nov 22, 2024
1 parent 0cb5a62 commit 05cfc44
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
8 changes: 7 additions & 1 deletion src/pytest_opentelemetry/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ def get_codebase_name() -> str:

@staticmethod
def get_codebase_version() -> str:
if not os.path.exists('.git'):
try:
response = subprocess.check_output(
['git', 'rev-parse', '--is-inside-work-tree']
)
if response.strip() != b'true':
return '[unknown: not a git repository]'
except Exception: # pylint: disable=broad-except
return '[unknown: not a git repository]'

try:
Expand Down
35 changes: 22 additions & 13 deletions tests/test_resource.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import os
import re
import subprocess
import tempfile
from typing import Generator
from unittest.mock import patch

import pytest
from opentelemetry.sdk.resources import Resource
Expand Down Expand Up @@ -35,19 +37,26 @@ def test_service_version_unknown(bare_codebase: str, resource: Resource) -> None
assert resource.attributes['service.version'] == '[unknown: not a git repository]'


@pytest.fixture
def broken_repo(bare_codebase: str) -> str:
# making an empty .git directory will get us past the first check, but then
# `git rev-parse HEAD` will fail
os.makedirs('.git')
return bare_codebase


def test_service_version_git_problems(broken_repo: str, resource: Resource) -> None:
assert resource.attributes['service.version'] == (
"[unknown: Command '['git', 'rev-parse', 'HEAD']' "
"returned non-zero exit status 128.]"
)
def test_service_version_git_problems() -> None:
with patch(
'pytest_opentelemetry.resource.subprocess.check_output',
side_effect=[
b'true',
subprocess.CalledProcessError(128, ['git', 'rev-parse', 'HEAD']),
],
):
resource = CodebaseResourceDetector().detect()
assert resource.attributes['service.version'] == (
"[unknown: Command '['git', 'rev-parse', 'HEAD']' "
"returned non-zero exit status 128.]"
)
with patch(
'pytest_opentelemetry.resource.subprocess.check_output', side_effect=[b'false']
):
resource = CodebaseResourceDetector().detect()
assert resource.attributes['service.version'] == (
"[unknown: not a git repository]"
)


@pytest.fixture
Expand Down

0 comments on commit 05cfc44

Please sign in to comment.