diff --git a/.github/workflows/commit_checks.yml b/.github/workflows/commit_checks.yml index 59fd1f81776..e7e44555610 100644 --- a/.github/workflows/commit_checks.yml +++ b/.github/workflows/commit_checks.yml @@ -32,8 +32,9 @@ jobs: id: check env: PR_TITLE: ${{ github.event.pull_request.title }} + BASE_REF: ${{ github.event.pull_request.base.ref }} run: | - python3 Tools/ci/check_pr_title.py "$PR_TITLE" --markdown-file comment.md && rc=0 || rc=$? + python3 Tools/ci/check_pr_title.py "$PR_TITLE" --base-ref "$BASE_REF" --markdown-file comment.md && rc=0 || rc=$? echo "exit_code=$rc" >> "$GITHUB_OUTPUT" - name: Post or clear comment @@ -57,7 +58,7 @@ jobs: # Output the entire content of the comment on the job log as a substitute for the comment. tee -a "$GITHUB_STEP_SUMMARY" < comment.md else - echo "::error::PR title does not follow conventional commits format. See the PR comment for details." + echo "::error::PR title check failed. See the PR comment for details." fi exit 1 diff --git a/.github/workflows/python_checks.yml b/.github/workflows/python_checks.yml index d1b52837790..5091d9bebb2 100644 --- a/.github/workflows/python_checks.yml +++ b/.github/workflows/python_checks.yml @@ -54,6 +54,10 @@ jobs: python3 -m unittest discover -s ai_review -t . -v python3 -m unittest -v test_pr_review_poster + - name: Test PR title check + working-directory: Tools/ci + run: python3 -m unittest -v test_check_pr_title + - name: Check ROS workspace tooling run: | flake8 Tools/ros2/*.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b429c5340fd..46138801558 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -110,6 +110,14 @@ perf(mc_rate_control): reduce loop latency The PR title follows the same `type(scope): description` format. This is enforced by CI. +A PR that backports a change to a release branch can put a backport tag in front of it: + +``` +[BACKPORT 1.18] fix(mavlink): correct BATTERY_STATUS_V2 parsing +``` + +CI accepts the tag only on PRs that target a `release/*` branch. + ### Merge policy PRs are typically squash-merged, so the PR title becomes the commit message on `main` and the individual commits on the branch are discarded. Write them well anyway: reviewers read them to follow how the PR evolved. diff --git a/Tools/ci/check_pr_title.py b/Tools/ci/check_pr_title.py index 4d500e66bf4..2d1d2cd8f6f 100755 --- a/Tools/ci/check_pr_title.py +++ b/Tools/ci/check_pr_title.py @@ -13,14 +13,33 @@ from conventional_commits import ( CONVENTIONAL_TYPES, EXEMPT_PREFIXES, parse_header, + split_backport_tag, suggest_scope, suggest_type, ) +RELEASE_BRANCH_PREFIX = 'release/' + + +def misplaced_backport(title: str, base_ref: str | None) -> str | None: + """Explain a backport tag on a PR that does not target a release branch. + + Returns None when the title has no tag, the base is a release branch, or + the base is not known. + """ + tag, _ = split_backport_tag(title) + if not tag or not base_ref or base_ref.startswith(RELEASE_BRANCH_PREFIX): + return None + return (f"The title is tagged `{tag}`, but this PR targets `{base_ref}`. " + f"Backports go to a `{RELEASE_BRANCH_PREFIX}*` branch.") + def suggest_title(title: str) -> str | None: """Try to suggest a corrected title in conventional commits format.""" - stripped = title.strip() + tag, stripped = split_backport_tag(title) + if tag: + suggestion = suggest_title(stripped) + return f"{tag} {suggestion}" if suggestion else None # Remove common bracket prefixes like [docs], [CI], etc. bracket_match = re.match(r'^\[([^\]]+)\]\s*(.+)', stripped) @@ -56,7 +75,7 @@ def suggest_title(title: str) -> str | None: return None -def check_title(title: str) -> bool: +def check_title(title: str, base_ref: str | None = None) -> bool: title = title.strip() if not title: @@ -68,7 +87,10 @@ def check_title(title: str) -> bool: return True if parse_header(title): - return True + misplaced = misplaced_backport(title, base_ref) + if misplaced: + print(misplaced, file=sys.stderr) + return not misplaced types_str = ', '.join(f'`{t}`' for t in CONVENTIONAL_TYPES.keys()) print( @@ -98,8 +120,25 @@ def check_title(title: str) -> bool: return False -def format_markdown(title: str) -> str: +def format_markdown(title: str, base_ref: str | None = None) -> str: """Format a markdown PR comment body for a bad title.""" + misplaced = misplaced_backport(title, base_ref) if parse_header(title) else None + if misplaced: + return '\n'.join([ + "## \u274c Backport PR does not target a release branch", + "", + misplaced, + "", + "**To fix this:** click the ✏️ next to the PR title and change the " + "base branch, or remove the tag from the title.", + "", + "See [CONTRIBUTING.md](https://github.com/PX4/PX4-Autopilot/blob/main/CONTRIBUTING.md#pr-titles) " + "for details.", + "", + "---", + "*This comment will be automatically removed once the issue is resolved.*", + ]) + lines = [ "## \u274c PR title needs conventional commit format", "", @@ -137,16 +176,19 @@ def main() -> None: import argparse parser = argparse.ArgumentParser(description='Check PR title format') parser.add_argument('title', help='The PR title to validate') + parser.add_argument('--base-ref', metavar='BRANCH', + help='Branch the PR targets; a backport tag is only ' + f'accepted on {RELEASE_BRANCH_PREFIX}* branches') parser.add_argument('--markdown', action='store_true', help='Output markdown to stdout on failure') parser.add_argument('--markdown-file', metavar='FILE', help='Write markdown to FILE on failure') args = parser.parse_args() - passed = check_title(args.title) + passed = check_title(args.title, args.base_ref) if not passed: - md = format_markdown(args.title) + md = format_markdown(args.title, args.base_ref) if args.markdown: print(md) if args.markdown_file: diff --git a/Tools/ci/conventional_commits.py b/Tools/ci/conventional_commits.py index 31a18e0580d..37531af64fb 100644 --- a/Tools/ci/conventional_commits.py +++ b/Tools/ci/conventional_commits.py @@ -34,6 +34,10 @@ HEADER_PATTERN = re.compile( EXEMPT_PREFIXES = ('Merge ',) +# Tag a backport PR puts in front of the header, with or without the release: +# "[BACKPORT 1.18] fix(ekf2): ...", "[backport] fix(ekf2): ..." +BACKPORT_TAG = re.compile(r'^(\[backport(?:\s+v?\d+(?:\.\d+)+)?\])\s*', re.IGNORECASE) + # Common PX4 subsystem scopes for suggestions KNOWN_SCOPES = [ 'ekf2', 'mavlink', 'commander', 'navigator', 'sensors', @@ -110,13 +114,26 @@ VERB_TYPE_MAP = [ ] +def split_backport_tag(text: str) -> tuple[str, str]: + """Split a title into its leading backport tag and the header after it. + + The tag is '' when the title has none. + """ + text = text.strip() + m = BACKPORT_TAG.match(text) + if not m: + return '', text + return m.group(1), text[m.end():] + + def parse_header(text: str) -> dict | None: """Parse a conventional commit header into components. - Returns dict with keys {type, scope, breaking, subject} or None if - the text doesn't match conventional commits format. + A leading backport tag is skipped. Returns dict with keys + {type, scope, breaking, subject} or None if the text doesn't match + conventional commits format. """ - text = text.strip() + _, text = split_backport_tag(text) m = HEADER_PATTERN.match(text) if not m: return None diff --git a/Tools/ci/test_check_pr_title.py b/Tools/ci/test_check_pr_title.py new file mode 100644 index 00000000000..84e7568c13c --- /dev/null +++ b/Tools/ci/test_check_pr_title.py @@ -0,0 +1,51 @@ +"""Exercise the PR title check on backport titles.""" + +import contextlib +import io +import unittest + +from check_pr_title import check_title, format_markdown, suggest_title + + +def passes(title, base_ref=None): + with contextlib.redirect_stderr(io.StringIO()): + return check_title(title, base_ref) + + +class BackportTitleTest(unittest.TestCase): + def test_backport_tag_in_front_of_a_valid_header_passes(self): + for title in ( + 'fix(mavlink): let a UDP client reconnect from a new port', + '[BACKPORT 1.18] fix(mavlink): let a UDP client reconnect from a new port', + '[BACKPORT v1.18] feat(boards/ark_fpv)!: add the LSM6DSV32X revision', + '[Backport 1.17] docs(docs): dynamically fetched navbar', + '[BACKPORT] fix(boards/matek-h743): correct board ID', + ): + with self.subTest(title=title): + self.assertTrue(passes(title)) + + def test_backport_tag_does_not_exempt_the_header(self): + for title in ( + '[BACKPORT 1.18] Fix the UDP client reconnect', + '[BACKPORT 1.18] mavlink: let a UDP client reconnect', + '[BACKPORT 1.18]', + '[Docs] fix(mavlink): let a UDP client reconnect from a new port', + ): + with self.subTest(title=title): + self.assertFalse(passes(title)) + + def test_backport_tag_needs_a_release_base_branch(self): + title = '[BACKPORT 1.18] fix(mavlink): let a UDP client reconnect from a new port' + self.assertTrue(passes(title, 'release/1.18')) + self.assertFalse(passes(title, 'main')) + self.assertIn('targets `main`', format_markdown(title, 'main')) + self.assertTrue(passes('fix(mavlink): let a UDP client reconnect from a new port', 'main')) + + def test_suggestion_keeps_the_backport_tag(self): + self.assertEqual( + suggest_title('[BACKPORT 1.18] mavlink: let a UDP client reconnect'), + '[BACKPORT 1.18] feat(mavlink): let a UDP client reconnect') + + +if __name__ == '__main__': + unittest.main()