__init__.py 14 KB

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