Skip to content
Open
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
34 changes: 33 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@ It operates on a per-branch basis, meaning you can have different settings for d
<li><a href="#depend_alerts">Dependabot alerts and updates</a></li>
<li><a href="#GHA_build_status">GitHub Actions build status emails</a></li>
<li><a href="#pages">GitHub Pages</a></li>
<li><a href="#pull_requests">Pull Request settings</a></li>
<li><a href="#pull_requests">Pull Request settings</a>
<ul>
<li><a href="#pr_creation_cap">Pull request creation cap</a></li>
</ul>
</li>
<li><a href="#copilot_code_review">Copilot code review</a></li>
<li><a href="#rulesets">Rulesets</a></li>
<li><a href="#merge">Merge buttons</a></li>
Expand Down Expand Up @@ -769,6 +773,7 @@ Projects can enable/disable various settings for PRs:
- allow [auto-merging](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/incorporating-changes-from-a-pull-request/automatically-merging-a-pull-request) of PRs
- allow [updating](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/keeping-your-pull-request-in-sync-with-the-base-branch) head branches of PRs
- automatically [delete](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches) head branches after merge
- cap the number of open PRs a user without write access may have at one time (see [creation cap](#pr_creation_cap) below)

Example:

Expand All @@ -783,6 +788,33 @@ github:
del_branch_on_merge: true
~~~

<h4 id="pr_creation_cap">Pull request creation cap</h4>

You can limit the number of open pull requests a user **without write access** may have open at one
time. This is GitHub's [pull request creation cap](https://github.blog/changelog/2026-06-17-limit-open-pull-requests-for-users-without-write-access/)
interaction limit, and it helps mitigate spam or automated PR floods. Users with write access are not
affected by the cap.

~~~yaml
github:
pull_requests:
creation_cap:
# turn the cap on or off
enabled: true
# maximum number of open PRs a user without write access may have (1-1000)
max_open_pull_requests: 5
~~~

Supported settings:

~~~yaml
enabled: <boolean> # required
max_open_pull_requests: <int> # optional, 1-1000; if omitted, GitHub's default is used
~~~

Set `enabled: false` to turn the cap off. Removing the `creation_cap` section also disables a cap that
was previously managed by `.asf.yaml`.

<h3 id="copilot_code_review">Copilot code review</h3>

Copilot code review can review code written in any coding language and provide feedback. It reviews your code from multiple angles to identify issues and suggest fixes, which you can apply with a couple of clicks.
Expand Down
9 changes: 9 additions & 0 deletions asfyaml/feature/github/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ class ASFGitHubFeature(ASFYamlFeature, name="github"):
strictyaml.Optional("del_branch_on_merge"): strictyaml.Bool(),
strictyaml.Optional("allow_auto_merge"): strictyaml.Bool(),
strictyaml.Optional("allow_update_branch"): strictyaml.Bool(),
# Pull request creation cap: limit the number of open pull requests a user
# without write access may have at one time.
strictyaml.Optional("creation_cap"): strictyaml.Map(
{
"enabled": strictyaml.Bool(),
strictyaml.Optional("max_open_pull_requests"): strictyaml.Int(),
}
),
}
),
# Generic repository rulesets
Expand Down Expand Up @@ -266,6 +274,7 @@ def run(self):
features,
branch_protection,
pull_requests,
pr_creation_cap,
merge_buttons,
pages,
custom_subjects,
Expand Down
79 changes: 79 additions & 0 deletions asfyaml/feature/github/pr_creation_cap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""GitHub pull request creation cap support.

Limits the number of open pull requests a user without write access may have open
at one time, via the repository interaction-limits API. See
https://github.com/community/maintainers/discussions/840 and
https://docs.github.com/rest/interactions/repos#update-pull-request-creation-cap-for-a-repository
"""

from typing import Any

from . import directive, ASFGitHubFeature

# Bounds enforced by the GitHub API for max_open_pull_requests.
MIN_OPEN_PULL_REQUESTS = 1
MAX_OPEN_PULL_REQUESTS = 1000


def _creation_cap_url(self: ASFGitHubFeature) -> str:
return f"/repos/{self.repository.org_id}/{self.repository.name}/interaction-limits/pulls/creation-cap"


@directive
def pr_creation_cap(self: ASFGitHubFeature):
pull_requests = self.yaml.get("pull_requests") or {}
creation_cap = pull_requests.get("creation_cap")

previous_yaml = self.previous_yaml if isinstance(self.previous_yaml, dict) else {}
previous_pull_requests = previous_yaml.get("pull_requests") or {}
was_previously_configured = "creation_cap" in previous_pull_requests

if creation_cap:
enabled = creation_cap.get("enabled", False)
max_open_pull_requests = creation_cap.get("max_open_pull_requests")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No default value provided here like for the above. Does anything undefined happen if we get None back here from get(), especially if we happen to get True from the line above?

elif was_previously_configured:
# The section was removed; disable the cap that .asf.yaml previously managed.
enabled = False
max_open_pull_requests = None
else:
return

if not enabled and not was_previously_configured:
return

payload: dict[str, Any] = {"enabled": enabled}
if enabled and max_open_pull_requests is not None:
if not MIN_OPEN_PULL_REQUESTS <= max_open_pull_requests <= MAX_OPEN_PULL_REQUESTS:
raise Exception(
"github.pull_requests.creation_cap.max_open_pull_requests must be between "
f"{MIN_OPEN_PULL_REQUESTS} and {MAX_OPEN_PULL_REQUESTS}, got {max_open_pull_requests}"
)
payload["max_open_pull_requests"] = max_open_pull_requests

if enabled:
if "max_open_pull_requests" in payload:
print(f"Setting pull request creation cap to enabled, max {max_open_pull_requests} open per user")
else:
print("Setting pull request creation cap to enabled")
else:
print("Disabling pull request creation cap")

if not self.noop("pr_creation_cap"):
self.ghrepo._requester.requestJson("PATCH", _creation_cap_url(self), input=payload)
227 changes: 227 additions & 0 deletions tests/github_pr_creation_cap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""Unit tests for .asf.yaml GitHub pull request creation cap feature."""

