Skip to contentSkip to conversation

patchtest: some refactor and simplification

PATCH In review Trevor Gamblin 3 participants 12 messages Sep 24, 2024 – Oct 1, 2024

lore
Share & tools
lore
#0 lore raw

cover patchtest: some refactor and simplification

Another smaller patch set for cleaning up the patchtest code. There are no major functional differences here, but a lot of code has been moved around, and some unused stuff was removed entirely. This also includes a reformat of all the relevant patchtest components with black for readability.

Trevor Gamblin (6):
patchtest: patterns: add module, refactor
patchtest: mbox.py: new data implementation
patchtest: test_mbox: change ismerged -> canbemerged
patchtest: simplify, rename modules scripts/patchtest: split out result messages
patchtest: use black to format libraries

 meta/lib/patchtest/data.py                    |  86 -------
 meta/lib/patchtest/mbox.py                    | 112 ++++++++
 meta/lib/patchtest/patch.py                   |  43 ----
 meta/lib/patchtest/patchtest_parser.py        | 102 ++++++++
 meta/lib/patchtest/patchtest_patterns.py      | 122 +++++++++
 meta/lib/patchtest/repo.py                    |  81 ++----
 meta/lib/patchtest/selftest/selftest          |  92 +++++--
 meta/lib/patchtest/tests/base.py              | 141 +++++-----
 meta/lib/patchtest/tests/pyparsing/common.py  |  26 --
 .../tests/pyparsing/parse_cve_tags.py         |  18 --
 .../tests/pyparsing/parse_shortlog.py         |  14 -
 .../tests/pyparsing/parse_signed_off_by.py    |  22 --
 .../tests/pyparsing/parse_upstream_status.py  |  24 --
 meta/lib/patchtest/tests/test_mbox.py         | 241 ++++++++++++------
 meta/lib/patchtest/tests/test_metadata.py     | 191 ++++++++------
 meta/lib/patchtest/tests/test_patch.py        | 135 ++++++----
 .../lib/patchtest/tests/test_python_pylint.py |  47 ++--
 meta/lib/patchtest/utils.py                   |  61 -----
 scripts/patchtest                             | 185 +++++++++-----
 scripts/patchtest-get-branch                  |  54 ++--
 scripts/patchtest-send-results                |  66 +++--
 21 files changed, 1108 insertions(+), 755 deletions(-)
 delete mode 100644 meta/lib/patchtest/data.py
 create mode 100644 meta/lib/patchtest/mbox.py
 delete mode 100644 meta/lib/patchtest/patch.py
 create mode 100644 meta/lib/patchtest/patchtest_parser.py
 create mode 100644 meta/lib/patchtest/patchtest_patterns.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/common.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_cve_tags.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_shortlog.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_signed_off_by.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_upstream_status.py
 delete mode 100644 meta/lib/patchtest/utils.py
Signature · 1 line
2.39.5
#1 lore raw

PATCH 1/6 patchtest: patterns: add module, refactor

Currently, patchtest has a lot of spread-out definitions for patterns used in various setup and test functions. Organize these by putting them all into a new patterns.py module. This allows the tests/pyparsing directory to be removed, as it is now redundant. Also remove some definitions where they were duplicated or unused, and perform some renames to improve readability and avoid collisions. Many of these variables are composed from others, so the file is only partially sorted.

---
 meta/lib/patchtest/patterns.py                | 92 +++++++++++++++++++
 meta/lib/patchtest/tests/pyparsing/common.py  | 26 ------
 .../tests/pyparsing/parse_cve_tags.py         | 18 ----
 .../tests/pyparsing/parse_shortlog.py         | 14 ---
 .../tests/pyparsing/parse_signed_off_by.py    | 22 -----
 .../tests/pyparsing/parse_upstream_status.py  | 24 -----
 meta/lib/patchtest/tests/test_mbox.py         | 36 +++-----
 meta/lib/patchtest/tests/test_metadata.py     | 56 ++++-------
 meta/lib/patchtest/tests/test_patch.py        | 31 +++----
 .../lib/patchtest/tests/test_python_pylint.py |  1 +
 10 files changed, 137 insertions(+), 183 deletions(-)
 create mode 100644 meta/lib/patchtest/patterns.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/common.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_cve_tags.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_shortlog.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_signed_off_by.py
 delete mode 100644 meta/lib/patchtest/tests/pyparsing/parse_upstream_status.py
