BBHandler.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #!/usr/bin/env python
  2. # ex:ts=4:sw=4:sts=4:et
  3. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  4. """
  5. class for handling .bb files
  6. Reads a .bb file and obtains its metadata
  7. """
  8. # Copyright (C) 2003, 2004 Chris Larson
  9. # Copyright (C) 2003, 2004 Phil Blundell
  10. #
  11. # SPDX-License-Identifier: GPL-2.0-only
  12. #
  13. # This program is free software; you can redistribute it and/or modify
  14. # it under the terms of the GNU General Public License version 2 as
  15. # published by the Free Software Foundation.
  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 along
  23. # with this program; if not, write to the Free Software Foundation, Inc.,
  24. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  25. import re, bb, os
  26. import logging
  27. import bb.build, bb.utils
  28. from bb import data
  29. from . import ConfHandler
  30. from .. import resolve_file, ast, logger, ParseError
  31. from .ConfHandler import include, init
  32. # For compatibility
  33. bb.deprecate_import(__name__, "bb.parse", ["vars_from_file"])
  34. __func_start_regexp__ = re.compile(r"(((?P<py>python)|(?P<fr>fakeroot))\s*)*(?P<func>[\w\.\-\+\{\}\$]+)?\s*\(\s*\)\s*{$" )
  35. __inherit_regexp__ = re.compile(r"inherit\s+(.+)" )
  36. __export_func_regexp__ = re.compile(r"EXPORT_FUNCTIONS\s+(.+)" )
  37. __addtask_regexp__ = re.compile(r"addtask\s+(?P<func>\w+)\s*((before\s*(?P<before>((.*(?=after))|(.*))))|(after\s*(?P<after>((.*(?=before))|(.*)))))*")
  38. __deltask_regexp__ = re.compile(r"deltask\s+(?P<func>\w+)(?P<ignores>.*)")
  39. __addhandler_regexp__ = re.compile(r"addhandler\s+(.+)" )
  40. __def_regexp__ = re.compile(r"def\s+(\w+).*:" )
  41. __python_func_regexp__ = re.compile(r"(\s+.*)|(^$)|(^#)" )
  42. __python_tab_regexp__ = re.compile(r" *\t")
  43. __infunc__ = []
  44. __inpython__ = False
  45. __body__ = []
  46. __classname__ = ""
  47. cached_statements = {}
  48. def supports(fn, d):
  49. """Return True if fn has a supported extension"""
  50. return os.path.splitext(fn)[-1] in [".bb", ".bbclass", ".inc"]
  51. def inherit(files, fn, lineno, d):
  52. __inherit_cache = d.getVar('__inherit_cache', False) or []
  53. files = d.expand(files).split()
  54. for file in files:
  55. if not os.path.isabs(file) and not file.endswith(".bbclass"):
  56. file = os.path.join('classes', '%s.bbclass' % file)
  57. if not os.path.isabs(file):
  58. bbpath = d.getVar("BBPATH")
  59. abs_fn, attempts = bb.utils.which(bbpath, file, history=True)
  60. for af in attempts:
  61. if af != abs_fn:
  62. bb.parse.mark_dependency(d, af)
  63. if abs_fn:
  64. file = abs_fn
  65. if not file in __inherit_cache:
  66. logger.debug(1, "Inheriting %s (from %s:%d)" % (file, fn, lineno))
  67. __inherit_cache.append( file )
  68. d.setVar('__inherit_cache', __inherit_cache)
  69. include(fn, file, lineno, d, "inherit")
  70. __inherit_cache = d.getVar('__inherit_cache', False) or []
  71. def get_statements(filename, absolute_filename, base_name):
  72. global cached_statements
  73. try:
  74. return cached_statements[absolute_filename]
  75. except KeyError:
  76. with open(absolute_filename, 'r') as f:
  77. statements = ast.StatementGroup()
  78. lineno = 0
  79. while True:
  80. lineno = lineno + 1
  81. s = f.readline()
  82. if not s: break
  83. s = s.rstrip()
  84. feeder(lineno, s, filename, base_name, statements)
  85. if __inpython__:
  86. # add a blank line to close out any python definition
  87. feeder(lineno, "", filename, base_name, statements, eof=True)
  88. if filename.endswith(".bbclass") or filename.endswith(".inc"):
  89. cached_statements[absolute_filename] = statements
  90. return statements
  91. def handle(fn, d, include):
  92. global __func_start_regexp__, __inherit_regexp__, __export_func_regexp__, __addtask_regexp__, __addhandler_regexp__, __infunc__, __body__, __residue__, __classname__
  93. __body__ = []
  94. __infunc__ = []
  95. __classname__ = ""
  96. __residue__ = []
  97. base_name = os.path.basename(fn)
  98. (root, ext) = os.path.splitext(base_name)
  99. init(d)
  100. if ext == ".bbclass":
  101. __classname__ = root
  102. __inherit_cache = d.getVar('__inherit_cache', False) or []
  103. if not fn in __inherit_cache:
  104. __inherit_cache.append(fn)
  105. d.setVar('__inherit_cache', __inherit_cache)
  106. if include != 0:
  107. oldfile = d.getVar('FILE', False)
  108. else:
  109. oldfile = None
  110. abs_fn = resolve_file(fn, d)
  111. # actual loading
  112. statements = get_statements(fn, abs_fn, base_name)
  113. # DONE WITH PARSING... time to evaluate
  114. if ext != ".bbclass" and abs_fn != oldfile:
  115. d.setVar('FILE', abs_fn)
  116. try:
  117. statements.eval(d)
  118. except bb.parse.SkipRecipe:
  119. d.setVar("__SKIPPED", True)
  120. if include == 0:
  121. return { "" : d }
  122. if __infunc__:
  123. raise ParseError("Shell function %s is never closed" % __infunc__[0], __infunc__[1], __infunc__[2])
  124. if __residue__:
  125. raise ParseError("Leftover unparsed (incomplete?) data %s from %s" % __residue__, fn)
  126. if ext != ".bbclass" and include == 0:
  127. return ast.multi_finalize(fn, d)
  128. if ext != ".bbclass" and oldfile and abs_fn != oldfile:
  129. d.setVar("FILE", oldfile)
  130. return d
  131. def feeder(lineno, s, fn, root, statements, eof=False):
  132. global __func_start_regexp__, __inherit_regexp__, __export_func_regexp__, __addtask_regexp__, __addhandler_regexp__, __def_regexp__, __python_func_regexp__, __inpython__, __infunc__, __body__, bb, __residue__, __classname__
  133. # Check tabs in python functions:
  134. # - def py_funcname(): covered by __inpython__
  135. # - python(): covered by '__anonymous' == __infunc__[0]
  136. # - python funcname(): covered by __infunc__[3]
  137. if __inpython__ or (__infunc__ and ('__anonymous' == __infunc__[0] or __infunc__[3])):
  138. tab = __python_tab_regexp__.match(s)
  139. if tab:
  140. bb.warn('python should use 4 spaces indentation, but found tabs in %s, line %s' % (root, lineno))
  141. if __infunc__:
  142. if s == '}':
  143. __body__.append('')
  144. ast.handleMethod(statements, fn, lineno, __infunc__[0], __body__, __infunc__[3], __infunc__[4])
  145. __infunc__ = []
  146. __body__ = []
  147. else:
  148. __body__.append(s)
  149. return
  150. if __inpython__:
  151. m = __python_func_regexp__.match(s)
  152. if m and not eof:
  153. __body__.append(s)
  154. return
  155. else:
  156. ast.handlePythonMethod(statements, fn, lineno, __inpython__,
  157. root, __body__)
  158. __body__ = []
  159. __inpython__ = False
  160. if eof:
  161. return
  162. if s and s[0] == '#':
  163. if len(__residue__) != 0 and __residue__[0][0] != "#":
  164. bb.fatal("There is a comment on line %s of file %s (%s) which is in the middle of a multiline expression.\nBitbake used to ignore these but no longer does so, please fix your metadata as errors are likely as a result of this change." % (lineno, fn, s))
  165. if len(__residue__) != 0 and __residue__[0][0] == "#" and (not s or s[0] != "#"):
  166. bb.fatal("There is a confusing multiline, partially commented expression on line %s of file %s (%s).\nPlease clarify whether this is all a comment or should be parsed." % (lineno, fn, s))
  167. if s and s[-1] == '\\':
  168. __residue__.append(s[:-1])
  169. return
  170. s = "".join(__residue__) + s
  171. __residue__ = []
  172. # Skip empty lines
  173. if s == '':
  174. return
  175. # Skip comments
  176. if s[0] == '#':
  177. return
  178. m = __func_start_regexp__.match(s)
  179. if m:
  180. __infunc__ = [m.group("func") or "__anonymous", fn, lineno, m.group("py") is not None, m.group("fr") is not None]
  181. return
  182. m = __def_regexp__.match(s)
  183. if m:
  184. __body__.append(s)
  185. __inpython__ = m.group(1)
  186. return
  187. m = __export_func_regexp__.match(s)
  188. if m:
  189. ast.handleExportFuncs(statements, fn, lineno, m, __classname__)
  190. return
  191. m = __addtask_regexp__.match(s)
  192. if m:
  193. if len(m.group().split()) == 2:
  194. # Check and warn for "addtask task1 task2"
  195. m2 = re.match(r"addtask\s+(?P<func>\w+)(?P<ignores>.*)", s)
  196. if m2 and m2.group('ignores'):
  197. logger.warning('addtask ignored: "%s"' % m2.group('ignores'))
  198. # Check and warn for "addtask task1 before task2 before task3", the
  199. # similar to "after"
  200. taskexpression = s.split()
  201. for word in ('before', 'after'):
  202. if taskexpression.count(word) > 1:
  203. logger.warning("addtask contained multiple '%s' keywords, only one is supported" % word)
  204. ast.handleAddTask(statements, fn, lineno, m)
  205. return
  206. m = __deltask_regexp__.match(s)
  207. if m:
  208. # Check and warn "for deltask task1 task2"
  209. if m.group('ignores'):
  210. logger.warning('deltask ignored: "%s"' % m.group('ignores'))
  211. ast.handleDelTask(statements, fn, lineno, m)
  212. return
  213. m = __addhandler_regexp__.match(s)
  214. if m:
  215. ast.handleBBHandlers(statements, fn, lineno, m)
  216. return
  217. m = __inherit_regexp__.match(s)
  218. if m:
  219. ast.handleInherit(statements, fn, lineno, m)
  220. return
  221. return ConfHandler.feeder(lineno, s, fn, statements)
  222. # Add us to the handlers list
  223. from .. import handlers
  224. handlers.append({'supports': supports, 'handle': handle, 'init': init})
  225. del handlers