(Very) basic script for pre-review style checking

Elvis Stansvik elvstone at gmail.com
Fri Nov 1 19:44:35 GMT 2013


Here it goes:

#!/usr/bin/env python

import re
import fileinput
import unidiff

# Add new checks as (<regex>, <message>) tuples.
checks = {
    (re.compile(r'.* \).*'),
        "Excessive space before ')'"),
    (re.compile(r'.*[A-Za-z_][A-Za-z0-9_]*\s*\( .*'),
        "Excessive space after '('"),
    (re.compile(r'\s+{\s*'),
        "Opening '{' on separate line"),
    (re.compile(r'.*,(?!\s|$).*', re.MULTILINE),
        "Missing space after ','"),
    (re.compile(r'.*for \(.*;[^\s].*'),
        "Missing space after ';'"),
    (re.compile(r'.*(?:\+=|-=|==|!=)[^\s].*'),
        "Missing space after operator"),
    (re.compile(r'.*[^\s](?:\+=|-=|==|!=).*'),
        "Missing space before operator"),
    (re.compile(r'.*if\(.*'),
        "Missing space after \"if\""),
    (re.compile(r'.*for\(.*'),
        "Missing space after \"for\""),
    (re.compile(r'.*while\(.*'),
        "Missing space after \"while\"")
}

for patch in unidiff.parser.parse_unidiff(fileinput.input()):
    suffix = patch.path.split('.')[-1]
    if suffix != 'cpp' and suffix != 'cc' and suffix != 'h':
        continue
    for hunk in patch:
        for i, line in enumerate(hunk.target_lines):
            if hunk.target_types[i] != unidiff.parser.LINE_TYPE_ADD:
                continue
            line_nr = hunk.target_start + i
            for (regex, message) in checks:
                if regex.match(line):
                    print("%s:%i: %s" % (patch.path, line_nr, message))

It needs python-unidiff [1] for diff parsing.

Example usage:

$ curl -s https://git.reviewboard.kde.org/r/109907/diff/raw/ | difflint
libs/main/KoFileDialogHelper.cpp:35: Excessive space before ')'
libs/main/KoFileDialogHelper.cpp:35: Excessive space after '('
libs/main/KoFileDialogHelper.cpp:36: Missing space after "if"
libs/main/KoFileDialogHelper.cpp:61: Missing space after "if"
libs/main/KoMainWindow.cpp:848: Excessive space before ')'
libs/main/KoMainWindow.cpp:860: Excessive space before ')'
libs/main/KoMainWindow.cpp:980: Missing space before operator
libs/main/KoMainWindow.cpp:980: Excessive space after '('
libs/main/KoMainWindow.cpp:1082: Excessive space before ')'
libs/main/KoMainWindow.cpp:1667: Excessive space before ')'
libs/main/KoMainWindow.cpp:1667: Excessive space after '('
libs/main/KoMainWindow.cpp:1731: Excessive space before ')'
libs/main/KoMainWindow.cpp:1731: Excessive space after '('

It makes a few false positives, but mostly points to real style breaks.
Perhaps it can be of some small use to reviewers/reviewees.

Cheers,
Elvis

[1]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.kde.org/pipermail/calligra-devel/attachments/20131101/4ec0e2e1/attachment.htm>


More information about the calligra-devel mailing list