devtool 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #!/usr/bin/env python
  2. # OpenEmbedded Development tool
  3. #
  4. # Copyright (C) 2014-2015 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. import sys
  19. import os
  20. import argparse
  21. import glob
  22. import re
  23. import ConfigParser
  24. import subprocess
  25. import logging
  26. basepath = ''
  27. workspace = {}
  28. config = None
  29. context = None
  30. scripts_path = os.path.dirname(os.path.realpath(__file__))
  31. lib_path = scripts_path + '/lib'
  32. sys.path = sys.path + [lib_path]
  33. from devtool import DevtoolError, setup_tinfoil
  34. import scriptutils
  35. import argparse_oe
  36. logger = scriptutils.logger_create('devtool')
  37. plugins = []
  38. class ConfigHandler(object):
  39. config_file = ''
  40. config_obj = None
  41. init_path = ''
  42. workspace_path = ''
  43. def __init__(self, filename):
  44. self.config_file = filename
  45. self.config_obj = ConfigParser.SafeConfigParser()
  46. def get(self, section, option, default=None):
  47. try:
  48. ret = self.config_obj.get(section, option)
  49. except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
  50. if default != None:
  51. ret = default
  52. else:
  53. raise
  54. return ret
  55. def read(self):
  56. if os.path.exists(self.config_file):
  57. self.config_obj.read(self.config_file)
  58. if self.config_obj.has_option('General', 'init_path'):
  59. pth = self.get('General', 'init_path')
  60. self.init_path = os.path.join(basepath, pth)
  61. if not os.path.exists(self.init_path):
  62. logger.error('init_path %s specified in config file cannot be found' % pth)
  63. return False
  64. else:
  65. self.config_obj.add_section('General')
  66. self.workspace_path = self.get('General', 'workspace_path', os.path.join(basepath, 'workspace'))
  67. return True
  68. def write(self):
  69. logger.debug('writing to config file %s' % self.config_file)
  70. self.config_obj.set('General', 'workspace_path', self.workspace_path)
  71. with open(self.config_file, 'w') as f:
  72. self.config_obj.write(f)
  73. def set(self, section, option, value):
  74. if not self.config_obj.has_section(section):
  75. self.config_obj.add_section(section)
  76. self.config_obj.set(section, option, value)
  77. class Context:
  78. def __init__(self, **kwargs):
  79. self.__dict__.update(kwargs)
  80. def read_workspace():
  81. global workspace
  82. workspace = {}
  83. if not os.path.exists(os.path.join(config.workspace_path, 'conf', 'layer.conf')):
  84. if context.fixed_setup:
  85. logger.error("workspace layer not set up")
  86. sys.exit(1)
  87. else:
  88. logger.info('Creating workspace layer in %s' % config.workspace_path)
  89. _create_workspace(config.workspace_path, config, basepath)
  90. if not context.fixed_setup:
  91. _enable_workspace_layer(config.workspace_path, config, basepath)
  92. logger.debug('Reading workspace in %s' % config.workspace_path)
  93. externalsrc_re = re.compile(r'^EXTERNALSRC(_pn-([^ =]+))? *= *"([^"]*)"$')
  94. for fn in glob.glob(os.path.join(config.workspace_path, 'appends', '*.bbappend')):
  95. with open(fn, 'r') as f:
  96. for line in f:
  97. res = externalsrc_re.match(line.rstrip())
  98. if res:
  99. pn = res.group(2) or os.path.splitext(os.path.basename(fn))[0].split('_')[0]
  100. # Find the recipe file within the workspace, if any
  101. bbfile = os.path.basename(fn).replace('.bbappend', '.bb').replace('%', '*')
  102. recipefile = glob.glob(os.path.join(config.workspace_path,
  103. 'recipes',
  104. pn,
  105. bbfile))
  106. if recipefile:
  107. recipefile = recipefile[0]
  108. workspace[pn] = {'srctree': res.group(3),
  109. 'bbappend': fn,
  110. 'recipefile': recipefile}
  111. logger.debug('Found recipe %s' % workspace[pn])
  112. def create_unlockedsigs():
  113. """ This function will make unlocked-sigs.inc match the recipes in the
  114. workspace. This runs on every run of devtool, but it lets us ensure
  115. the unlocked items are in sync with the workspace. """
  116. confdir = os.path.join(basepath, 'conf')
  117. unlockedsigs = os.path.join(confdir, 'unlocked-sigs.inc')
  118. bb.utils.mkdirhier(confdir)
  119. with open(os.path.join(confdir, 'unlocked-sigs.inc'), 'w') as f:
  120. f.write("# DO NOT MODIFY! YOUR CHANGES WILL BE LOST.\n" +
  121. "# This layer was created by the OpenEmbedded devtool" +
  122. " utility in order to\n" +
  123. "# contain recipes that are unlocked.\n")
  124. f.write('SIGGEN_UNLOCKED_RECIPES += "\\\n')
  125. for pn in workspace:
  126. f.write(' ' + pn)
  127. f.write('"')
  128. def create_workspace(args, config, basepath, workspace):
  129. if args.layerpath:
  130. workspacedir = os.path.abspath(args.layerpath)
  131. else:
  132. workspacedir = os.path.abspath(os.path.join(basepath, 'workspace'))
  133. _create_workspace(workspacedir, config, basepath)
  134. if not args.create_only:
  135. _enable_workspace_layer(workspacedir, config, basepath)
  136. def _create_workspace(workspacedir, config, basepath):
  137. import bb
  138. confdir = os.path.join(workspacedir, 'conf')
  139. if os.path.exists(os.path.join(confdir, 'layer.conf')):
  140. logger.info('Specified workspace already set up, leaving as-is')
  141. else:
  142. # Add a config file
  143. bb.utils.mkdirhier(confdir)
  144. with open(os.path.join(confdir, 'layer.conf'), 'w') as f:
  145. f.write('# ### workspace layer auto-generated by devtool ###\n')
  146. f.write('BBPATH =. "$' + '{LAYERDIR}:"\n')
  147. f.write('BBFILES += "$' + '{LAYERDIR}/recipes/*/*.bb \\\n')
  148. f.write(' $' + '{LAYERDIR}/appends/*.bbappend"\n')
  149. f.write('BBFILE_COLLECTIONS += "workspacelayer"\n')
  150. f.write('BBFILE_PATTERN_workspacelayer = "^$' + '{LAYERDIR}/"\n')
  151. f.write('BBFILE_PATTERN_IGNORE_EMPTY_workspacelayer = "1"\n')
  152. f.write('BBFILE_PRIORITY_workspacelayer = "99"\n')
  153. # Add a README file
  154. with open(os.path.join(workspacedir, 'README'), 'w') as f:
  155. f.write('This layer was created by the OpenEmbedded devtool utility in order to\n')
  156. f.write('contain recipes and bbappends. In most instances you should use the\n')
  157. f.write('devtool utility to manage files within it rather than modifying files\n')
  158. f.write('directly (although recipes added with "devtool add" will often need\n')
  159. f.write('direct modification.)\n')
  160. f.write('\nIf you no longer need to use devtool you can remove the path to this\n')
  161. f.write('workspace layer from your conf/bblayers.conf file (and then delete the\n')
  162. f.write('layer, if you wish).\n')
  163. f.write('\nNote that by default, if devtool fetches and unpacks source code, it\n')
  164. f.write('will place it in a subdirectory of a "sources" subdirectory of the\n')
  165. f.write('layer. If you prefer it to be elsewhere you can specify the source\n')
  166. f.write('tree path on the command line.\n')
  167. def _enable_workspace_layer(workspacedir, config, basepath):
  168. """Ensure the workspace layer is in bblayers.conf"""
  169. import bb
  170. bblayers_conf = os.path.join(basepath, 'conf', 'bblayers.conf')
  171. if not os.path.exists(bblayers_conf):
  172. logger.error('Unable to find bblayers.conf')
  173. return
  174. _, added = bb.utils.edit_bblayers_conf(bblayers_conf, workspacedir, config.workspace_path)
  175. if added:
  176. logger.info('Enabling workspace layer in bblayers.conf')
  177. if config.workspace_path != workspacedir:
  178. # Update our config to point to the new location
  179. config.workspace_path = workspacedir
  180. config.write()
  181. def main():
  182. global basepath
  183. global config
  184. global context
  185. context = Context(fixed_setup=False)
  186. # Default basepath
  187. basepath = os.path.dirname(os.path.abspath(__file__))
  188. parser = argparse_oe.ArgumentParser(description="OpenEmbedded development tool",
  189. add_help=False,
  190. epilog="Use %(prog)s <subcommand> --help to get help on a specific command")
  191. parser.add_argument('--basepath', help='Base directory of SDK / build directory')
  192. parser.add_argument('--bbpath', help='Explicitly specify the BBPATH, rather than getting it from the metadata')
  193. parser.add_argument('-d', '--debug', help='Enable debug output', action='store_true')
  194. parser.add_argument('-q', '--quiet', help='Print only errors', action='store_true')
  195. parser.add_argument('--color', choices=['auto', 'always', 'never'], default='auto', help='Colorize output (where %(metavar)s is %(choices)s)', metavar='COLOR')
  196. global_args, unparsed_args = parser.parse_known_args()
  197. # Help is added here rather than via add_help=True, as we don't want it to
  198. # be handled by parse_known_args()
  199. parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
  200. help='show this help message and exit')
  201. if global_args.debug:
  202. logger.setLevel(logging.DEBUG)
  203. elif global_args.quiet:
  204. logger.setLevel(logging.ERROR)
  205. if global_args.basepath:
  206. # Override
  207. basepath = global_args.basepath
  208. if os.path.exists(os.path.join(basepath, '.devtoolbase')):
  209. context.fixed_setup = True
  210. else:
  211. pth = basepath
  212. while pth != '' and pth != os.sep:
  213. if os.path.exists(os.path.join(pth, '.devtoolbase')):
  214. context.fixed_setup = True
  215. basepath = pth
  216. break
  217. pth = os.path.dirname(pth)
  218. if not context.fixed_setup:
  219. basepath = os.environ.get('BUILDDIR')
  220. if not basepath:
  221. logger.error("This script can only be run after initialising the build environment (e.g. by using oe-init-build-env)")
  222. sys.exit(1)
  223. logger.debug('Using basepath %s' % basepath)
  224. config = ConfigHandler(os.path.join(basepath, 'conf', 'devtool.conf'))
  225. if not config.read():
  226. return -1
  227. context.config = config
  228. bitbake_subdir = config.get('General', 'bitbake_subdir', '')
  229. if bitbake_subdir:
  230. # Normally set for use within the SDK
  231. logger.debug('Using bitbake subdir %s' % bitbake_subdir)
  232. sys.path.insert(0, os.path.join(basepath, bitbake_subdir, 'lib'))
  233. core_meta_subdir = config.get('General', 'core_meta_subdir')
  234. sys.path.insert(0, os.path.join(basepath, core_meta_subdir, 'lib'))
  235. else:
  236. # Standard location
  237. import scriptpath
  238. bitbakepath = scriptpath.add_bitbake_lib_path()
  239. if not bitbakepath:
  240. logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
  241. sys.exit(1)
  242. logger.debug('Using standard bitbake path %s' % bitbakepath)
  243. scriptpath.add_oe_lib_path()
  244. scriptutils.logger_setup_color(logger, global_args.color)
  245. if global_args.bbpath is None:
  246. tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
  247. global_args.bbpath = tinfoil.config_data.getVar('BBPATH', True)
  248. else:
  249. tinfoil = None
  250. for path in [scripts_path] + global_args.bbpath.split(':'):
  251. pluginpath = os.path.join(path, 'lib', 'devtool')
  252. scriptutils.load_plugins(logger, plugins, pluginpath)
  253. if tinfoil:
  254. tinfoil.shutdown()
  255. subparsers = parser.add_subparsers(dest="subparser_name", title='subcommands', metavar='<subcommand>')
  256. subparsers.add_subparser_group('sdk', 'SDK maintenance', -2)
  257. subparsers.add_subparser_group('advanced', 'Advanced', -1)
  258. subparsers.add_subparser_group('starting', 'Beginning work on a recipe', 100)
  259. subparsers.add_subparser_group('info', 'Getting information')
  260. subparsers.add_subparser_group('working', 'Working on a recipe in the workspace')
  261. subparsers.add_subparser_group('testbuild', 'Testing changes on target')
  262. if not context.fixed_setup:
  263. parser_create_workspace = subparsers.add_parser('create-workspace',
  264. help='Set up workspace in an alternative location',
  265. description='Sets up a new workspace. NOTE: other devtool subcommands will create a workspace automatically as needed, so you only need to use %(prog)s if you want to specify where the workspace should be located.',
  266. group='advanced')
  267. parser_create_workspace.add_argument('layerpath', nargs='?', help='Path in which the workspace layer should be created')
  268. parser_create_workspace.add_argument('--create-only', action="store_true", help='Only create the workspace layer, do not alter configuration')
  269. parser_create_workspace.set_defaults(func=create_workspace, no_workspace=True)
  270. for plugin in plugins:
  271. if hasattr(plugin, 'register_commands'):
  272. plugin.register_commands(subparsers, context)
  273. args = parser.parse_args(unparsed_args, namespace=global_args)
  274. if not getattr(args, 'no_workspace', False):
  275. read_workspace()
  276. create_unlockedsigs()
  277. try:
  278. ret = args.func(args, config, basepath, workspace)
  279. except DevtoolError as err:
  280. if str(err):
  281. logger.error(str(err))
  282. ret = 1
  283. except argparse_oe.ArgumentUsageError as ae:
  284. parser.error_subcommand(ae.message, ae.subcommand)
  285. return ret
  286. if __name__ == "__main__":
  287. try:
  288. ret = main()
  289. except Exception:
  290. ret = 1
  291. import traceback
  292. traceback.print_exc()
  293. sys.exit(ret)