__init__.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. logger = logging.getLogger('devtool')
  25. class DevtoolError(Exception):
  26. """Exception for handling devtool errors"""
  27. def __init__(self, message, exitcode=1):
  28. super(DevtoolError, self).__init__(message)
  29. self.exitcode = exitcode
  30. def exec_build_env_command(init_path, builddir, cmd, watch=False, **options):
  31. """Run a program in bitbake build context"""
  32. import bb
  33. if not 'cwd' in options:
  34. options["cwd"] = builddir
  35. if init_path:
  36. # As the OE init script makes use of BASH_SOURCE to determine OEROOT,
  37. # and can't determine it when running under dash, we need to set
  38. # the executable to bash to correctly set things up
  39. if not 'executable' in options:
  40. options['executable'] = 'bash'
  41. logger.debug('Executing command: "%s" using init path %s' % (cmd, init_path))
  42. init_prefix = '. %s %s > /dev/null && ' % (init_path, builddir)
  43. else:
  44. logger.debug('Executing command "%s"' % cmd)
  45. init_prefix = ''
  46. if watch:
  47. if sys.stdout.isatty():
  48. # Fool bitbake into thinking it's outputting to a terminal (because it is, indirectly)
  49. cmd = 'script -e -q -c "%s" /dev/null' % cmd
  50. return exec_watch('%s%s' % (init_prefix, cmd), **options)
  51. else:
  52. return bb.process.run('%s%s' % (init_prefix, cmd), **options)
  53. def exec_watch(cmd, **options):
  54. """Run program with stdout shown on sys.stdout"""
  55. import bb
  56. if isinstance(cmd, str) and not "shell" in options:
  57. options["shell"] = True
  58. process = subprocess.Popen(
  59. cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **options
  60. )
  61. buf = ''
  62. while True:
  63. out = process.stdout.read(1)
  64. out = out.decode('utf-8')
  65. if out:
  66. sys.stdout.write(out)
  67. sys.stdout.flush()
  68. buf += out
  69. elif out == '' and process.poll() != None:
  70. break
  71. if process.returncode != 0:
  72. raise bb.process.ExecutionError(cmd, process.returncode, buf, None)
  73. return buf, None
  74. def exec_fakeroot(d, cmd, **kwargs):
  75. """Run a command under fakeroot (pseudo, in fact) so that it picks up the appropriate file permissions"""
  76. # Grab the command and check it actually exists
  77. fakerootcmd = d.getVar('FAKEROOTCMD', True)
  78. if not os.path.exists(fakerootcmd):
  79. 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')
  80. return 2
  81. # Set up the appropriate environment
  82. newenv = dict(os.environ)
  83. fakerootenv = d.getVar('FAKEROOTENV', True)
  84. for varvalue in fakerootenv.split():
  85. if '=' in varvalue:
  86. splitval = varvalue.split('=', 1)
  87. newenv[splitval[0]] = splitval[1]
  88. return subprocess.call("%s %s" % (fakerootcmd, cmd), env=newenv, **kwargs)
  89. def setup_tinfoil(config_only=False, basepath=None, tracking=False):
  90. """Initialize tinfoil api from bitbake"""
  91. import scriptpath
  92. orig_cwd = os.path.abspath(os.curdir)
  93. try:
  94. if basepath:
  95. os.chdir(basepath)
  96. bitbakepath = scriptpath.add_bitbake_lib_path()
  97. if not bitbakepath:
  98. logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
  99. sys.exit(1)
  100. import bb.tinfoil
  101. tinfoil = bb.tinfoil.Tinfoil(tracking=tracking)
  102. tinfoil.prepare(config_only)
  103. tinfoil.logger.setLevel(logger.getEffectiveLevel())
  104. finally:
  105. os.chdir(orig_cwd)
  106. return tinfoil
  107. def get_recipe_file(cooker, pn):
  108. """Find recipe file corresponding a package name"""
  109. import oe.recipeutils
  110. recipefile = oe.recipeutils.pn_to_recipe(cooker, pn)
  111. if not recipefile:
  112. skipreasons = oe.recipeutils.get_unavailable_reasons(cooker, pn)
  113. if skipreasons:
  114. logger.error('\n'.join(skipreasons))
  115. else:
  116. logger.error("Unable to find any recipe file matching %s" % pn)
  117. return recipefile
  118. def parse_recipe(config, tinfoil, pn, appends, filter_workspace=True):
  119. """Parse recipe of a package"""
  120. import oe.recipeutils
  121. recipefile = get_recipe_file(tinfoil.cooker, pn)
  122. if not recipefile:
  123. # Error already logged
  124. return None
  125. if appends:
  126. append_files = tinfoil.cooker.collection.get_file_appends(recipefile)
  127. if filter_workspace:
  128. # Filter out appends from the workspace
  129. append_files = [path for path in append_files if
  130. not path.startswith(config.workspace_path)]
  131. else:
  132. append_files = None
  133. return oe.recipeutils.parse_recipe(tinfoil.cooker, recipefile, append_files)
  134. def check_workspace_recipe(workspace, pn, checksrc=True, bbclassextend=False):
  135. """
  136. Check that a recipe is in the workspace and (optionally) that source
  137. is present.
  138. """
  139. workspacepn = pn
  140. for recipe, value in workspace.items():
  141. if recipe == pn:
  142. break
  143. if bbclassextend:
  144. recipefile = value['recipefile']
  145. if recipefile:
  146. targets = get_bbclassextend_targets(recipefile, recipe)
  147. if pn in targets:
  148. workspacepn = recipe
  149. break
  150. else:
  151. raise DevtoolError("No recipe named '%s' in your workspace" % pn)
  152. if checksrc:
  153. srctree = workspace[workspacepn]['srctree']
  154. if not os.path.exists(srctree):
  155. raise DevtoolError("Source tree %s for recipe %s does not exist" % (srctree, workspacepn))
  156. if not os.listdir(srctree):
  157. raise DevtoolError("Source tree %s for recipe %s is empty" % (srctree, workspacepn))
  158. return workspacepn
  159. def use_external_build(same_dir, no_same_dir, d):
  160. """
  161. Determine if we should use B!=S (separate build and source directories) or not
  162. """
  163. b_is_s = True
  164. if no_same_dir:
  165. logger.info('Using separate build directory since --no-same-dir specified')
  166. b_is_s = False
  167. elif same_dir:
  168. logger.info('Using source tree as build directory since --same-dir specified')
  169. elif bb.data.inherits_class('autotools-brokensep', d):
  170. logger.info('Using source tree as build directory since recipe inherits autotools-brokensep')
  171. elif d.getVar('B', True) == os.path.abspath(d.getVar('S', True)):
  172. logger.info('Using source tree as build directory since that would be the default for this recipe')
  173. else:
  174. b_is_s = False
  175. return b_is_s
  176. def setup_git_repo(repodir, version, devbranch, basetag='devtool-base'):
  177. """
  178. Set up the git repository for the source tree
  179. """
  180. import bb.process
  181. if not os.path.exists(os.path.join(repodir, '.git')):
  182. bb.process.run('git init', cwd=repodir)
  183. bb.process.run('git add .', cwd=repodir)
  184. commit_cmd = ['git', 'commit', '-q']
  185. stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
  186. if not stdout:
  187. commit_cmd.append('--allow-empty')
  188. commitmsg = "Initial empty commit with no upstream sources"
  189. elif version:
  190. commitmsg = "Initial commit from upstream at version %s" % version
  191. else:
  192. commitmsg = "Initial commit from upstream"
  193. commit_cmd += ['-m', commitmsg]
  194. bb.process.run(commit_cmd, cwd=repodir)
  195. bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
  196. bb.process.run('git tag -f %s' % basetag, cwd=repodir)
  197. def recipe_to_append(recipefile, config, wildcard=False):
  198. """
  199. Convert a recipe file to a bbappend file path within the workspace.
  200. NOTE: if the bbappend already exists, you should be using
  201. workspace[args.recipename]['bbappend'] instead of calling this
  202. function.
  203. """
  204. appendname = os.path.splitext(os.path.basename(recipefile))[0]
  205. if wildcard:
  206. appendname = re.sub(r'_.*', '_%', appendname)
  207. appendpath = os.path.join(config.workspace_path, 'appends')
  208. appendfile = os.path.join(appendpath, appendname + '.bbappend')
  209. return appendfile
  210. def get_bbclassextend_targets(recipefile, pn):
  211. """
  212. Cheap function to get BBCLASSEXTEND and then convert that to the
  213. list of targets that would result.
  214. """
  215. import bb.utils
  216. values = {}
  217. def get_bbclassextend_varfunc(varname, origvalue, op, newlines):
  218. values[varname] = origvalue
  219. return origvalue, None, 0, True
  220. with open(recipefile, 'r') as f:
  221. bb.utils.edit_metadata(f, ['BBCLASSEXTEND'], get_bbclassextend_varfunc)
  222. targets = []
  223. bbclassextend = values.get('BBCLASSEXTEND', '').split()
  224. if bbclassextend:
  225. for variant in bbclassextend:
  226. if variant == 'nativesdk':
  227. targets.append('%s-%s' % (variant, pn))
  228. elif variant in ['native', 'cross', 'crosssdk']:
  229. targets.append('%s-%s' % (pn, variant))
  230. return targets