meta/lib/patchtest/patterns.py new file +92 -0
new file mode 100644
index 00000000000..ba97a4ffe9f
@@ -0,0 +1,92 @@
+# common pyparsing variables
+#
+# Copyright (C) 2016 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+import pyparsing
+
+# general
+colon = pyparsing.Literal(":")
+line_start = pyparsing.LineStart()
+line_end = pyparsing.LineEnd()
+at = pyparsing.Literal("@")
+lessthan = pyparsing.Literal("<")
+greaterthan = pyparsing.Literal(">")
+opensquare = pyparsing.Literal("[")
+closesquare = pyparsing.Literal("]")
+inappropriate = pyparsing.CaselessLiteral("Inappropriate")
+submitted = pyparsing.CaselessLiteral("Submitted")
+
+# word related
+nestexpr = pyparsing.nestedExpr(opener='[', closer=']')
+inappropriateinfo = pyparsing.Literal("Inappropriate") + nestexpr
+submittedinfo = pyparsing.Literal("Submitted") + nestexpr
+word = pyparsing.Word(pyparsing.alphas)
+worddot = pyparsing.Word(pyparsing.alphas+".")
+
+# metadata
+
+metadata_lic = 'LICENSE'
+invalid_license = 'PATCHTESTINVALID'
+metadata_chksum = 'LIC_FILES_CHKSUM'
+license_var  = 'LICENSE'
+closed   = 'CLOSED'
+lictag_re  = pyparsing.AtLineStart("License-Update:")
+lic_chksum_added = pyparsing.AtLineStart("+" + metadata_chksum)
+lic_chksum_removed = pyparsing.AtLineStart("-" + metadata_chksum)
+add_mark = pyparsing.Regex('\\+ ')
+patch_max_line_length = 200
+metadata_src_uri  = 'SRC_URI'
+metadata_summary = 'SUMMARY'
+cve_check_ignore_var = 'CVE_CHECK_IGNORE'
+cve_status_var = 'CVE_STATUS'
+
+# mbox
+auh_email = '[email protected]'
+
+invalid_submitters = [pyparsing.Regex("^Upgrade Helper.+"),
+            pyparsing.Regex(auh_email),
+            pyparsing.Regex("uh@not\.set"),
+            pyparsing.Regex("\S+@example\.com")]
+
+mbox_bugzilla = pyparsing.Regex('\[\s?YOCTO.*\]')
+mbox_bugzilla_validation = pyparsing.Regex('\[(\s?YOCTO\s?#\s?(\d+)\s?,?)+\]')
+mbox_revert_shortlog_regex = pyparsing.Regex('Revert\s+".*"')
+mbox_shortlog_maxlength = 90
+
+# patch
+
+cve = pyparsing.Regex("CVE\-\d{4}\-\d+")
+cve_payload_tag = pyparsing.Regex("\+CVE:(\s+CVE\-\d{4}\-\d+)+")
+upstream_status_regex = pyparsing.AtLineStart("+" + "Upstream-Status")
+
+# shortlog
+
+shortlog_target = pyparsing.OneOrMore(pyparsing.Word(pyparsing.printables.replace(':','')))
+shortlog_summary = pyparsing.OneOrMore(pyparsing.Word(pyparsing.printables))
+shortlog = line_start + shortlog_target + colon + shortlog_summary + line_end
+
+# signed-off-bys
+
+email_pattern = pyparsing.Regex(r"(?P<user>[A-Za-z0-9._%+-]+)@(?P<hostname>[A-Za-z0-9.-]+)\.(?P<domain>[A-Za-z]{2,})")
+
+signed_off_by_prefix = pyparsing.Literal("Signed-off-by:")
+signed_off_by_name = pyparsing.Regex('\S+.*(?= <)')
+signed_off_by_email = lessthan + email_pattern + greaterthan
+signed_off_by = pyparsing.AtLineStart(signed_off_by_prefix + signed_off_by_name + signed_off_by_email)
+patch_signed_off_by = pyparsing.AtLineStart("+" + signed_off_by_prefix + signed_off_by_name + signed_off_by_email)
+
+# upstream-status
+
+upstream_status_literal_valid_status = ["Pending", "Backport", "Denied", "Inappropriate", "Submitted"]
+upstream_status_nonliteral_valid_status = ["Pending", "Backport", "Denied", "Inappropriate [reason]", "Submitted [where]"]
+
+upstream_status_valid_status = pyparsing.Or(
+    [pyparsing.Literal(status) for status in upstream_status_literal_valid_status]
+)
+
+upstream_status_prefix = pyparsing.Literal("Upstream-Status")
+upstream_status = line_start + upstream_status_prefix + colon + upstream_status_valid_status
+upstream_status_inappropriate_info = line_start + upstream_status_prefix + colon + inappropriateinfo
+upstream_status_submitted_info = line_start + upstream_status_prefix + colon + submittedinfo
meta/lib/patchtest/tests/pyparsing/common.py deleted +0 -26
deleted file mode 100644
index cbce4c38bc8..00000000000
@@ -1,26 +0,0 @@
-# common pyparsing variables
-#
-# Copyright (C) 2016 Intel Corporation
-#
-# SPDX-License-Identifier: GPL-2.0-only
-
-import pyparsing
-
-# general
-colon = pyparsing.Literal(":")
-start = pyparsing.LineStart()
-end   = pyparsing.LineEnd()
-at = pyparsing.Literal("@")
-lessthan = pyparsing.Literal("<")
-greaterthan = pyparsing.Literal(">")
-opensquare = pyparsing.Literal("[")
-closesquare = pyparsing.Literal("]")
-inappropriate = pyparsing.CaselessLiteral("Inappropriate")
-submitted = pyparsing.CaselessLiteral("Submitted")
-
-# word related
-nestexpr = pyparsing.nestedExpr(opener='[', closer=']')
-inappropriateinfo = pyparsing.Literal("Inappropriate") + nestexpr
-submittedinfo = pyparsing.Literal("Submitted") + nestexpr
-word = pyparsing.Word(pyparsing.alphas)
-worddot = pyparsing.Word(pyparsing.alphas+".")
meta/lib/patchtest/tests/pyparsing/parse_cve_tags.py deleted +0 -18
deleted file mode 100644
index f7fb82ec2bd..00000000000
@@ -1,18 +0,0 @@
-# signed-off-by pyparsing definition
-#
-# Copyright (C) 2016 Intel Corporation
-#
-# SPDX-License-Identifier: GPL-2.0-only
-
-
-import pyparsing
-import common
-
-name = pyparsing.Regex('\S+.*(?= <)')
-username = pyparsing.OneOrMore(common.worddot)
-domain = pyparsing.OneOrMore(common.worddot)
-cve = pyparsing.Regex('CVE\-\d{4}\-\d+')
-cve_mark = pyparsing.Literal("CVE:")
-
-cve_tag = pyparsing.AtLineStart(cve_mark + cve)
-patch_cve_tag = pyparsing.AtLineStart("+" + cve_mark + cve)
meta/lib/patchtest/tests/pyparsing/parse_shortlog.py deleted +0 -14
deleted file mode 100644
index 30d3ab35b32..00000000000
@@ -1,14 +0,0 @@
-# subject pyparsing definition
-#
-# Copyright (C) 2016 Intel Corporation
-#
-# SPDX-License-Identifier: GPL-2.0-only
-
-# NOTE:This is an oversimplified syntax of the mbox's summary
-
-import pyparsing
-import common
-
-target        = pyparsing.OneOrMore(pyparsing.Word(pyparsing.printables.replace(':','')))
-summary       = pyparsing.OneOrMore(pyparsing.Word(pyparsing.printables))
-shortlog       = common.start + target + common.colon + summary + common.end
meta/lib/patchtest/tests/pyparsing/parse_signed_off_by.py deleted +0 -22
deleted file mode 100644
index 692ebec3ffc..00000000000
@@ -1,22 +0,0 @@
-# signed-off-by pyparsing definition
-#
-# Copyright (C) 2016 Intel Corporation
-#
-# SPDX-License-Identifier: GPL-2.0-only
-
-
-import pyparsing
-import common
-
-name = pyparsing.Regex('\S+.*(?= <)')
-username = pyparsing.OneOrMore(common.worddot)
-domain = pyparsing.OneOrMore(common.worddot)
-
-# taken from https://pyparsing-public.wikispaces.com/Helpful+Expressions
-email = pyparsing.Regex(r"(?P<user>[A-Za-z0-9._%+-]+)@(?P<hostname>[A-Za-z0-9.-]+)\.(?P<domain>[A-Za-z]{2,})")
-
-email_enclosed = common.lessthan + email + common.greaterthan
-
-signed_off_by_mark = pyparsing.Literal("Signed-off-by:")
-signed_off_by = pyparsing.AtLineStart(signed_off_by_mark + name + email_enclosed)
-patch_signed_off_by = pyparsing.AtLineStart("+" + signed_off_by_mark + name + email_enclosed)
meta/lib/patchtest/tests/pyparsing/parse_upstream_status.py deleted +0 -24
deleted file mode 100644
index bc6c427c4ce..00000000000
@@ -1,24 +0,0 @@
-# upstream-status pyparsing definition
-#
-# Copyright (C) 2016 Intel Corporation
-#
-# SPDX-License-Identifier: GPL-2.0-only
-
-
-import common
-import pyparsing
-
-upstream_status_literal_valid_status = ["Pending", "Backport", "Denied", "Inappropriate", "Submitted"]
-upstream_status_nonliteral_valid_status = ["Pending", "Backport", "Denied", "Inappropriate [reason]", "Submitted [where]"]
-
-upstream_status_valid_status = pyparsing.Or(
-    [pyparsing.Literal(status) for status in upstream_status_literal_valid_status]
-)
-
-upstream_status_mark         = pyparsing.Literal("Upstream-Status")
-inappropriate_status_mark    = common.inappropriate
-submitted_status_mark        = common.submitted
-
-upstream_status              = common.start + upstream_status_mark + common.colon + upstream_status_valid_status
-upstream_status_inappropriate_info = common.start + upstream_status_mark + common.colon + common.inappropriateinfo
-upstream_status_submitted_info = common.start + upstream_status_mark + common.colon + common.submittedinfo
meta/lib/patchtest/tests/test_mbox.py +11 -25
index cd76e58a717..e6b8ad21f80 100644
@@ -6,8 +6,7 @@
 
 import base
 import collections
-import parse_shortlog
-import parse_signed_off_by
+import patterns
 import pyparsing
 import re
 import subprocess
@@ -23,19 +22,6 @@ def headlog():
 
 class TestMbox(base.Base):
 
