check_kconfigs.py 20 KB

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