From 02da2f2d369bcfdcf543902d00e29e7bf5bc599e Mon Sep 17 00:00:00 2001 From: Philipp Schuster Date: Thu, 13 Nov 2025 13:24:03 +0100 Subject: [PATCH] misc: gitlint: python code improvements Signed-off-by: Philipp Schuster On-behalf-of: SAP philipp.schuster@sap.com --- scripts/gitlint/rules/BodyMaxLineLengthEx.py | 59 ++++++++++++-------- 1 file changed, 35 insertions(+), 24 deletions(-) diff --git a/scripts/gitlint/rules/BodyMaxLineLengthEx.py b/scripts/gitlint/rules/BodyMaxLineLengthEx.py index 34b213e5b..60b555d83 100644 --- a/scripts/gitlint/rules/BodyMaxLineLengthEx.py +++ b/scripts/gitlint/rules/BodyMaxLineLengthEx.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 from gitlint.rules import LineRule, RuleViolation, CommitMessageBody +from typing import List, Optional import re @@ -29,9 +30,23 @@ IGNORE_PREFIXES = [ "\t", ] +# Pattern allowing: +# - [0]: https://example.com +# - [0] https://example.com +# - https://example.com +LINK_REGEX = re.compile(r"^(([\[0-9]+]:?\s?)?https?://).*$") + +MAX_LEN = 72 + class BodyMaxLineLengthEx(LineRule): - """A rule to enforce a line limit of 72 characters, except for valid cases.""" + """ + A rule to enforce a line limit of 72 characters, except for valid cases: + + - Markdown-style code blocks + - Commit tags, such as Signed-off-by + - Links + """ # A rule MUST have a human friendly name name = "body-max-line-length-ex" @@ -43,38 +58,34 @@ class BodyMaxLineLengthEx(LineRule): # A line-rule MUST have a target (not required for CommitRules). target = CommitMessageBody - max_len = 72 - # Updated property as the commit messages is validated line by line. inside_open_codeblock = False - def validate(self, line, commit): - # Pattern allowing: - # - [0]: https://foobar - # - [0] https://foobar - # - https://foobar - link_regex = re.compile(r"^((\[[0-9]+\]:?\s?)?https?:\/\/).*$") - + def validate(self, line, commit) -> Optional[List[RuleViolation]]: + # We keep track of whether we are in an open code block. is_codeblock_marker = line.startswith("```") - inside_open_codeblock_ = self.inside_open_codeblock if is_codeblock_marker: self.inside_open_codeblock = not self.inside_open_codeblock - if len(line) > self.max_len: - is_link = link_regex.match(line) + # Begin checks + if len(line) <= MAX_LEN: + return None - if inside_open_codeblock_: - return + if inside_open_codeblock_: + return None - if is_link: - return + if None is not LINK_REGEX.match(line): + return None - # Don't check lines with allowed prefixes - for prefix in IGNORE_PREFIXES: - if line.startswith(prefix): - return None + # Don't check lines with allowed prefixes + for prefix in IGNORE_PREFIXES: + if line.startswith(prefix): + return None - return [ - RuleViolation(self.id, f"Line '{line}' exceeds limit of {self.max_len}") - ] + return [ + RuleViolation( + self.id, + f"Line '{line}' exceeds limit of {MAX_LEN}: {len(line)}", + ) + ]