-    auh_email = '[email protected]'
-
-    invalids = [pyparsing.Regex("^Upgrade Helper.+"),
-                pyparsing.Regex(auh_email),
-                pyparsing.Regex("uh@not\.set"),
-                pyparsing.Regex("\S+@example\.com")]
-
-    rexp_detect = pyparsing.Regex('\[\s?YOCTO.*\]')
-    rexp_validation = pyparsing.Regex('\[(\s?YOCTO\s?#\s?(\d+)\s?,?)+\]')
-    signoff_prog = parse_signed_off_by.signed_off_by
-    revert_shortlog_regex = pyparsing.Regex('Revert\s+".*"')
-    maxlength = 90
-
     # base paths of main yocto project sub-projects
     paths = {
         'oe-core': ['meta-selftest', 'meta-skeleton', 'meta', 'scripts'],
@@ -59,9 +45,9 @@ class TestMbox(base.Base):
     def test_signed_off_by_presence(self):
         for commit in TestMbox.commits:
             # skip those patches that revert older commits, these do not required the tag presence
-            if self.revert_shortlog_regex.search_string(commit.shortlog):
+            if patterns.mbox_revert_shortlog_regex.search_string(commit.shortlog):
                 continue
-            if not self.signoff_prog.search_string(commit.payload):
+            if not patterns.signed_off_by.search_string(commit.payload):
                 self.fail('Mbox is missing Signed-off-by. Add it manually or with "git commit --amend -s"',
                           commit=commit)
 
@@ -75,7 +61,7 @@ class TestMbox(base.Base):
                 if shortlog.startswith('Revert "'):
                     continue
                 try:
-                    parse_shortlog.shortlog.parseString(shortlog)
+                    patterns.shortlog.parseString(shortlog)
                 except pyparsing.ParseException as pe:
                     self.fail('Commit shortlog (first line of commit message) should follow the format "<target>: <summary>"',
                               commit=commit)
@@ -87,8 +73,8 @@ class TestMbox(base.Base):
             if shortlog.startswith('Revert "'):
                 continue
             l = len(shortlog)
-            if l > self.maxlength:
-                self.fail('Edit shortlog so that it is %d characters or less (currently %d characters)' % (self.maxlength, l),
+            if l > patterns.mbox_shortlog_maxlength:
+                self.fail('Edit shortlog so that it is %d characters or less (currently %d characters)' % (patterns.mbox_shortlog_maxlength, l),
                           commit=commit)
 
     def test_series_merge_on_head(self):
@@ -142,18 +128,18 @@ class TestMbox(base.Base):
 
     def test_bugzilla_entry_format(self):
         for commit in TestMbox.commits:
-            if not self.rexp_detect.search_string(commit.commit_message):
+            if not patterns.mbox_bugzilla.search_string(commit.commit_message):
                 self.skip("No bug ID found")
-            elif not self.rexp_validation.search_string(commit.commit_message):
+            elif not patterns.mbox_bugzilla_validation.search_string(commit.commit_message):
                 self.fail('Bugzilla issue ID is not correctly formatted - specify it with format: "[YOCTO #<bugzilla ID>]"', commit=commit)
 
     def test_author_valid(self):
         for commit in self.commits:
-            for invalid in self.invalids:
+            for invalid in patterns.invalid_submitters:
                 if invalid.search_string(commit.author):
                     self.fail('Invalid author %s. Resend the series with a valid patch author' % commit.author, commit=commit)
 
     def test_non_auh_upgrade(self):
         for commit in self.commits:
-            if self.auh_email in commit.commit_message:
-                self.fail('Invalid author %s. Resend the series with a valid patch author' % self.auh_email, commit=commit)
+            if patterns.auh_email in commit.commit_message:
+                self.fail('Invalid author %s. Resend the series with a valid patch author' % patterns.auh_email, commit=commit)
meta/lib/patchtest/tests/test_metadata.py +20 -36

127 lines not on this page · raw message

meta/lib/patchtest/tests/test_patch.py +13 -18
index d7187a0cb1b..d856b216f09 100644
@@ -7,16 +7,11 @@
 
 import base
 import os
-import parse_signed_off_by
-import parse_upstream_status
+import patterns
 import pyparsing
 
 class TestPatch(base.Base):
 
-    re_cve_pattern = pyparsing.Regex("CVE\-\d{4}\-\d+")
-    re_cve_payload_tag = pyparsing.Regex("\+CVE:(\s+CVE\-\d{4}\-\d+)+")
-    upstream_status_regex = pyparsing.AtLineStart("+" + "Upstream-Status")
-
     @classmethod
     def setUpClassLocal(cls):
         cls.newpatches = []
@@ -25,16 +20,16 @@ class TestPatch(base.Base):
             if patch.path.endswith('.patch') and patch.is_added_file:
                 cls.newpatches.append(patch)
 
-        cls.mark = str(parse_signed_off_by.signed_off_by_mark).strip('"')
+        cls.mark = str(patterns.signed_off_by_prefix).strip('"')
 
         # match PatchSignedOffBy.mark with '+' preceding it
-        cls.prog = parse_signed_off_by.patch_signed_off_by
+        cls.prog = patterns.patch_signed_off_by
 
     def setUp(self):
         if self.unidiff_parse_error:
             self.skip('Parse error %s' % self.unidiff_parse_error)
 
-        self.valid_status    = ', '.join(parse_upstream_status.upstream_status_nonliteral_valid_status)
+        self.valid_status    = ', '.join(patterns.upstream_status_nonliteral_valid_status)
         self.standard_format = 'Upstream-Status: <Valid status>'
 
         # we are just interested in series that introduce CVE patches, thus discard other
@@ -50,28 +45,28 @@ class TestPatch(base.Base):
 
         for newpatch in TestPatch.newpatches:
             payload = newpatch.__str__()
-            if not self.upstream_status_regex.search_string(payload):
+            if not patterns.upstream_status_regex.search_string(payload):
                 self.fail('Added patch file is missing Upstream-Status: <Valid status> in the commit message',
                           data=[('Standard format', self.standard_format), ('Valid status', self.valid_status)])
             for line in payload.splitlines():
                 if self.patchmetadata_regex.match(line):
                     continue
-                if self.upstream_status_regex.search_string(line):
-                        if parse_upstream_status.inappropriate_status_mark.searchString(line):
+                if patterns.upstream_status_regex.search_string(line):
+                        if patterns.inappropriate.searchString(line):
                             try:
-                                parse_upstream_status.upstream_status_inappropriate_info.parseString(line.lstrip('+'))
+                                patterns.upstream_status_inappropriate_info.parseString(line.lstrip('+'))
                             except pyparsing.ParseException as pe:
                                 self.fail('Upstream-Status is Inappropriate, but no reason was provided',
                                           data=[('Current', pe.pstr), ('Standard format', 'Upstream-Status: Inappropriate [reason]')])
-                        elif parse_upstream_status.submitted_status_mark.searchString(line):
+                        elif patterns.submitted.searchString(line):
                             try:
-                                parse_upstream_status.upstream_status_submitted_info.parseString(line.lstrip('+'))
+                                patterns.upstream_status_submitted_info.parseString(line.lstrip('+'))
                             except pyparsing.ParseException as pe:
                                 self.fail('Upstream-Status is Submitted, but it is not mentioned where',
                                           data=[('Current', pe.pstr), ('Standard format', 'Upstream-Status: Submitted [where]')])
                         else:
                             try:
-                                parse_upstream_status.upstream_status.parseString(line.lstrip('+'))
+                                patterns.upstream_status.parseString(line.lstrip('+'))
                             except pyparsing.ParseException as pe:
                                 self.fail('Upstream-Status is in incorrect format',
                                           data=[('Current', pe.pstr), ('Standard format', self.standard_format), ('Valid status', self.valid_status)])
@@ -92,10 +87,10 @@ class TestPatch(base.Base):
 
     def test_cve_tag_format(self):
         for commit in TestPatch.commits:
-            if self.re_cve_pattern.search_string(commit.shortlog) or self.re_cve_pattern.search_string(commit.commit_message):
+            if patterns.cve.search_string(commit.shortlog) or patterns.cve.search_string(commit.commit_message):
                 tag_found = False
                 for line in commit.payload.splitlines():
-                    if self.re_cve_payload_tag.search_string(line):
+                    if patterns.cve_payload_tag.search_string(line):
                         tag_found = True
                         break
                 if not tag_found:
meta/lib/patchtest/tests/test_python_pylint.py +1 -0
index ef315e591ca..b03fd6f4f65 100644
@@ -5,6 +5,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
 import base
+import patterns
 from io import StringIO
 from data import PatchTestInput
 from pylint.reporters.text import TextReporter
Signature · 1 line
2.39.5
#2 lore raw

PATCH 2/6 patchtest: mbox.py: new data implementation

In reply to Trevor Gamblin

Consolidate and improve some objects:

- absorb utils.py functionality
- repo.py: use mbox.py
- repo.py: remove some cruft
- utils.py: replace with logs.py
- utils.py: delete
- patch.py: delete
- scripts/patchtest: use logging directly
- general cleanup

---
 meta/lib/patchtest/mbox.py                | 108 ++++++++++++++++++++++
 meta/lib/patchtest/patch.py               |  43 ---------
 meta/lib/patchtest/patterns.py            |   3 -
 meta/lib/patchtest/repo.py                |  63 +++----------
 meta/lib/patchtest/tests/base.py          |   5 +-
 meta/lib/patchtest/tests/test_metadata.py |   2 +-
 meta/lib/patchtest/utils.py               |  61 ------------
 scripts/patchtest                         |  17 ++--
 8 files changed, 134 insertions(+), 168 deletions(-)
 create mode 100644 meta/lib/patchtest/mbox.py
 delete mode 100644 meta/lib/patchtest/patch.py
 delete mode 100644 meta/lib/patchtest/utils.py
meta/lib/patchtest/mbox.py new file +108 -0
new file mode 100644
index 00000000000..1d95819b7ae
@@ -0,0 +1,108 @@
+#! /usr/bin/env python3
+
+# series.py
+#
+# Read a series' mbox file and get information about the patches
+# contained
+#
+# Copyright (C) 2024 BayLibre SAS
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import email
+import re
+
+# From: https://stackoverflow.com/questions/59681461/read-a-big-mbox-file-with-python
+class MboxReader:
+    def __init__(self, filepath):
+        self.handle = open(filepath, 'rb')
+        assert self.handle.readline().startswith(b'From ')
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, exc_type, exc_value, exc_traceback):
+        self.handle.close()
+
+    def __iter__(self):
+        return iter(self.__next__())
+
+    def __next__(self):
+        lines = []
+        while True:
+            line = self.handle.readline()
+            if line == b'' or line.startswith(b'From '):
+                yield email.message_from_bytes(b''.join(lines))
+                if line == b'':
+                    break
+                lines = []
+                continue
+            lines.append(line)
+
+class Patch:
+    def __init__(self, data):
+        self.author = data['From']
+        self.to = data['To']
+        self.cc = data['Cc']
+        self.subject = data['Subject']
+        self.split_body = re.split('---', data.get_payload(), maxsplit=1)
+        self.commit_message = self.split_body[0]
+        self.diff = self.split_body[1]
+
+class PatchSeries:
+    def __init__(self, filepath):
+        with MboxReader(filepath) as mbox:
+            self.patches = [Patch(message) for message in mbox]
+
+        assert self.patches
+        self.patch_count = len(self.patches)
+        self.path = filepath
+
+        @property
+        def path(self):
+            return self.path
+
+        self.branch = self.get_branch()
+
+    def get_branch(self):
+        fullprefix = ""
+        pattern = re.compile(r"(\[.*\])", re.DOTALL)
+
+        # There should be at least one patch in the series and it should
+        # include the branch name in the subject, so parse that
+        match = pattern.search(self.patches[0].subject)
+        if match:
+            fullprefix = match.group(1)
+
+        branch, branches, valid_branches = None, [], []
+
+        if fullprefix:
+            prefix = fullprefix.strip('[]')
+            branches = [ b.strip() for b in prefix.split(',')]
+            valid_branches = [b for b in branches if PatchSeries.valid_branch(b)]
+
+        if len(valid_branches):
+            branch = valid_branches[0]
+
+        # Get the branch name excluding any brackets. If nothing was
+        # found, then assume there was no branch tag in the subject line
+        # and that the patch targets master
+        if branch is not None:
+            return branch.split(']')[0]
+        else:
+            return "master"
+
+    @staticmethod
+    def valid_branch(branch):
+        """ Check if branch is valid name """
+        lbranch = branch.lower()
+
+        invalid  = lbranch.startswith('patch') or \
+                   lbranch.startswith('rfc') or \
+                   lbranch.startswith('resend') or \
+                   re.search(r'^v\d+', lbranch) or \
+                   re.search(r'^\d+/\d+', lbranch)
+
+        return not invalid
+
meta/lib/patchtest/patch.py deleted +0 -43

43 lines not on this page · raw message

meta/lib/patchtest/patterns.py +0 -3
index ba97a4ffe9f..b703b0c8b99 100644
@@ -10,11 +10,8 @@ import pyparsing
 colon = pyparsing.Literal(":")
 line_start = pyparsing.LineStart()
 line_end = pyparsing.LineEnd()
-at = pyparsing.Literal("@")
 lessthan = pyparsing.Literal("<")
 greaterthan = pyparsing.Literal(">")
-opensquare = pyparsing.Literal("[")
-closesquare = pyparsing.Literal("]")
 inappropriate = pyparsing.CaselessLiteral("Inappropriate")
 submitted = pyparsing.CaselessLiteral("Submitted")
 
meta/lib/patchtest/repo.py +14 -49

113 lines not on this page · raw message

meta/lib/patchtest/tests/base.py +2 -3
index 424e61b5be2..911addb199a 100644
@@ -37,7 +37,6 @@ class Base(unittest.TestCase):
     endcommit_messages_regex = re.compile(r'\(From \w+-\w+ rev:|(?<!\S)Signed-off-by|(?<!\S)---\n')
     patchmetadata_regex   = re.compile(r'-{3} \S+|\+{3} \S+|@{2} -\d+,\d+ \+\d+,\d+ @{2} \S+')
 
-
     @staticmethod
     def msg_to_commit(msg):
         payload = msg.get_payload()
@@ -66,13 +65,13 @@ class Base(unittest.TestCase):
     def setUpClass(cls):
 
         # General objects: mailbox.mbox and patchset
-        cls.mbox = mailbox.mbox(PatchTestInput.repo.patch)
+        cls.mbox = mailbox.mbox(PatchTestInput.repo.patch.path)
 
         # Patch may be malformed, so try parsing it
         cls.unidiff_parse_error = ''
         cls.patchset = None
         try:
-            cls.patchset = unidiff.PatchSet.from_filename(PatchTestInput.repo.patch, encoding=u'UTF-8')
+            cls.patchset = unidiff.PatchSet.from_filename(PatchTestInput.repo.patch.path, encoding=u'UTF-8')
         except unidiff.UnidiffParseError as upe:
             cls.patchset = []
             cls.unidiff_parse_error = str(upe)
meta/lib/patchtest/tests/test_metadata.py +1 -1
index 8c2305a1840..d7e5e187f64 100644
@@ -168,7 +168,7 @@ class TestMetadata(base.Metadata):
     def test_cve_check_ignore(self):
         # Skip if we neither modified a recipe or target branches are not
         # Nanbield and newer. CVE_CHECK_IGNORE was first deprecated in Nanbield.
-        if not self.modified or PatchTestInput.repo.branch == "kirkstone" or PatchTestInput.repo.branch == "dunfell":
+        if not self.modified or PatchTestInput.repo.patch.branch == "kirkstone" or PatchTestInput.repo.patch.branch == "dunfell":
             self.skip('No modified recipes or older target branch, skipping test')
         for pn in self.modified:
             # we are not interested in images
meta/lib/patchtest/utils.py deleted +0 -61

61 lines not on this page · raw message

scripts/patchtest +9 -8
index 0be7062dc2e..3ca8c6e48fe 100755
@@ -9,12 +9,12 @@
 # SPDX-License-Identifier: GPL-2.0-only
 #
 
-import sys
-import os
-import unittest
+import json
 import logging
+import os
+import sys
 import traceback
-import json
+import unittest
 
 # Include current path so test cases can see it
 sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
@@ -25,13 +25,14 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..
 from data import PatchTestInput
 from repo import PatchTestRepo
 
-import utils
-logger = utils.logger_create('patchtest')
+logger = logging.getLogger("patchtest")
+loggerhandler = logging.StreamHandler()
+loggerhandler.setFormatter(logging.Formatter("%(message)s"))
+logger.addHandler(loggerhandler)
+logger.setLevel(logging.INFO)
 info = logger.info
 error = logger.error
 
-import repo
-
 def getResult(patch, mergepatch, logfile=None):
 
     class PatchTestResult(unittest.TextTestResult):
Signature · 1 line
2.39.5
#3 lore raw

PATCH 3/6 patchtest: test_mbox: change ismerged -> canbemerged

In reply to Trevor Gamblin

The merge logic is a bit weird as-is. Remove the ismerged() method and replace it where appropriate with canbemerged().

---
 meta/lib/patchtest/tests/test_mbox.py | 24 +++++++++++++-----------
 1 file changed, 13 insertions(+), 11 deletions(-)
meta/lib/patchtest/tests/test_mbox.py +13 -11
index e6b8ad21f80..895ffde42b0 100644
@@ -43,7 +43,7 @@ class TestMbox(base.Base):
 
 
     def test_signed_off_by_presence(self):
-        for commit in TestMbox.commits:
+        for commit in self.commits:
             # skip those patches that revert older commits, these do not required the tag presence
             if patterns.mbox_revert_shortlog_regex.search_string(commit.shortlog):
                 continue
@@ -52,7 +52,7 @@ class TestMbox(base.Base):
                           commit=commit)
 
     def test_shortlog_format(self):
