check_kconfigs.py 19 KB

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