__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. tinfoil.prepare(config_only)
  104. tinfoil.logger.setLevel(logger.getEffectiveLevel())
  105. finally:
  106. os.chdir(orig_cwd)
  107. return tinfoil
  108. def parse_recipe(config, tinfoil, pn, appends, filter_workspace=True):
  109. """Parse the specified recipe"""
  110. try:
  111. recipefile = tinfoil.get_recipe_file(pn)
  112. except bb.providers.NoProvider as e:
  113. logger.error(str(e))
  114. return None
  115. if appends:
  116. append_files = tinfoil.get_file_appends(recipefile)
  117. if filter_workspace:
  118. # Filter out appends from the workspace
  119. append_files = [path for path in append_files if
  120. not path.startswith(config.workspace_path)]
  121. else:
  122. append_files = None
  123. return tinfoil.parse_recipe_file(recipefile, appends, append_files)
  124. def check_workspace_recipe(workspace, pn, checksrc=True, bbclassextend=False):
  125. """
  126. Check that a recipe is in the workspace and (optionally) that source
  127. is present.
  128. """
  129. workspacepn = pn
  130. for recipe, value in workspace.items():
  131. if recipe == pn:
  132. break
  133. if bbclassextend:
  134. recipefile = value['recipefile']
  135. if recipefile:
  136. targets = get_bbclassextend_targets(recipefile, recipe)
  137. if pn in targets:
  138. workspacepn = recipe
  139. break
  140. else:
  141. raise DevtoolError("No recipe named '%s' in your workspace" % pn)
  142. if checksrc:
  143. srctree = workspace[workspacepn]['srctree']
  144. if not os.path.exists(srctree):
  145. raise DevtoolError("Source tree %s for recipe %s does not exist" % (srctree, workspacepn))
  146. if not os.listdir(srctree):
  147. raise DevtoolError("Source tree %s for recipe %s is empty" % (srctree, workspacepn))
  148. return workspacepn
  149. def use_external_build(same_dir, no_same_dir, d):
  150. """
  151. Determine if we should use B!=S (separate build and source directories) or not
  152. """
  153. b_is_s = True
  154. if no_same_dir:
  155. logger.info('Using separate build directory since --no-same-dir specified')
  156. b_is_s = False
  157. elif same_dir:
  158. logger.info('Using source tree as build directory since --same-dir specified')
  159. elif bb.data.inherits_class('autotools-brokensep', d):
  160. logger.info('Using source tree as build directory since recipe inherits autotools-brokensep')
  161. elif d.getVar('B') == os.path.abspath(d.getVar('S')):
  162. logger.info('Using source tree as build directory since that would be the default for this recipe')
  163. else:
  164. b_is_s = False
  165. return b_is_s
  166. def setup_git_repo(repodir, version, devbranch, basetag='devtool-base', d=None):
  167. """
  168. Set up the git repository for the source tree
  169. """
  170. import bb.process
  171. import oe.patch
  172. if not os.path.exists(os.path.join(repodir, '.git')):
  173. bb.process.run('git init', cwd=repodir)
  174. bb.process.run('git add .', cwd=repodir)
  175. commit_cmd = ['git']
  176. oe.patch.GitApplyTree.gitCommandUserOptions(commit_cmd, d=d)
  177. commit_cmd += ['commit', '-q']
  178. stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
  179. if not stdout:
  180. commit_cmd.append('--allow-empty')
  181. commitmsg = "Initial empty commit with no upstream sources"
  182. elif version:
  183. commitmsg = "Initial commit from upstream at version %s" % version
  184. else:
  185. commitmsg = "Initial commit from upstream"
  186. commit_cmd += ['-m', commitmsg]
  187. bb.process.run(commit_cmd, cwd=repodir)
  188. bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
  189. bb.process.run('git tag -f %s' % basetag, cwd=repodir)
  190. def recipe_to_append(recipefile, config, wildcard=False):
  191. """
  192. Convert a recipe file to a bbappend file path within the workspace.
  193. NOTE: if the bbappend already exists, you should be using
  194. workspace[args.recipename]['bbappend'] instead of calling this
  195. function.
  196. """
  197. appendname = os.path.splitext(os.path.basename(recipefile))[0]
  198. if wildcard:
  199. appendname = re.sub(r'_.*', '_%', appendname)
  200. appendpath = os.path.join(config.workspace_path, 'appends')
  201. appendfile = os.path.join(appendpath, appendname + '.bbappend')
  202. return appendfile
  203. def get_bbclassextend_targets(recipefile, pn):
  204. """
  205. Cheap function to get BBCLASSEXTEND and then convert that to the
  206. list of targets that would result.
  207. """
  208. import bb.utils
  209. values = {}
  210. def get_bbclassextend_varfunc(varname, origvalue, op, newlines):
  211. values[varname] = origvalue
  212. return origvalue, None, 0, True
  213. with open(recipefile, 'r') as f:
  214. bb.utils.edit_metadata(f, ['BBCLASSEXTEND'], get_bbclassextend_varfunc)
  215. targets = []
  216. bbclassextend = values.get('BBCLASSEXTEND', '').split()
  217. if bbclassextend:
  218. for variant in bbclassextend:
  219. if variant == 'nativesdk':
  220. targets.append('%s-%s' % (variant, pn))
  221. elif variant in ['native', 'cross', 'crosssdk']:
  222. targets.append('%s-%s' % (pn, variant))
  223. return targets
  224. def ensure_npm(config, basepath, fixed_setup=False):
  225. """
  226. Ensure that npm is available and either build it or show a
  227. reasonable error message
  228. """
  229. tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
  230. try:
  231. nativepath = tinfoil.config_data.getVar('STAGING_BINDIR_NATIVE')
  232. finally:
  233. tinfoil.shutdown()
  234. npmpath = os.path.join(nativepath, 'npm')
  235. if not os.path.exists(npmpath):
  236. logger.info('Building nodejs-native')
  237. try:
  238. exec_build_env_command(config.init_path, basepath,
  239. 'bitbake -q nodejs-native', watch=True)
  240. except bb.process.ExecutionError as e:
  241. if "Nothing PROVIDES 'nodejs-native'" in e.stdout:
  242. if fixed_setup:
  243. msg = 'nodejs-native is required for npm but is not available within this SDK'
  244. else:
  245. msg = 'nodejs-native is required for npm but is not available - you will likely need to add a layer that provides nodejs'
  246. raise DevtoolError(msg)
  247. else:
  248. raise
  249. if not os.path.exists(npmpath):
  250. raise DevtoolError('Built nodejs-native but npm binary still could not be found at %s' % npmpath)