-        for commit in TestMbox.commits:
+        for commit in self.commits:
             shortlog = commit.shortlog
             if not shortlog.strip():
                 self.skip('Empty shortlog, no reason to execute shortlog format test')
@@ -67,7 +67,7 @@ class TestMbox(base.Base):
                               commit=commit)
 
     def test_shortlog_length(self):
-        for commit in TestMbox.commits:
+        for commit in self.commits:
             # no reason to re-check on revert shortlogs
             shortlog = re.sub('^(\[.*?\])+ ', '', commit.shortlog)
             if shortlog.startswith('Revert "'):
@@ -79,22 +79,24 @@ class TestMbox(base.Base):
 
     def test_series_merge_on_head(self):
         self.skip("Merge test is disabled for now")
-        if PatchTestInput.repo.branch != "master":
-            self.skip("Skipping merge test since patch is not intended for master branch. Target detected is %s" % PatchTestInput.repo.branch)
-        if not PatchTestInput.repo.ismerged:
+        if PatchTestInput.repo.patch.branch != "master":
+            self.skip(
+                "Skipping merge test since patch is not intended"
+                " for master branch. Target detected is %s"
+                % PatchTestInput.repo.patch.branch
+            )
+        if not PatchTestInput.repo.canbemerged:
             commithash, author, date, shortlog = headlog()
             self.fail('Series does not apply on top of target branch %s' % PatchTestInput.repo.branch,
                       data=[('Targeted branch', '%s (currently at %s)' % (PatchTestInput.repo.branch, commithash))])
 
     def test_target_mailing_list(self):
-        """In case of merge failure, check for other targeted projects"""
-        if PatchTestInput.repo.ismerged:
-            self.skip('Series merged, no reason to check other mailing lists')
+        """Check for other targeted projects"""
 
         # a meta project may be indicted in the message subject, if this is the case, just fail
         # TODO: there may be other project with no-meta prefix, we also need to detect these
         project_regex = pyparsing.Regex("\[(?P<project>meta-.+)\]")
