devtool 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. import scriptutils
  34. logger = scriptutils.logger_create('devtool')
  35. plugins = []
  36. class ConfigHandler(object):
  37. config_file = ''
  38. config_obj = None
  39. init_path = ''
  40. workspace_path = ''
  41. def __init__(self, filename):
  42. self.config_file = filename
  43. self.config_obj = ConfigParser.SafeConfigParser()
  44. def get(self, section, option, default=None):
  45. try:
  46. ret = self.config_obj.get(section, option)
  47. except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
  48. if default != None:
  49. ret = default
  50. else:
  51. raise
  52. return ret
  53. def read(self):
  54. if os.path.exists(self.config_file):
  55. self.config_obj.read(self.config_file)
  56. if self.config_obj.has_option('General', 'init_path'):
  57. pth = self.get('General', 'init_path')
  58. self.init_path = os.path.join(basepath, pth)
  59. if not os.path.exists(self.init_path):
  60. logger.error('init_path %s specified in config file cannot be found' % pth)
  61. return False
  62. else:
  63. self.config_obj.add_section('General')
  64. self.workspace_path = self.get('General', 'workspace_path', os.path.join(basepath, 'workspace'))
  65. return True
  66. def write(self):
  67. logger.debug('writing to config file %s' % self.config_file)
  68. self.config_obj.set('General', 'workspace_path', self.workspace_path)
  69. with open(self.config_file, 'w') as f:
  70. self.config_obj.write(f)
  71. class Context:
  72. def __init__(self, **kwargs):
  73. self.__dict__.update(kwargs)
  74. def read_workspace():
  75. global workspace
  76. workspace = {}
  77. if not os.path.exists(os.path.join(config.workspace_path, 'conf', 'layer.conf')):
  78. if context.fixed_setup:
  79. logger.error("workspace layer not set up")
  80. sys.exit(1)
  81. else:
  82. logger.info('Creating workspace layer in %s' % config.workspace_path)
  83. _create_workspace(config.workspace_path, config, basepath)
  84. if not context.fixed_setup:
  85. _enable_workspace_layer(config.workspace_path, config, basepath)
  86. logger.debug('Reading workspace in %s' % config.workspace_path)
  87. externalsrc_re = re.compile(r'^EXTERNALSRC(_pn-[^ =]+)? =.*$')
  88. for fn in glob.glob(os.path.join(config.workspace_path, 'appends', '*.bbappend')):
  89. pn = os.path.splitext(os.path.basename(fn))[0].split('_')[0]
  90. with open(fn, 'r') as f:
  91. for line in f:
  92. if externalsrc_re.match(line.rstrip()):
  93. splitval = line.split('=', 2)
  94. workspace[pn] = splitval[1].strip('" \n\r\t')
  95. break
  96. def create_workspace(args, config, basepath, workspace):
  97. if args.layerpath:
  98. workspacedir = os.path.abspath(args.layerpath)
  99. else:
  100. workspacedir = os.path.abspath(os.path.join(basepath, 'workspace'))
  101. _create_workspace(workspacedir, config, basepath)
  102. if not args.create_only:
  103. _enable_workspace_layer(workspacedir, config, basepath)
  104. def _create_workspace(workspacedir, config, basepath):
  105. import bb
  106. confdir = os.path.join(workspacedir, 'conf')
  107. if os.path.exists(os.path.join(confdir, 'layer.conf')):
  108. logger.info('Specified workspace already set up, leaving as-is')
  109. else:
  110. # Add a config file
  111. bb.utils.mkdirhier(confdir)
  112. with open(os.path.join(confdir, 'layer.conf'), 'w') as f:
  113. f.write('# ### workspace layer auto-generated by devtool ###\n')
  114. f.write('BBPATH =. "$' + '{LAYERDIR}:"\n')
  115. f.write('BBFILES += "$' + '{LAYERDIR}/recipes/*/*.bb \\\n')
  116. f.write(' $' + '{LAYERDIR}/appends/*.bbappend"\n')
  117. f.write('BBFILE_COLLECTIONS += "workspacelayer"\n')
  118. f.write('BBFILE_PATTERN_workspacelayer = "^$' + '{LAYERDIR}/"\n')
  119. f.write('BBFILE_PATTERN_IGNORE_EMPTY_workspacelayer = "1"\n')
  120. f.write('BBFILE_PRIORITY_workspacelayer = "99"\n')
  121. # Add a README file
  122. with open(os.path.join(workspacedir, 'README'), 'w') as f:
  123. f.write('This layer was created by the OpenEmbedded devtool utility in order to\n')
  124. f.write('contain recipes and bbappends. In most instances you should use the\n')
  125. f.write('devtool utility to manage files within it rather than modifying files\n')
  126. f.write('directly (although recipes added with "devtool add" will often need\n')
  127. f.write('direct modification.)\n')
  128. f.write('\nIf you no longer need to use devtool you can remove the path to this\n')
  129. f.write('workspace layer from your conf/bblayers.conf file (and then delete the\n')
  130. f.write('layer, if you wish).\n')
  131. def _enable_workspace_layer(workspacedir, config, basepath):
  132. """Ensure the workspace layer is in bblayers.conf"""
  133. import bb
  134. bblayers_conf = os.path.join(basepath, 'conf', 'bblayers.conf')
  135. if not os.path.exists(bblayers_conf):
  136. logger.error('Unable to find bblayers.conf')
  137. return -1
  138. _, added = bb.utils.edit_bblayers_conf(bblayers_conf, workspacedir, config.workspace_path)
  139. if added:
  140. logger.info('Enabling workspace layer in bblayers.conf')
  141. if config.workspace_path != workspacedir:
  142. # Update our config to point to the new location
  143. config.workspace_path = workspacedir
  144. config.write()
  145. def main():
  146. global basepath
  147. global config
  148. global context
  149. context = Context(fixed_setup=False)
  150. # Default basepath
  151. basepath = os.path.dirname(os.path.abspath(__file__))
  152. pth = basepath
  153. while pth != '' and pth != os.sep:
  154. if os.path.exists(os.path.join(pth, '.devtoolbase')):
  155. context.fixed_setup = True
  156. basepath = pth
  157. break
  158. pth = os.path.dirname(pth)
  159. parser = argparse.ArgumentParser(description="OpenEmbedded development tool",
  160. epilog="Use %(prog)s <subcommand> --help to get help on a specific command")
  161. parser.add_argument('--basepath', help='Base directory of SDK / build directory')
  162. parser.add_argument('-d', '--debug', help='Enable debug output', action='store_true')
  163. parser.add_argument('-q', '--quiet', help='Print only errors', action='store_true')
  164. parser.add_argument('--color', choices=['auto', 'always', 'never'], default='auto', help='Colorize output (where %(metavar)s is %(choices)s)', metavar='COLOR')
  165. subparsers = parser.add_subparsers(dest="subparser_name", title='subcommands', metavar='<subcommand>')
  166. if not context.fixed_setup:
  167. parser_create_workspace = subparsers.add_parser('create-workspace',
  168. help='Set up a workspace',
  169. 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.')
  170. parser_create_workspace.add_argument('layerpath', nargs='?', help='Path in which the workspace layer should be created')
  171. parser_create_workspace.add_argument('--create-only', action="store_true", help='Only create the workspace layer, do not alter configuration')
  172. parser_create_workspace.set_defaults(func=create_workspace)
  173. scriptutils.load_plugins(logger, plugins, os.path.join(scripts_path, 'lib', 'devtool'))
  174. for plugin in plugins:
  175. if hasattr(plugin, 'register_commands'):
  176. plugin.register_commands(subparsers, context)
  177. args = parser.parse_args()
  178. if args.debug:
  179. logger.setLevel(logging.DEBUG)
  180. elif args.quiet:
  181. logger.setLevel(logging.ERROR)
  182. if args.basepath:
  183. # Override
  184. basepath = args.basepath
  185. elif not context.fixed_setup:
  186. basepath = os.environ.get('BUILDDIR')
  187. if not basepath:
  188. logger.error("This script can only be run after initialising the build environment (e.g. by using oe-init-build-env)")
  189. sys.exit(1)
  190. logger.debug('Using basepath %s' % basepath)
  191. config = ConfigHandler(os.path.join(basepath, 'conf', 'devtool.conf'))
  192. if not config.read():
  193. return -1
  194. bitbake_subdir = config.get('General', 'bitbake_subdir', '')
  195. if bitbake_subdir:
  196. # Normally set for use within the SDK
  197. logger.debug('Using bitbake subdir %s' % bitbake_subdir)
  198. sys.path.insert(0, os.path.join(basepath, bitbake_subdir, 'lib'))
  199. core_meta_subdir = config.get('General', 'core_meta_subdir')
  200. sys.path.insert(0, os.path.join(basepath, core_meta_subdir, 'lib'))
  201. else:
  202. # Standard location
  203. import scriptpath
  204. bitbakepath = scriptpath.add_bitbake_lib_path()
  205. if not bitbakepath:
  206. logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
  207. sys.exit(1)
  208. logger.debug('Using standard bitbake path %s' % bitbakepath)
  209. scriptpath.add_oe_lib_path()
  210. scriptutils.logger_setup_color(logger, args.color)
  211. if args.subparser_name != 'create-workspace':
  212. read_workspace()
  213. ret = args.func(args, config, basepath, workspace)
  214. return ret
  215. if __name__ == "__main__":
  216. try:
  217. ret = main()
  218. except Exception:
  219. ret = 1
  220. import traceback
  221. traceback.print_exc(5)
  222. sys.exit(ret)