]> rtime.felk.cvut.cz Git - coffee/buildroot.git/blob - utils/check-package
check-package: prepare to extend to other directories
[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     "package/",
50     ]))
51 DO_NOT_CHECK_INTREE = re.compile("|".join([
52     "package/doc-asciidoc\.mk$",
53     "package/pkg-\S*\.mk$",
54     ]))
55
56
57 def get_lib_from_filename(fname):
58     if flags.intree_only:
59         if DO_CHECK_INTREE.match(fname) is None:
60             return None
61         if DO_NOT_CHECK_INTREE.match(fname):
62             return None
63     if CONFIG_IN_FILENAME.search(fname):
64         return checkpackagelib.lib_config
65     if fname.endswith(".hash"):
66         return checkpackagelib.lib_hash
67     if fname.endswith(".mk"):
68         return checkpackagelib.lib_mk
69     if fname.endswith(".patch"):
70         return checkpackagelib.lib_patch
71     return None
72
73
74 def is_a_check_function(m):
75     if not inspect.isclass(m):
76         return False
77     # do not call the base class
78     if m.__name__.startswith("_"):
79         return False
80     if flags.include_list and m.__name__ not in flags.include_list:
81         return False
82     if flags.exclude_list and m.__name__ in flags.exclude_list:
83         return False
84     return True
85
86
87 def print_warnings(warnings):
88     # Avoid the need to use 'return []' at the end of every check function.
89     if warnings is None:
90         return 0  # No warning generated.
91
92     for level, message in enumerate(warnings):
93         if flags.verbose >= level:
94             print(message.replace("\t", "< tab  >").rstrip())
95     return 1  # One more warning to count.
96
97
98 def check_file_using_lib(fname):
99     # Count number of warnings generated and lines processed.
100     nwarnings = 0
101     nlines = 0
102
103     lib = get_lib_from_filename(fname)
104     if not lib:
105         if flags.verbose >= VERBOSE_LEVEL_TO_SHOW_IGNORED_FILES:
106             print("{}: ignored".format(fname))
107         return nwarnings, nlines
108     classes = inspect.getmembers(lib, is_a_check_function)
109
110     if flags.dry_run:
111         functions_to_run = [c[0] for c in classes]
112         print("{}: would run: {}".format(fname, functions_to_run))
113         return nwarnings, nlines
114
115     objects = [c[1](fname, flags.manual_url) for c in classes]
116
117     for cf in objects:
118         nwarnings += print_warnings(cf.before())
119     for lineno, text in enumerate(open(fname, "r").readlines()):
120         nlines += 1
121         for cf in objects:
122             nwarnings += print_warnings(cf.check_line(lineno + 1, text))
123     for cf in objects:
124         nwarnings += print_warnings(cf.after())
125
126     return nwarnings, nlines
127
128
129 def __main__():
130     global flags
131     flags = parse_args()
132
133     if flags.intree_only:
134         # change all paths received to be relative to the base dir
135         base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
136         files_to_check = [os.path.relpath(os.path.abspath(f), base_dir) for f in flags.files]
137         # move current dir so the script find the files
138         os.chdir(base_dir)
139     else:
140         files_to_check = flags.files
141
142     if len(files_to_check) == 0:
143         print("No files to check style")
144         sys.exit(1)
145
146     # Accumulate number of warnings generated and lines processed.
147     total_warnings = 0
148     total_lines = 0
149
150     for fname in files_to_check:
151         nwarnings, nlines = check_file_using_lib(fname)
152         total_warnings += nwarnings
153         total_lines += nlines
154
155     # The warning messages are printed to stdout and can be post-processed
156     # (e.g. counted by 'wc'), so for stats use stderr. Wait all warnings are
157     # printed, for the case there are many of them, before printing stats.
158     sys.stdout.flush()
159     print("{} lines processed".format(total_lines), file=sys.stderr)
160     print("{} warnings generated".format(total_warnings), file=sys.stderr)
161
162     if total_warnings > 0:
163         sys.exit(1)
164
165
166 __main__()