-        for commit in TestMbox.commits:
+        for commit in self.commits:
             match = project_regex.search_string(commit.subject)
             if match:
                 self.fail('Series sent to the wrong mailing list or some patches from the series correspond to different mailing lists',
@@ -122,7 +124,7 @@ class TestMbox(base.Base):
                       data=[('Diff line',self.unidiff_parse_error)])
 
     def test_commit_message_presence(self):
-        for commit in TestMbox.commits:
+        for commit in self.commits:
             if not commit.commit_message.strip():
                 self.fail('Please include a commit message on your patch explaining the change', commit=commit)
 
Signature · 1 line
2.39.5
#4 lore raw

PATCH 4/6 patchtest: simplify, rename modules

In reply to Trevor Gamblin

- simplify base.py, data.py
- move some leftover regex patterns to patterns.py
- remove pyparsing path logic, since this is no longer needed
- rename PatchTestInput class to PatchtestParser
- data.py: rename to patchtest_parser.py
- patterns.py: rename to patchtest_patterns.py
- move PatchTestDataStore to test_metadata.py since that's the only place it's used
- remove unused logger code

---
 .../{data.py => patchtest_parser.py}          | 10 +-
 .../{patterns.py => patchtest_patterns.py}    | 15 ++-
 meta/lib/patchtest/tests/base.py              | 48 ++++++----
 meta/lib/patchtest/tests/test_mbox.py         | 69 +++++++++-----
 meta/lib/patchtest/tests/test_metadata.py     | 91 ++++++++++++------
 meta/lib/patchtest/tests/test_patch.py        | 95 +++++++++++++------
 .../lib/patchtest/tests/test_python_pylint.py |  3 +-
 scripts/patchtest                             | 34 ++++---
 8 files changed, 234 insertions(+), 131 deletions(-)
 rename meta/lib/patchtest/{data.py => patchtest_parser.py} (92%)
 rename meta/lib/patchtest/{patterns.py => patchtest_patterns.py} (90%)
meta/lib/patchtest/patchtest_parser.py renamed from meta/lib/patchtest/data.py +1 -9
similarity index 92%
rename from meta/lib/patchtest/data.py
rename to meta/lib/patchtest/patchtest_parser.py
index 356259921da..2a11cb76c23 100644
@@ -15,19 +15,11 @@
 
 import os
 import argparse
-import collections
-import logging
-
-logger=logging.getLogger('patchtest')
-info=logger.info
 
 default_testdir = os.path.abspath(os.path.dirname(__file__) + "/tests")
 default_repodir = os.path.abspath(os.path.dirname(__file__) + "/../../..")
 
-# Data store commonly used to share values between pre and post-merge tests
-PatchTestDataStore = collections.defaultdict(str)
-
-class PatchTestInput(object):
+class PatchtestParser(object):
     """Abstract the patchtest argument parser"""
 
     @classmethod
meta/lib/patchtest/patchtest_patterns.py renamed from meta/lib/patchtest/patterns.py +11 -4
similarity index 90%
rename from meta/lib/patchtest/patterns.py
rename to meta/lib/patchtest/patchtest_patterns.py
index b703b0c8b99..8c2e192fc9f 100644
@@ -5,6 +5,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
 import pyparsing
+import re
 
 # general
 colon = pyparsing.Literal(":")
@@ -34,10 +35,16 @@ lic_chksum_added = pyparsing.AtLineStart("+" + metadata_chksum)
 lic_chksum_removed = pyparsing.AtLineStart("-" + metadata_chksum)
 add_mark = pyparsing.Regex('\\+ ')
 patch_max_line_length = 200
-metadata_src_uri  = 'SRC_URI'
-metadata_summary = 'SUMMARY'
-cve_check_ignore_var = 'CVE_CHECK_IGNORE'
-cve_status_var = 'CVE_STATUS'
+metadata_src_uri = "SRC_URI"
+metadata_summary = "SUMMARY"
+cve_check_ignore_var = "CVE_CHECK_IGNORE"
+cve_status_var = "CVE_STATUS"
+endcommit_messages_regex = re.compile(
+    r"\(From \w+-\w+ rev:|(?<!\S)Signed-off-by|(?<!\S)---\n"
+)
+patchmetadata_regex = re.compile(
+    r"-{3} \S+|\+{3} \S+|@{2} -\d+,\d+ \+\d+,\d+ @{2} \S+"
+)
 
 # mbox
 auh_email = '[email protected]'
meta/lib/patchtest/tests/base.py +31 -17

98 lines not on this page · raw message

meta/lib/patchtest/tests/test_mbox.py +46 -23

120 lines not on this page · raw message

meta/lib/patchtest/tests/test_metadata.py +61 -30

168 lines not on this page · raw message

meta/lib/patchtest/tests/test_patch.py +64 -31

136 lines not on this page · raw message

meta/lib/patchtest/tests/test_python_pylint.py +1 -2
index b03fd6f4f65..ec9129bc796 100644
@@ -5,9 +5,8 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
 import base
-import patterns
 from io import StringIO
-from data import PatchTestInput
+from patchtest_parser import PatchtestParser
 from pylint.reporters.text import TextReporter
 import pylint.lint as lint
 
scripts/patchtest +19 -15
index 3ca8c6e48fe..278fc4e6e09 100755
@@ -22,7 +22,7 @@ sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
 # Include patchtest library
 sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '../meta/lib/patchtest'))
 
-from data import PatchTestInput
+from patchtest_parser import PatchtestParser
 from repo import PatchTestRepo
 
 logger = logging.getLogger("patchtest")
@@ -47,10 +47,10 @@ def getResult(patch, mergepatch, logfile=None):
         def startTestRun(self):
             # let's create the repo already, it can be used later on
             repoargs = {
-                'repodir': PatchTestInput.repodir,
-                'commit' : PatchTestInput.basecommit,
-                'branch' : PatchTestInput.basebranch,
-                'patch'  : patch,
+                "repodir": PatchtestParser.repodir,
+                "commit": PatchtestParser.basecommit,
+                "branch": PatchtestParser.basebranch,
+                "patch": patch,
             }
 
             self.repo_error    = False
@@ -58,7 +58,7 @@ def getResult(patch, mergepatch, logfile=None):
             self.test_failure  = False
 
             try:
-                self.repo = PatchTestInput.repo = PatchTestRepo(**repoargs)
+                self.repo = PatchtestParser.repo = PatchTestRepo(**repoargs)
             except:
                 logger.error(traceback.print_exc())
                 self.repo_error = True
@@ -129,7 +129,11 @@ def _runner(resultklass, prefix=None):
         loader.testMethodPrefix = prefix
 
     # create the suite with discovered tests and the corresponding runner
-    suite = loader.discover(start_dir=PatchTestInput.testdir, pattern=PatchTestInput.pattern, top_level_dir=PatchTestInput.topdir)
+    suite = loader.discover(
+        start_dir=PatchtestParser.testdir,
+        pattern=PatchtestParser.pattern,
+        top_level_dir=PatchtestParser.topdir,
+    )
     ntc = suite.countTestCases()
 
     # if there are no test cases, just quit
@@ -173,12 +177,12 @@ def run(patch, logfile=None):
 
 def main():
     tmp_patch = False
-    patch_path = PatchTestInput.patch_path
-    log_results = PatchTestInput.log_results
+    patch_path = PatchtestParser.patch_path
+    log_results = PatchtestParser.log_results
     log_path = None
     patch_list = None
 
-    git_status = os.popen("(cd %s && git status)" % PatchTestInput.repodir).read()
+    git_status = os.popen("(cd %s && git status)" % PatchtestParser.repodir).read()
     status_matches = ["Changes not staged for commit", "Changes to be committed"]
     if any([match in git_status for match in status_matches]):
         logger.error("patchtest: there are uncommitted changes in the target repo that would be overwritten. Please commit or restore them before running patchtest")
@@ -213,16 +217,16 @@ def main():
 if __name__ == '__main__':
     ret = 1
 
-    # Parse the command line arguments and store it on the PatchTestInput namespace
-    PatchTestInput.set_namespace()
+    # Parse the command line arguments and store it on the PatchtestParser namespace
+    PatchtestParser.set_namespace()
 
     # set debugging level
-    if PatchTestInput.debug:
+    if PatchtestParser.debug:
         logger.setLevel(logging.DEBUG)
 
     # if topdir not define, default it to testdir
-    if not PatchTestInput.topdir:
-        PatchTestInput.topdir = PatchTestInput.testdir
+    if not PatchtestParser.topdir:
+        PatchtestParser.topdir = PatchtestParser.testdir
 
     try:
         ret = main()
Signature · 1 line
2.39.5
#5 lore raw

PATCH 5/6 scripts/patchtest: split out result messages

