BBHandler.py 9.5 KB

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