diff --git a/README.md b/README.md index 04e31a8..22ae93b 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,11 @@ It operates on a per-branch basis, meaning you can have different settings for d
  • Dependabot alerts and updates
  • GitHub Actions build status emails
  • GitHub Pages
  • -
  • Pull Request settings
  • +
  • Pull Request settings + +
  • Copilot code review
  • Rulesets
  • Merge buttons
  • @@ -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: @@ -783,6 +788,33 @@ github: del_branch_on_merge: true ~~~ +

    Pull request creation cap

    + +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: # required +max_open_pull_requests: # 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`. +

    Copilot code review

    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. diff --git a/asfyaml/feature/github/__init__.py b/asfyaml/feature/github/__init__.py index a00bde8..79ec019 100644 --- a/asfyaml/feature/github/__init__.py +++ b/asfyaml/feature/github/__init__.py @@ -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 @@ -266,6 +274,7 @@ def run(self): features, branch_protection, pull_requests, + pr_creation_cap, merge_buttons, pages, custom_subjects, diff --git a/asfyaml/feature/github/pr_creation_cap.py b/asfyaml/feature/github/pr_creation_cap.py new file mode 100644 index 0000000..cc89dad --- /dev/null +++ b/asfyaml/feature/github/pr_creation_cap.py @@ -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") + 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) diff --git a/tests/github_pr_creation_cap.py b/tests/github_pr_creation_cap.py new file mode 100644 index 0000000..42f2982 --- /dev/null +++ b/tests/github_pr_creation_cap.py @@ -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 == []