In reply to Trevor Gamblin

Add a minor refactor for the result output.

---
 scripts/patchtest | 23 +++++++++++++++--------
 1 file changed, 15 insertions(+), 8 deletions(-)
scripts/patchtest +15 -8
index 278fc4e6e09..9218db232a7 100755
@@ -165,16 +165,23 @@ def run(patch, logfile=None):
     postmerge_resultklass = getResult(patch, True, logfile)
     postmerge_result = _runner(postmerge_resultklass, 'test')
 
-    print('----------------------------------------------------------------------\n')
-    if premerge_result == 2 and postmerge_result == 2:
-        logger.error('patchtest: No test cases found - did you specify the correct suite directory?')
-    if premerge_result == 1 or postmerge_result == 1:
-        logger.error('WARNING: patchtest: At least one patchtest caused a failure or an error - please check https://wiki.yoctoproject.org/wiki/Patchtest for further guidance')
-    else:
-        logger.info('OK: patchtest: All patchtests passed')
-    print('----------------------------------------------------------------------\n')
+    print_result_message(premerge_result, postmerge_result)
     return premerge_result or postmerge_result
 
+def print_result_message(preresult, postresult):
+    print("----------------------------------------------------------------------\n")
+    if preresult == 2 and postresult == 2:
+        logger.error(
+            "patchtest: No test cases found - did you specify the correct suite directory?"
+        )
+    if preresult == 1 or postresult == 1:
+        logger.error(
+            "WARNING: patchtest: At least one patchtest caused a failure or an error - please check https://wiki.yoctoproject.org/wiki/Patchtest for further guidance"
+        )
+    else:
+        logger.info("OK: patchtest: All patchtests passed")
+    print("----------------------------------------------------------------------\n")
+
 def main():
     tmp_patch = False
     patch_path = PatchtestParser.patch_path
Signature · 1 line
2.39.5
#6 lore raw

PATCH 6/6 patchtest: use black to format libraries

In reply to Trevor Gamblin

Black makes things easier to read.

---
 meta/lib/patchtest/mbox.py                    |  44 +++---
 meta/lib/patchtest/patchtest_parser.py        | 106 ++++++++-----
 meta/lib/patchtest/patchtest_patterns.py      |  84 ++++++----
 meta/lib/patchtest/repo.py                    |  32 ++--
 meta/lib/patchtest/selftest/selftest          |  92 ++++++++---
 meta/lib/patchtest/tests/base.py              |  86 ++++++-----
 meta/lib/patchtest/tests/test_mbox.py         | 144 +++++++++++++-----
 meta/lib/patchtest/tests/test_metadata.py     |  94 ++++++++----
 meta/lib/patchtest/tests/test_patch.py        |  39 +++--
 .../lib/patchtest/tests/test_python_pylint.py |  45 ++++--
 scripts/patchtest                             | 113 +++++++++-----
 scripts/patchtest-get-branch                  |  54 ++++---
 scripts/patchtest-send-results                |  66 +++++---
 13 files changed, 660 insertions(+), 339 deletions(-)
meta/lib/patchtest/mbox.py +24 -20
index 1d95819b7ae..aad07356f1f 100644
@@ -13,11 +13,12 @@
 import email
 import re
 
+
 # From: https://stackoverflow.com/questions/59681461/read-a-big-mbox-file-with-python
 class MboxReader:
     def __init__(self, filepath):
-        self.handle = open(filepath, 'rb')
-        assert self.handle.readline().startswith(b'From ')
+        self.handle = open(filepath, "rb")
+        assert self.handle.readline().startswith(b"From ")
 
     def __enter__(self):
         return self
@@ -32,24 +33,26 @@ class MboxReader:
         lines = []
         while True:
             line = self.handle.readline()
-            if line == b'' or line.startswith(b'From '):
-                yield email.message_from_bytes(b''.join(lines))
-                if line == b'':
+            if line == b"" or line.startswith(b"From "):
+                yield email.message_from_bytes(b"".join(lines))
+                if line == b"":
                     break
                 lines = []
                 continue
             lines.append(line)
 
+
 class Patch:
     def __init__(self, data):
-        self.author = data['From']
-        self.to = data['To']
-        self.cc = data['Cc']
-        self.subject = data['Subject']
-        self.split_body = re.split('---', data.get_payload(), maxsplit=1)
+        self.author = data["From"]
+        self.to = data["To"]
+        self.cc = data["Cc"]
+        self.subject = data["Subject"]
+        self.split_body = re.split("---", data.get_payload(), maxsplit=1)
         self.commit_message = self.split_body[0]
         self.diff = self.split_body[1]
 
+
 class PatchSeries:
     def __init__(self, filepath):
         with MboxReader(filepath) as mbox:
@@ -78,8 +81,8 @@ class PatchSeries:
         branch, branches, valid_branches = None, [], []
 
         if fullprefix:
-            prefix = fullprefix.strip('[]')
-            branches = [ b.strip() for b in prefix.split(',')]
+            prefix = fullprefix.strip("[]")
+            branches = [b.strip() for b in prefix.split(",")]
             valid_branches = [b for b in branches if PatchSeries.valid_branch(b)]
 
         if len(valid_branches):
@@ -89,20 +92,21 @@ class PatchSeries:
         # found, then assume there was no branch tag in the subject line
         # and that the patch targets master
         if branch is not None:
-            return branch.split(']')[0]
+            return branch.split("]")[0]
         else:
             return "master"
 
     @staticmethod
     def valid_branch(branch):
-        """ Check if branch is valid name """
+        """Check if branch is valid name"""
         lbranch = branch.lower()
 
-        invalid  = lbranch.startswith('patch') or \
-                   lbranch.startswith('rfc') or \
-                   lbranch.startswith('resend') or \
-                   re.search(r'^v\d+', lbranch) or \
-                   re.search(r'^\d+/\d+', lbranch)
+        invalid = (
+            lbranch.startswith("patch")
+            or lbranch.startswith("rfc")
+            or lbranch.startswith("resend")
+            or re.search(r"^v\d+", lbranch)
+            or re.search(r"^\d+/\d+", lbranch)
+        )
 
         return not invalid
-
meta/lib/patchtest/patchtest_parser.py +65 -41

117 lines not on this page · raw message

meta/lib/patchtest/patchtest_patterns.py +55 -29

128 lines not on this page · raw message

meta/lib/patchtest/repo.py +21 -11
index 8ec8f68a0bc..89ef2c2a5a4 100644
@@ -12,10 +12,11 @@ import git
 import os
 import mbox
 
+
 class PatchTestRepo(object):
 
     # prefixes used for temporal branches/stashes
-    prefix = 'patchtest'
+    prefix = "patchtest"
 
     def __init__(self, patch, repodir, commit=None, branch=None):
         self.repodir = repodir
@@ -28,23 +29,27 @@ class PatchTestRepo(object):
         valid_patch_branch = None
         if self.patch.branch in self.repo.branches:
             valid_patch_branch = self.patch.branch
-            
+
         # Target Commit
         # Priority (top has highest priority):
         #    1. commit given at cmd line
         #    2. branch given at cmd line
         #    3. branch given at the patch
         #    3. current HEAD
-        self._commit = self._get_commitid(commit) or \
-          self._get_commitid(branch) or \
-          self._get_commitid(valid_patch_branch) or \
-          self._get_commitid('HEAD')
+        self._commit = (
+            self._get_commitid(commit)
+            or self._get_commitid(branch)
+            or self._get_commitid(valid_patch_branch)
+            or self._get_commitid("HEAD")
+        )
 
         self._workingbranch = "%s_%s" % (PatchTestRepo.prefix, os.getpid())
 
         # create working branch. Use the '-B' flag so that we just
         # check out the existing one if it's there
-        self.repo.git.execute(['git', 'checkout', '-B', self._workingbranch, self._commit])
+        self.repo.git.execute(
+            ["git", "checkout", "-B", self._workingbranch, self._commit]
+        )
 
         self._patchmerged = False
 
@@ -52,7 +57,10 @@ class PatchTestRepo(object):
         self._patchcanbemerged = True
         try:
             # Make sure to get the absolute path of the file
-            self.repo.git.execute(['git', 'apply', '--check', os.path.abspath(self.patch.path)], with_exceptions=True)
+            self.repo.git.execute(
+                ["git", "apply", "--check", os.path.abspath(self.patch.path)],
+                with_exceptions=True,
+            )
         except git.exc.GitCommandError as ce:
             self._patchcanbemerged = False
 
@@ -76,10 +84,12 @@ class PatchTestRepo(object):
 
     def merge(self):
         if self._patchcanbemerged:
-            self.repo.git.execute(['git', 'am', '--keep-cr', os.path.abspath(self.patch.path)])
+            self.repo.git.execute(
+                ["git", "am", "--keep-cr", os.path.abspath(self.patch.path)]
+            )
             self._patchmerged = True
 
     def clean(self):
