2
1

gen-manual-lists.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. ## gen-manual-lists.py
  2. ##
  3. ## This script generates the following Buildroot manual appendices:
  4. ## - the package tables (one for the target, the other for host tools);
  5. ## - the deprecated items.
  6. ##
  7. ## Author(s):
  8. ## - Samuel Martin <s.martin49@gmail.com>
  9. ##
  10. ## Copyright (C) 2013 Samuel Martin
  11. ##
  12. ## This program is free software; you can redistribute it and/or modify
  13. ## it under the terms of the GNU General Public License as published by
  14. ## the Free Software Foundation; either version 2 of the License, or
  15. ## (at your option) any later version.
  16. ##
  17. ## This program is distributed in the hope that it will be useful,
  18. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ## GNU General Public License for more details.
  21. ##
  22. ## You should have received a copy of the GNU General Public License
  23. ## along with this program; if not, write to the Free Software
  24. ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  25. ##
  26. ## Note about python2.
  27. ##
  28. ## This script can currently only be run using python2 interpreter due to
  29. ## its kconfiglib dependency (which is not yet python3 friendly).
  30. from __future__ import print_function
  31. from __future__ import unicode_literals
  32. import os
  33. import re
  34. import sys
  35. import datetime
  36. from argparse import ArgumentParser
  37. try:
  38. import kconfiglib
  39. except ImportError:
  40. message = """
  41. Could not find the module 'kconfiglib' in the PYTHONPATH:
  42. """
  43. message += "\n".join([" {0}".format(path) for path in sys.path])
  44. message += """
  45. Make sure the Kconfiglib directory is in the PYTHONPATH, then relaunch the
  46. script.
  47. You can get kconfiglib from:
  48. https://github.com/ulfalizer/Kconfiglib
  49. """
  50. sys.stderr.write(message)
  51. raise
  52. def get_symbol_subset(root, filter_func):
  53. """ Return a generator of kconfig items.
  54. :param root_item: Root item of the generated subset of items
  55. :param filter_func: Filter function
  56. """
  57. if hasattr(root, "get_items"):
  58. get_items = root.get_items
  59. elif hasattr(root, "get_top_level_items"):
  60. get_items = root.get_top_level_items
  61. else:
  62. message = "The symbol does not contain any subset of symbols"
  63. raise Exception(message)
  64. for item in get_items():
  65. if item.is_symbol():
  66. if not item.prompts:
  67. continue
  68. if not filter_func(item):
  69. continue
  70. yield item
  71. elif item.is_menu() or item.is_choice():
  72. for i in get_symbol_subset(item, filter_func):
  73. yield i
  74. def get_symbol_parents(item, root=None, enable_choice=False):
  75. """ Return the list of the item's parents. The last item of the list is
  76. the closest parent, the first the furthest.
  77. :param item: Item from which the the parent list is generated
  78. :param root: Root item stopping the search (not included in the
  79. parent list)
  80. :param enable_choice: Flag enabling choices to appear in the parent list
  81. """
  82. parent = item.get_parent()
  83. parents = []
  84. while parent and parent != root:
  85. if parent.is_menu():
  86. parents.append(parent.get_title())
  87. elif enable_choice and parent.is_choice():
  88. parents.append(parent.prompts[0][0])
  89. parent = parent.get_parent()
  90. if isinstance(root, kconfiglib.Menu) or \
  91. (enable_choice and isinstance(root, kconfiglib.Choice)):
  92. parents.append("") # Dummy empty parent to get a leading arrow ->
  93. parents.reverse()
  94. return parents
  95. def format_asciidoc_table(root, get_label_func, filter_func=lambda x: True,
  96. enable_choice=False, sorted=True, sub_menu=True,
  97. item_label=None):
  98. """ Return the asciidoc formatted table of the items and their location.
  99. :param root: Root item of the item subset
  100. :param get_label_func: Item's label getter function
  101. :param filter_func: Filter function to apply on the item subset
  102. :param enable_choice: Enable choices to appear as part of the item's
  103. location
  104. :param sorted: Flag to alphabetically sort the table
  105. :param sub_menu: Output the column with the sub-menu path
  106. """
  107. def _format_entry(item, parents, sub_menu):
  108. """ Format an asciidoc table entry.
  109. """
  110. if sub_menu:
  111. return "| {0:<40} <| {1}\n".format(item, " -> ".join(parents))
  112. else:
  113. return "| {0:<40}\n".format(item)
  114. lines = []
  115. for item in get_symbol_subset(root, filter_func):
  116. if not item.is_symbol() or not item.prompts:
  117. continue
  118. loc = get_symbol_parents(item, root, enable_choice=enable_choice)
  119. lines.append(_format_entry(get_label_func(item), loc, sub_menu))
  120. if sorted:
  121. lines.sort(key=lambda x: x.lower())
  122. if hasattr(root, "get_title"):
  123. loc_label = get_symbol_parents(root, None, enable_choice=enable_choice)
  124. loc_label += [root.get_title(), "..."]
  125. else:
  126. loc_label = ["Location"]
  127. if not item_label:
  128. item_label = "Items"
  129. table = ":halign: center\n\n"
  130. if sub_menu:
  131. width = "100%"
  132. columns = "^1,4"
  133. else:
  134. width = "30%"
  135. columns = "^1"
  136. table = "[width=\"{0}\",cols=\"{1}\",options=\"header\"]\n".format(width, columns)
  137. table += "|===================================================\n"
  138. table += _format_entry(item_label, loc_label, sub_menu)
  139. table += "\n" + "".join(lines) + "\n"
  140. table += "|===================================================\n"
  141. return table
  142. class Buildroot:
  143. """ Buildroot configuration object.
  144. """
  145. root_config = "Config.in"
  146. package_dirname = "package"
  147. package_prefixes = ["BR2_PACKAGE_", "BR2_PACKAGE_HOST_"]
  148. re_pkg_prefix = re.compile(r"^(" + "|".join(package_prefixes) + ").*")
  149. deprecated_symbol = "BR2_DEPRECATED"
  150. list_in = """\
  151. //
  152. // Automatically generated list for Buildroot manual.
  153. //
  154. {table}
  155. """
  156. list_info = {
  157. 'target-packages': {
  158. 'filename': "package-list",
  159. 'root_menu': "Target packages",
  160. 'filter': "_is_real_package",
  161. 'sorted': True,
  162. 'sub_menu': True,
  163. },
  164. 'host-packages': {
  165. 'filename': "host-package-list",
  166. 'root_menu': "Host utilities",
  167. 'filter': "_is_real_package",
  168. 'sorted': True,
  169. 'sub_menu': False,
  170. },
  171. 'deprecated': {
  172. 'filename': "deprecated-list",
  173. 'root_menu': None,
  174. 'filter': "_is_deprecated",
  175. 'sorted': False,
  176. 'sub_menu': True,
  177. },
  178. }
  179. def __init__(self):
  180. self.base_dir = os.environ.get("TOPDIR")
  181. self.output_dir = os.environ.get("O")
  182. self.package_dir = os.path.join(self.base_dir, self.package_dirname)
  183. # The kconfiglib requires an environment variable named "srctree" to
  184. # load the configuration, so set it.
  185. os.environ.update({'srctree': self.base_dir})
  186. self.config = kconfiglib.Config(os.path.join(self.base_dir,
  187. self.root_config))
  188. self._deprecated = self.config.get_symbol(self.deprecated_symbol)
  189. self.gen_date = datetime.datetime.utcnow()
  190. self.br_version_full = os.environ.get("BR2_VERSION_FULL")
  191. if self.br_version_full and self.br_version_full.endswith("-git"):
  192. self.br_version_full = self.br_version_full[:-4]
  193. if not self.br_version_full:
  194. self.br_version_full = "undefined"
  195. def _get_package_symbols(self, package_name):
  196. """ Return a tuple containing the target and host package symbol.
  197. """
  198. symbols = re.sub("[-+.]", "_", package_name)
  199. symbols = symbols.upper()
  200. symbols = tuple([prefix + symbols for prefix in self.package_prefixes])
  201. return symbols
  202. def _is_deprecated(self, symbol):
  203. """ Return True if the symbol is marked as deprecated, otherwise False.
  204. """
  205. # This also catches BR2_DEPRECATED_SINCE_xxxx_xx
  206. return bool([ symbol for x in symbol.get_referenced_symbols()
  207. if x.get_name().startswith(self._deprecated.get_name()) ])
  208. def _is_package(self, symbol, type='real'):
  209. """ Return True if the symbol is a package or a host package, otherwise
  210. False.
  211. :param symbol: The symbol to check
  212. :param type: Limit to 'real' or 'virtual' types of packages,
  213. with 'real' being the default.
  214. Note: only 'real' is (implictly) handled for now
  215. """
  216. if not self.re_pkg_prefix.match(symbol.get_name()):
  217. return False
  218. pkg_name = self._get_pkg_name(symbol)
  219. pattern = "^(HOST_)?" + pkg_name + "$"
  220. pattern = re.sub("_", ".", pattern)
  221. pattern = re.compile(pattern, re.IGNORECASE)
  222. # Here, we cannot just check for the location of the Config.in because
  223. # of the "virtual" package.
  224. #
  225. # So, to check that a symbol is a package (not a package option or
  226. # anything else), we check for the existence of the package *.mk file.
  227. #
  228. # By the way, to actually check for a package, we should grep all *.mk
  229. # files for the following regex:
  230. # "\$\(eval \$\((host-)?(generic|autotools|cmake)-package\)\)"
  231. #
  232. # Implementation details:
  233. #
  234. # * The package list is generated from the *.mk file existence, the
  235. # first time this function is called. Despite the memory consumption,
  236. # this list is stored because the execution time of this script is
  237. # noticeably shorter than rescanning the package sub-tree for each
  238. # symbol.
  239. if not hasattr(self, "_package_list"):
  240. pkg_list = []
  241. for _, _, files in os.walk(self.package_dir):
  242. for file_ in (f for f in files if f.endswith(".mk")):
  243. pkg_list.append(re.sub(r"(.*?)\.mk", r"\1", file_))
  244. setattr(self, "_package_list", pkg_list)
  245. for pkg in getattr(self, "_package_list"):
  246. if type == 'real':
  247. if pattern.match(pkg) and not self._exists_virt_symbol(pkg):
  248. return True
  249. return False
  250. def _is_real_package(self, symbol):
  251. return self._is_package(symbol, 'real')
  252. def _exists_virt_symbol(self, pkg_name):
  253. """ Return True if a symbol exists that defines the package as
  254. a virtual package, False otherwise
  255. :param pkg_name: The name of the package, for which to check if
  256. a symbol exists defining it as a virtual package
  257. """
  258. virt_pattern = "BR2_PACKAGE_HAS_" + pkg_name + "$"
  259. virt_pattern = re.sub("_", ".", virt_pattern)
  260. virt_pattern = re.compile(virt_pattern, re.IGNORECASE)
  261. for sym in self.config:
  262. if virt_pattern.match(sym.get_name()):
  263. return True
  264. return False
  265. def _get_pkg_name(self, symbol):
  266. """ Return the package name of the specified symbol.
  267. :param symbol: The symbol to get the package name of
  268. """
  269. return re.sub("BR2_PACKAGE_(HOST_)?(.*)", r"\2", symbol.get_name())
  270. def _get_symbol_label(self, symbol, mark_deprecated=True):
  271. """ Return the label (a.k.a. prompt text) of the symbol.
  272. :param symbol: The symbol
  273. :param mark_deprecated: Append a 'deprecated' to the label
  274. """
  275. label = symbol.prompts[0][0]
  276. if self._is_deprecated(symbol) and mark_deprecated:
  277. label += " *(deprecated)*"
  278. return label
  279. def print_list(self, list_type, enable_choice=True, enable_deprecated=True,
  280. dry_run=False, output=None):
  281. """ Print the requested list. If not dry run, then the list is
  282. automatically written in its own file.
  283. :param list_type: The list type to be generated
  284. :param enable_choice: Flag enabling choices to appear in the list
  285. :param enable_deprecated: Flag enabling deprecated items to appear in
  286. the package lists
  287. :param dry_run: Dry run (print the list in stdout instead of
  288. writing the list file
  289. """
  290. def _get_menu(title):
  291. """ Return the first symbol menu matching the given title.
  292. """
  293. menus = self.config.get_menus()
  294. menu = [m for m in menus if m.get_title().lower() == title.lower()]
  295. if not menu:
  296. message = "No such menu: '{0}'".format(title)
  297. raise Exception(message)
  298. return menu[0]
  299. list_config = self.list_info[list_type]
  300. root_title = list_config.get('root_menu')
  301. if root_title:
  302. root_item = _get_menu(root_title)
  303. else:
  304. root_item = self.config
  305. filter_ = getattr(self, list_config.get('filter'))
  306. filter_func = lambda x: filter_(x)
  307. if not enable_deprecated and list_type != "deprecated":
  308. filter_func = lambda x: filter_(x) and not self._is_deprecated(x)
  309. mark_depr = list_type != "deprecated"
  310. get_label = lambda x: self._get_symbol_label(x, mark_depr)
  311. item_label = "Features" if list_type == "deprecated" else "Packages"
  312. table = format_asciidoc_table(root_item, get_label,
  313. filter_func=filter_func,
  314. enable_choice=enable_choice,
  315. sorted=list_config.get('sorted'),
  316. sub_menu=list_config.get('sub_menu'),
  317. item_label=item_label)
  318. content = self.list_in.format(table=table)
  319. if dry_run:
  320. print(content)
  321. return
  322. if not output:
  323. output_dir = self.output_dir
  324. if not output_dir:
  325. print("Warning: Undefined output directory.")
  326. print("\tUse source directory as output location.")
  327. output_dir = self.base_dir
  328. output = os.path.join(output_dir,
  329. list_config.get('filename') + ".txt")
  330. if not os.path.exists(os.path.dirname(output)):
  331. os.makedirs(os.path.dirname(output))
  332. print("Writing the {0} list in:\n\t{1}".format(list_type, output))
  333. with open(output, 'w') as fout:
  334. fout.write(content)
  335. if __name__ == '__main__':
  336. list_types = ['target-packages', 'host-packages', 'deprecated']
  337. parser = ArgumentParser()
  338. parser.add_argument("list_type", nargs="?", choices=list_types,
  339. help="""\
  340. Generate the given list (generate all lists if unspecified)""")
  341. parser.add_argument("-n", "--dry-run", dest="dry_run", action='store_true',
  342. help="Output the generated list to stdout")
  343. parser.add_argument("--output-target", dest="output_target",
  344. help="Output target package file")
  345. parser.add_argument("--output-host", dest="output_host",
  346. help="Output host package file")
  347. parser.add_argument("--output-deprecated", dest="output_deprecated",
  348. help="Output deprecated file")
  349. args = parser.parse_args()
  350. lists = [args.list_type] if args.list_type else list_types
  351. buildroot = Buildroot()
  352. for list_name in lists:
  353. output = getattr(args, "output_" + list_name.split("-", 1)[0])
  354. buildroot.print_list(list_name, dry_run=args.dry_run, output=output)