check_kconfigs.py 20 KB

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