Skip to content
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

fix branch protection fetch #894

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
109 changes: 61 additions & 48 deletions bot/kodiak/queries/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,56 @@ class GraphQLResponse(TypedDict, total=False):
query (
$owner: String!,
$repo: String!,
$qualifiedBaseRef: String!,
$rootConfigFileExpression: String!,
$githubConfigFileExpression: String!,
$orgRootConfigFileExpression: String,
$orgGithubConfigFileExpression: String
) {
repository(owner: $owner, name: $repo) {
ref(qualifiedName: $qualifiedBaseRef) {
name
branchProtectionRule {
requiresStatusChecks
requiredStatusCheckContexts
requiresCodeOwnerReviews
requiresStrictStatusChecks

requiresLinearHistory

requiresConversationResolution
requiresCommitSignatures
restrictsPushes
requiredApprovingReviewCount
requireLastPushApproval

requiredStatusChecks {
app {
slug
}
context
}

pushAllowances(first: 100) {
nodes {
actor {
... on Team {
name
}
... on Actor {
login
}
... on User {
login
}
... on App {
databaseId
}
}
}
}
}
}
rootConfigFile: object(expression: $rootConfigFileExpression) {
... on Blob {
text
Expand Down Expand Up @@ -156,30 +200,6 @@ def get_event_info_query(
return """
query GetEventInfo($owner: String!, $repo: String!, $PRNumber: Int!) {
repository(owner: $owner, name: $repo) {
branchProtectionRules(first: 100) {
nodes {
matchingRefs(first: 100) {
nodes {
name
}
}
requiresStatusChecks
requiredStatusCheckContexts
requiresStrictStatusChecks
requiresCommitSignatures
%(requiresConversationResolution)s
restrictsPushes
pushAllowances(first: 100) {
nodes {
actor {
... on App {
databaseId
}
}
}
}
}
}
mergeCommitAllowed
rebaseMergeAllowed
squashMergeAllowed
Expand Down Expand Up @@ -606,29 +626,20 @@ def get_sha(*, pr: Dict[str, Any]) -> Optional[str]:
return None


def get_branch_protection_dicts(*, repo: Dict[str, Any]) -> List[Dict[str, Any]]:
try:
return cast(List[Dict[str, Any]], repo["branchProtectionRules"]["nodes"])
except (KeyError, TypeError):
return []


def get_branch_protection(
*, repo: Dict[str, Any], ref_name: str
*, config_response: Dict[str, Any], ref_name: str
) -> Optional[BranchProtectionRule]:
for rule in get_branch_protection_dicts(repo=repo):
try:
branchProtectionRule = config_response["repository"]["ref"][
"branchProtectionRule"
]
try:
nodes = rule["matchingRefs"]["nodes"]
except (KeyError, TypeError):
nodes = []
for node in nodes:
if node["name"] == ref_name:
try:
return BranchProtectionRule.parse_obj(rule)
except ValueError:
logger.warning("Could not parse branch protection", exc_info=True)
return None
return None
return BranchProtectionRule.parse_obj(branchProtectionRule)
except ValueError:
logger.warning("Could not parse branch protection", exc_info=True)
return None
except (KeyError, TypeError):
return None


def get_review_requests_dicts(*, pr: Dict[str, Any]) -> List[Dict[str, Any]]:
Expand Down Expand Up @@ -793,6 +804,7 @@ class CfgInfo:
parsed: V1 | pydantic.ValidationError | toml.TomlDecodeError
text: str
file_expression: str
branch_protection: Optional[BranchProtectionRule] = None


@dataclass
Expand Down Expand Up @@ -977,6 +989,7 @@ async def get_config_for_ref(
variables=dict(
owner=self.owner,
repo=self.repo,
qualifiedBaseRef=f"refs/heads/{ref}",
rootConfigFileExpression=repo_root_config_expression,
githubConfigFileExpression=repo_github_config_expression,
orgRootConfigFileExpression=org_root_config_expression,
Expand All @@ -991,6 +1004,8 @@ async def get_config_for_ref(
self.log.error("could not fetch default branch name", res=res)
return None

branch_protection = get_branch_protection(config_response=data, ref_name=ref)

parsed_config = parse_config(data)
if parsed_config is None:
return None
Expand All @@ -1013,6 +1028,7 @@ def get_file_expression() -> str:
parsed=V1.parse_toml(parsed_config.text),
text=parsed_config.text,
file_expression=get_file_expression(),
branch_protection=branch_protection,
)

async def get_event_info(self, pr_number: int) -> Optional[EventInfoResponse]:
Expand Down Expand Up @@ -1109,9 +1125,6 @@ async def get_event_info(self, pr_number: int) -> Optional[EventInfoResponse]:
if cfg is None:
log.info("no config found")
return None
branch_protection = get_branch_protection(
repo=repository, ref_name=pr.baseRefName
)

all_reviews = get_reviews(pr=pull_request)
bot_reviews = self.get_bot_reviews(reviews=all_reviews)
Expand All @@ -1128,7 +1141,7 @@ async def get_event_info(self, pr_number: int) -> Optional[EventInfoResponse]:
is_private=repository.get("isPrivate") is True,
),
subscription=subscription,
branch_protection=branch_protection,
branch_protection=cfg.branch_protection,
review_requests=get_requested_reviews(pr=pull_request),
bot_reviews=bot_reviews,
status_contexts=get_status_contexts(pr=pull_request),
Expand Down
40 changes: 0 additions & 40 deletions bot/kodiak/test/fixtures/api/get_event/no_author.json
Original file line number Diff line number Diff line change
@@ -1,46 +1,6 @@
{
"data": {
"repository": {
"branchProtectionRules": {
"nodes": [
{
"matchingRefs": {
"nodes": [
{
"name": "master"
}
]
},
"requiresApprovingReviews": true,
"requiredApprovingReviewCount": 2,
"requiresStatusChecks": true,
"requiredStatusCheckContexts": [
"ci/circleci: backend_lint",
"ci/circleci: backend_test",
"ci/circleci: frontend_lint",
"ci/circleci: frontend_test",
"WIP (beta)"
],
"requiresStrictStatusChecks": true,
"requiresCodeOwnerReviews": false,
"requiresCommitSignatures": false,
"requiresConversationResolution": false,
"restrictsPushes": true,
"pushAllowances": {
"nodes": [
{
"actor": {}
},
{
"actor": {
"databaseId": 53453
}
}
]
}
}
]
},
"mergeCommitAllowed": false,
"rebaseMergeAllowed": false,
"squashMergeAllowed": true,
Expand Down
87 changes: 56 additions & 31 deletions bot/kodiak/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,67 @@ async def test_get_config_for_ref_dot_github(
api_client,
"send_query",
return_value=wrap_future(
dict(
data=dict(
repository=dict(
rootConfigFile=None,
githubConfigFile=dict(
text="# .github/.kodiak.toml\nversion = 1\nmerge.method = 'rebase'"
),
)
)
)
{
"data": {
"repository": {
"rootConfigFile": None,
"githubConfigFile": {
"text": "# .github/.kodiak.toml\nversion = 1\nmerge.method = 'rebase'"
},
"ref": {
"branchProtectionRule": {
"requiresApprovingReviews": True,
"requiredApprovingReviewCount": 2,
"requiresStatusChecks": True,
"requiredStatusCheckContexts": [
"ci/circleci: backend_lint",
"ci/circleci: backend_test",
"ci/circleci: frontend_lint",
"ci/circleci: frontend_test",
"WIP (beta)",
],
"requiresStrictStatusChecks": True,
"requiresCodeOwnerReviews": False,
"requiresCommitSignatures": False,
"requiresConversationResolution": False,
"restrictsPushes": True,
"pushAllowances": {
"nodes": [
{"actor": {}},
{"actor": {"databaseId": 53453}},
]
},
}
},
}
}
}
),
)

res = await api_client.get_config_for_ref(ref="main", org_repo_default_branch=None)
assert res is not None
assert isinstance(res.parsed, V1) and res.parsed.merge.method == MergeMethod.rebase
assert res.branch_protection == BranchProtectionRule(
requiresStatusChecks=True,
requiredStatusCheckContexts=[
"ci/circleci: backend_lint",
"ci/circleci: backend_test",
"ci/circleci: frontend_lint",
"ci/circleci: frontend_test",
"WIP (beta)",
],
requiresStrictStatusChecks=True,
requiresCommitSignatures=False,
requiresConversationResolution=False,
restrictsPushes=True,
pushAllowances=NodeListPushAllowance(
nodes=[
PushAllowance(actor=PushAllowanceActor(databaseId=None)),
PushAllowance(actor=PushAllowanceActor(databaseId=53453)),
]
),
)


@pytest.fixture
Expand Down Expand Up @@ -157,26 +202,6 @@ def block_event() -> EventInfoResponse:
delete_branch_on_merge=True,
is_private=True,
)
branch_protection = BranchProtectionRule(
requiresStatusChecks=True,
requiredStatusCheckContexts=[
"ci/circleci: backend_lint",
"ci/circleci: backend_test",
"ci/circleci: frontend_lint",
"ci/circleci: frontend_test",
"WIP (beta)",
],
requiresStrictStatusChecks=True,
requiresCommitSignatures=False,
requiresConversationResolution=False,
restrictsPushes=True,
pushAllowances=NodeListPushAllowance(
nodes=[
PushAllowance(actor=PushAllowanceActor(databaseId=None)),
PushAllowance(actor=PushAllowanceActor(databaseId=53453)),
]
),
)

return EventInfoResponse(
config=config,
Expand All @@ -192,7 +217,7 @@ def block_event() -> EventInfoResponse:
subscription=Subscription(
account_id="D1606A79-A1A1-4550-BA7B-C9ED0D792B1E", subscription_blocker=None
),
branch_protection=branch_protection,
branch_protection=None,
review_requests=[
PRReviewRequest(name="ghost"),
PRReviewRequest(name="ghost-team"),
Expand Down
Loading