__init__.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 add .', cwd=repodir)
  187. commit_cmd = ['git']
  188. oe.patch.GitApplyTree.gitCommandUserOptions(commit_cmd, d=d)
  189. commit_cmd += ['commit', '-q']
  190. stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
  191. if not stdout:
  192. commit_cmd.append('--allow-empty')
  193. commitmsg = "Initial empty commit with no upstream sources"
  194. elif version:
  195. commitmsg = "Initial commit from upstream at version %s" % version
  196. else:
  197. commitmsg = "Initial commit from upstream"
  198. commit_cmd += ['-m', commitmsg]
  199. bb.process.run(commit_cmd, cwd=repodir)
  200. bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
  201. bb.process.run('git tag -f %s' % basetag, cwd=repodir)
  202. def recipe_to_append(recipefile, config, wildcard=False):
  203. """
  204. Convert a recipe file to a bbappend file path within the workspace.
  205. NOTE: if the bbappend already exists, you should be using
  206. workspace[args.recipename]['bbappend'] instead of calling this
  207. function.
  208. """
  209. appendname = os.path.splitext(os.path.basename(recipefile))[0]
  210. if wildcard:
  211. appendname = re.sub(r'_.*', '_%', appendname)
  212. appendpath = os.path.join(config.workspace_path, 'appends')
  213. appendfile = os.path.join(appendpath, appendname + '.bbappend')
  214. return appendfile
  215. def get_bbclassextend_targets(recipefile, pn):
  216. """
  217. Cheap function to get BBCLASSEXTEND and then convert that to the
  218. list of targets that would result.
  219. """
  220. import bb.utils
  221. values = {}
  222. def get_bbclassextend_varfunc(varname, origvalue, op, newlines):
  223. values[varname] = origvalue
  224. return origvalue, None, 0, True
  225. with open(recipefile, 'r') as f:
  226. bb.utils.edit_metadata(f, ['BBCLASSEXTEND'], get_bbclassextend_varfunc)
  227. targets = []
  228. bbclassextend = values.get('BBCLASSEXTEND', '').split()
  229. if bbclassextend:
  230. for variant in bbclassextend:
  231. if variant == 'nativesdk':
  232. targets.append('%s-%s' % (variant, pn))
  233. elif variant in ['native', 'cross', 'crosssdk']:
  234. targets.append('%s-%s' % (pn, variant))
  235. return targets