diff --git a/.github/instructions/code-review.instructions.md b/.github/instructions/code-review.instructions.md index 469d7419333..f7a7e4ad7e0 100644 --- a/.github/instructions/code-review.instructions.md +++ b/.github/instructions/code-review.instructions.md @@ -10,9 +10,8 @@ applyTo: "src/**,boards/**,platforms/**,msg/**,cmake/**,Makefile,CMakeLists.txt, - Types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert` - Scope should match the primary area of changed files - Append `!` before the colon for breaking changes -- Both squash merge and rebase merge are enabled; merge commits are disabled -- Commits should be atomic and independently revertable -- WIP or review-response commits should be squashed before merge +- PRs are typically squash-merged, so the PR title becomes the commit message on `main`; merge commits are disabled +- Review feedback is addressed with new commits; do not ask for a squash or force-push during review, except to rebase onto `main` ## Core Checks (always apply) diff --git a/.github/workflows/commit_checks.yml b/.github/workflows/commit_checks.yml index fb8b813ae34..0ef67cfc5e9 100644 --- a/.github/workflows/commit_checks.yml +++ b/.github/workflows/commit_checks.yml @@ -56,51 +56,6 @@ jobs: echo "::error::PR title does not follow conventional commits format. See the PR comment for details." exit 1 - commit-messages: - name: Commit Messages - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - sparse-checkout: Tools/ci - fetch-depth: 1 - - - name: Check commit messages - id: check - env: - GH_TOKEN: ${{ github.token }} - run: | - gh api \ - "repos/${{ github.repository }}/pulls/${PR_NUMBER}/commits?per_page=100" \ - | python3 Tools/ci/check_commit_messages.py --markdown-file comment.md && rc=0 || rc=$? - echo "exit_code=$rc" >> "$GITHUB_OUTPUT" - # Check for warnings (non-empty markdown on exit 0) - if [ "$rc" -eq 0 ] && [ -s comment.md ]; then - echo "has_warnings=true" >> "$GITHUB_OUTPUT" - else - echo "has_warnings=false" >> "$GITHUB_OUTPUT" - fi - - - name: Post or clear comment - if: env.IS_FORK == 'false' - env: - GH_TOKEN: ${{ github.token }} - run: | - if [ "${{ steps.check.outputs.exit_code }}" != "0" ]; then - python3 Tools/ci/pr_comment.py --marker commit-msgs --pr "$PR_NUMBER" --result fail < comment.md - elif [ "${{ steps.check.outputs.has_warnings }}" == "true" ]; then - python3 Tools/ci/pr_comment.py --marker commit-msgs --pr "$PR_NUMBER" --result warn < comment.md - else - python3 Tools/ci/pr_comment.py --marker commit-msgs --pr "$PR_NUMBER" --result pass - fi - - - name: Result - if: steps.check.outputs.exit_code != '0' - run: | - echo "::error::Commit message errors found. See the PR comment for details." - exit 1 - pr-body: name: PR Description runs-on: ubuntu-latest diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8a385674a7c..b429c5340fd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -106,42 +106,22 @@ feat(boards/px4_fmu-v6x)!: remove deprecated driver API perf(mc_rate_control): reduce loop latency ``` -### Commits to avoid - -These will be flagged by CI and should be squashed or reworded before merging: - -``` -fix # too vague, no type or scope -update # too vague, no type or scope -ekf2: fix something # missing type prefix -apply suggestions from code review # squash into parent commit -do make format # squash into parent commit -WIP: trying something # not ready for main -oops # not descriptive -``` - ### PR titles -The PR title follows the same `type(scope): description` format. This is enforced by CI and is especially important because the PR title becomes the commit message when a PR is squash-merged. +The PR title follows the same `type(scope): description` format. This is enforced by CI. ### Merge policy -Commits should be atomic and independently revertable. Squash at reviewer discretion for obvious cases (multiple WIP commits, messy review-response history). When your commits are clean and logical, they will be preserved as individual commits on `main`. +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. -### Cleaning up commits +### Updating a PR under review -If CI flags your commit messages, you can fix them with an interactive rebase: +Once review has begun, address feedback by adding new commits. Do not amend, squash or otherwise rewrite commits that are already pushed: a force-push erases the history a reviewer has read, and they can no longer see what changed since their last review. + +Rebasing onto `main` is the exception, because it cannot be pushed without force. Rebase only when the PR needs it (merge conflicts, or a change on `main` it depends on), and keep the existing commits where possible rather than squashing them: ```bash -# Squash all commits into one: -git rebase -i HEAD~N # replace N with the number of commits -# mark all commits except the first as 'squash' or 'fixup' -# reword the remaining commit to follow the format -git push --force-with-lease - -# Or reword specific commits: -git rebase -i HEAD~N -# mark the bad commits as 'reword' +git rebase main git push --force-with-lease ``` diff --git a/Tools/ci/check_commit_messages.py b/Tools/ci/check_commit_messages.py deleted file mode 100755 index 5359f737cb9..00000000000 --- a/Tools/ci/check_commit_messages.py +++ /dev/null @@ -1,331 +0,0 @@ -#!/usr/bin/env python3 -"""Validate commit messages in a PR against conventional commits format. - -Reads a JSON array of GitHub commit objects from stdin (as returned by the -GitHub API's /pulls/{n}/commits endpoint) and checks each message for -blocking errors and advisory warnings. - -With --markdown, outputs a formatted PR comment body instead of plain text. -""" - -import json -import sys - -from conventional_commits import ( - EXEMPT_PREFIXES, - parse_header, -) - -# Blocking: prefixes that indicate unsquashed fixup commits -FIXUP_PREFIXES = ('fixup!', 'squash!', 'amend!') - -# Blocking: single-word throwaway messages (case-insensitive exact match) -THROWAWAY_WORDS = frozenset({ - 'fix', 'fixed', 'fixes', - 'update', 'updated', 'updates', - 'test', 'tests', 'testing', - 'tmp', 'temp', - 'oops', 'wip', - 'debug', 'cleanup', -}) - -# Blocking: debug session leftovers -DEBUG_KEYWORDS = ('tmate',) - -# Warning: review-response messages (case-insensitive substring match) -REVIEW_RESPONSE_PATTERNS = ( - 'address review', - 'apply suggestions from code review', - 'code review', -) - -# Warning: formatter-only commits -FORMATTER_PATTERNS = ( - 'do make format', - 'make format', - 'run formatter', - 'apply format', -) - -MIN_MESSAGE_LENGTH = 5 - - -def check_commit(message: str) -> tuple[list[str], list[str]]: - """Return (errors, warnings) for a single commit message.""" - errors: list[str] = [] - warnings: list[str] = [] - - first_line = message.split('\n', 1)[0].strip() - lower = first_line.lower() - - # --- Blocking checks --- - - for prefix in FIXUP_PREFIXES: - if lower.startswith(prefix): - errors.append(f'Unsquashed commit: starts with "{prefix}"') - - if lower == 'wip' or lower.startswith('wip ') or lower.startswith('wip:'): - errors.append('WIP commit should not be merged') - - if len(first_line) < MIN_MESSAGE_LENGTH: - errors.append(f'Message too short ({len(first_line)} chars, minimum {MIN_MESSAGE_LENGTH})') - - if first_line.strip() and first_line.strip().lower() in THROWAWAY_WORDS: - errors.append(f'Single-word throwaway message: "{first_line.strip()}"') - - for kw in DEBUG_KEYWORDS: - if kw in lower: - errors.append(f'Debug session leftover: contains "{kw}"') - - # --- Warning checks --- - - for pattern in REVIEW_RESPONSE_PATTERNS: - if pattern in lower: - warnings.append('Review-response commit') - break - - for pattern in FORMATTER_PATTERNS: - if pattern in lower: - warnings.append('Formatter-only commit') - break - - if not parse_header(first_line): - # Exempt merge commits - for prefix in EXEMPT_PREFIXES: - if first_line.startswith(prefix): - break - else: - warnings.append( - 'Missing conventional commit format ' - '(e.g. "feat(ekf2): add something")' - ) - - return errors, warnings - - -def suggest_commit(message: str) -> str | None: - """Suggest how to fix a bad commit message.""" - first_line = message.split('\n', 1)[0].strip() - lower = first_line.lower() - - for prefix in FIXUP_PREFIXES: - if lower.startswith(prefix): - return 'Squash this into the commit it fixes' - - if lower == 'wip' or lower.startswith('wip ') or lower.startswith('wip:'): - return 'Reword with a descriptive message (e.g. "feat(scope): what changed")' - - if len(first_line) < MIN_MESSAGE_LENGTH: - return 'Reword with a descriptive message (e.g. "feat(ekf2): what changed")' - - if first_line.strip().lower() in THROWAWAY_WORDS: - return 'Reword with a descriptive message (e.g. "fix(scope): what changed")' - - return None - - -def format_plain(data: list) -> tuple[bool, bool]: - """Print plain text output. Returns (has_blocking, has_warnings).""" - has_blocking = False - has_warnings = False - - for commit in data: - sha = commit.get('sha', '?')[:10] - message = commit.get('commit', {}).get('message', '') - first_line = message.split('\n', 1)[0].strip() - - errors, warnings = check_commit(message) - - if errors or warnings: - print(f"\n {sha} {first_line}") - - for err in errors: - print(f" ERROR: {err}") - has_blocking = True - - for warn in warnings: - print(f" WARNING: {warn}") - has_warnings = True - - if has_blocking: - print( - "\n" - "ERROR = must fix before merging (CI will block the PR)\n" - "WARNING = advisory, not blocking, but recommended to fix\n" - "\n" - "See the contributing guide for details:\n" - " https://github.com/PX4/PX4-Autopilot/blob/main/CONTRIBUTING.md#commit-message-convention\n", - ) - - elif has_warnings: - print( - "\n" - "WARNING = advisory, not blocking, but recommended to fix\n" - "\n" - "See the contributing guide for details:\n" - " https://github.com/PX4/PX4-Autopilot/blob/main/CONTRIBUTING.md#commit-message-convention\n", - ) - - return has_blocking, has_warnings - - -def format_markdown_blocking(data: list) -> str: - """Format a blocking error markdown comment.""" - error_groups: dict[str, list[str]] = {} - unique_commits: list[tuple[str, str, list[str], str]] = [] - - for commit in data: - sha = commit.get('sha', '?')[:10] - message = commit.get('commit', {}).get('message', '') - first_line = message.split('\n', 1)[0].strip() - - errors, _ = check_commit(message) - if not errors: - continue - - suggestion = suggest_commit(message) or '' - unique_commits.append((sha, first_line, errors, suggestion)) - - for err in errors: - error_groups.setdefault(err, []).append(sha) - - lines = [ - "## \u274c Commit messages need attention before merging", - "", - ] - - has_large_group = any(len(shas) > 3 for shas in error_groups.values()) - - if has_large_group: - lines.extend([ - "**Issues found:**", - "", - ]) - for err_msg, shas in error_groups.items(): - if len(shas) > 3: - lines.append(f"- **{len(shas)} commits**: {err_msg} " - f"(`{shas[0]}`, `{shas[1]}`, ... `{shas[-1]}`)") - else: - sha_list = ', '.join(f'`{s}`' for s in shas) - lines.append(f"- {err_msg}: {sha_list}") - - distinct_messages = {msg for _, msg, _, _ in unique_commits} - if len(distinct_messages) <= 5: - lines.extend(["", "**Affected commits:**", ""]) - for sha, msg, errors, suggestion in unique_commits: - safe_msg = msg.replace('|', '\\|') - lines.append(f"- `{sha}` {safe_msg}") - else: - lines.extend([ - "| Commit | Message | Issue | Suggested fix |", - "|--------|---------|-------|---------------|", - ]) - for sha, msg, errors, suggestion in unique_commits: - issues = '; '.join(errors) - safe_msg = msg.replace('|', '\\|') - lines.append(f"| `{sha}` | {safe_msg} | {issues} | {suggestion} |") - - lines.extend([ - "", - "See [CONTRIBUTING.md](https://github.com/PX4/PX4-Autopilot/blob/main/CONTRIBUTING.md#commit-message-convention) " - "for how to clean up commits.", - "", - "---", - "*This comment will be automatically removed once the issues are resolved.*", - ]) - - return '\n'.join(lines) - - -def format_markdown_advisory(data: list) -> str: - """Format an advisory warning markdown comment.""" - lines = [ - "## \U0001f4a1 Commit messages could be improved", - "", - "Not blocking, but these commit messages could use some cleanup.", - "", - "| Commit | Message | Suggestion |", - "|--------|---------|------------|", - ] - - for commit in data: - sha = commit.get('sha', '?')[:10] - message = commit.get('commit', {}).get('message', '') - first_line = message.split('\n', 1)[0].strip() - - _, warnings = check_commit(message) - if not warnings: - continue - - suggestion = '; '.join(warnings) - safe_msg = first_line.replace('|', '\\|') - lines.append(f"| `{sha}` | {safe_msg} | {suggestion} |") - - lines.extend([ - "", - "See the [commit message convention](https://github.com/PX4/PX4-Autopilot/blob/main/CONTRIBUTING.md#commit-message-convention) " - "for details.", - "", - "---", - "*This comment will be automatically removed once the issues are resolved.*", - ]) - - return '\n'.join(lines) - - -def main() -> None: - markdown_stdout = '--markdown' in sys.argv - markdown_file = None - for i, a in enumerate(sys.argv): - if a == '--markdown-file' and i + 1 < len(sys.argv): - markdown_file = sys.argv[i + 1] - elif a.startswith('--markdown-file='): - markdown_file = a.split('=', 1)[1] - - try: - data = json.load(sys.stdin) - except json.JSONDecodeError as exc: - print(f"Failed to parse JSON input: {exc}", file=sys.stderr) - sys.exit(2) - - if not isinstance(data, list): - print("Expected a JSON array of commit objects.", file=sys.stderr) - sys.exit(2) - - # Always compute blocking/warning state - has_blocking = False - has_warnings = False - for commit in data: - message = commit.get('commit', {}).get('message', '') - errors, warnings = check_commit(message) - if errors: - has_blocking = True - if warnings: - has_warnings = True - - # Generate markdown if needed - md = None - if has_blocking: - md = format_markdown_blocking(data) - elif has_warnings: - md = format_markdown_advisory(data) - - if md: - if markdown_stdout: - print(md) - if markdown_file: - with open(markdown_file, 'w') as f: - f.write(md + '\n') - elif markdown_file: - with open(markdown_file, 'w') as f: - pass - - # Plain text output to stderr for CI logs (always, unless --markdown only) - if not markdown_stdout: - has_blocking, _ = format_plain(data) - - sys.exit(1 if has_blocking else 0) - - -if __name__ == '__main__': - main() diff --git a/Tools/ci/pr_comment.py b/Tools/ci/pr_comment.py index 6306b13ef4c..2d461fc33f7 100755 --- a/Tools/ci/pr_comment.py +++ b/Tools/ci/pr_comment.py @@ -55,7 +55,7 @@ def find_comment(repo: str, pr: int, marker: str) -> str | None: def main() -> None: parser = argparse.ArgumentParser(description='Manage PR quality comments') parser.add_argument('--marker', required=True, - help='Marker name (e.g. pr-title, commit-msgs, pr-body)') + help='Marker name (e.g. pr-title, pr-body)') parser.add_argument('--pr', required=True, type=int, help='Pull request number') parser.add_argument('--result', required=True, choices=['pass', 'fail', 'warn'], diff --git a/docs/en/contribute/git_examples.md b/docs/en/contribute/git_examples.md index 4964d5e4f9a..52aadfd8000 100644 --- a/docs/en/contribute/git_examples.md +++ b/docs/en/contribute/git_examples.md @@ -273,7 +273,13 @@ git checkout ### Force push to forked repository -After having done the first PR, people from the PX4 community will review your changes. In most cases this means that you have to fix your local branch according to the review. After changing the files locally, the feature branch needs to be rebased again with the most recent upstream/main. However, after the rebase, it is no longer possible to push the feature branch to your forked repository directly, but instead you need to use a force push: +After you open a PR, people from the PX4 community will review your changes. +In most cases this means that you have to fix your local branch according to the review. +Add the fixes as new commits and push them normally. +Do not amend or squash commits that are already pushed: a force push erases the history a reviewer has read, and they can no longer see what changed since their last review. + +A force push is only needed after the feature branch has been rebased on the most recent upstream/main, for example to resolve merge conflicts. +Keep the existing commits when rebasing, where possible: ```sh git push --force-with-lease origin