BBHandler.py 8.8 KB

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