__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #!/usr/bin/env python3
  2. # Development tool - utility functions for plugins
  3. #
  4. # Copyright (C) 2014 Intel Corporation
  5. #
  6. # SPDX-License-Identifier: GPL-2.0-only
  7. #
  8. """Devtool plugins module"""
  9. import os
  10. import sys
  11. import subprocess
  12. import logging
  13. import re
  14. import codecs
  15. logger = logging.getLogger('devtool')
  16. class DevtoolError(Exception):
  17. """Exception for handling devtool errors"""
  18. def __init__(self, message, exitcode=1):
  19. super(DevtoolError, self).__init__(message)
  20. self.exitcode = exitcode
  21. def exec_build_env_command(init_path, builddir, cmd, watch=False, **options):
  22. """Run a program in bitbake build context"""
  23. import bb
  24. if not 'cwd' in options:
  25. options["cwd"] = builddir
  26. if init_path:
  27. # As the OE init script makes use of BASH_SOURCE to determine OEROOT,
  28. # and can't determine it when running under dash, we need to set
  29. # the executable to bash to correctly set things up
  30. if not 'executable' in options:
  31. options['executable'] = 'bash'
  32. logger.debug('Executing command: "%s" using init path %s' % (cmd, init_path))
  33. init_prefix = '. %s %s > /dev/null && ' % (init_path, builddir)
  34. else:
  35. logger.debug('Executing command "%s"' % cmd)
  36. init_prefix = ''
  37. if watch:
  38. if sys.stdout.isatty():
  39. # Fool bitbake into thinking it's outputting to a terminal (because it is, indirectly)
  40. cmd = 'script -e -q -c "%s" /dev/null' % cmd
  41. return exec_watch('%s%s' % (init_prefix, cmd), **options)
  42. else:
  43. return bb.process.run('%s%s' % (init_prefix, cmd), **options)
  44. def exec_watch(cmd, **options):
  45. """Run program with stdout shown on sys.stdout"""
  46. import bb
  47. if isinstance(cmd, str) and not "shell" in options:
  48. options["shell"] = True
  49. process = subprocess.Popen(
  50. cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **options
  51. )
  52. reader = codecs.getreader('utf-8')(process.stdout)
  53. buf = ''
  54. while True:
  55. out = reader.read(1, 1)
  56. if out:
  57. sys.stdout.write(out)
  58. sys.stdout.flush()
  59. buf += out
  60. elif out == '' and process.poll() != None:
  61. break
  62. if process.returncode != 0:
  63. raise bb.process.ExecutionError(cmd, process.returncode, buf, None)
  64. return buf, None
  65. def exec_fakeroot(d, cmd, **kwargs):
  66. """Run a command under fakeroot (pseudo, in fact) so that it picks up the appropriate file permissions"""
  67. # Grab the command and check it actually exists
  68. fakerootcmd = d.getVar('FAKEROOTCMD')
  69. fakerootenv = d.getVar('FAKEROOTENV')
  70. exec_fakeroot_no_d(fakerootcmd, fakerootenv, cmd, kwargs)
  71. def exec_fakeroot_no_d(fakerootcmd, fakerootenv, cmd, **kwargs):
  72. if not os.path.exists(fakerootcmd):
  73. logger.error('pseudo executable %s could not be found - have you run a build yet? pseudo-native should install this and if you have run any build then that should have been built')
  74. return 2
  75. # Set up the appropriate environment
  76. newenv = dict(os.environ)
  77. for varvalue in fakerootenv.split():
  78. if '=' in varvalue:
  79. splitval = varvalue.split('=', 1)
  80. newenv[splitval[0]] = splitval[1]
  81. return subprocess.call("%s %s" % (fakerootcmd, cmd), env=newenv, **kwargs)
  82. def setup_tinfoil(config_only=False, basepath=None, tracking=False):
  83. """Initialize tinfoil api from bitbake"""
  84. import scriptpath
  85. orig_cwd = os.path.abspath(os.curdir)
  86. try:
  87. if basepath:
  88. os.chdir(basepath)
  89. bitbakepath = scriptpath.add_bitbake_lib_path()
  90. if not bitbakepath:
  91. logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
  92. sys.exit(1)
  93. import bb.tinfoil
  94. tinfoil = bb.tinfoil.Tinfoil(tracking=tracking)
  95. try:
  96. tinfoil.logger.setLevel(logger.getEffectiveLevel())
  97. tinfoil.prepare(config_only)
  98. except bb.tinfoil.TinfoilUIException:
  99. tinfoil.shutdown()
  100. raise DevtoolError('Failed to start bitbake environment')
  101. except:
  102. tinfoil.shutdown()
  103. raise
  104. finally:
  105. os.chdir(orig_cwd)
  106. return tinfoil
  107. def parse_recipe(config, tinfoil, pn, appends, filter_workspace=True):
  108. """Parse the specified recipe"""
  109. try:
  110. recipefile = tinfoil.get_recipe_file(pn)
  111. except bb.providers.NoProvider as e:
  112. logger.error(str(e))
  113. return None
  114. if appends:
  115. append_files = tinfoil.get_file_appends(recipefile)
  116. if filter_workspace:
  117. # Filter out appends from the workspace
  118. append_files = [path for path in append_files if
  119. not path.startswith(config.workspace_path)]
  120. else:
  121. append_files = None
  122. try:
  123. rd = tinfoil.parse_recipe_file(recipefile, appends, append_files)
  124. except Exception as e:
  125. logger.error(str(e))
  126. return None
  127. return rd
  128. def check_workspace_recipe(workspace, pn, checksrc=True, bbclassextend=False):
  129. """
  130. Check that a recipe is in the workspace and (optionally) that source
  131. is present.
  132. """
  133. workspacepn = pn
  134. for recipe, value in workspace.items():
  135. if recipe == pn:
  136. break
  137. if bbclassextend:
  138. recipefile = value['recipefile']
  139. if recipefile:
  140. targets = get_bbclassextend_targets(recipefile, recipe)
  141. if pn in targets:
  142. workspacepn = recipe
  143. break
  144. else:
  145. raise DevtoolError("No recipe named '%s' in your workspace" % pn)
  146. if checksrc:
  147. srctree = workspace[workspacepn]['srctree']
  148. if not os.path.exists(srctree):
  149. raise DevtoolError("Source tree %s for recipe %s does not exist" % (srctree, workspacepn))
  150. if not os.listdir(srctree):
  151. raise DevtoolError("Source tree %s for recipe %s is empty" % (srctree, workspacepn))
  152. return workspacepn
  153. def use_external_build(same_dir, no_same_dir, d):
  154. """
  155. Determine if we should use B!=S (separate build and source directories) or not
  156. """
  157. b_is_s = True
  158. if no_same_dir:
  159. logger.info('Using separate build directory since --no-same-dir specified')
  160. b_is_s = False
  161. elif same_dir:
  162. logger.info('Using source tree as build directory since --same-dir specified')
  163. elif bb.data.inherits_class('autotools-brokensep', d):
  164. logger.info('Using source tree as build directory since recipe inherits autotools-brokensep')
  165. elif os.path.abspath(d.getVar('B')) == os.path.abspath(d.getVar('S')):
  166. logger.info('Using source tree as build directory since that would be the default for this recipe')
  167. else:
  168. b_is_s = False
  169. return b_is_s
  170. def setup_git_repo(repodir, version, devbranch, basetag='devtool-base', d=None):
  171. """
  172. Set up the git repository for the source tree
  173. """
  174. import bb.process
  175. import oe.patch
  176. if not os.path.exists(os.path.join(repodir, '.git')):
  177. bb.process.run('git init', cwd=repodir)
  178. bb.process.run('git config --local gc.autodetach 0', cwd=repodir)
  179. bb.process.run('git add -f -A .', cwd=repodir)
  180. commit_cmd = ['git']
  181. oe.patch.GitApplyTree.gitCommandUserOptions(commit_cmd, d=d)
  182. commit_cmd += ['commit', '-q']
  183. stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
  184. if not stdout:
  185. commit_cmd.append('--allow-empty')
  186. commitmsg = "Initial empty commit with no upstream sources"
  187. elif version:
  188. commitmsg = "Initial commit from upstream at version %s" % version
  189. else:
  190. commitmsg = "Initial commit from upstream"
  191. commit_cmd += ['-m', commitmsg]
  192. bb.process.run(commit_cmd, cwd=repodir)
  193. # Ensure singletask.lock (as used by externalsrc.bbclass) is ignored by git
  194. gitinfodir = os.path.join(repodir, '.git', 'info')
  195. try:
  196. os.mkdir(gitinfodir)
  197. except FileExistsError:
  198. pass
  199. excludes = []
  200. excludefile = os.path.join(gitinfodir, 'exclude')
  201. try:
  202. with open(excludefile, 'r') as f:
  203. excludes = f.readlines()
  204. except FileNotFoundError:
  205. pass
  206. if 'singletask.lock\n' not in excludes:
  207. excludes.append('singletask.lock\n')
  208. with open(excludefile, 'w') as f:
  209. for line in excludes:
  210. f.write(line)
  211. bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
  212. bb.process.run('git tag -f --no-sign %s' % basetag, cwd=repodir)
  213. # if recipe unpacks another git repo inside S, we need to declare it as a regular git submodule now,
  214. # so we will be able to tag branches on it and extract patches when doing finish/update on the recipe
  215. stdout, _ = bb.process.run("git status --porcelain", cwd=repodir)
  216. found = False
  217. for line in stdout.splitlines():
  218. if line.endswith("/"):
  219. new_dir = line.split()[1]
  220. for root, dirs, files in os.walk(os.path.join(repodir, new_dir)):
  221. if ".git" in dirs + files:
  222. (stdout, _) = bb.process.run('git remote', cwd=root)
  223. remote = stdout.splitlines()[0]
  224. (stdout, _) = bb.process.run('git remote get-url %s' % remote, cwd=root)
  225. remote_url = stdout.splitlines()[0]
  226. logger.error(os.path.relpath(os.path.join(root, ".."), root))
  227. bb.process.run('git submodule add %s %s' % (remote_url, os.path.relpath(root, os.path.join(root, ".."))), cwd=os.path.join(root, ".."))
  228. found = True
  229. if found:
  230. oe.patch.GitApplyTree.commitIgnored("Add additional submodule from SRC_URI", dir=os.path.join(root, ".."), d=d)
  231. found = False
  232. if os.path.exists(os.path.join(repodir, '.gitmodules')):
  233. bb.process.run('git submodule foreach --recursive "git tag -f --no-sign %s"' % basetag, cwd=repodir)
  234. def recipe_to_append(recipefile, config, wildcard=False):
  235. """
  236. Convert a recipe file to a bbappend file path within the workspace.
  237. NOTE: if the bbappend already exists, you should be using
  238. workspace[args.recipename]['bbappend'] instead of calling this
  239. function.
  240. """
  241. appendname = os.path.splitext(os.path.basename(recipefile))[0]
  242. if wildcard:
  243. appendname = re.sub(r'_.*', '_%', appendname)
  244. appendpath = os.path.join(config.workspace_path, 'appends')
  245. appendfile = os.path.join(appendpath, appendname + '.bbappend')
  246. return appendfile
  247. def get_bbclassextend_targets(recipefile, pn):
  248. """
  249. Cheap function to get BBCLASSEXTEND and then convert that to the
  250. list of targets that would result.
  251. """
  252. import bb.utils
  253. values = {}
  254. def get_bbclassextend_varfunc(varname, origvalue, op, newlines):
  255. values[varname] = origvalue
  256. return origvalue, None, 0, True
  257. with open(recipefile, 'r') as f:
  258. bb.utils.edit_metadata(f, ['BBCLASSEXTEND'], get_bbclassextend_varfunc)
  259. targets = []
  260. bbclassextend = values.get('BBCLASSEXTEND', '').split()
  261. if bbclassextend:
  262. for variant in bbclassextend:
  263. if variant == 'nativesdk':
  264. targets.append('%s-%s' % (variant, pn))
  265. elif variant in ['native', 'cross', 'crosssdk']:
  266. targets.append('%s-%s' % (pn, variant))
  267. return targets
  268. def replace_from_file(path, old, new):
  269. """Replace strings on a file"""
  270. def read_file(path):
  271. data = None
  272. with open(path) as f:
  273. data = f.read()
  274. return data
  275. def write_file(path, data):
  276. if data is None:
  277. return
  278. wdata = data.rstrip() + "\n"
  279. with open(path, "w") as f:
  280. f.write(wdata)
  281. # In case old is None, return immediately
  282. if old is None:
  283. return
  284. try:
  285. rdata = read_file(path)
  286. except IOError as e:
  287. # if file does not exit, just quit, otherwise raise an exception
  288. if e.errno == errno.ENOENT:
  289. return
  290. else:
  291. raise
  292. old_contents = rdata.splitlines()
  293. new_contents = []
  294. for old_content in old_contents:
  295. try:
  296. new_contents.append(old_content.replace(old, new))
  297. except ValueError:
  298. pass
  299. write_file(path, "\n".join(new_contents))
  300. def update_unlockedsigs(basepath, workspace, fixed_setup, extra=None):
  301. """ This function will make unlocked-sigs.inc match the recipes in the
  302. workspace plus any extras we want unlocked. """
  303. if not fixed_setup:
  304. # Only need to write this out within the eSDK
  305. return
  306. if not extra:
  307. extra = []
  308. confdir = os.path.join(basepath, 'conf')
  309. unlockedsigs = os.path.join(confdir, 'unlocked-sigs.inc')
  310. # Get current unlocked list if any
  311. values = {}
  312. def get_unlockedsigs_varfunc(varname, origvalue, op, newlines):
  313. values[varname] = origvalue
  314. return origvalue, None, 0, True
  315. if os.path.exists(unlockedsigs):
  316. with open(unlockedsigs, 'r') as f:
  317. bb.utils.edit_metadata(f, ['SIGGEN_UNLOCKED_RECIPES'], get_unlockedsigs_varfunc)
  318. unlocked = sorted(values.get('SIGGEN_UNLOCKED_RECIPES', []))
  319. # If the new list is different to the current list, write it out
  320. newunlocked = sorted(list(workspace.keys()) + extra)
  321. if unlocked != newunlocked:
  322. bb.utils.mkdirhier(confdir)
  323. with open(unlockedsigs, 'w') as f:
  324. f.write("# DO NOT MODIFY! YOUR CHANGES WILL BE LOST.\n" +
  325. "# This layer was created by the OpenEmbedded devtool" +
  326. " utility in order to\n" +
  327. "# contain recipes that are unlocked.\n")
  328. f.write('SIGGEN_UNLOCKED_RECIPES += "\\\n')
  329. for pn in newunlocked:
  330. f.write(' ' + pn)
  331. f.write('"')
  332. def check_prerelease_version(ver, operation):
  333. if 'pre' in ver or 'rc' in ver:
  334. logger.warning('Version "%s" looks like a pre-release version. '
  335. 'If that is the case, in order to ensure that the '
  336. 'version doesn\'t appear to go backwards when you '
  337. 'later upgrade to the final release version, it is '
  338. 'recommmended that instead you use '
  339. '<current version>+<pre-release version> e.g. if '
  340. 'upgrading from 1.9 to 2.0-rc2 use "1.9+2.0-rc2". '
  341. 'If you prefer not to reset and re-try, you can change '
  342. 'the version after %s succeeds using "devtool rename" '
  343. 'with -V/--version.' % (ver, operation))
  344. def check_git_repo_dirty(repodir):
  345. """Check if a git repository is clean or not"""
  346. stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
  347. return stdout
  348. def check_git_repo_op(srctree, ignoredirs=None):
  349. """Check if a git repository is in the middle of a rebase"""
  350. stdout, _ = bb.process.run('git rev-parse --show-toplevel', cwd=srctree)
  351. topleveldir = stdout.strip()
  352. if ignoredirs and topleveldir in ignoredirs:
  353. return
  354. gitdir = os.path.join(topleveldir, '.git')
  355. if os.path.exists(os.path.join(gitdir, 'rebase-merge')):
  356. raise DevtoolError("Source tree %s appears to be in the middle of a rebase - please resolve this first" % srctree)
  357. if os.path.exists(os.path.join(gitdir, 'rebase-apply')):
  358. raise DevtoolError("Source tree %s appears to be in the middle of 'git am' or 'git apply' - please resolve this first" % srctree)