|
| 1 | +import re |
| 2 | + |
| 3 | +from commitizen.cz.base import BaseCommitizen, ValidationResult |
| 4 | + |
| 5 | +_TITLE_ISSUE_RE = re.compile(r"^[A-Z][^\n]* \#(\d+)$") |
| 6 | + |
| 7 | + |
| 8 | +class OpenWispCommitizen(BaseCommitizen): |
| 9 | + """Commitizen plugin for OpenWISP commit conventions.""" |
| 10 | + |
| 11 | + # Single source for allowed prefixes |
| 12 | + ALLOWED_PREFIXES = [ |
| 13 | + "feature", |
| 14 | + "change", |
| 15 | + "fix", |
| 16 | + "docs", |
| 17 | + "test", |
| 18 | + "ci", |
| 19 | + "chores", |
| 20 | + "qa", |
| 21 | + "deps", |
| 22 | + "release", |
| 23 | + "bump", |
| 24 | + ] |
| 25 | + |
| 26 | + ERROR_TEMPLATE = ( |
| 27 | + "Invalid commit message format\n\n" |
| 28 | + "Expected format:\n\n" |
| 29 | + " [prefix] Capitalized title #<issue>\n\n" |
| 30 | + " <long-description>\n\n" |
| 31 | + " Fixes #<issue>\n\n" |
| 32 | + "Examples:\n\n" |
| 33 | + " [feature] Add subnet import support #104\n\n" |
| 34 | + " Add support for importing multiple subnets from a CSV file.\n\n" |
| 35 | + " Fixes #104" |
| 36 | + ) |
| 37 | + |
| 38 | + def _validate_title(self, value: str) -> bool | str: |
| 39 | + value = value.strip() |
| 40 | + if not value: |
| 41 | + return "Commit title cannot be empty." |
| 42 | + if not _TITLE_ISSUE_RE.match(value): |
| 43 | + return ( |
| 44 | + "Commit title must start with a capital letter and " |
| 45 | + "end with an issue number (e.g. #104)." |
| 46 | + ) |
| 47 | + return True |
| 48 | + |
| 49 | + def questions(self): |
| 50 | + return [ |
| 51 | + { |
| 52 | + "type": "list", |
| 53 | + "name": "change_type", |
| 54 | + "message": "Select the type of change you are committing", |
| 55 | + "choices": [ |
| 56 | + {"value": prefix, "name": f"[{prefix}]"} |
| 57 | + for prefix in self.ALLOWED_PREFIXES |
| 58 | + ], |
| 59 | + }, |
| 60 | + { |
| 61 | + "type": "input", |
| 62 | + "name": "title", |
| 63 | + "message": "Commit title (short, first letter capital)", |
| 64 | + "validate": self._validate_title, |
| 65 | + }, |
| 66 | + { |
| 67 | + "type": "input", |
| 68 | + "name": "how", |
| 69 | + "message": ("Describe what you changed and how it addresses the issue"), |
| 70 | + "validate": lambda v: ( |
| 71 | + True if v.strip() else "Commit body cannot be empty." |
| 72 | + ), |
| 73 | + }, |
| 74 | + ] |
| 75 | + |
| 76 | + def message(self, answers): |
| 77 | + prefix_value = answers["change_type"] |
| 78 | + prefix = f"[{prefix_value}]" |
| 79 | + title = answers["title"].strip() |
| 80 | + body = answers["how"].strip() |
| 81 | + # Extract issue number from title |
| 82 | + match = _TITLE_ISSUE_RE.search(title) |
| 83 | + if not match: |
| 84 | + raise ValueError( |
| 85 | + "Commit title must end with an issue reference like #<issue_number>." |
| 86 | + ) |
| 87 | + issue_number = match.group(1) |
| 88 | + return f"{prefix} {title}\n\n" f"{body}\n\n" f"Fixes #{issue_number}" |
| 89 | + |
| 90 | + def validate_commit_message( |
| 91 | + self, |
| 92 | + *, |
| 93 | + commit_msg: str, |
| 94 | + pattern: re.Pattern[str], |
| 95 | + allow_abort: bool, |
| 96 | + allowed_prefixes: list[str], |
| 97 | + max_msg_length: int | None, |
| 98 | + commit_hash: str, |
| 99 | + ) -> ValidationResult: |
| 100 | + """Validate commit message and return user-friendly errors.""" |
| 101 | + if not commit_msg: |
| 102 | + return ValidationResult( |
| 103 | + allow_abort, [] if allow_abort else ["commit message is empty"] |
| 104 | + ) |
| 105 | + # First check if it matches the pattern |
| 106 | + match_result = pattern.fullmatch(commit_msg) |
| 107 | + if not match_result: |
| 108 | + return ValidationResult(False, [self.ERROR_TEMPLATE]) |
| 109 | + # Then verify it starts with an allowed prefix or is a merge commit |
| 110 | + # Use self.ALLOWED_PREFIXES for our custom prefixes |
| 111 | + # Allow compound prefixes like [tests:fix] as long as first part is allowed |
| 112 | + if commit_msg.startswith("Merge "): |
| 113 | + pass # Merge commits are allowed |
| 114 | + elif not any( |
| 115 | + re.match(rf"\[{prefix}([!/:]|\])", commit_msg) |
| 116 | + for prefix in self.ALLOWED_PREFIXES |
| 117 | + ): |
| 118 | + return ValidationResult(False, [self.ERROR_TEMPLATE]) |
| 119 | + # Check message length limit |
| 120 | + if max_msg_length is not None and max_msg_length > 0: |
| 121 | + msg_len = len(commit_msg.partition("\n")[0].strip()) |
| 122 | + if msg_len > max_msg_length: |
| 123 | + return ValidationResult( |
| 124 | + False, |
| 125 | + [ |
| 126 | + f"commit message length exceeds the limit ({max_msg_length} chars)", |
| 127 | + ], |
| 128 | + ) |
| 129 | + return ValidationResult(True, []) |
| 130 | + |
| 131 | + def format_error_message(self, message: str) -> str: |
| 132 | + return self.ERROR_TEMPLATE |
| 133 | + |
| 134 | + def example(self) -> str: |
| 135 | + return ( |
| 136 | + "[feature] Add commit convention enforcement #110\n\n" |
| 137 | + "Introduce a Commitizen-based commit workflow to standardize\n" |
| 138 | + "commit messages across the OpenWISP project.\n\n" |
| 139 | + "Fixes #110" |
| 140 | + ) |
| 141 | + |
| 142 | + def schema(self) -> str: |
| 143 | + return "[<type>] <Title>" |
| 144 | + |
| 145 | + def schema_pattern(self) -> str: |
| 146 | + # Allow merge commits (starting with "Merge") or regular commits with prefix |
| 147 | + # Using \Z instead of $ to truly anchor to end-of-string |
| 148 | + # Split into two alternatives: merge commits and regular commits |
| 149 | + merge_pattern = r"Merge .*" |
| 150 | + # Regular commits: header with optional footer section |
| 151 | + # Footer section: blank line + optional body + "Fixes #<issue>" |
| 152 | + # Body is optional (.* allows empty) and there's no second blank line required |
| 153 | + regular_pattern = ( |
| 154 | + r"\[[a-z0-9!/:-]+\] [A-Z][^\n]*( #(?P<issue>\d+))?" |
| 155 | + r"$(\n\n(.*\n)?(?:Close|Closes|Closed|Fix|Fixes|Fixed" |
| 156 | + r"|Resolve|Resolves|Resolved|Related to) #(?P=issue)\n?)?" |
| 157 | + ) |
| 158 | + return rf"(?sm)^(?:{merge_pattern}|{regular_pattern})\Z" |
| 159 | + |
| 160 | + def info(self) -> str: |
| 161 | + prefixes_list = "\n".join(f" - {prefix}" for prefix in self.ALLOWED_PREFIXES) |
| 162 | + return ( |
| 163 | + "OpenWISP Commit Convention\n\n" |
| 164 | + "Commit messages must follow this structure:\n\n" |
| 165 | + " [type] Capitalized title #<issue_number>\n\n" |
| 166 | + " <description>\n\n" |
| 167 | + " Fixes #<issue_number>\n\n" |
| 168 | + f"Allowed commit prefixes:\n\n{prefixes_list}\n\n" |
| 169 | + "If in doubt, use chores." |
| 170 | + ) |
| 171 | + |
| 172 | + |
| 173 | +__all__ = ["OpenWispCommitizen"] |
0 commit comments