blob: 4111746b51103270430c9b1fd464fa52bc578ce8 [file] [log] [blame]
Valentin Rothberg7c5227a2016-08-28 08:51:28 +02001#!/usr/bin/env python3
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02002
Valentin Rothbergb1a3f242015-03-16 12:16:14 +01003"""Find Kconfig symbols that are referenced but not defined."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02004
Valentin Rothbergf175ba12016-08-27 10:59:07 +02005# (c) 2014-2016 Valentin Rothberg <valentinrothberg@gmail.com>
Valentin Rothbergcc641d552014-11-08 20:56:35 +01006# (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02007#
Valentin Rothbergcc641d552014-11-08 20:56:35 +01008# Licensed under the terms of the GNU GPL License version 2
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02009
10
Valentin Rothberg14390e32016-08-28 08:51:29 +020011import argparse
Valentin Rothberg1b2c8412015-11-26 14:17:15 +010012import difflib
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020013import os
14import re
Valentin Rothberge2042a82015-10-15 10:37:47 +020015import signal
Valentin Rothbergf175ba12016-08-27 10:59:07 +020016import subprocess
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010017import sys
Valentin Rothberge2042a82015-10-15 10:37:47 +020018from multiprocessing import Pool, cpu_count
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020019
Valentin Rothbergcc641d552014-11-08 20:56:35 +010020
21# regex expressions
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020022OPERATORS = r"&|\(|\)|\||\!"
Valentin Rothbergcc641d552014-11-08 20:56:35 +010023FEATURE = r"(?:\w*[A-Z0-9]\w*){2,}"
24DEF = r"^\s*(?:menu){,1}config\s+(" + FEATURE + r")\s*"
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020025EXPR = r"(?:" + OPERATORS + r"|\s|" + FEATURE + r")+"
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +020026DEFAULT = r"default\s+.*?(?:if\s.+){,1}"
27STMT = r"^\s*(?:if|select|depends\s+on|(?:" + DEFAULT + r"))\s+" + EXPR
Valentin Rothbergcc641d552014-11-08 20:56:35 +010028SOURCE_FEATURE = r"(?:\W|\b)+[D]{,1}CONFIG_(" + FEATURE + r")"
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020029
Valentin Rothbergcc641d552014-11-08 20:56:35 +010030# regex objects
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020031REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
Valentin Rothberge2042a82015-10-15 10:37:47 +020032REGEX_FEATURE = re.compile(r'(?!\B)' + FEATURE + r'(?!\B)')
Valentin Rothbergcc641d552014-11-08 20:56:35 +010033REGEX_SOURCE_FEATURE = re.compile(SOURCE_FEATURE)
34REGEX_KCONFIG_DEF = re.compile(DEF)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020035REGEX_KCONFIG_EXPR = re.compile(EXPR)
36REGEX_KCONFIG_STMT = re.compile(STMT)
37REGEX_KCONFIG_HELP = re.compile(r"^\s+(help|---help---)\s*$")
38REGEX_FILTER_FEATURES = re.compile(r"[A-Za-z0-9]$")
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +020039REGEX_NUMERIC = re.compile(r"0[xX][0-9a-fA-F]+|[0-9]+")
Valentin Rothberge2042a82015-10-15 10:37:47 +020040REGEX_QUOTES = re.compile("(\"(.*?)\")")
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020041
42
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010043def parse_options():
44 """The user interface of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +020045 usage = "Run this tool to detect Kconfig symbols that are referenced but " \
46 "not defined in Kconfig. If no option is specified, " \
47 "checkkconfigsymbols defaults to check your current tree. " \
48 "Please note that specifying commits will 'git reset --hard\' " \
49 "your current tree! You may save uncommitted changes to avoid " \
50 "losing data."
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010051
Valentin Rothberg14390e32016-08-28 08:51:29 +020052 parser = argparse.ArgumentParser(description=usage)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010053
Valentin Rothberg14390e32016-08-28 08:51:29 +020054 parser.add_argument('-c', '--commit', dest='commit', action='store',
55 default="",
56 help="check if the specified commit (hash) introduces "
57 "undefined Kconfig symbols")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010058
Valentin Rothberg14390e32016-08-28 08:51:29 +020059 parser.add_argument('-d', '--diff', dest='diff', action='store',
60 default="",
61 help="diff undefined symbols between two commits "
62 "(e.g., -d commmit1..commit2)")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010063
Valentin Rothberg14390e32016-08-28 08:51:29 +020064 parser.add_argument('-f', '--find', dest='find', action='store_true',
65 default=False,
66 help="find and show commits that may cause symbols to be "
67 "missing (required to run with --diff)")
Valentin Rothberga42fa922015-06-01 16:00:19 +020068
Valentin Rothberg14390e32016-08-28 08:51:29 +020069 parser.add_argument('-i', '--ignore', dest='ignore', action='store',
70 default="",
71 help="ignore files matching this Python regex "
72 "(e.g., -i '.*defconfig')")
Valentin Rothbergcf132e42015-04-29 16:58:27 +020073
Valentin Rothberg14390e32016-08-28 08:51:29 +020074 parser.add_argument('-s', '--sim', dest='sim', action='store', default="",
75 help="print a list of max. 10 string-similar symbols")
Valentin Rothberg1b2c8412015-11-26 14:17:15 +010076
Valentin Rothberg14390e32016-08-28 08:51:29 +020077 parser.add_argument('--force', dest='force', action='store_true',
78 default=False,
79 help="reset current Git tree even when it's dirty")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010080
Valentin Rothberg14390e32016-08-28 08:51:29 +020081 parser.add_argument('--no-color', dest='color', action='store_false',
82 default=True,
83 help="don't print colored output (default when not "
84 "outputting to a terminal)")
Andrew Donnellan4c73c082016-07-05 17:47:37 +100085
Valentin Rothberg14390e32016-08-28 08:51:29 +020086 args = parser.parse_args()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010087
Valentin Rothberg14390e32016-08-28 08:51:29 +020088 if args.commit and args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010089 sys.exit("Please specify only one option at once.")
90
Valentin Rothberg14390e32016-08-28 08:51:29 +020091 if args.diff and not re.match(r"^[\w\-\.]+\.\.[\w\-\.]+$", args.diff):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010092 sys.exit("Please specify valid input in the following format: "
Andreas Ziegler38cbfe42016-03-31 09:24:29 +020093 "\'commit1..commit2\'")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010094
Valentin Rothberg14390e32016-08-28 08:51:29 +020095 if args.commit or args.diff:
96 if not args.force and tree_is_dirty():
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010097 sys.exit("The current Git tree is dirty (see 'git status'). "
98 "Running this script may\ndelete important data since it "
99 "calls 'git reset --hard' for some performance\nreasons. "
100 " Please run this script in a clean Git tree or pass "
101 "'--force' if you\nwant to ignore this warning and "
102 "continue.")
103
Valentin Rothberg14390e32016-08-28 08:51:29 +0200104 if args.commit:
105 args.find = False
Valentin Rothberga42fa922015-06-01 16:00:19 +0200106
Valentin Rothberg14390e32016-08-28 08:51:29 +0200107 if args.ignore:
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200108 try:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200109 re.match(args.ignore, "this/is/just/a/test.c")
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200110 except:
111 sys.exit("Please specify a valid Python regex.")
112
Valentin Rothberg14390e32016-08-28 08:51:29 +0200113 return args
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100114
115
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200116def main():
117 """Main function of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +0200118 args = parse_options()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100119
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200120 global COLOR
121 COLOR = args.color and sys.stdout.isatty()
Andrew Donnellan4c73c082016-07-05 17:47:37 +1000122
Valentin Rothberg14390e32016-08-28 08:51:29 +0200123 if args.sim and not args.commit and not args.diff:
124 sims = find_sims(args.sim, args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100125 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200126 print("%s: %s" % (yel("Similar symbols"), ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100127 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200128 print("%s: no similar symbols found" % yel("Similar symbols"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100129 sys.exit(0)
130
131 # dictionary of (un)defined symbols
132 defined = {}
133 undefined = {}
134
Valentin Rothberg14390e32016-08-28 08:51:29 +0200135 if args.commit or args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100136 head = get_head()
137
138 # get commit range
139 commit_a = None
140 commit_b = None
Valentin Rothberg14390e32016-08-28 08:51:29 +0200141 if args.commit:
142 commit_a = args.commit + "~"
143 commit_b = args.commit
144 elif args.diff:
145 split = args.diff.split("..")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100146 commit_a = split[0]
147 commit_b = split[1]
148 undefined_a = {}
149 undefined_b = {}
150
151 # get undefined items before the commit
152 execute("git reset --hard %s" % commit_a)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200153 undefined_a, _ = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100154
155 # get undefined items for the commit
156 execute("git reset --hard %s" % commit_b)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200157 undefined_b, defined = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100158
159 # report cases that are present for the commit but not before
Valentin Rothberge9533ae2015-03-23 18:40:49 +0100160 for feature in sorted(undefined_b):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100161 # feature has not been undefined before
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200162 if feature not in undefined_a:
Valentin Rothberge9533ae2015-03-23 18:40:49 +0100163 files = sorted(undefined_b.get(feature))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100164 undefined[feature] = files
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100165 # check if there are new files that reference the undefined feature
166 else:
Valentin Rothberge9533ae2015-03-23 18:40:49 +0100167 files = sorted(undefined_b.get(feature) -
168 undefined_a.get(feature))
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100169 if files:
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100170 undefined[feature] = files
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100171
172 # reset to head
173 execute("git reset --hard %s" % head)
174
175 # default to check the entire tree
176 else:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200177 undefined, defined = check_symbols(args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100178
179 # now print the output
180 for feature in sorted(undefined):
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200181 print(red(feature))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100182
183 files = sorted(undefined.get(feature))
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200184 print("%s: %s" % (yel("Referencing files"), ", ".join(files)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100185
Valentin Rothberg14390e32016-08-28 08:51:29 +0200186 sims = find_sims(feature, args.ignore, defined)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100187 sims_out = yel("Similar symbols")
188 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200189 print("%s: %s" % (sims_out, ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100190 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200191 print("%s: %s" % (sims_out, "no similar symbols found"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100192
Valentin Rothberg14390e32016-08-28 08:51:29 +0200193 if args.find:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200194 print("%s:" % yel("Commits changing symbol"))
Valentin Rothberg14390e32016-08-28 08:51:29 +0200195 commits = find_commits(feature, args.diff)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100196 if commits:
197 for commit in commits:
198 commit = commit.split(" ", 1)
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200199 print("\t- %s (\"%s\")" % (yel(commit[0]), commit[1]))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100200 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200201 print("\t- no commit found")
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200202 print() # new line
Valentin Rothbergc7455662015-06-01 16:00:20 +0200203
204
205def yel(string):
206 """
207 Color %string yellow.
208 """
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200209 return "\033[33m%s\033[0m" % string if COLOR else string
Valentin Rothbergc7455662015-06-01 16:00:20 +0200210
211
212def red(string):
213 """
214 Color %string red.
215 """
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200216 return "\033[31m%s\033[0m" % string if COLOR else string
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100217
218
219def execute(cmd):
220 """Execute %cmd and return stdout. Exit in case of error."""
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200221 try:
222 cmdlist = cmd.split(" ")
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200223 stdout = subprocess.check_output(cmdlist, stderr=subprocess.STDOUT, shell=False)
224 stdout = stdout.decode(errors='replace')
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200225 except subprocess.CalledProcessError as fail:
226 exit("Failed to execute %s\n%s" % (cmd, fail))
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100227 return stdout
228
229
Valentin Rothberga42fa922015-06-01 16:00:19 +0200230def find_commits(symbol, diff):
231 """Find commits changing %symbol in the given range of %diff."""
232 commits = execute("git log --pretty=oneline --abbrev-commit -G %s %s"
233 % (symbol, diff))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100234 return [x for x in commits.split("\n") if x]
Valentin Rothberga42fa922015-06-01 16:00:19 +0200235
236
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100237def tree_is_dirty():
238 """Return true if the current working tree is dirty (i.e., if any file has
239 been added, deleted, modified, renamed or copied but not committed)."""
240 stdout = execute("git status --porcelain")
241 for line in stdout:
242 if re.findall(r"[URMADC]{1}", line[:2]):
243 return True
244 return False
245
246
247def get_head():
248 """Return commit hash of current HEAD."""
249 stdout = execute("git rev-parse HEAD")
250 return stdout.strip('\n')
251
252
Valentin Rothberge2042a82015-10-15 10:37:47 +0200253def partition(lst, size):
254 """Partition list @lst into eveni-sized lists of size @size."""
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200255 return [lst[i::size] for i in range(size)]
Valentin Rothberge2042a82015-10-15 10:37:47 +0200256
257
258def init_worker():
259 """Set signal handler to ignore SIGINT."""
260 signal.signal(signal.SIGINT, signal.SIG_IGN)
261
262
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200263def find_sims(symbol, ignore, defined=[]):
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100264 """Return a list of max. ten Kconfig symbols that are string-similar to
265 @symbol."""
266 if defined:
267 return sorted(difflib.get_close_matches(symbol, set(defined), 10))
268
269 pool = Pool(cpu_count(), init_worker)
270 kfiles = []
271 for gitfile in get_files():
272 if REGEX_FILE_KCONFIG.match(gitfile):
273 kfiles.append(gitfile)
274
275 arglist = []
276 for part in partition(kfiles, cpu_count()):
277 arglist.append((part, ignore))
278
279 for res in pool.map(parse_kconfig_files, arglist):
280 defined.extend(res[0])
281
282 return sorted(difflib.get_close_matches(symbol, set(defined), 10))
283
284
285def get_files():
286 """Return a list of all files in the current git directory."""
287 # use 'git ls-files' to get the worklist
288 stdout = execute("git ls-files")
289 if len(stdout) > 0 and stdout[-1] == "\n":
290 stdout = stdout[:-1]
291
292 files = []
293 for gitfile in stdout.rsplit("\n"):
294 if ".git" in gitfile or "ChangeLog" in gitfile or \
295 ".log" in gitfile or os.path.isdir(gitfile) or \
296 gitfile.startswith("tools/"):
297 continue
298 files.append(gitfile)
299 return files
300
301
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200302def check_symbols(ignore):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100303 """Find undefined Kconfig symbols and return a dict with the symbol as key
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200304 and a list of referencing files as value. Files matching %ignore are not
305 checked for undefined symbols."""
Valentin Rothberge2042a82015-10-15 10:37:47 +0200306 pool = Pool(cpu_count(), init_worker)
307 try:
308 return check_symbols_helper(pool, ignore)
309 except KeyboardInterrupt:
310 pool.terminate()
311 pool.join()
312 sys.exit(1)
313
314
315def check_symbols_helper(pool, ignore):
316 """Helper method for check_symbols(). Used to catch keyboard interrupts in
317 check_symbols() in order to properly terminate running worker processes."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200318 source_files = []
319 kconfig_files = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200320 defined_features = []
321 referenced_features = dict() # {file: [features]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200322
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100323 for gitfile in get_files():
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200324 if REGEX_FILE_KCONFIG.match(gitfile):
325 kconfig_files.append(gitfile)
326 else:
Valentin Rothberge2042a82015-10-15 10:37:47 +0200327 if ignore and not re.match(ignore, gitfile):
328 continue
329 # add source files that do not match the ignore pattern
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200330 source_files.append(gitfile)
331
Valentin Rothberge2042a82015-10-15 10:37:47 +0200332 # parse source files
333 arglist = partition(source_files, cpu_count())
334 for res in pool.map(parse_source_files, arglist):
335 referenced_features.update(res)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200336
Valentin Rothberge2042a82015-10-15 10:37:47 +0200337 # parse kconfig files
338 arglist = []
339 for part in partition(kconfig_files, cpu_count()):
340 arglist.append((part, ignore))
341 for res in pool.map(parse_kconfig_files, arglist):
342 defined_features.extend(res[0])
343 referenced_features.update(res[1])
344 defined_features = set(defined_features)
345
346 # inverse mapping of referenced_features to dict(feature: [files])
347 inv_map = dict()
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200348 for _file, features in referenced_features.items():
Valentin Rothberge2042a82015-10-15 10:37:47 +0200349 for feature in features:
350 inv_map[feature] = inv_map.get(feature, set())
351 inv_map[feature].add(_file)
352 referenced_features = inv_map
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200353
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100354 undefined = {} # {feature: [files]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200355 for feature in sorted(referenced_features):
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100356 # filter some false positives
357 if feature == "FOO" or feature == "BAR" or \
358 feature == "FOO_BAR" or feature == "XXX":
359 continue
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200360 if feature not in defined_features:
361 if feature.endswith("_MODULE"):
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100362 # avoid false positives for kernel modules
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200363 if feature[:-len("_MODULE")] in defined_features:
364 continue
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100365 undefined[feature] = referenced_features.get(feature)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100366 return undefined, defined_features
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200367
368
Valentin Rothberge2042a82015-10-15 10:37:47 +0200369def parse_source_files(source_files):
370 """Parse each source file in @source_files and return dictionary with source
371 files as keys and lists of references Kconfig symbols as values."""
372 referenced_features = dict()
373 for sfile in source_files:
374 referenced_features[sfile] = parse_source_file(sfile)
375 return referenced_features
376
377
378def parse_source_file(sfile):
379 """Parse @sfile and return a list of referenced Kconfig features."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200380 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200381 references = []
382
383 if not os.path.exists(sfile):
384 return references
385
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200386 with open(sfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200387 lines = stream.readlines()
388
389 for line in lines:
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200390 if "CONFIG_" not in line:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200391 continue
392 features = REGEX_SOURCE_FEATURE.findall(line)
393 for feature in features:
394 if not REGEX_FILTER_FEATURES.search(feature):
395 continue
Valentin Rothberge2042a82015-10-15 10:37:47 +0200396 references.append(feature)
397
398 return references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200399
400
401def get_features_in_line(line):
402 """Return mentioned Kconfig features in @line."""
403 return REGEX_FEATURE.findall(line)
404
405
Valentin Rothberge2042a82015-10-15 10:37:47 +0200406def parse_kconfig_files(args):
407 """Parse kconfig files and return tuple of defined and references Kconfig
408 symbols. Note, @args is a tuple of a list of files and the @ignore
409 pattern."""
410 kconfig_files = args[0]
411 ignore = args[1]
412 defined_features = []
413 referenced_features = dict()
414
415 for kfile in kconfig_files:
416 defined, references = parse_kconfig_file(kfile)
417 defined_features.extend(defined)
418 if ignore and re.match(ignore, kfile):
419 # do not collect references for files that match the ignore pattern
420 continue
421 referenced_features[kfile] = references
422 return (defined_features, referenced_features)
423
424
425def parse_kconfig_file(kfile):
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200426 """Parse @kfile and update feature definitions and references."""
427 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200428 defined = []
429 references = []
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200430 skip = False
431
Valentin Rothberge2042a82015-10-15 10:37:47 +0200432 if not os.path.exists(kfile):
433 return defined, references
434
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200435 with open(kfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200436 lines = stream.readlines()
437
438 for i in range(len(lines)):
439 line = lines[i]
440 line = line.strip('\n')
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100441 line = line.split("#")[0] # ignore comments
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200442
443 if REGEX_KCONFIG_DEF.match(line):
444 feature_def = REGEX_KCONFIG_DEF.findall(line)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200445 defined.append(feature_def[0])
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200446 skip = False
447 elif REGEX_KCONFIG_HELP.match(line):
448 skip = True
449 elif skip:
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100450 # ignore content of help messages
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200451 pass
452 elif REGEX_KCONFIG_STMT.match(line):
Valentin Rothberge2042a82015-10-15 10:37:47 +0200453 line = REGEX_QUOTES.sub("", line)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200454 features = get_features_in_line(line)
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100455 # multi-line statements
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200456 while line.endswith("\\"):
457 i += 1
458 line = lines[i]
459 line = line.strip('\n')
460 features.extend(get_features_in_line(line))
461 for feature in set(features):
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +0200462 if REGEX_NUMERIC.match(feature):
463 # ignore numeric values
464 continue
Valentin Rothberge2042a82015-10-15 10:37:47 +0200465 references.append(feature)
466
467 return defined, references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200468
469
470if __name__ == "__main__":
471 main()