BBHandler.py 8.8 KB

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