-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpull_request.py
More file actions
144 lines (118 loc) · 5.28 KB
/
Copy pathpull_request.py
File metadata and controls
144 lines (118 loc) · 5.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import re
from dataclasses import dataclass
from typing import Mapping, Optional
from urllib.parse import urlparse
from socketsecurity.core.git_remote import parse_git_remote
@dataclass(frozen=True)
class PullRequestContext:
number: int = 0
url: Optional[str] = None
def parse_pull_request_number(value) -> int:
"""Coerce a configured or CI-supplied pull request number to a positive int.
Anything that is not a positive integer means "no pull request", including the
literal ``false`` that Buildkite puts in ``BUILDKITE_PULL_REQUEST`` on non-PR
builds. Callers that hand the value on to a comment adapter should store this
result rather than the raw string, which is truthy.
"""
try:
parsed = int(value)
except (TypeError, ValueError):
return 0
return parsed if parsed > 0 else 0
def _http_url(value: Optional[str]) -> Optional[str]:
"""Return ``value`` if it is an http(s) URL with a host, else ``None``.
Every URL fragment read out of the CI environment goes through here before it
is composed into a link, because the result is sent to the API as a diff scan's
``external_href``. Standard runners set these variables themselves, so this is
defense in depth rather than a live hole.
"""
if not value:
return None
url = value.strip().rstrip("/")
parsed = urlparse(url)
return url if parsed.scheme in ("http", "https") and parsed.netloc else None
def _repository_url(value: Optional[str]) -> Optional[str]:
if not value:
return None
url = value.strip().rstrip("/")
if url.endswith(".git"):
url = url[:-4]
return _http_url(url)
def _github_number(env: Mapping[str, str]) -> int:
number = parse_pull_request_number(env.get("PR_NUMBER"))
if number:
return number
match = re.match(r"^refs/pull/(\d+)/", env.get("GITHUB_REF", ""))
return parse_pull_request_number(match.group(1)) if match else 0
def _github_url(number: int, repo: Optional[str], env: Mapping[str, str]) -> Optional[str]:
remote_host, remote_path = parse_git_remote(env.get("BUILDKITE_REPO"))
# config.repo is only ever a bare repository name, so it cannot produce a
# slug on its own; it is kept last for callers that pass a full owner/repo.
repository = env.get("GITHUB_REPOSITORY") or remote_path or repo
if not repository or "/" not in repository:
return None
server = (
_http_url(env.get("GITHUB_SERVER_URL"))
or (_http_url(f"https://{remote_host}") if remote_host else None)
or "https://github.com"
)
return f"{server}/{repository.strip('/')}/pull/{number}"
def _gitlab_url(number: int, repo: Optional[str], env: Mapping[str, str]) -> Optional[str]:
project_url = _repository_url(env.get("CI_PROJECT_URL"))
if not project_url:
remote_host, remote_path = parse_git_remote(env.get("BUILDKITE_REPO"))
project_path = env.get("CI_PROJECT_PATH") or remote_path or repo
server = (
_http_url(env.get("CI_SERVER_URL"))
or (_http_url(f"https://{remote_host}") if remote_host else None)
)
if server and project_path and "/" in project_path:
project_url = f"{server}/{project_path.strip('/')}"
return f"{project_url}/-/merge_requests/{number}" if project_url else None
def _azure_url(number: int, env: Mapping[str, str], github_pr: bool) -> Optional[str]:
repository_url = _repository_url(
env.get("BUILD_REPOSITORY_URI") or
env.get("SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI")
)
if not repository_url:
return None
github_pr = github_pr or "github" in urlparse(repository_url).netloc.lower()
path = "pull" if github_pr else "pullrequest"
return f"{repository_url}/{path}/{number}"
def resolve_pull_request_context(
integration_type: str,
configured_number,
repo: Optional[str],
*,
configured_explicit: bool = False,
env: Optional[Mapping[str, str]] = None,
) -> PullRequestContext:
"""Resolve PR metadata without making provider API calls.
Explicit CLI/config values win, including an explicit zero used to disable
association. Otherwise the provider's standard CI environment is used.
"""
environment = env or {}
provider = str(integration_type or "api").lower()
number = parse_pull_request_number(configured_number)
if not configured_explicit and not number:
if provider == "github":
number = _github_number(environment)
elif provider == "gitlab":
number = parse_pull_request_number(environment.get("CI_MERGE_REQUEST_IID"))
elif provider == "azure":
number = (
parse_pull_request_number(environment.get("SYSTEM_PULLREQUEST_PULLREQUESTNUMBER")) or
parse_pull_request_number(environment.get("SYSTEM_PULLREQUEST_PULLREQUESTID"))
)
if not number:
return PullRequestContext()
if provider == "github":
url = _github_url(number, repo, environment)
elif provider == "gitlab":
url = _gitlab_url(number, repo, environment)
elif provider == "azure":
github_pr = bool(environment.get("SYSTEM_PULLREQUEST_PULLREQUESTNUMBER"))
url = _azure_url(number, environment, github_pr)
else:
url = None
return PullRequestContext(number=number, url=url)