from types import SimpleNamespace
from typing import Any

import asfyaml.asfyaml
import asfyaml.dataobjects
from asfyaml.feature.github.pr_creation_cap import pr_creation_cap
from helpers import YamlTest

# Set .asf.yaml to debug mode
asfyaml.asfyaml.DEBUG = True

CAP_URL = "/repos/apache/infrastructure-asfyaml/interaction-limits/pulls/creation-cap"


valid_creation_cap = YamlTest(
None,
None,
"""
github:
pull_requests:
creation_cap:
enabled: true
max_open_pull_requests: 5
""",
)

valid_creation_cap_disabled = YamlTest(
None,
None,
"""
github:
pull_requests:
creation_cap:
enabled: false
""",
)

invalid_creation_cap_type = YamlTest(
asfyaml.asfyaml.ASFYAMLException,
"when expecting an integer",
"""
github:
pull_requests:
creation_cap:
enabled: true
max_open_pull_requests: lots
""",
)


class FakeRequester:
def __init__(self):
self.calls: list[dict[str, Any]] = []

def requestJson(self, method: str, url: str, input: dict[str, Any] | None = None): # noqa: N802
self.calls.append({"method": method, "url": url, "input": input})
return 200, {}, "{}"


class FakeFeature:
def __init__(
self,
*,
yaml: dict[str, Any],
previous_yaml: dict[str, Any],
requester: FakeRequester,
noop_enabled: bool = False,
):
self.yaml = yaml
self.previous_yaml = previous_yaml
self.repository = SimpleNamespace(org_id="apache", name="infrastructure-asfyaml")
self.ghrepo = SimpleNamespace(_requester=requester)
self._noop_enabled = noop_enabled

def noop(self, directive: str) -> bool:
if self._noop_enabled:
print(f"[github::{directive}] Not applying changes, noop mode active.")
return True
return False


def test_basic_yaml(test_repo: asfyaml.dataobjects.Repository):
print("[github] Testing pull request creation cap")

tests_to_run = (
valid_creation_cap,
valid_creation_cap_disabled,
invalid_creation_cap_type,
)

for test in tests_to_run:
with test.ctx():
a = asfyaml.asfyaml.ASFYamlInstance(
repo=test_repo, committer="humbedooh", config_data=test.yaml, branch=asfyaml.dataobjects.DEFAULT_BRANCH
)
a.environments_enabled.add("noop")
a.no_cache = True
a.run_parts()


def test_enable_creation_cap_with_max():
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"creation_cap": {"enabled": True, "max_open_pull_requests": 5}}},
previous_yaml={},
requester=requester,
)

pr_creation_cap(feature)

assert requester.calls == [
{"method": "PATCH", "url": CAP_URL, "input": {"enabled": True, "max_open_pull_requests": 5}}
]


def test_enable_creation_cap_without_max():
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"creation_cap": {"enabled": True}}},
previous_yaml={},
requester=requester,
)

pr_creation_cap(feature)

assert requester.calls == [{"method": "PATCH", "url": CAP_URL, "input": {"enabled": True}}]


def test_disable_creation_cap():
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"creation_cap": {"enabled": False}}},
previous_yaml={"pull_requests": {"creation_cap": {"enabled": True, "max_open_pull_requests": 5}}},
requester=requester,
)

pr_creation_cap(feature)

assert requester.calls == [{"method": "PATCH", "url": CAP_URL, "input": {"enabled": False}}]


def test_removed_section_disables_cap():
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"allow_auto_merge": True}},
previous_yaml={"pull_requests": {"creation_cap": {"enabled": True, "max_open_pull_requests": 5}}},
requester=requester,
)

pr_creation_cap(feature)

assert requester.calls == [{"method": "PATCH", "url": CAP_URL, "input": {"enabled": False}}]


def test_disabled_and_never_configured_is_noop():
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"creation_cap": {"enabled": False}}},
previous_yaml={},
requester=requester,
)

pr_creation_cap(feature)

assert requester.calls == []


def test_no_creation_cap_section_is_noop():
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"allow_auto_merge": True}},
previous_yaml={},
requester=requester,
)

pr_creation_cap(feature)

assert requester.calls == []


def test_out_of_range_max_raises():
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"creation_cap": {"enabled": True, "max_open_pull_requests": 5000}}},
previous_yaml={},
requester=requester,
)

with YamlTest(Exception, "must be between 1 and 1000", "").ctx():
pr_creation_cap(feature)

assert requester.calls == []


def test_noop_mode_does_not_call_api(capsys):
requester = FakeRequester()
feature = FakeFeature(
yaml={"pull_requests": {"creation_cap": {"enabled": True, "max_open_pull_requests": 5}}},
previous_yaml={},
requester=requester,
noop_enabled=True,
)

pr_creation_cap(feature)

captured = capsys.readouterr()
assert "noop mode active" in captured.out
assert requester.calls == []
Loading