check_kconfigs.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. from __future__ import unicode_literals
  18. import argparse
  19. import os
  20. import re
  21. import sys
  22. from io import open
  23. from idf_ci_utils import get_submodule_dirs, IDF_PATH
  24. # regular expression for matching Kconfig files
  25. RE_KCONFIG = r'^Kconfig(\.projbuild)?(\.in)?$'
  26. # ouput file with suggestions will get this suffix
  27. OUTPUT_SUFFIX = '.new'
  28. # ignored directories (makes sense only when run on IDF_PATH)
  29. # Note: IGNORE_DIRS is a tuple in order to be able to use it directly with the startswith() built-in function which
  30. # accepts tuples but no lists.
  31. IGNORE_DIRS = (
  32. # Kconfigs from submodules need to be ignored:
  33. os.path.join(IDF_PATH, 'components', 'mqtt', 'esp-mqtt'),
  34. # Test Kconfigs are also ignored
  35. os.path.join(IDF_PATH, 'tools', 'ldgen', 'test', 'data'),
  36. os.path.join(IDF_PATH, 'tools', 'kconfig_new', 'test'),
  37. )
  38. SPACES_PER_INDENT = 4
  39. CONFIG_NAME_MAX_LENGTH = 40
  40. CONFIG_NAME_MIN_PREFIX_LENGTH = 3
  41. # The checker will not fail if it encounters this string (it can be used for temporarily resolve conflicts)
  42. RE_NOERROR = re.compile(r'\s+#\s+NOERROR\s+$')
  43. # list or rules for lines
  44. LINE_ERROR_RULES = [
  45. # (regular expression for finding, error message, correction)
  46. (re.compile(r'\t'), 'tabulators should be replaced by spaces', r' ' * SPACES_PER_INDENT),
  47. (re.compile(r'\s+\n'), 'trailing whitespaces should be removed', r'\n'),
  48. (re.compile(r'.{120}'), 'line should be shorter than 120 characters', None),
  49. # "\<CR><LF>" is not recognized due to a bug in tools/kconfig/zconf.l. The bug was fixed but the rebuild of
  50. # mconf-idf is not enforced and an incorrect version is supplied with all previous IDF versions. Backslashes
  51. # cannot be enabled unless everybody updates mconf-idf.
  52. (re.compile(r'\\\n'), 'line cannot be wrapped by backslash', None),
  53. ]
  54. class InputError(RuntimeError):
  55. """
  56. Represents and error on the input
  57. """
  58. def __init__(self, path, line_number, error_msg, suggested_line):
  59. super(InputError, self).__init__('{}:{}: {}'.format(path, line_number, error_msg))
  60. self.suggested_line = suggested_line
  61. class BaseChecker(object):
  62. """
  63. Base class for all checker objects
  64. """
  65. def __init__(self, path_in_idf):
  66. self.path_in_idf = path_in_idf
  67. def __enter__(self):
  68. return self
  69. def __exit__(self, type, value, traceback):
  70. pass
  71. class SourceChecker(BaseChecker):
  72. # allow to source only files which will be also checked by the script
  73. # Note: The rules are complex and the LineRuleChecker cannot be used
  74. def process_line(self, line, line_number):
  75. m = re.search(r'^\s*source(\s*)"([^"]+)"', line)
  76. if m:
  77. if len(m.group(1)) == 0:
  78. raise InputError(self.path_in_idf, line_number, '"source" has to been followed by space',
  79. line.replace('source', 'source '))
  80. path = m.group(2)
  81. filename = os.path.basename(path)
  82. if path in ['$COMPONENT_KCONFIGS_SOURCE_FILE', '$COMPONENT_KCONFIGS_PROJBUILD_SOURCE_FILE']:
  83. pass
  84. elif not filename.startswith('Kconfig.'):
  85. raise InputError(self.path_in_idf, line_number, "only filenames starting with Kconfig.* can be sourced",
  86. line.replace(path, os.path.join(os.path.dirname(path), 'Kconfig.' + filename)))
  87. class LineRuleChecker(BaseChecker):
  88. """
  89. checks LINE_ERROR_RULES for each line
  90. """
  91. def process_line(self, line, line_number):
  92. suppress_errors = RE_NOERROR.search(line) is not None
  93. errors = []
  94. for rule in LINE_ERROR_RULES:
  95. m = rule[0].search(line)
  96. if m:
  97. if suppress_errors:
  98. # just print but no failure
  99. e = InputError(self.path_in_idf, line_number, rule[1], line)
  100. print(e)
  101. else:
  102. errors.append(rule[1])
  103. if rule[2]:
  104. line = rule[0].sub(rule[2], line)
  105. if len(errors) > 0:
  106. raise InputError(self.path_in_idf, line_number, "; ".join(errors), line)
  107. class IndentAndNameChecker(BaseChecker):
  108. """
  109. checks the indentation of each line and configuration names
  110. """
  111. def __init__(self, path_in_idf, debug=False):
  112. super(IndentAndNameChecker, self).__init__(path_in_idf)
  113. self.debug = debug
  114. self.min_prefix_length = CONFIG_NAME_MIN_PREFIX_LENGTH
  115. # stack of the nested menuconfig items, e.g. ['mainmenu', 'menu', 'config']
  116. self.level_stack = []
  117. # stack common prefixes of configs
  118. self.prefix_stack = []
  119. # if the line ends with '\' then we force the indent of the next line
  120. self.force_next_indent = 0
  121. # menu items which increase the indentation of the next line
  122. self.re_increase_level = re.compile(r'''^\s*
  123. (
  124. (menu(?!config))
  125. |(mainmenu)
  126. |(choice)
  127. |(config)
  128. |(menuconfig)
  129. |(help)
  130. |(if)
  131. |(source)
  132. )
  133. ''', re.X)
  134. # closing menu items which decrease the indentation
  135. self.re_decrease_level = re.compile(r'''^\s*
  136. (
  137. (endmenu)
  138. |(endchoice)
  139. |(endif)
  140. )
  141. ''', re.X)
  142. # matching beginning of the closing menuitems
  143. self.pair_dic = {'endmenu': 'menu',
  144. 'endchoice': 'choice',
  145. 'endif': 'if',
  146. }
  147. # regex for config names
  148. self.re_name = re.compile(r'''^
  149. (
  150. (?:config)
  151. |(?:menuconfig)
  152. |(?:choice)
  153. )\s+
  154. (\w+)
  155. ''', re.X)
  156. # regex for new prefix stack
  157. self.re_new_stack = re.compile(r'''^
  158. (
  159. (?:menu(?!config))
  160. |(?:mainmenu)
  161. |(?:choice)
  162. )
  163. ''', re.X)
  164. def __exit__(self, type, value, traceback):
  165. super(IndentAndNameChecker, self).__exit__(type, value, traceback)
  166. if len(self.prefix_stack) > 0:
  167. self.check_common_prefix('', 'EOF')
  168. if len(self.prefix_stack) != 0:
  169. if self.debug:
  170. print(self.prefix_stack)
  171. raise RuntimeError("Prefix stack should be empty. Perhaps a menu/choice hasn't been closed")
  172. def del_from_level_stack(self, count):
  173. """ delete count items from the end of the level_stack """
  174. if count > 0:
  175. # del self.level_stack[-0:] would delete everything and we expect not to delete anything for count=0
  176. del self.level_stack[-count:]
  177. def update_level_for_inc_pattern(self, new_item):
  178. if self.debug:
  179. print('level+', new_item, ': ', self.level_stack, end=' -> ')
  180. # "config" and "menuconfig" don't have a closing pair. So if new_item is an item which need to be indented
  181. # outside the last "config" or "menuconfig" then we need to find to a parent where it belongs
  182. if new_item in ['config', 'menuconfig', 'menu', 'choice', 'if', 'source']:
  183. # item is not belonging to a previous "config" or "menuconfig" so need to indent to parent
  184. for i, item in enumerate(reversed(self.level_stack)):
  185. if item in ['menu', 'mainmenu', 'choice', 'if']:
  186. # delete items ("config", "menuconfig", "help") until the appropriate parent
  187. self.del_from_level_stack(i)
  188. break
  189. else:
  190. # delete everything when configs are at top level without a parent menu, mainmenu...
  191. self.del_from_level_stack(len(self.level_stack))
  192. self.level_stack.append(new_item)
  193. if self.debug:
  194. print(self.level_stack)
  195. # The new indent is for the next line. Use the old one for the current line:
  196. return len(self.level_stack) - 1
  197. def update_level_for_dec_pattern(self, new_item):
  198. if self.debug:
  199. print('level-', new_item, ': ', self.level_stack, end=' -> ')
  200. target = self.pair_dic[new_item]
  201. for i, item in enumerate(reversed(self.level_stack)):
  202. # find the matching beginning for the closing item in reverse-order search
  203. # Note: "menuconfig", "config" and "help" don't have closing pairs and they are also on the stack. Now they
  204. # will be deleted together with the "menu" or "choice" we are closing.
  205. if item == target:
  206. i += 1 # delete also the matching beginning
  207. if self.debug:
  208. print('delete ', i, end=' -> ')
  209. self.del_from_level_stack(i)
  210. break
  211. if self.debug:
  212. print(self.level_stack)
  213. return len(self.level_stack)
  214. def check_name_and_update_prefix(self, line, line_number):
  215. m = self.re_name.search(line)
  216. if m:
  217. name = m.group(2)
  218. name_length = len(name)
  219. if name_length > CONFIG_NAME_MAX_LENGTH:
  220. raise InputError(self.path_in_idf, line_number,
  221. '{} is {} characters long and it should be {} at most'
  222. ''.format(name, name_length, CONFIG_NAME_MAX_LENGTH),
  223. line + '\n') # no suggested correction for this
  224. if len(self.prefix_stack) == 0:
  225. self.prefix_stack.append(name)
  226. elif self.prefix_stack[-1] is None:
  227. self.prefix_stack[-1] = name
  228. else:
  229. # this has nothing common with paths but the algorithm can be used for this also
  230. self.prefix_stack[-1] = os.path.commonprefix([self.prefix_stack[-1], name])
  231. if self.debug:
  232. print('prefix+', self.prefix_stack)
  233. m = self.re_new_stack.search(line)
  234. if m:
  235. self.prefix_stack.append(None)
  236. if self.debug:
  237. print('prefix+', self.prefix_stack)
  238. def check_common_prefix(self, line, line_number):
  239. common_prefix = self.prefix_stack.pop()
  240. if self.debug:
  241. print('prefix-', self.prefix_stack)
  242. if common_prefix is None:
  243. return
  244. common_prefix_len = len(common_prefix)
  245. if common_prefix_len < self.min_prefix_length:
  246. raise InputError(self.path_in_idf, line_number,
  247. 'The common prefix for the config names of the menu ending at this line is "{}".\n'
  248. '\tAll config names in this menu should start with the same prefix of {} characters '
  249. 'or more.'.format(common_prefix, self.min_prefix_length),
  250. line) # no suggested correction for this
  251. if len(self.prefix_stack) > 0:
  252. parent_prefix = self.prefix_stack[-1]
  253. if parent_prefix is None:
  254. # propagate to parent level where it will influence the prefix checking with the rest which might
  255. # follow later on that level
  256. self.prefix_stack[-1] = common_prefix
  257. else:
  258. if len(self.level_stack) > 0 and self.level_stack[-1] in ['mainmenu', 'menu']:
  259. # the prefix from menu is not required to propagate to the children
  260. return
  261. if not common_prefix.startswith(parent_prefix):
  262. raise InputError(self.path_in_idf, line_number,
  263. 'Common prefix "{}" should start with {}'
  264. ''.format(common_prefix, parent_prefix),
  265. line) # no suggested correction for this
  266. def process_line(self, line, line_number):
  267. stripped_line = line.strip()
  268. if len(stripped_line) == 0:
  269. self.force_next_indent = 0
  270. return
  271. current_level = len(self.level_stack)
  272. m = re.search(r'\S', line) # indent found as the first non-space character
  273. if m:
  274. current_indent = m.start()
  275. else:
  276. current_indent = 0
  277. if current_level > 0 and self.level_stack[-1] == 'help':
  278. if current_indent >= current_level * SPACES_PER_INDENT:
  279. # this line belongs to 'help'
  280. self.force_next_indent = 0
  281. return
  282. if self.force_next_indent > 0:
  283. if current_indent != self.force_next_indent:
  284. raise InputError(self.path_in_idf, line_number,
  285. 'Indentation consists of {} spaces instead of {}'.format(current_indent,
  286. self.force_next_indent),
  287. (' ' * self.force_next_indent) + line.lstrip())
  288. else:
  289. if not stripped_line.endswith('\\'):
  290. self.force_next_indent = 0
  291. return
  292. elif stripped_line.endswith('\\') and stripped_line.startswith(('config', 'menuconfig', 'choice')):
  293. raise InputError(self.path_in_idf, line_number,
  294. 'Line-wrap with backslash is not supported here',
  295. line) # no suggestion for this
  296. self.check_name_and_update_prefix(stripped_line, line_number)
  297. m = self.re_increase_level.search(line)
  298. if m:
  299. current_level = self.update_level_for_inc_pattern(m.group(1))
  300. else:
  301. m = self.re_decrease_level.search(line)
  302. if m:
  303. new_item = m.group(1)
  304. current_level = self.update_level_for_dec_pattern(new_item)
  305. if new_item not in ['endif']:
  306. # endif doesn't require to check the prefix because the items inside if/endif belong to the
  307. # same prefix level
  308. self.check_common_prefix(line, line_number)
  309. expected_indent = current_level * SPACES_PER_INDENT
  310. if stripped_line.endswith('\\'):
  311. self.force_next_indent = expected_indent + SPACES_PER_INDENT
  312. else:
  313. self.force_next_indent = 0
  314. if current_indent != expected_indent:
  315. raise InputError(self.path_in_idf, line_number,
  316. 'Indentation consists of {} spaces instead of {}'.format(current_indent, expected_indent),
  317. (' ' * expected_indent) + line.lstrip())
  318. def valid_directory(path):
  319. if not os.path.isdir(path):
  320. raise argparse.ArgumentTypeError("{} is not a valid directory!".format(path))
  321. return path
  322. def validate_kconfig_file(kconfig_full_path, verbose=False): # type: (str, bool) -> bool
  323. suggestions_full_path = kconfig_full_path + OUTPUT_SUFFIX
  324. fail = False
  325. with open(kconfig_full_path, 'r', encoding='utf-8') as f, \
  326. open(suggestions_full_path, 'w', encoding='utf-8', newline='\n') as f_o, \
  327. LineRuleChecker(kconfig_full_path) as line_checker, \
  328. SourceChecker(kconfig_full_path) as source_checker, \
  329. IndentAndNameChecker(kconfig_full_path, debug=verbose) as indent_and_name_checker:
  330. try:
  331. for line_number, line in enumerate(f, start=1):
  332. try:
  333. for checker in [line_checker, indent_and_name_checker, source_checker]:
  334. checker.process_line(line, line_number)
  335. # The line is correct therefore we echo it to the output file
  336. f_o.write(line)
  337. except InputError as e:
  338. print(e)
  339. fail = True
  340. f_o.write(e.suggested_line)
  341. except UnicodeDecodeError:
  342. raise ValueError("The encoding of {} is not Unicode.".format(kconfig_full_path))
  343. if fail:
  344. print('\t{} has been saved with suggestions for resolving the issues.\n'
  345. '\tPlease note that the suggestions can be wrong and '
  346. 'you might need to re-run the checker several times '
  347. 'for solving all issues'.format(suggestions_full_path))
  348. print('\tPlease fix the errors and run {} for checking the correctness of '
  349. 'Kconfig files.'.format(os.path.abspath(__file__)))
  350. return False
  351. else:
  352. print('{}: OK'.format(kconfig_full_path))
  353. try:
  354. os.remove(suggestions_full_path)
  355. except Exception:
  356. # not a serious error is when the file cannot be deleted
  357. print('{} cannot be deleted!'.format(suggestions_full_path))
  358. finally:
  359. return True
  360. def main():
  361. parser = argparse.ArgumentParser(description='Kconfig style checker')
  362. parser.add_argument('files', nargs='*',
  363. help='Kconfig files')
  364. parser.add_argument('--verbose', '-v', action='store_true',
  365. help='Print more information (useful for debugging)')
  366. parser.add_argument('--includes', '-d', nargs='*',
  367. help='Extra paths for recursively searching Kconfig files. (for example $IDF_PATH)',
  368. type=valid_directory)
  369. parser.add_argument('--exclude-submodules', action='store_true',
  370. help='Exclude submodules')
  371. args = parser.parse_args()
  372. success_counter = 0
  373. failure_counter = 0
  374. ignore_counter = 0
  375. ignore_dirs = IGNORE_DIRS
  376. if args.exclude_submodules:
  377. ignore_dirs = ignore_dirs + tuple(get_submodule_dirs(full_path=True))
  378. files = [os.path.abspath(file_path) for file_path in args.files]
  379. if args.includes:
  380. for directory in args.includes:
  381. for root, dirnames, filenames in os.walk(directory):
  382. for filename in filenames:
  383. full_path = os.path.join(root, filename)
  384. if re.search(RE_KCONFIG, filename):
  385. files.append(full_path)
  386. elif re.search(RE_KCONFIG, filename, re.IGNORECASE):
  387. # On Windows Kconfig files are working with different cases!
  388. print('{}: Incorrect filename. The case should be "Kconfig"!'.format(full_path))
  389. failure_counter += 1
  390. for full_path in files:
  391. if full_path.startswith(ignore_dirs):
  392. print('{}: Ignored'.format(full_path))
  393. ignore_counter += 1
  394. continue
  395. is_valid = validate_kconfig_file(full_path, args.verbose)
  396. if is_valid:
  397. success_counter += 1
  398. else:
  399. failure_counter += 1
  400. if ignore_counter > 0:
  401. print('{} files have been ignored.'.format(ignore_counter))
  402. if success_counter > 0:
  403. print('{} files have been successfully checked.'.format(success_counter))
  404. if failure_counter > 0:
  405. print('{} files have errors. Please take a look at the log.'.format(failure_counter))
  406. return 1
  407. if not files:
  408. print('WARNING: no files specified. Please specify files or use '
  409. '"--includes" to search Kconfig files recursively')
  410. return 0
  411. if __name__ == "__main__":
  412. sys.exit(main())