externalsrc.bbclass 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # Copyright (C) 2012 Linux Foundation
  2. # Author: Richard Purdie
  3. # Some code and influence taken from srctree.bbclass:
  4. # Copyright (C) 2009 Chris Larson <clarson@kergoth.com>
  5. #
  6. # SPDX-License-Identifier: MIT
  7. #
  8. # externalsrc.bbclass enables use of an existing source tree, usually external to
  9. # the build system to build a piece of software rather than the usual fetch/unpack/patch
  10. # process.
  11. #
  12. # To use, add externalsrc to the global inherit and set EXTERNALSRC to point at the
  13. # directory you want to use containing the sources e.g. from local.conf for a recipe
  14. # called "myrecipe" you would do:
  15. #
  16. # INHERIT += "externalsrc"
  17. # EXTERNALSRC:pn-myrecipe = "/path/to/my/source/tree"
  18. #
  19. # In order to make this class work for both target and native versions (or with
  20. # multilibs/cross or other BBCLASSEXTEND variants), B is set to point to a separate
  21. # directory under the work directory (split source and build directories). This is
  22. # the default, but the build directory can be set to the source directory if
  23. # circumstances dictate by setting EXTERNALSRC_BUILD to the same value, e.g.:
  24. #
  25. # EXTERNALSRC_BUILD:pn-myrecipe = "/path/to/my/source/tree"
  26. #
  27. SRCTREECOVEREDTASKS ?= "do_patch do_unpack do_fetch"
  28. EXTERNALSRC_SYMLINKS ?= "oe-workdir:${WORKDIR} oe-logs:${T}"
  29. python () {
  30. externalsrc = d.getVar('EXTERNALSRC')
  31. externalsrcbuild = d.getVar('EXTERNALSRC_BUILD')
  32. if externalsrc and not externalsrc.startswith("/"):
  33. bb.error("EXTERNALSRC must be an absolute path")
  34. if externalsrcbuild and not externalsrcbuild.startswith("/"):
  35. bb.error("EXTERNALSRC_BUILD must be an absolute path")
  36. # If this is the base recipe and EXTERNALSRC is set for it or any of its
  37. # derivatives, then enable BB_DONT_CACHE to force the recipe to always be
  38. # re-parsed so that the file-checksums function for do_compile is run every
  39. # time.
  40. bpn = d.getVar('BPN')
  41. classextend = (d.getVar('BBCLASSEXTEND') or '').split()
  42. if bpn == d.getVar('PN') or not classextend:
  43. if (externalsrc or
  44. ('native' in classextend and
  45. d.getVar('EXTERNALSRC:pn-%s-native' % bpn)) or
  46. ('nativesdk' in classextend and
  47. d.getVar('EXTERNALSRC:pn-nativesdk-%s' % bpn)) or
  48. ('cross' in classextend and
  49. d.getVar('EXTERNALSRC:pn-%s-cross' % bpn))):
  50. d.setVar('BB_DONT_CACHE', '1')
  51. if externalsrc:
  52. import oe.recipeutils
  53. import oe.path
  54. d.setVar('S', externalsrc)
  55. if externalsrcbuild:
  56. d.setVar('B', externalsrcbuild)
  57. else:
  58. d.setVar('B', '${WORKDIR}/${BPN}-${PV}')
  59. bb.fetch.get_hashvalue(d)
  60. local_srcuri = []
  61. fetch = bb.fetch2.Fetch((d.getVar('SRC_URI') or '').split(), d)
  62. for url in fetch.urls:
  63. url_data = fetch.ud[url]
  64. parm = url_data.parm
  65. if url_data.type in ['file', 'npmsw', 'crate'] or parm.get('type') in ['kmeta', 'git-dependency']:
  66. local_srcuri.append(url)
  67. d.setVar('SRC_URI', ' '.join(local_srcuri))
  68. # sstate is never going to work for external source trees, disable it
  69. d.setVar('SSTATE_SKIP_CREATION', '1')
  70. if d.getVar('CONFIGUREOPT_DEPTRACK') == '--disable-dependency-tracking':
  71. d.setVar('CONFIGUREOPT_DEPTRACK', '')
  72. tasks = filter(lambda k: d.getVarFlag(k, "task"), d.keys())
  73. for task in tasks:
  74. if os.path.realpath(d.getVar('S')) == os.path.realpath(d.getVar('B')):
  75. # Since configure will likely touch ${S}, ensure only we lock so one task has access at a time
  76. d.appendVarFlag(task, "lockfiles", " ${S}/singletask.lock")
  77. for v in d.keys():
  78. cleandirs = d.getVarFlag(v, "cleandirs", False)
  79. if cleandirs:
  80. # We do not want our source to be wiped out, ever (kernel.bbclass does this for do_clean)
  81. cleandirs = oe.recipeutils.split_var_value(cleandirs)
  82. setvalue = False
  83. for cleandir in cleandirs[:]:
  84. if oe.path.is_path_parent(externalsrc, d.expand(cleandir)):
  85. cleandirs.remove(cleandir)
  86. setvalue = True
  87. if setvalue:
  88. d.setVarFlag(v, 'cleandirs', ' '.join(cleandirs))
  89. fetch_tasks = ['do_fetch', 'do_unpack']
  90. # If we deltask do_patch, there's no dependency to ensure do_unpack gets run, so add one
  91. # Note that we cannot use d.appendVarFlag() here because deps is expected to be a list object, not a string
  92. d.setVarFlag('do_configure', 'deps', (d.getVarFlag('do_configure', 'deps', False) or []) + ['do_unpack'])
  93. d.setVarFlag('do_populate_lic', 'deps', (d.getVarFlag('do_populate_lic', 'deps', False) or []) + ['do_unpack'])
  94. for task in d.getVar("SRCTREECOVEREDTASKS").split():
  95. if local_srcuri and task in fetch_tasks:
  96. continue
  97. bb.build.deltask(task, d)
  98. if task == 'do_unpack':
  99. # The reproducible build create_source_date_epoch_stamp function must
  100. # be run after the source is available and before the
  101. # do_deploy_source_date_epoch task. In the normal case, it's attached
  102. # to do_unpack as a postfuncs, but since we removed do_unpack (above)
  103. # we need to move the function elsewhere. The easiest thing to do is
  104. # move it into the prefuncs of the do_deploy_source_date_epoch task.
  105. # This is safe, as externalsrc runs with the source already unpacked.
  106. d.prependVarFlag('do_deploy_source_date_epoch', 'prefuncs', 'create_source_date_epoch_stamp ')
  107. d.prependVarFlag('do_compile', 'prefuncs', "externalsrc_compile_prefunc ")
  108. d.prependVarFlag('do_configure', 'prefuncs', "externalsrc_configure_prefunc ")
  109. d.setVarFlag('do_compile', 'file-checksums', '${@srctree_hash_files(d)}')
  110. d.setVarFlag('do_configure', 'file-checksums', '${@srctree_configure_hash_files(d)}')
  111. d.appendVarFlag('do_compile', 'prefuncs', ' fetcher_hashes_dummyfunc')
  112. d.appendVarFlag('do_configure', 'prefuncs', ' fetcher_hashes_dummyfunc')
  113. # We don't want the workdir to go away
  114. d.appendVar('RM_WORK_EXCLUDE', ' ' + d.getVar('PN'))
  115. bb.build.addtask('do_buildclean',
  116. 'do_clean' if d.getVar('S') == d.getVar('B') else None,
  117. None, d)
  118. # If B=S the same builddir is used even for different architectures.
  119. # Thus, use a shared CONFIGURESTAMPFILE and STAMP directory so that
  120. # change of do_configure task hash is correctly detected and stamps are
  121. # invalidated if e.g. MACHINE changes.
  122. if d.getVar('S') == d.getVar('B'):
  123. configstamp = '${TMPDIR}/work-shared/${PN}/${EXTENDPE}${PV}-${PR}/configure.sstate'
  124. d.setVar('CONFIGURESTAMPFILE', configstamp)
  125. d.setVar('STAMP', '${STAMPS_DIR}/work-shared/${PN}/${EXTENDPE}${PV}-${PR}')
  126. d.setVar('STAMPCLEAN', '${STAMPS_DIR}/work-shared/${PN}/*-*')
  127. }
  128. python externalsrc_configure_prefunc() {
  129. s_dir = d.getVar('S')
  130. # Create desired symlinks
  131. symlinks = (d.getVar('EXTERNALSRC_SYMLINKS') or '').split()
  132. newlinks = []
  133. for symlink in symlinks:
  134. symsplit = symlink.split(':', 1)
  135. lnkfile = os.path.join(s_dir, symsplit[0])
  136. target = d.expand(symsplit[1])
  137. if len(symsplit) > 1:
  138. if os.path.islink(lnkfile):
  139. # Link already exists, leave it if it points to the right location already
  140. if os.readlink(lnkfile) == target:
  141. continue
  142. os.unlink(lnkfile)
  143. elif os.path.exists(lnkfile):
  144. # File/dir exists with same name as link, just leave it alone
  145. continue
  146. os.symlink(target, lnkfile)
  147. newlinks.append(symsplit[0])
  148. # Hide the symlinks from git
  149. try:
  150. git_exclude_file = os.path.join(s_dir, '.git/info/exclude')
  151. if os.path.exists(git_exclude_file):
  152. with open(git_exclude_file, 'r+') as efile:
  153. elines = efile.readlines()
  154. for link in newlinks:
  155. if link in elines or '/'+link in elines:
  156. continue
  157. efile.write('/' + link + '\n')
  158. except IOError as ioe:
  159. bb.note('Failed to hide EXTERNALSRC_SYMLINKS from git')
  160. }
  161. python externalsrc_compile_prefunc() {
  162. # Make it obvious that this is happening, since forgetting about it could lead to much confusion
  163. bb.plain('NOTE: %s: compiling from external source tree %s' % (d.getVar('PN'), d.getVar('EXTERNALSRC')))
  164. }
  165. do_buildclean[dirs] = "${S} ${B}"
  166. do_buildclean[nostamp] = "1"
  167. do_buildclean[doc] = "Call 'make clean' or equivalent in ${B}"
  168. externalsrc_do_buildclean() {
  169. if [ -e Makefile -o -e makefile -o -e GNUmakefile ]; then
  170. rm -f ${@' '.join([x.split(':')[0] for x in (d.getVar('EXTERNALSRC_SYMLINKS') or '').split()])}
  171. if [ "${CLEANBROKEN}" != "1" ]; then
  172. oe_runmake clean || die "make failed"
  173. fi
  174. else
  175. bbnote "nothing to do - no makefile found"
  176. fi
  177. }
  178. def srctree_hash_files(d, srcdir=None):
  179. import shutil
  180. import subprocess
  181. import tempfile
  182. import hashlib
  183. s_dir = srcdir or d.getVar('EXTERNALSRC')
  184. git_dir = None
  185. try:
  186. git_dir = os.path.join(s_dir,
  187. subprocess.check_output(['git', '-C', s_dir, 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL).decode("utf-8").rstrip())
  188. top_git_dir = os.path.join(d.getVar("TOPDIR"),
  189. subprocess.check_output(['git', '-C', d.getVar("TOPDIR"), 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL).decode("utf-8").rstrip())
  190. if git_dir == top_git_dir:
  191. git_dir = None
  192. except subprocess.CalledProcessError:
  193. pass
  194. ret = " "
  195. if git_dir is not None:
  196. oe_hash_file = os.path.join(git_dir, 'oe-devtool-tree-sha1-%s' % d.getVar('PN'))
  197. with tempfile.NamedTemporaryFile(prefix='oe-devtool-index') as tmp_index:
  198. # Clone index
  199. shutil.copyfile(os.path.join(git_dir, 'index'), tmp_index.name)
  200. # Update our custom index
  201. env = os.environ.copy()
  202. env['GIT_INDEX_FILE'] = tmp_index.name
  203. subprocess.check_output(['git', 'add', '-A', '.'], cwd=s_dir, env=env)
  204. git_sha1 = subprocess.check_output(['git', 'write-tree'], cwd=s_dir, env=env).decode("utf-8")
  205. if os.path.exists(os.path.join(s_dir, ".gitmodules")) and os.path.getsize(os.path.join(s_dir, ".gitmodules")) > 0:
  206. submodule_helper = subprocess.check_output(["git", "config", "--file", ".gitmodules", "--get-regexp", "path"], cwd=s_dir, env=env).decode("utf-8")
  207. for line in submodule_helper.splitlines():
  208. module_dir = os.path.join(s_dir, line.rsplit(maxsplit=1)[1])
  209. if os.path.isdir(module_dir):
  210. proc = subprocess.Popen(['git', 'add', '-A', '.'], cwd=module_dir, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  211. proc.communicate()
  212. proc = subprocess.Popen(['git', 'write-tree'], cwd=module_dir, env=env, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  213. stdout, _ = proc.communicate()
  214. git_sha1 += stdout.decode("utf-8")
  215. sha1 = hashlib.sha1(git_sha1.encode("utf-8")).hexdigest()
  216. with open(oe_hash_file, 'w') as fobj:
  217. fobj.write(sha1)
  218. ret = oe_hash_file + ':True'
  219. else:
  220. ret = s_dir + '/*:True'
  221. return ret
  222. def srctree_configure_hash_files(d):
  223. """
  224. Get the list of files that should trigger do_configure to re-execute,
  225. based on the value of CONFIGURE_FILES
  226. """
  227. import fnmatch
  228. in_files = (d.getVar('CONFIGURE_FILES') or '').split()
  229. out_items = []
  230. search_files = []
  231. for entry in in_files:
  232. if entry.startswith('/'):
  233. out_items.append('%s:%s' % (entry, os.path.exists(entry)))
  234. else:
  235. search_files.append(entry)
  236. if search_files:
  237. s_dir = d.getVar('EXTERNALSRC')
  238. for root, _, files in os.walk(s_dir):
  239. for p in search_files:
  240. for f in fnmatch.filter(files, p):
  241. out_items.append('%s:True' % os.path.join(root, f))
  242. return ' '.join(out_items)
  243. EXPORT_FUNCTIONS do_buildclean