Skip to content

feat(bitbucket-server): Commit context (Suspect Commit) #87680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions src/sentry/integrations/bitbucket_server/blame.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import logging
from collections.abc import Mapping, Sequence
from dataclasses import asdict
from datetime import datetime, timezone
from typing import Any

from sentry.integrations.bitbucket_server.utils import BitbucketServerAPIPath
from sentry.integrations.source_code_management.commit_context import (
CommitInfo,
FileBlameInfo,
SourceLineInfo,
)
from sentry.shared_integrations.client.base import BaseApiClient
from sentry.shared_integrations.exceptions import ApiError

logger = logging.getLogger("sentry.integrations.bitbucket_server")


def _blame_file(
client: BaseApiClient, file: SourceLineInfo, extra: Mapping[str, Any]
) -> FileBlameInfo | None:
if file.lineno is None:
logger.warning("blame_file.no_lineno", extra=extra)
return None

project = file.repo.config["project"]
repo = file.repo.config["repo"]

browse_url = BitbucketServerAPIPath.get_browse(
project=project,
repo=repo,
path=file.path,
sha=file.ref,
blame=True,
no_content=True,
)

try:
data = client.get(browse_url)
except ApiError as e:
if e.code in (401, 403, 404):
logger.warning(
"blame_file.browse.api_error",
extra={
**extra,
"code": e.code,
"error_message": e.text,
},
)
return None
raise

for entry in data:
start = entry["lineNumber"]
span = entry["spannedLines"]
Comment on lines +54 to +55
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there an example of what the blame response looks like? i couldn't find any on the Bitbucket Server API docs

end = start + span - 1 # inclusive range

if start <= file.lineno <= end:
commit_id = entry["commitId"]
commited_date = datetime.fromtimestamp(
entry["committerTimestamp"] / 1000.0, tz=timezone.utc
)

try:
commit_data = client.get_cached(
BitbucketServerAPIPath.repository_commit.format(
project=project, repo=repo, commit=commit_id
),
)
except ApiError as e:
logger.warning(
"blame_file.commit.api_error",
extra={
**extra,
"code": e.code,
"error_message": e.text,
"commit_id": commit_id,
},
)
commit_message = None
else:
commit_message = commit_data.get("message")

return FileBlameInfo(
**asdict(file),
commit=CommitInfo(
commitId=commit_id,
committedDate=commited_date,
commitMessage=commit_message,
commitAuthorName=entry["author"].get("name"),
commitAuthorEmail=entry["author"].get("emailAddress"),
),
)

return None


def fetch_file_blames(
client: BaseApiClient, files: Sequence[SourceLineInfo], extra: Mapping[str, Any]
) -> list[FileBlameInfo]:
blames = []
for file in files:
extra_file = {
**extra,
"repo_name": file.repo.name,
"file_path": file.path,
"branch_name": file.ref,
"file_lineno": file.lineno,
}

blame = _blame_file(client, file, extra_file)
if blame:
blames.append(blame)
else:
logger.warning(
"fetch_file_blames.no_blame",
extra=extra_file,
)
return blames
69 changes: 53 additions & 16 deletions src/sentry/integrations/bitbucket_server/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import logging
from collections.abc import Mapping, Sequence
from typing import Any
from urllib.parse import parse_qsl

from oauthlib.oauth1 import SIGNATURE_RSA
Expand All @@ -7,30 +9,24 @@

from sentry.identity.services.identity.model import RpcIdentity
from sentry.integrations.base import IntegrationFeatureNotImplementedError
from sentry.integrations.bitbucket_server.blame import fetch_file_blames
from sentry.integrations.bitbucket_server.utils import BitbucketServerAPIPath
from sentry.integrations.client import ApiClient
from sentry.integrations.models.integration import Integration
from sentry.integrations.services.integration.model import RpcIntegration
from sentry.integrations.source_code_management.commit_context import (
CommitContextClient,
FileBlameInfo,
SourceLineInfo,
)
from sentry.integrations.source_code_management.repository import RepositoryClient
from sentry.models.repository import Repository
from sentry.shared_integrations.exceptions import ApiError
from sentry.utils import metrics

logger = logging.getLogger("sentry.integrations.bitbucket_server")


