check_kconfigs.py 20 KB

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