blob: 322c5e817b4c514bcfaf857227b7e021a5847df0 [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 Rothbergcc641d52014-11-08 20:56:35 +01006# (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02007#
Valentin Rothbergcc641d52014-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 Rothberge2042a82015-10-15 10:37:47 +020019from subprocess import Popen, PIPE, STDOUT
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020020
Valentin Rothbergcc641d52014-11-08 20:56:35 +010021
22# regex expressions
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020023OPERATORS = r"&|\(|\)|\||\!"
Valentin Rothbergcc641d52014-11-08 20:56:35 +010024FEATURE = r"(?:\w*[A-Z0-9]\w*){2,}"
25DEF = r"^\s*(?:menu){,1}config\s+(" + FEATURE + r")\s*"
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020026EXPR = r"(?:" + OPERATORS + r"|\s|" + FEATURE + r")+"
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +020027DEFAULT = r"default\s+.*?(?:if\s.+){,1}"
28STMT = r"^\s*(?:if|select|depends\s+on|(?:" + DEFAULT + r"))\s+" + EXPR
Valentin Rothbergcc641d52014-11-08 20:56:35 +010029SOURCE_FEATURE = r"(?:\W|\b)+[D]{,1}CONFIG_(" + FEATURE + r")"
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020030
Valentin Rothbergcc641d52014-11-08 20:56:35 +010031# regex objects
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020032REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
Valentin Rothberge2042a82015-10-15 10:37:47 +020033REGEX_FEATURE = re.compile(r'(?!\B)' + FEATURE + r'(?!\B)')
Valentin Rothbergcc641d52014-11-08 20:56:35 +010034REGEX_SOURCE_FEATURE = re.compile(SOURCE_FEATURE)
35REGEX_KCONFIG_DEF = re.compile(DEF)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020036REGEX_KCONFIG_EXPR = re.compile(EXPR)
37REGEX_KCONFIG_STMT = re.compile(STMT)
38REGEX_KCONFIG_HELP = re.compile(r"^\s+(help|---help---)\s*$")
39REGEX_FILTER_FEATURES = re.compile(r"[A-Za-z0-9]$")
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +020040REGEX_NUMERIC = re.compile(r"0[xX][0-9a-fA-F]+|[0-9]+")
Valentin Rothberge2042a82015-10-15 10:37:47 +020041REGEX_QUOTES = re.compile("(\"(.*?)\")")
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020042
43
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010044def parse_options():
45 """The user interface of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +020046 usage = "Run this tool to detect Kconfig symbols that are referenced but " \
47 "not defined in Kconfig. If no option is specified, " \
48 "checkkconfigsymbols defaults to check your current tree. " \
49 "Please note that specifying commits will 'git reset --hard\' " \
50 "your current tree! You may save uncommitted changes to avoid " \
51 "losing data."
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010052
Valentin Rothberg14390e32016-08-28 08:51:29 +020053 parser = argparse.ArgumentParser(description=usage)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010054
Valentin Rothberg14390e32016-08-28 08:51:29 +020055 parser.add_argument('-c', '--commit', dest='commit', action='store',
56 default="",
57 help="check if the specified commit (hash) introduces "
58 "undefined Kconfig symbols")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010059
Valentin Rothberg14390e32016-08-28 08:51:29 +020060 parser.add_argument('-d', '--diff', dest='diff', action='store',
61 default="",
62 help="diff undefined symbols between two commits "
63 "(e.g., -d commmit1..commit2)")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010064
Valentin Rothberg14390e32016-08-28 08:51:29 +020065 parser.add_argument('-f', '--find', dest='find', action='store_true',
66 default=False,
67 help="find and show commits that may cause symbols to be "
68 "missing (required to run with --diff)")
Valentin Rothberga42fa922015-06-01 16:00:19 +020069
Valentin Rothberg14390e32016-08-28 08:51:29 +020070 parser.add_argument('-i', '--ignore', dest='ignore', action='store',
71 default="",
72 help="ignore files matching this Python regex "
73 "(e.g., -i '.*defconfig')")
Valentin Rothbergcf132e42015-04-29 16:58:27 +020074
Valentin Rothberg14390e32016-08-28 08:51:29 +020075 parser.add_argument('-s', '--sim', dest='sim', action='store', default="",
76 help="print a list of max. 10 string-similar symbols")
Valentin Rothberg1b2c8412015-11-26 14:17:15 +010077
Valentin Rothberg14390e32016-08-28 08:51:29 +020078 parser.add_argument('--force', dest='force', action='store_true',
79 default=False,
80 help="reset current Git tree even when it's dirty")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010081
Valentin Rothberg14390e32016-08-28 08:51:29 +020082 parser.add_argument('--no-color', dest='color', action='store_false',
83 default=True,
84 help="don't print colored output (default when not "
85 "outputting to a terminal)")
Andrew Donnellan4c73c082016-07-05 17:47:37 +100086
Valentin Rothberg14390e32016-08-28 08:51:29 +020087 args = parser.parse_args()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010088
Valentin Rothberg14390e32016-08-28 08:51:29 +020089 if args.commit and args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010090 sys.exit("Please specify only one option at once.")
91
Valentin Rothberg14390e32016-08-28 08:51:29 +020092 if args.diff and not re.match(r"^[\w\-\.]+\.\.[\w\-\.]+$", args.diff):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010093 sys.exit("Please specify valid input in the following format: "
Andreas Ziegler38cbfe42016-03-31 09:24:29 +020094 "\'commit1..commit2\'")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010095
Valentin Rothberg14390e32016-08-28 08:51:29 +020096 if args.commit or args.diff:
97 if not args.force and tree_is_dirty():
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010098 sys.exit("The current Git tree is dirty (see 'git status'). "
99 "Running this script may\ndelete important data since it "
100 "calls 'git reset --hard' for some performance\nreasons. "
101 " Please run this script in a clean Git tree or pass "
102 "'--force' if you\nwant to ignore this warning and "
103 "continue.")
104
Valentin Rothberg14390e32016-08-28 08:51:29 +0200105 if args.commit:
106 args.find = False
Valentin Rothberga42fa922015-06-01 16:00:19 +0200107
Valentin Rothberg14390e32016-08-28 08:51:29 +0200108 if args.ignore:
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200109 try:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200110 re.match(args.ignore, "this/is/just/a/test.c")
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200111 except:
112 sys.exit("Please specify a valid Python regex.")
113
Valentin Rothberg14390e32016-08-28 08:51:29 +0200114 return args
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100115
116
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200117def main():
118 """Main function of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +0200119 args = parse_options()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100120
Andrew Donnellan4c73c082016-07-05 17:47:37 +1000121 global color
Valentin Rothberg14390e32016-08-28 08:51:29 +0200122 color = args.color and sys.stdout.isatty()
Andrew Donnellan4c73c082016-07-05 17:47:37 +1000123
Valentin Rothberg14390e32016-08-28 08:51:29 +0200124 if args.sim and not args.commit and not args.diff:
125 sims = find_sims(args.sim, args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100126 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200127 print("%s: %s" % (yel("Similar symbols"), ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100128 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200129 print("%s: no similar symbols found" % yel("Similar symbols"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100130 sys.exit(0)
131
132 # dictionary of (un)defined symbols
133 defined = {}
134 undefined = {}
135
Valentin Rothberg14390e32016-08-28 08:51:29 +0200136 if args.commit or args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100137 head = get_head()
138
139 # get commit range
140 commit_a = None
141 commit_b = None
Valentin Rothberg14390e32016-08-28 08:51:29 +0200142 if args.commit:
143 commit_a = args.commit + "~"
144 commit_b = args.commit
145 elif args.diff:
146 split = args.diff.split("..")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100147 commit_a = split[0]
148 commit_b = split[1]
149 undefined_a = {}
150 undefined_b = {}
151
152 # get undefined items before the commit
153 execute("git reset --hard %s" % commit_a)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200154 undefined_a, _ = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100155
156 # get undefined items for the commit
157 execute("git reset --hard %s" % commit_b)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200158 undefined_b, defined = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100159
160 # report cases that are present for the commit but not before
Valentin Rothberge9533ae2015-03-23 18:40:49 +0100161 for feature in sorted(undefined_b):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100162 # feature has not been undefined before
163 if not feature in undefined_a:
Valentin Rothberge9533ae2015-03-23 18:40:49 +0100164 files = sorted(undefined_b.get(feature))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100165 undefined[feature] = files
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100166 # check if there are new files that reference the undefined feature
167 else:
Valentin Rothberge9533ae2015-03-23 18:40:49 +0100168 files = sorted(undefined_b.get(feature) -
169 undefined_a.get(feature))
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100170 if files:
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100171 undefined[feature] = files
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100172
173 # reset to head
174 execute("git reset --hard %s" % head)
175
176 # default to check the entire tree
177 else:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200178 undefined, defined = check_symbols(args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100179
180 # now print the output
181 for feature in sorted(undefined):
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200182 print(red(feature))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100183
184 files = sorted(undefined.get(feature))
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200185 print("%s: %s" % (yel("Referencing files"), ", ".join(files)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100186
Valentin Rothberg14390e32016-08-28 08:51:29 +0200187 sims = find_sims(feature, args.ignore, defined)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100188 sims_out = yel("Similar symbols")
189 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200190 print("%s: %s" % (sims_out, ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100191 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200192 print("%s: %s" % (sims_out, "no similar symbols found"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100193
Valentin Rothberg14390e32016-08-28 08:51:29 +0200194 if args.find:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200195 print("%s:" % yel("Commits changing symbol"))
Valentin Rothberg14390e32016-08-28 08:51:29 +0200196 commits = find_commits(feature, args.diff)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100197 if commits:
198 for commit in commits:
199 commit = commit.split(" ", 1)
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200200 print("\t- %s (\"%s\")" % (yel(commit[0]), commit[1]))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100201 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200202 print("\t- no commit found")
203 print() # new line
Valentin Rothbergc7455662015-06-01 16:00:20 +0200204
205
206def yel(string):
207 """
208 Color %string yellow.
209 """
Andrew Donnellan4c73c082016-07-05 17:47:37 +1000210 return "\033[33m%s\033[0m" % string if color else string
Valentin Rothbergc7455662015-06-01 16:00:20 +0200211
212
213def red(string):
214 """
215 Color %string red.
216 """
Andrew Donnellan4c73c082016-07-05 17:47:37 +1000217 return "\033[31m%s\033[0m" % string if color else string
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100218
219
220def execute(cmd):
221 """Execute %cmd and return stdout. Exit in case of error."""
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200222 try:
223 cmdlist = cmd.split(" ")
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200224 stdout = subprocess.check_output(cmdlist, stderr=subprocess.STDOUT, shell=False)
225 stdout = stdout.decode(errors='replace')
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200226 except subprocess.CalledProcessError as fail:
227 exit("Failed to execute %s\n%s" % (cmd, fail))
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100228 return stdout
229
230
Valentin Rothberga42fa922015-06-01 16:00:19 +0200231def find_commits(symbol, diff):
232 """Find commits changing %symbol in the given range of %diff."""
233 commits = execute("git log --pretty=oneline --abbrev-commit -G %s %s"
234 % (symbol, diff))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100235 return [x for x in commits.split("\n") if x]
Valentin Rothberga42fa922015-06-01 16:00:19 +0200236
237
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100238def tree_is_dirty():
239 """Return true if the current working tree is dirty (i.e., if any file has
240 been added, deleted, modified, renamed or copied but not committed)."""
241 stdout = execute("git status --porcelain")
242 for line in stdout:
243 if re.findall(r"[URMADC]{1}", line[:2]):
244 return True
245 return False
246
247
248def get_head():
249 """Return commit hash of current HEAD."""
250 stdout = execute("git rev-parse HEAD")
251 return stdout.strip('\n')
252
253
Valentin Rothberge2042a82015-10-15 10:37:47 +0200254def partition(lst, size):
255 """Partition list @lst into eveni-sized lists of size @size."""
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200256 return [lst[i::size] for i in range(size)]
Valentin Rothberge2042a82015-10-15 10:37:47 +0200257
258
259def init_worker():
260 """Set signal handler to ignore SIGINT."""
261 signal.signal(signal.SIGINT, signal.SIG_IGN)
262
263
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100264def find_sims(symbol, ignore, defined = []):
265 """Return a list of max. ten Kconfig symbols that are string-similar to
266 @symbol."""
267 if defined:
268 return sorted(difflib.get_close_matches(symbol, set(defined), 10))
269
270 pool = Pool(cpu_count(), init_worker)
271 kfiles = []
272 for gitfile in get_files():
273 if REGEX_FILE_KCONFIG.match(gitfile):
274 kfiles.append(gitfile)
275
276 arglist = []
277 for part in partition(kfiles, cpu_count()):
278 arglist.append((part, ignore))
279
280 for res in pool.map(parse_kconfig_files, arglist):
281 defined.extend(res[0])
282
283 return sorted(difflib.get_close_matches(symbol, set(defined), 10))
284
285
286def get_files():
287 """Return a list of all files in the current git directory."""
288 # use 'git ls-files' to get the worklist
289 stdout = execute("git ls-files")
290 if len(stdout) > 0 and stdout[-1] == "\n":
291 stdout = stdout[:-1]
292
293 files = []
294 for gitfile in stdout.rsplit("\n"):
295 if ".git" in gitfile or "ChangeLog" in gitfile or \
296 ".log" in gitfile or os.path.isdir(gitfile) or \
297 gitfile.startswith("tools/"):
298 continue
299 files.append(gitfile)
300 return files
301
302
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200303def check_symbols(ignore):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100304 """Find undefined Kconfig symbols and return a dict with the symbol as key
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200305 and a list of referencing files as value. Files matching %ignore are not
306 checked for undefined symbols."""
Valentin Rothberge2042a82015-10-15 10:37:47 +0200307 pool = Pool(cpu_count(), init_worker)
308 try:
309 return check_symbols_helper(pool, ignore)
310 except KeyboardInterrupt:
311 pool.terminate()
312 pool.join()
313 sys.exit(1)
314
315
316def check_symbols_helper(pool, ignore):
317 """Helper method for check_symbols(). Used to catch keyboard interrupts in
318 check_symbols() in order to properly terminate running worker processes."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200319 source_files = []
320 kconfig_files = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200321 defined_features = []
322 referenced_features = dict() # {file: [features]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200323
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100324 for gitfile in get_files():
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200325 if REGEX_FILE_KCONFIG.match(gitfile):
326 kconfig_files.append(gitfile)
327 else:
Valentin Rothberge2042a82015-10-15 10:37:47 +0200328 if ignore and not re.match(ignore, gitfile):
329 continue
330 # add source files that do not match the ignore pattern
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200331 source_files.append(gitfile)
332
Valentin Rothberge2042a82015-10-15 10:37:47 +0200333 # parse source files
334 arglist = partition(source_files, cpu_count())
335 for res in pool.map(parse_source_files, arglist):
336 referenced_features.update(res)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200337
Valentin Rothberge2042a82015-10-15 10:37:47 +0200338
339 # parse kconfig files
340 arglist = []
341 for part in partition(kconfig_files, cpu_count()):
342 arglist.append((part, ignore))
343 for res in pool.map(parse_kconfig_files, arglist):
344 defined_features.extend(res[0])
345 referenced_features.update(res[1])
346 defined_features = set(defined_features)
347
348 # inverse mapping of referenced_features to dict(feature: [files])
349 inv_map = dict()
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200350 for _file, features in referenced_features.items():
Valentin Rothberge2042a82015-10-15 10:37:47 +0200351 for feature in features:
352 inv_map[feature] = inv_map.get(feature, set())
353 inv_map[feature].add(_file)
354 referenced_features = inv_map
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200355
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100356 undefined = {} # {feature: [files]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200357 for feature in sorted(referenced_features):
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100358 # filter some false positives
359 if feature == "FOO" or feature == "BAR" or \
360 feature == "FOO_BAR" or feature == "XXX":
361 continue
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200362 if feature not in defined_features:
363 if feature.endswith("_MODULE"):
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100364 # avoid false positives for kernel modules
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200365 if feature[:-len("_MODULE")] in defined_features:
366 continue
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100367 undefined[feature] = referenced_features.get(feature)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100368 return undefined, defined_features
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200369
370
Valentin Rothberge2042a82015-10-15 10:37:47 +0200371def parse_source_files(source_files):
372 """Parse each source file in @source_files and return dictionary with source
373 files as keys and lists of references Kconfig symbols as values."""
374 referenced_features = dict()
375 for sfile in source_files:
376 referenced_features[sfile] = parse_source_file(sfile)
377 return referenced_features
378
379
380def parse_source_file(sfile):
381 """Parse @sfile and return a list of referenced Kconfig features."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200382 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200383 references = []
384
385 if not os.path.exists(sfile):
386 return references
387
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200388 with open(sfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200389 lines = stream.readlines()
390
391 for line in lines:
392 if not "CONFIG_" in line:
393 continue
394 features = REGEX_SOURCE_FEATURE.findall(line)
395 for feature in features:
396 if not REGEX_FILTER_FEATURES.search(feature):
397 continue
Valentin Rothberge2042a82015-10-15 10:37:47 +0200398 references.append(feature)
399
400 return references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200401
402
403def get_features_in_line(line):
404 """Return mentioned Kconfig features in @line."""
405 return REGEX_FEATURE.findall(line)
406
407
Valentin Rothberge2042a82015-10-15 10:37:47 +0200408def parse_kconfig_files(args):
409 """Parse kconfig files and return tuple of defined and references Kconfig
410 symbols. Note, @args is a tuple of a list of files and the @ignore
411 pattern."""
412 kconfig_files = args[0]
413 ignore = args[1]
414 defined_features = []
415 referenced_features = dict()
416
417 for kfile in kconfig_files:
418 defined, references = parse_kconfig_file(kfile)
419 defined_features.extend(defined)
420 if ignore and re.match(ignore, kfile):
421 # do not collect references for files that match the ignore pattern
422 continue
423 referenced_features[kfile] = references
424 return (defined_features, referenced_features)
425
426
427def parse_kconfig_file(kfile):
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200428 """Parse @kfile and update feature definitions and references."""
429 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200430 defined = []
431 references = []
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200432 skip = False
433
Valentin Rothberge2042a82015-10-15 10:37:47 +0200434 if not os.path.exists(kfile):
435 return defined, references
436
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200437 with open(kfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200438 lines = stream.readlines()
439
440 for i in range(len(lines)):
441 line = lines[i]
442 line = line.strip('\n')
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100443 line = line.split("#")[0] # ignore comments
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200444
445 if REGEX_KCONFIG_DEF.match(line):
446 feature_def = REGEX_KCONFIG_DEF.findall(line)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200447 defined.append(feature_def[0])
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200448 skip = False
449 elif REGEX_KCONFIG_HELP.match(line):
450 skip = True
451 elif skip:
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100452 # ignore content of help messages
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200453 pass
454 elif REGEX_KCONFIG_STMT.match(line):
Valentin Rothberge2042a82015-10-15 10:37:47 +0200455 line = REGEX_QUOTES.sub("", line)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200456 features = get_features_in_line(line)
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100457 # multi-line statements
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200458 while line.endswith("\\"):
459 i += 1
460 line = lines[i]
461 line = line.strip('\n')
462 features.extend(get_features_in_line(line))
463 for feature in set(features):
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +0200464 if REGEX_NUMERIC.match(feature):
465 # ignore numeric values
466 continue
Valentin Rothberge2042a82015-10-15 10:37:47 +0200467 references.append(feature)
468
469 return defined, references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200470
471
472if __name__ == "__main__":
473 main()