]> rtime.felk.cvut.cz Git - coffee/buildroot.git/blob - utils/check-package
check-package: enable for arch/ and system/
[coffee/buildroot.git] / utils / check-package
1 #!/usr/bin/env python
2 # See utils/checkpackagelib/readme.txt before editing this file.
3
4 from __future__ import print_function
5 import argparse
6 import inspect
7 import os
8 import re
9 import sys
10
11 import checkpackagelib.lib_config
12 import checkpackagelib.lib_hash
13 import checkpackagelib.lib_mk
14 import checkpackagelib.lib_patch
15
16 VERBOSE_LEVEL_TO_SHOW_IGNORED_FILES = 3
17 flags = None  # Command line arguments.
18
19
20 def parse_args():
21     parser = argparse.ArgumentParser()
22
23     # Do not use argparse.FileType("r") here because only files with known
24     # format will be open based on the filename.
25     parser.add_argument("files", metavar="F", type=str, nargs="*",
26                         help="list of files")
27
28     parser.add_argument("--br2-external", "-b", dest='intree_only', action="store_false",
29                         help="do not apply the pathname filters used for intree files")
30
31     parser.add_argument("--manual-url", action="store",
32                         default="http://nightly.buildroot.org/",
33                         help="default: %(default)s")
34     parser.add_argument("--verbose", "-v", action="count", default=0)
35
36     # Now the debug options in the order they are processed.
37     parser.add_argument("--include-only", dest="include_list", action="append",
38                         help="run only the specified functions (debug)")
39     parser.add_argument("--exclude", dest="exclude_list", action="append",
40                         help="do not run the specified functions (debug)")
41     parser.add_argument("--dry-run", action="store_true", help="print the "
42                         "functions that would be called for each file (debug)")
43
44     return parser.parse_args()
45
46
47 CONFIG_IN_FILENAME = re.compile("/Config\.\S*$")
48 DO_CHECK_INTREE = re.compile("|".join([
49     "arch/",
50     "package/",
51     "system/",
52     ]))
53 DO_NOT_CHECK_INTREE = re.compile("|".join([
54     "package/doc-asciidoc\.mk$",
55     "package/pkg-\S*\.mk$",
56     ]))
57
58
59 def get_lib_from_filename(fname):
60     if flags.intree_only:
61         if DO_CHECK_INTREE.match(fname) is None:
62             return None
63         if DO_NOT_CHECK_INTREE.match(fname):
64             return None
65     if CONFIG_IN_FILENAME.search(fname):
66         return checkpackagelib.lib_config
67     if fname.endswith(".hash"):
68         return checkpackagelib.lib_hash
69     if fname.endswith(".mk"):
70         return checkpackagelib.lib_mk
71     if fname.endswith(".patch"):
72         return checkpackagelib.lib_patch
73     return None
74
75
76 def is_a_check_function(m):
77     if not inspect.isclass(m):
78         return False
79     # do not call the base class
80     if m.__name__.startswith("_"):
81         return False
82     if flags.include_list and m.__name__ not in flags.include_list:
83         return False
84     if flags.exclude_list and m.__name__ in flags.exclude_list:
85         return False
86     return True
87
88
89 def print_warnings(warnings):
90     # Avoid the need to use 'return []' at the end of every check function.
91     if warnings is None:
92         return 0  # No warning generated.
93
94     for level, message in enumerate(warnings):
95         if flags.verbose >= level:
96             print(message.replace("\t", "< tab  >").rstrip())
97     return 1  # One more warning to count.
98
99
100 def check_file_using_lib(fname):
101     # Count number of warnings generated and lines processed.
102     nwarnings = 0
103     nlines = 0
104
105     lib = get_lib_from_filename(fname)
106     if not lib:
107         if flags.verbose >= VERBOSE_LEVEL_TO_SHOW_IGNORED_FILES:
108             print("{}: ignored".format(fname))
109         return nwarnings, nlines
110     classes = inspect.getmembers(lib, is_a_check_function)
111
112     if flags.dry_run:
113         functions_to_run = [c[0] for c in classes]
114         print("{}: would run: {}".format(fname, functions_to_run))
115         return nwarnings, nlines
116
117     objects = [c[1](fname, flags.manual_url) for c in classes]
118
119     for cf in objects:
120         nwarnings += print_warnings(cf.before())
121     for lineno, text in enumerate(open(fname, "r").readlines()):
122         nlines += 1
123         for cf in objects:
124             nwarnings += print_warnings(cf.check_line(lineno + 1, text))
125     for cf in objects:
126         nwarnings += print_warnings(cf.after())
127
128     return nwarnings, nlines
129
130
131 def __main__():
132     global flags
133     flags = parse_args()
134
135     if flags.intree_only:
136         # change all paths received to be relative to the base dir
137         base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
138         files_to_check = [os.path.relpath(os.path.abspath(f), base_dir) for f in flags.files]
139         # move current dir so the script find the files
140         os.chdir(base_dir)
141     else:
142         files_to_check = flags.files
143
144     if len(files_to_check) == 0:
145         print("No files to check style")
146         sys.exit(1)
147
148     # Accumulate number of warnings generated and lines processed.
149     total_warnings = 0
150     total_lines = 0
151
152     for fname in files_to_check:
153         nwarnings, nlines = check_file_using_lib(fname)
154         total_warnings += nwarnings
155         total_lines += nlines
156
157     # The warning messages are printed to stdout and can be post-processed
158     # (e.g. counted by 'wc'), so for stats use stderr. Wait all warnings are
159     # printed, for the case there are many of them, before printing stats.
160     sys.stdout.flush()
161     print("{} lines processed".format(total_lines), file=sys.stderr)
162     print("{} warnings generated".format(total_warnings), file=sys.stderr)
163
164     if total_warnings > 0:
165         sys.exit(1)
166
167
168 __main__()