-        self.repo.git.execute(['git', 'checkout', self.current_branch])
-        self.repo.git.execute(['git', 'branch', '-D', self._workingbranch])
+        self.repo.git.execute(["git", "checkout", self.current_branch])
+        self.repo.git.execute(["git", "branch", "-D", self._workingbranch])
         self._patchmerged = False
meta/lib/patchtest/selftest/selftest +69 -23

147 lines not on this page · raw message

meta/lib/patchtest/tests/base.py +49 -37

200 lines not on this page · raw message

meta/lib/patchtest/tests/test_mbox.py +104 -40

209 lines not on this page · raw message

meta/lib/patchtest/tests/test_metadata.py +61 -33

218 lines not on this page · raw message

meta/lib/patchtest/tests/test_patch.py +28 -11
index d08b8a50192..6f4799e3ead 100644
@@ -10,6 +10,7 @@ import os
 import patchtest_patterns
 import pyparsing
 
+
 class TestPatch(base.Base):
 
     @classmethod
@@ -17,7 +18,7 @@ class TestPatch(base.Base):
         cls.newpatches = []
         # get just those relevant patches: new software patches
         for patch in cls.patchset:
-            if patch.path.endswith('.patch') and patch.is_added_file:
+            if patch.path.endswith(".patch") and patch.is_added_file:
                 cls.newpatches.append(patch)
 
         cls.mark = str(patchtest_patterns.signed_off_by_prefix).strip('"')
@@ -27,21 +28,27 @@ class TestPatch(base.Base):
 
     def setUp(self):
         if self.unidiff_parse_error:
-            self.skip('Parse error %s' % self.unidiff_parse_error)
+            self.skip("Parse error %s" % self.unidiff_parse_error)
 
-        self.valid_status = ", ".join(patchtest_patterns.upstream_status_nonliteral_valid_status)
+        self.valid_status = ", ".join(
+            patchtest_patterns.upstream_status_nonliteral_valid_status
+        )
         self.standard_format = "Upstream-Status: <Valid status>"
 
         # we are just interested in series that introduce CVE patches, thus discard other
         # possibilities: modification to current CVEs, patch directly introduced into the
         # recipe, upgrades already including the CVE, etc.
-        new_cves = [p for p in self.patchset if p.path.endswith('.patch') and p.is_added_file]
+        new_cves = [
+            p for p in self.patchset if p.path.endswith(".patch") and p.is_added_file
+        ]
         if not new_cves:
-            self.skip('No new CVE patches introduced')
+            self.skip("No new CVE patches introduced")
 
     def test_upstream_status_presence_format(self):
         if not TestPatch.newpatches:
-            self.skip("There are no new software patches, no reason to test Upstream-Status presence/format")
+            self.skip(
+                "There are no new software patches, no reason to test Upstream-Status presence/format"
+            )
 
         for newpatch in TestPatch.newpatches:
             payload = newpatch.__str__()
@@ -91,7 +98,9 @@ class TestPatch(base.Base):
                             )
                     else:
                         try:
-                            patchtest_patterns.upstream_status.parseString(line.lstrip("+"))
+                            patchtest_patterns.upstream_status.parseString(
+                                line.lstrip("+")
+                            )
                         except pyparsing.ParseException as pe:
                             self.fail(
                                 "Upstream-Status is in incorrect format",
@@ -104,7 +113,10 @@ class TestPatch(base.Base):
 
     def test_signed_off_by_presence(self):
         if not TestPatch.newpatches:
-            self.skip("There are no new software patches, no reason to test %s presence" % PatchSignedOffBy.mark)
+            self.skip(
+                "There are no new software patches, no reason to test %s presence"
+                % PatchSignedOffBy.mark
+            )
 
         for newpatch in TestPatch.newpatches:
             payload = newpatch.__str__()
@@ -114,7 +126,10 @@ class TestPatch(base.Base):
                 if TestPatch.prog.search_string(payload):
                     break
             else:
-                self.fail('A patch file has been added without a Signed-off-by tag: \'%s\'' % os.path.basename(newpatch.path))
+                self.fail(
+                    "A patch file has been added without a Signed-off-by tag: '%s'"
+                    % os.path.basename(newpatch.path)
+                )
 
     def test_cve_tag_format(self):
         for commit in TestPatch.commits:
@@ -127,5 +142,7 @@ class TestPatch(base.Base):
                         tag_found = True
                         break
                 if not tag_found:
-                    self.fail('Missing or incorrectly formatted CVE tag in patch file. Correct or include the CVE tag in the patch with format: "CVE: CVE-YYYY-XXXX"',
-                              commit=commit)
+                    self.fail(
+                        'Missing or incorrectly formatted CVE tag in patch file. Correct or include the CVE tag in the patch with format: "CVE: CVE-YYYY-XXXX"',
+                        commit=commit,
+                    )
meta/lib/patchtest/tests/test_python_pylint.py +30 -15

78 lines not on this page · raw message

scripts/patchtest +74 -39

219 lines not on this page · raw message

scripts/patchtest-get-branch +33 -21

87 lines not on this page · raw message

scripts/patchtest-send-results +47 -19

114 lines not on this page · raw message

Signature · 1 line
2.39.5
#7 lore raw

Re: [OE-core][PATCH 6/6] patchtest: use black to format libraries

Quoted 17 lines · Trevor Gamblin via lists.openembedded.org

Black makes things easier to read.

---
 meta/lib/patchtest/mbox.py                    |  44 +++--- meta/lib/patchtest/patchtest_parser.py        | 106 ++++++++----- meta/lib/patchtest/patchtest_patterns.py      |  84 ++++++---- meta/lib/patchtest/repo.py                    |  32 ++-- meta/lib/patchtest/selftest/selftest          |  92 ++++++++--- meta/lib/patchtest/tests/base.py              |  86 ++++++----- meta/lib/patchtest/tests/test_mbox.py         | 144 +++++++++++++----- meta/lib/patchtest/tests/test_metadata.py     |  94 ++++++++---- meta/lib/patchtest/tests/test_patch.py        |  39 +++-- .../lib/patchtest/tests/test_python_pylint.py |  45 ++++-- scripts/patchtest                             | 113 +++++++++----- scripts/patchtest-get-branch                  |  54 ++++--- scripts/patchtest-send-results                |  66 +++++---

Quoted 1 line
 13 files changed, 660 insertions(+), 339 deletions(-)

I'm a bit nervous about this change for a few reasons. Firstly, it sets a precedent where others will want to do this on other areas of the code and I'm not sure we really want to do that.

black is quite opinionated and I don't agree with everything it is changing. Some of the code does look more readable before it made changes compared to the end result, particularly around how it is choosing to line wrap the code. Some of the changes are also just rearranging things for little gain such as changing quoting characters.

I'm therefore in two minds of this. I do want to empower people to maintain code but I don't want to end up forced into taking style changes I really don't agree with :/.

Cheers,

Richard

#8 lore raw

Re: [OE-core][PATCH 6/6] patchtest: use black to format libraries

Quoted 29 lines · Richard Purdie
Quoted 18 lines · Trevor Gamblin via lists.openembedded.org

Black makes things easier to read.

---
  meta/lib/patchtest/mbox.py                    |  44 +++---
  meta/lib/patchtest/patchtest_parser.py        | 106 ++++++++-----
  meta/lib/patchtest/patchtest_patterns.py      |  84 ++++++----
  meta/lib/patchtest/repo.py                    |  32 ++--
  meta/lib/patchtest/selftest/selftest          |  92 ++++++++---
  meta/lib/patchtest/tests/base.py              |  86 ++++++-----
  meta/lib/patchtest/tests/test_mbox.py         | 144 +++++++++++++-----
  meta/lib/patchtest/tests/test_metadata.py     |  94 ++++++++----
  meta/lib/patchtest/tests/test_patch.py        |  39 +++--
  .../lib/patchtest/tests/test_python_pylint.py |  45 ++++--
  scripts/patchtest                             | 113 +++++++++-----
  scripts/patchtest-get-branch                  |  54 ++++---
  scripts/patchtest-send-results                |  66 +++++---
  13 files changed, 660 insertions(+), 339 deletions(-)

I'm a bit nervous about this change for a few reasons. Firstly, it sets a precedent where others will want to do this on other areas of the code and I'm not sure we really want to do that.

black is quite opinionated and I don't agree with everything it is changing. Some of the code does look more readable before it made changes compared to the end result, particularly around how it is choosing to line wrap the code. Some of the changes are also just rearranging things for little gain such as changing quoting characters.

Quoted 3 lines

I'm therefore in two minds of this. I do want to empower people to maintain code but I don't want to end up forced into taking style changes I really don't agree with :/.

I agree that it may lead to a rush of reformatting efforts that aren't desired. We certainly don't have to take this patch now if you don't want to, although the more minor changes (e.g. the quotations) were actually a bigger part of the draw for me when I ran it.

On the other hand, some experience with using checkpatch.pl in the kernel has me wondering if we should be considering standardizing our formats for Python scripts and modules (over time) anyway. I have no strong preference on which formatter would be best (to be honest, I haven't even tried the others like YAPF or Ruff). Black, however, seems to be the one recommended most, and though it's opinionated it helps keep things consistent (the example above where the string quoting was sometimes single and sometimes double drove me nuts every time I looked at it).

Is this a reasonable goal for some distant release? I've CC'd Ross and Tim since they're also doing some Python work. I might bring it up at the weekly today.

- Trevor

Quoted 10 lines

Cheers,

Richard

#9 lore raw

Re: [OE-core][PATCH 6/6] patchtest: use black to format libraries

Quoted 50 lines · Trevor Gamblin
Quoted 29 lines · Richard Purdie
Quoted 17 lines · Trevor Gamblin via lists.openembedded.org

Black makes things easier to read.

---
  meta/lib/patchtest/mbox.py                    |  44 +++--- meta/lib/patchtest/patchtest_parser.py        | 106 ++++++++----- meta/lib/patchtest/patchtest_patterns.py      |  84 ++++++---- meta/lib/patchtest/repo.py                    |  32 ++-- meta/lib/patchtest/selftest/selftest          |  92 ++++++++--- meta/lib/patchtest/tests/base.py              |  86 ++++++----- meta/lib/patchtest/tests/test_mbox.py         | 144 +++++++++++++----- meta/lib/patchtest/tests/test_metadata.py     |  94 ++++++++---- meta/lib/patchtest/tests/test_patch.py        |  39 +++-- .../lib/patchtest/tests/test_python_pylint.py |  45 ++++-- scripts/patchtest                             | 113 +++++++++----- scripts/patchtest-get-branch                  |  54 ++++--- scripts/patchtest-send-results                |  66 +++++---

Quoted 1 line
  13 files changed, 660 insertions(+), 339 deletions(-)

I'm a bit nervous about this change for a few reasons. Firstly, it sets a precedent where others will want to do this on other areas of the code and I'm not sure we really want to do that.

black is quite opinionated and I don't agree with everything it is changing. Some of the code does look more readable before it made changes compared to the end result, particularly around how it is choosing to line wrap the code. Some of the changes are also just rearranging things for little gain such as changing quoting characters.

Quoted 3 lines

I'm therefore in two minds of this. I do want to empower people to maintain code but I don't want to end up forced into taking style changes I really don't agree with :/.

I agree that it may lead to a rush of reformatting efforts that aren't desired. We certainly don't have to take this patch now if you don't want to, although the more minor changes (e.g. the quotations) were actually a bigger part of the draw for me when I ran it.

On the other hand, some experience with using checkpatch.pl in the kernel has me wondering if we should be considering standardizing our formats for Python scripts and modules (over time) anyway. I have no strong preference on which formatter would be best (to be honest, I haven't even tried the others like YAPF or Ruff). Black, however, seems to be the one recommended most, and though it's opinionated it helps keep things consistent (the example above where the string quoting was sometimes single and sometimes double drove me nuts every time I looked at it).

Quoted 3 lines

Is this a reasonable goal for some distant release? I've CC'd Ross and Tim since they're also doing some Python work. I might bring it up at the weekly today.

Seemingly simple formatting changes have been some of the more contentious issues in the past. The churn such patches introduce make history difficult to read and make LTS maintanenace hard as patches become hard to backport. I've "lived" through the discussion multiple times in one format or another and I'm still not convinced that adopting hard "rules" around format X or Y is a great idea.

We have been adopting a rough standardisation of things slowly over time as code gets updated but it doesn't extend to the quotes or line wrapping as there were other bigger problems. I'm not against doing that as we update code but I'm not sure I'm convinced about block formatting changes like this patch.

If there was a specific issue like the quoting, I'd in many ways prefer to fix that in a specific patch rather than have multiple formatting changes all mixed together. Our metadata quoting really doesn't help things there :/. Different people are triggered by different issues, I know personally quoting bothers much much less that function parameter white spacing.

I worry this is a topic where there is no right answer too :/

Cheers,

Richard

#10 lore raw

Re: [OE-core][PATCH 6/6] patchtest: use black to format libraries

Quoted 65 lines · Richard Purdie
Quoted 48 lines · Trevor Gamblin
Quoted 29 lines · Richard Purdie
Quoted 18 lines · Trevor Gamblin via lists.openembedded.org

Black makes things easier to read.

---
   meta/lib/patchtest/mbox.py                    |  44 +++---
   meta/lib/patchtest/patchtest_parser.py        | 106 ++++++++-----
   meta/lib/patchtest/patchtest_patterns.py      |  84 ++++++----
   meta/lib/patchtest/repo.py                    |  32 ++--
   meta/lib/patchtest/selftest/selftest          |  92 ++++++++---
   meta/lib/patchtest/tests/base.py              |  86 ++++++-----
   meta/lib/patchtest/tests/test_mbox.py         | 144 +++++++++++++-----
   meta/lib/patchtest/tests/test_metadata.py     |  94 ++++++++----
   meta/lib/patchtest/tests/test_patch.py        |  39 +++--
   .../lib/patchtest/tests/test_python_pylint.py |  45 ++++--
   scripts/patchtest                             | 113 +++++++++-----
   scripts/patchtest-get-branch                  |  54 ++++---
   scripts/patchtest-send-results                |  66 +++++---
   13 files changed, 660 insertions(+), 339 deletions(-)

I'm a bit nervous about this change for a few reasons. Firstly, it sets a precedent where others will want to do this on other areas of the code and I'm not sure we really want to do that.

black is quite opinionated and I don't agree with everything it is changing. Some of the code does look more readable before it made changes compared to the end result, particularly around how it is choosing to line wrap the code. Some of the changes are also just rearranging things for little gain such as changing quoting characters.

Quoted 3 lines

I'm therefore in two minds of this. I do want to empower people to maintain code but I don't want to end up forced into taking style changes I really don't agree with :/.

I agree that it may lead to a rush of reformatting efforts that aren't desired. We certainly don't have to take this patch now if you don't want to, although the more minor changes (e.g. the quotations) were actually a bigger part of the draw for me when I ran it.

On the other hand, some experience with using checkpatch.pl in the kernel has me wondering if we should be considering standardizing our formats for Python scripts and modules (over time) anyway. I have no strong preference on which formatter would be best (to be honest, I haven't even tried the others like YAPF or Ruff). Black, however, seems to be the one recommended most, and though it's opinionated it helps keep things consistent (the example above where the string quoting was sometimes single and sometimes double drove me nuts every time I looked at it).

Quoted 3 lines

Is this a reasonable goal for some distant release? I've CC'd Ross and Tim since they're also doing some Python work. I might bring it up at the weekly today.

Seemingly simple formatting changes have been some of the more contentious issues in the past. The churn such patches introduce make history difficult to read and make LTS maintanenace hard as patches become hard to backport. I've "lived" through the discussion multiple times in one format or another and I'm still not convinced that adopting hard "rules" around format X or Y is a great idea.

We have been adopting a rough standardisation of things slowly over time as code gets updated but it doesn't extend to the quotes or line wrapping as there were other bigger problems. I'm not against doing that as we update code but I'm not sure I'm convinced about block formatting changes like this patch.

Quoted 8 lines

If there was a specific issue like the quoting, I'd in many ways prefer to fix that in a specific patch rather than have multiple formatting changes all mixed together. Our metadata quoting really doesn't help things there :/. Different people are triggered by different issues, I know personally quoting bothers much much less that function parameter white spacing.

I worry this is a topic where there is no right answer too :/

Let's just drop it then, since Alex has raised an objection too. I'll submit another one to fix the quoting at some point soon.

- Trevor

Quoted 14 lines

Cheers,

Richard

#11 lore raw

Re: [OE-core][PATCH 6/6] patchtest: use black to format libraries

In reply to Trevor Gamblin
Quoted 3 lines · Trevor Gamblin via lists.openembedded.org

Is this a reasonable goal for some distant release? I've CC'd Ross and Tim since they're also doing some Python work. I might bring it up at the weekly today.

Can I raise a strong objection? I've been writing python for over 20 years, and I haven't once been in a situation where formatting would affect my ability to form a mental picture of what the code is doing. It's by far the most overrated item in various coding guidelines. As long as people stay roughly consistent with what is already there, and remember to wrap or split long lines, I utterly don't care about anything else, and feel it's a waste of time to enforce a particular style.

Alex