class BitbucketServerAPIPath:
"""
project is the short key of the project
repo is the fully qualified slug
"""

repository = "/rest/api/1.0/projects/{project}/repos/{repo}"
repositories = "/rest/api/1.0/repos"
repository_hook = "/rest/api/1.0/projects/{project}/repos/{repo}/webhooks/{id}"
repository_hooks = "/rest/api/1.0/projects/{project}/repos/{repo}/webhooks"
repository_commits = "/rest/api/1.0/projects/{project}/repos/{repo}/commits"
commit_changes = "/rest/api/1.0/projects/{project}/repos/{repo}/commits/{commit}/changes"


class BitbucketServerSetupClient(ApiClient):
"""
Client for making requests to Bitbucket Server to follow OAuth1 flow.
Expand Down Expand Up @@ -100,7 +96,7 @@ def request(self, *args, **kwargs):
return self._request(*args, **kwargs)


class BitbucketServerClient(ApiClient, RepositoryClient):
class BitbucketServerClient(ApiClient, RepositoryClient, CommitContextClient):
"""
Contains the BitBucket Server specifics in order to communicate with bitbucket

Expand Down Expand Up @@ -256,9 +252,50 @@ def _get_values(self, uri, params, max_pages=1000000):
return values

def check_file(self, repo: Repository, path: str, version: str | None) -> object | None:
raise IntegrationFeatureNotImplementedError
return self.head_cached(
path=BitbucketServerAPIPath.build_source(
project=repo.config["project"],
repo=repo.config["repo"],
path=path,
sha=version,
),
)

def get_file(
self, repo: Repository, path: str, ref: str | None, codeowners: bool = False
) -> str:
response = self.get_cached(
path=BitbucketServerAPIPath.build_raw(
project=repo.config["project"],
repo=repo.config["repo"],
path=path,
sha=ref,
),
raw_response=True,
)
return response.text

def get_blame_for_files(
self, files: Sequence[SourceLineInfo], extra: Mapping[str, Any]
) -> list[FileBlameInfo]:
metrics.incr("integrations.bitbucket_server.get_blame_for_files")
return fetch_file_blames(
self,
files,
extra={
**extra,
"provider": "bitbucket_server",
"org_integration_id": self.integration_id,
},
)

def create_comment(self, repo: str, issue_id: str, data: Mapping[str, Any]) -> Any:
raise IntegrationFeatureNotImplementedError

def update_comment(
self, repo: str, issue_id: str, comment_id: str, data: Mapping[str, Any]
) -> Any:
raise IntegrationFeatureNotImplementedError

