metrics.py 1.92 KB
Newer Older
1
2
#!/usr/bin/python

3
4
5
6
# Implementation of various source code metrics.
# These are currently ad-hoc string operations and regexps.
# We might want to use a proper static analysis library in the future, if we want to get more advanced metrics.

7
8
import re

9
def get_file_len(f):
10
    """Get file length of file"""
11
    i = -1
12
13
14
15
    for i, l in enumerate(f):
        pass
    return i + 1

16
17
18
19
def get_include_count(f):
    """Get number of #include statements in the file"""
    include_count = 0
    for line in f:
20
        if re.match(r'\s*#\s*include', line):
21
22
23
            include_count += 1
    return include_count

24
def get_function_lines(f):
25
26
27
28
    """
    Return iterator which iterates over functions and returns (function name, function lines)
    """

29
30
    # Skip lines that look like they are defining functions with these
    # names: they aren't real function definitions.
31
32
33
    REGEXP_CONFUSE_TERMS = {"MOCK_IMPL", "MOCK_DECL", "HANDLE_DECL",
                            "ENABLE_GCC_WARNINGS", "ENABLE_GCC_WARNING",
                            "DUMMY_TYPECHECK_INSTANCE",
34
                            "DISABLE_GCC_WARNING", "DISABLE_GCC_WARNINGS"}
35

36
    in_function = False
37
    found_openbrace = False
38
39
40
41
42
43
    for lineno, line in enumerate(f):
        if not in_function:
            # find the start of a function
            m = re.match(r'^([a-zA-Z_][a-zA-Z_0-9]*),?\(', line)
            if m:
                func_name = m.group(1)
44
45
                if func_name in REGEXP_CONFUSE_TERMS:
                    continue
46
47
                func_start = lineno
                in_function = True
48
49
50
        elif not found_openbrace and line.startswith("{"):
            found_openbrace = True
            func_start = lineno
51
        else:
52
            # Find the end of a function
53
            if line.startswith("}"):
54
                n_lines = lineno - func_start + 1
55
                in_function = False
56
                found_openbrace = False
57
                yield (func_name, n_lines)