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