def get_merge_commit_sha_from_commit(self, repo: str, sha: str) -> str | None:
raise IntegrationFeatureNotImplementedError
61 changes: 53 additions & 8 deletions src/sentry/integrations/bitbucket_server/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from collections.abc import Mapping
from typing import Any
from urllib.parse import urlparse
from urllib.parse import parse_qs, quote, urlencode, urlparse

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key
Expand All @@ -19,14 +19,14 @@
FeatureDescription,
IntegrationData,
IntegrationDomain,
IntegrationFeatureNotImplementedError,
IntegrationFeatures,
IntegrationMetadata,
IntegrationProvider,
)
from sentry.integrations.models.integration import Integration
from sentry.integrations.services.repository import repository_service
from sentry.integrations.services.repository.model import RpcRepository
from sentry.integrations.source_code_management.commit_context import CommitContextIntegration
from sentry.integrations.source_code_management.repository import RepositoryIntegration
from sentry.integrations.tasks.migrate_repo import migrate_repo
from sentry.integrations.utils.metrics import (
Expand Down Expand Up @@ -62,6 +62,19 @@
""",
IntegrationFeatures.COMMITS,
),
FeatureDescription(
"""
Link your Sentry stack traces back to your Bitbucket Server source code with stack
trace linking.
""",
IntegrationFeatures.STACKTRACE_LINK,
),
FeatureDescription(
"""
Import your Bitbucket Server [CODEOWNERS file](https://support.atlassian.com/bitbucket-cloud/docs/set-up-and-use-code-owners/) and use it alongside your ownership rules to assign Sentry issues.
""",
IntegrationFeatures.CODEOWNERS,
),
]

setup_alert = {
Expand Down Expand Up @@ -239,13 +252,15 @@ def dispatch(self, request: HttpRequest, pipeline: Pipeline) -> HttpResponseBase
)


class BitbucketServerIntegration(RepositoryIntegration):
class BitbucketServerIntegration(RepositoryIntegration, CommitContextIntegration):
"""
IntegrationInstallation implementation for Bitbucket Server
"""

default_identity = None

codeowners_locations = [".bitbucket/CODEOWNERS"]

@property
def integration_name(self) -> str:
return "bitbucket_server"
Expand Down Expand Up @@ -312,16 +327,40 @@ def get_unmigratable_repositories(self):
return list(filter(lambda repo: repo.name not in accessible_repos, repos))

def source_url_matches(self, url: str) -> bool:
raise IntegrationFeatureNotImplementedError
return url.startswith(self.model.metadata["base_url"])

def format_source_url(self, repo: Repository, filepath: str, branch: str | None) -> str:
raise IntegrationFeatureNotImplementedError
project = quote(repo.config["project"])
repo_name = quote(repo.config["repo"])
source_url = f"{self.model.metadata["base_url"]}/projects/{project}/repos/{repo_name}/browse/{filepath}"

if branch:
source_url += "?" + urlencode({"at": branch})

return source_url

def extract_branch_from_source_url(self, repo: Repository, url: str) -> str:
raise IntegrationFeatureNotImplementedError
parsed_url = urlparse(url)
qs = parse_qs(parsed_url.query)

if "at" in qs and len(qs["at"]) == 1:
branch = qs["at"][0]

# branch name may be prefixed with refs/heads/, so we strip that
refs_prefix = "refs/heads/"
if branch.startswith(refs_prefix):
branch = branch[len(refs_prefix) :]

return branch

return ""

def extract_source_path_from_source_url(self, repo: Repository, url: str) -> str:
raise IntegrationFeatureNotImplementedError
if repo.url is None:
return ""
parsed_repo_url = urlparse(repo.url)
parsed_url = urlparse(url)
return parsed_url.path.replace(parsed_repo_url.path + "/", "")

# Bitbucket Server only methods

Expand All @@ -336,7 +375,13 @@ class BitbucketServerIntegrationProvider(IntegrationProvider):
metadata = metadata
integration_cls = BitbucketServerIntegration
needs_default_identity = True
features = frozenset([IntegrationFeatures.COMMITS])
features = frozenset(
[
IntegrationFeatures.COMMITS,
IntegrationFeatures.STACKTRACE_LINK,
IntegrationFeatures.CODEOWNERS,
]
)
setup_dialog_config = {"width": 1030, "height": 1000}

def get_pipeline_views(self) -> list[PipelineView]:
Expand Down
37 changes: 37 additions & 0 deletions src/sentry/integrations/bitbucket_server/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from urllib.parse import quote, urlencode


class BitbucketServerAPIPath:
"""
project is the short key of the project
repo is the fully qualified slug
"""

repository = "/rest/api/1.0/projects/{project}/repos/{repo}"
repositories = "/rest/api/1.0/repos"
repository_hook = "/rest/api/1.0/projects/{project}/repos/{repo}/webhooks/{id}"
repository_hooks = "/rest/api/1.0/projects/{project}/repos/{repo}/webhooks"
repository_commits = "/rest/api/1.0/projects/{project}/repos/{repo}/commits"
commit_changes = "/rest/api/1.0/projects/{project}/repos/{repo}/commits/{commit}/changes"

@staticmethod
def build_raw(project: str, repo: str, path: str, sha: str) -> str:
project = quote(project)
repo = quote(repo)

params = {}
if sha:
params["at"] = sha

return f"/projects/{project}/repos/{repo}/raw/{path}?{urlencode(params)}"

@staticmethod
def build_source(project: str, repo: str, path: str, sha: str) -> str:
project = quote(project)
repo = quote(repo)

params = {}
if sha:
params["at"] = sha

return f"/rest/api/1.0/projects/{project}/repos/{repo}/browse/{path}?{urlencode(params)}"
Loading
Loading