1#!/usr/bin/env python 2# 3# Copyright 2009, Alexandre Deckner, alex@zappotek.com 4# Distributed under the terms of the MIT License. 5# 6import re, sys, os 7from utils import * 8 9 10def processMatches(matches, name, text, highlights): 11 for match in matches: 12 printMatch(name, match, text) 13 highlights.append((match.start(), match.end(), name)) 14 15 16def run(fileSet, rules, outputFileName): 17 openHtml(fileSet, outputFileName) 18 19 for fileName in fileSet: 20 print "\nChecking " + fileName + ":" 21 file = open(fileName, 'r') 22 text = file.read() 23 24 highlights = [] 25 26 for name, regexp in rules.items(): 27 processMatches(regexp.finditer(text), name, text, highlights) 28 29 highlights.sort() 30 highlights = checkHighlights(highlights) 31 32 file.close() 33 34 renderHtml(text, highlights, fileName, outputFileName) 35 36 closeHtml(outputFileName) 37 38 39def visit(result, dir, names): 40 extensions = [".cpp", ".h"] 41 names.remove(".git") 42 for name in names: 43 path = os.path.join(dir, name) 44 if os.path.isfile(path) and os.path.splitext(name)[1] in extensions: 45 print "adding", path 46 result.append(path) 47 48 49cppRules = {} 50cppRules["Line over 80 char"] = re.compile('[^\n]{81,}') 51cppRules["Spaces instead of tabs"] = re.compile(' ') 52cppRules["Missing space after control statement"] \ 53 = re.compile('(for|if|while|switch)\(') 54cppRules["Missing space at comment start"] = re.compile('//\w') 55cppRules["Missing space after operator"] \ 56 = re.compile('\w(==|[,=>/+\-*;\|])\w') 57cppRules["Operator at line end"] = re.compile('([*=/+\-\|\&\?]|\&&|\|\|)(?=\n)') 58cppRules["Missing space"] = re.compile('\){') 59cppRules["Mixed tabs/spaces"] = re.compile('( \t]|\t )+') 60cppRules["Malformed else"] = re.compile('}[ \t]*\n[ \t]*else') 61cppRules["Lines between functions > 2"] \ 62 = re.compile('(?<=\n})([ \t]*\n){3,}(?=\n)') 63cppRules["Lines between functions < 2"] \ 64 = re.compile('(?<=\n})([ \t]*\n){0,2}(?=.)') 65cppRules["Windows Line Ending"] = re.compile('\r') 66cppRules["Bad pointer/reference style"] \ 67 = re.compile('(?<=\w) [*&](?=(\w|[,\)]))') 68 69# TODO: ignore some rules in comments 70#cppRules["-Comment 1"] = re.compile('[^/]/\*(.|[\r\n])*?\*/') 71#cppRules["-Comment 2"] = re.compile('(//)[^\n]*') 72 73 74if len(sys.argv) >= 2 and sys.argv[1] != "--help": 75 files = [] 76 for arg in sys.argv[1:]: 77 if os.path.isfile(arg): 78 files.append(arg) 79 else: 80 os.path.walk(arg, visit, files) 81 run(files, cppRules, "styleviolations.html") 82else: 83 print "Usage: python checkstyle.py file.cpp [file2.cpp] [directory]\n" 84 print "Checks c++ source files against the Haiku Coding Guidelines." 85 print "Outputs an html report in the styleviolations.html file.\n" 86