summaryrefslogtreecommitdiff
path: root/utils
diff options
context:
space:
mode:
authorLaurent Pinchart <laurent.pinchart@ideasonboard.com>2019-06-25 20:03:13 +0300
committerLaurent Pinchart <laurent.pinchart@ideasonboard.com>2019-07-01 02:24:21 +0300
commitbc6b758c71a806039d2f5c4a34a72cc369228cc0 (patch)
tree6fa4a28e092dee07b1e3e1df99633610a2b25a13 /utils
parent0116a940ba0232b625ab84bb90bb1bc3ddd47658 (diff)
utils: checkstyle.py: Refactor formatters and checkers support
Introduce two new base classes for the code formatters and style checkers, with an auto-registration mechanism that automatically uses all derived classes. This will allow easier addition of new formatters and checkers. Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Diffstat (limited to 'utils')
-rwxr-xr-xutils/checkstyle.py208
1 files changed, 152 insertions, 56 deletions
diff --git a/utils/checkstyle.py b/utils/checkstyle.py
index 9abd2687..5c8bde6e 100755
--- a/utils/checkstyle.py
+++ b/utils/checkstyle.py
@@ -15,6 +15,8 @@
import argparse
import difflib
+import fnmatch
+import os.path
import re
import shutil
import subprocess
@@ -39,12 +41,6 @@ dependencies = {
'git': True,
}
-source_extensions = (
- '.c',
- '.cpp',
- '.h'
-)
-
# ------------------------------------------------------------------------------
# Colour terminal handling
#
@@ -195,44 +191,61 @@ def parse_diff(diff):
# ------------------------------------------------------------------------------
-# Code reformatting
+# Style Checkers
#
-def formatter_astyle(filename, data):
- ret = subprocess.run(['astyle', *astyle_options],
- input=data.encode('utf-8'), stdout=subprocess.PIPE)
- return ret.stdout.decode('utf-8')
-
-
-def formatter_clang_format(filename, data):
- ret = subprocess.run(['clang-format', '-style=file',
- '-assume-filename=' + filename],
- input=data.encode('utf-8'), stdout=subprocess.PIPE)
- return ret.stdout.decode('utf-8')
-
+_style_checkers = []
+
+class StyleCheckerRegistry(type):
+ def __new__(cls, clsname, bases, attrs):
+ newclass = super(StyleCheckerRegistry, cls).__new__(cls, clsname, bases, attrs)
+ if clsname != 'StyleChecker':
+ _style_checkers.append(newclass)
+ return newclass
+
+
+class StyleChecker(metaclass=StyleCheckerRegistry):
+ def __init__(self):
+ pass
+
+ #
+ # Class methods
+ #
+ @classmethod
+ def checkers(cls, filename):
+ for checker in _style_checkers:
+ if checker.supports(filename):
+ yield checker
+
+ @classmethod
+ def supports(cls, filename):
+ for pattern in cls.patterns:
+ if fnmatch.fnmatch(os.path.basename(filename), pattern):
+ return True
+ return False
-def formatter_strip_trailing_space(filename, data):
- lines = data.split('\n')
- for i in range(len(lines)):
- lines[i] = lines[i].rstrip() + '\n'
- return ''.join(lines)
+ @classmethod
+ def all_patterns(cls):
+ patterns = set()
+ for checker in _style_checkers:
+ patterns.update(checker.patterns)
+ return patterns
-available_formatters = {
- 'astyle': formatter_astyle,
- 'clang-format': formatter_clang_format,
- 'strip-trailing-spaces': formatter_strip_trailing_space,
-}
+class StyleIssue(object):
+ def __init__(self, line_number, line, msg):
+ self.line_number = line_number
+ self.line = line
+ self.msg = msg
-# ------------------------------------------------------------------------------
-# Style checking
-#
-class LogCategoryChecker(object):
+class LogCategoryChecker(StyleChecker):
log_regex = re.compile('\\bLOG\((Debug|Info|Warning|Error|Fatal)\)')
+ patterns = ('*.cpp',)
def __init__(self, content):
+ super().__init__()
self.__content = content
def check(self, line_numbers):
@@ -242,17 +255,101 @@ class LogCategoryChecker(object):
if not LogCategoryChecker.log_regex.search(line):
continue
- issues.append([line_number, line, 'LOG() should use categories'])
+ issues.append(StyleIssue(line_number, line, 'LOG() should use categories'))
return issues
-available_checkers = {
- 'log_category': LogCategoryChecker,
-}
+# ------------------------------------------------------------------------------
+# Formatters
+#
+
+_formatters = []
+
+class FormatterRegistry(type):
+ def __new__(cls, clsname, bases, attrs):
+ newclass = super(FormatterRegistry, cls).__new__(cls, clsname, bases, attrs)
+ if clsname != 'Formatter':
+ _formatters.append(newclass)
+ return newclass
+
+
+class Formatter(metaclass=FormatterRegistry):
+ enabled = True
+
+ def __init__(self):
+ pass
+
+ #
+ # Class methods
+ #
+ @classmethod
+ def formatters(cls, filename):
+ for formatter in _formatters:
+ if not cls.enabled:
+ continue
+ if formatter.supports(filename):
+ yield formatter
+
+ @classmethod
+ def supports(cls, filename):
+ if not cls.enabled:
+ return False
+ for pattern in cls.patterns:
+ if fnmatch.fnmatch(os.path.basename(filename), pattern):
+ return True
+ return False
+
+ @classmethod
+ def all_patterns(cls):
+ patterns = set()
+ for formatter in _formatters:
+ if not cls.enabled:
+ continue
+ patterns.update(formatter.patterns)
+
+ return patterns
+
+
+class AStyleFormatter(Formatter):
+ enabled = False
+ patterns = ('*.c', '*.cpp', '*.h')
+
+ @classmethod
+ def format(cls, filename, data):
+ ret = subprocess.run(['astyle', *astyle_options],
+ input=data.encode('utf-8'), stdout=subprocess.PIPE)
+ return ret.stdout.decode('utf-8')
+
+class CLangFormatter(Formatter):
+ enabled = False
+ patterns = ('*.c', '*.cpp', '*.h')
-def check_file(top_level, commit, filename, formatters):
+ @classmethod
+ def format(cls, filename, data):
+ ret = subprocess.run(['clang-format', '-style=file',
+ '-assume-filename=' + filename],
+ input=data.encode('utf-8'), stdout=subprocess.PIPE)
+ return ret.stdout.decode('utf-8')
+
+
+class StripTrailingSpaceFormatter(Formatter):
+ patterns = ('*.c', '*.cpp', '*.h', '*.py', 'meson.build')
+
+ @classmethod
+ def format(cls, filename, data):
+ lines = data.split('\n')
+ for i in range(len(lines)):
+ lines[i] = lines[i].rstrip() + '\n'
+ return ''.join(lines)
+
+
+# ------------------------------------------------------------------------------
+# Style checking
+#
+
+def check_file(top_level, commit, filename):
# Extract the line numbers touched by the commit.
diff = subprocess.run(['git', 'diff', '%s~..%s' % (commit, commit), '--',
'%s/%s' % (top_level, filename)],
@@ -275,9 +372,8 @@ def check_file(top_level, commit, filename, formatters):
after = after.decode('utf-8')
formatted = after
- for formatter in formatters:
- formatter = available_formatters[formatter]
- formatted = formatter(filename, formatted)
+ for formatter in Formatter.formatters(filename):
+ formatted = formatter.format(filename, formatted)
after = after.splitlines(True)
formatted = formatted.splitlines(True)
@@ -290,8 +386,8 @@ def check_file(top_level, commit, filename, formatters):
# Check for code issues not related to formatting.
issues = []
- for checker in available_checkers:
- checker = available_checkers[checker](after)
+ for checker in StyleChecker.checkers(filename):
+ checker = checker(after)
for hunk in commit_diff:
issues += checker.check(hunk.side('to').touched)
@@ -307,15 +403,15 @@ def check_file(top_level, commit, filename, formatters):
print(hunk)
if len(issues):
- issues.sort()
+ issues = sorted(issues, key=lambda i: i.line_number)
for issue in issues:
- print('%s#%u: %s' % (Colours.fg(Colours.Yellow), issue[0], issue[2]))
- print('+%s%s' % (issue[1].rstrip(), Colours.reset()))
+ print('%s#%u: %s' % (Colours.fg(Colours.Yellow), issue.line_number, issue.msg))
+ print('+%s%s' % (issue.line.rstrip(), Colours.reset()))
return len(formatted_diff) + len(issues)
-def check_style(top_level, commit, formatters):
+def check_style(top_level, commit):
# Get the commit title and list of files.
ret = subprocess.run(['git', 'show', '--pretty=oneline','--name-only', commit],
stdout=subprocess.PIPE)
@@ -328,15 +424,18 @@ def check_style(top_level, commit, formatters):
print(title)
print(separator)
- # Filter out non C/C++ files.
- files = [f for f in files if f.endswith(source_extensions)]
+ # Filter out files we have no checker for.
+ patterns = set()
+ patterns.update(StyleChecker.all_patterns())
+ patterns.update(Formatter.all_patterns())
+ files = [f for f in files if len([p for p in patterns if fnmatch.fnmatch(os.path.basename(f), p)])]
if len(files) == 0:
print("Commit doesn't touch source files, skipping")
return
issues = 0
for f in files:
- issues += check_file(top_level, commit, f, formatters)
+ issues += check_file(top_level, commit, f)
if issues == 0:
print("No style issue detected")
@@ -407,16 +506,13 @@ def main(argv):
formatter = args.formatter
else:
if dependencies['clang-format']:
- formatter = 'clang-format'
+ CLangFormatter.enabled = True
elif dependencies['astyle']:
- formatter = 'astyle'
+ AStyleFormatter.enabled = True
else:
print("No formatter found, please install clang-format or astyle")
return 1
- # Create the list of formatters to be applied.
- formatters = [formatter, 'strip-trailing-spaces']
-
# Get the top level directory to pass absolute file names to git diff
# commands, in order to support execution from subdirectories of the git
# tree.
@@ -427,7 +523,7 @@ def main(argv):
revlist = extract_revlist(args.revision_range)
for commit in revlist:
- check_style(top_level, commit, formatters)
+ check_style(top_level, commit)
print('')
return 0
n603' href='#n603'>603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (C) 2019, Raspberry Pi (Trading) Limited
#
# ctt_macbeth_locator.py - camera tuning tool Macbeth chart locator

from ctt_ransac import *
from ctt_tools import *
import warnings

"""
NOTE: some custom functions have been used here to make the code more readable.
These are defined in tools.py if they are needed for reference.
"""

"""
Some inconsistencies between packages cause runtime warnings when running
the clustering algorithm. This catches these warnings so they don't flood the
output to the console
"""
def fxn():
    warnings.warn("runtime", RuntimeWarning)

"""
Define the success message
"""
success_msg = 'Macbeth chart located successfully'

def find_macbeth(Cam, img, mac_config=(0, 0)):
    small_chart, show = mac_config
    print('Locating macbeth chart')
    Cam.log += '\nLocating macbeth chart'
    """
    catch the warnings
    """
    warnings.simplefilter("ignore")
    fxn()

    """
    Reference macbeth chart is created that will be correlated with the located
    macbeth chart guess to produce a confidence value for the match.
    """
    ref = cv2.imread(Cam.path + 'ctt_ref.pgm', flags=cv2.IMREAD_GRAYSCALE)
    ref_w = 120
    ref_h = 80
    rc1 = (0, 0)
    rc2 = (0, ref_h)
    rc3 = (ref_w, ref_h)
    rc4 = (ref_w, 0)
    ref_corns = np.array((rc1, rc2, rc3, rc4), np.float32)
    ref_data = (ref, ref_w, ref_h, ref_corns)

    """
    locate macbeth chart
    """
    cor, mac, coords, msg = get_macbeth_chart(img, ref_data)

    """
    following bits of code tries to fix common problems with simple
    techniques.
    If now or at any point the best correlation is of above 0.75, then
    nothing more is tried as this is a high enough confidence to ensure
    reliable macbeth square centre placement.
    """

    """
    brighten image 2x
    """
    if cor < 0.75:
        a = 2
        img_br = cv2.convertScaleAbs(img, alpha=a, beta=0)
        cor_b, mac_b, coords_b, msg_b = get_macbeth_chart(img_br, ref_data)
        if cor_b > cor:
            cor, mac, coords, msg = cor_b, mac_b, coords_b, msg_b

    """
    brighten image 4x
    """
    if cor < 0.75:
        a = 4
        img_br = cv2.convertScaleAbs(img, alpha=a, beta=0)
        cor_b, mac_b, coords_b, msg_b = get_macbeth_chart(img_br, ref_data)
        if cor_b > cor:
            cor, mac, coords, msg = cor_b, mac_b, coords_b, msg_b

    """
    In case macbeth chart is too small, take a selection of the image and
    attempt to locate macbeth chart within that. The scale increment is
    root 2
    """
    """
    These variables will be used to transform the found coordinates at smaller
    scales back into the original. If ii is still -1 after this section that
    means it was not successful
    """
    ii = -1
    w_best = 0
    h_best = 0
    d_best = 100
    """
    d_best records the scale of the best match. Macbeth charts are only looked
    for at one scale increment smaller than the current best match in order to avoid
    unecessarily searching for macbeth charts at small scales.
    If a macbeth chart ha already been found then set d_best to 0
    """
    if cor != 0:
        d_best = 0

    """
    scale 3/2 (approx root2)
    """
    if cor < 0.75:
        imgs = []
        """
        get size of image
        """
        shape = list(img.shape[:2])
        w, h = shape
        """
        set dimensions of the subselection and the step along each axis between
        selections
        """
        w_sel = int(2*w/3)
        h_sel = int(2*h/3)
        w_inc = int(w/6)
        h_inc = int(h/6)
        """
        for each subselection, look for a macbeth chart
        """
        for i in range(3):
            for j in range(3):
                w_s, h_s = i*w_inc, j*h_inc
                img_sel = img[w_s:w_s+w_sel, h_s:h_s+h_sel]
                cor_ij, mac_ij, coords_ij, msg_ij = get_macbeth_chart(img_sel, ref_data)
                """
                if the correlation is better than the best then record the
                scale and current subselection at which macbeth chart was
                found. Also record the coordinates, macbeth chart and message.
                """
                if cor_ij > cor:
                    cor = cor_ij
                    mac, coords, msg = mac_ij, coords_ij, msg_ij
                    ii, jj = i, j
                    w_best, h_best = w_inc, h_inc
                    d_best = 1

    """
    scale 2
    """
    if cor < 0.75:
        imgs = []
        shape = list(img.shape[:2])
        w, h = shape
        w_sel = int(w/2)
        h_sel = int(h/2)
        w_inc = int(w/8)
        h_inc = int(h/8)
        for i in range(5):
            for j in range(5):
                w_s, h_s = i*w_inc, j*h_inc
                img_sel = img[w_s:w_s+w_sel, h_s:h_s+h_sel]
                cor_ij, mac_ij, coords_ij, msg_ij = get_macbeth_chart(img_sel, ref_data)
                if cor_ij > cor:
                    cor = cor_ij
                    mac, coords, msg = mac_ij, coords_ij, msg_ij
                    ii, jj = i, j
                    w_best, h_best = w_inc, h_inc
                    d_best = 2

    """
    The following code checks for macbeth charts at even smaller scales. This
    slows the code down significantly and has therefore been omitted by default,
    however it is not unusably slow so might be useful if the macbeth chart
    is too small to be picked up to by the current subselections.
    Use this for macbeth charts with side lengths around 1/5 image dimensions
    (and smaller...?) it is, however, recommended that macbeth charts take up as
    large as possible a proportion of the image.
    """

    if small_chart:

        if cor < 0.75 and d_best > 1:
            imgs = []
            shape = list(img.shape[:2])
            w, h = shape
            w_sel = int(w/3)
            h_sel = int(h/3)
            w_inc = int(w/12)
            h_inc = int(h/12)
            for i in range(9):
                for j in range(9):
                    w_s, h_s = i*w_inc, j*h_inc
                    img_sel = img[w_s:w_s+w_sel, h_s:h_s+h_sel]
                    cor_ij, mac_ij, coords_ij, msg_ij = get_macbeth_chart(img_sel, ref_data)
                    if cor_ij > cor:
                        cor = cor_ij
                        mac, coords, msg = mac_ij, coords_ij, msg_ij
                        ii, jj = i, j
                        w_best, h_best = w_inc, h_inc
                        d_best = 3

        if cor < 0.75 and d_best > 2:
            imgs = []
            shape = list(img.shape[:2])
            w, h = shape
            w_sel = int(w/4)
            h_sel = int(h/4)
            w_inc = int(w/16)
            h_inc = int(h/16)
            for i in range(13):
                for j in range(13):
                    w_s, h_s = i*w_inc, j*h_inc
                    img_sel = img[w_s:w_s+w_sel, h_s:h_s+h_sel]
                    cor_ij, mac_ij, coords_ij, msg_ij = get_macbeth_chart(img_sel, ref_data)
                    if cor_ij > cor:
                        cor = cor_ij
                        mac, coords, msg = mac_ij, coords_ij, msg_ij
                        ii, jj = i, j
                        w_best, h_best = w_inc, h_inc

    """
    Transform coordinates from subselection to original image
    """
    if ii != -1:
        for a in range(len(coords)):
            for b in range(len(coords[a][0])):
                coords[a][0][b][1] += ii*w_best
                coords[a][0][b][0] += jj*h_best

    """
    initialise coords_fit variable
    """
    coords_fit = None
    # print('correlation: {}'.format(cor))
    """
    print error or success message
    """
    print(msg)
    Cam.log += '\n' + msg
    if msg == success_msg:
        coords_fit = coords
        Cam.log += '\nMacbeth chart vertices:\n'
        Cam.log += '{}'.format(2*np.round(coords_fit[0][0]), 0)
        """