blob: ff97dfc94b29ad39aef54d9e68041dcf0b20b578 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/usr/bin/env python
2
3# Development tool - utility functions for plugins
4#
5# Copyright (C) 2014 Intel Corporation
6#
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License version 2 as
9# published by the Free Software Foundation.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License along
17# with this program; if not, write to the Free Software Foundation, Inc.,
18# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19"""Devtool plugins module"""
20
21import os
22import sys
23import subprocess
24import logging
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050025import re
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026
27logger = logging.getLogger('devtool')
28
29
30class DevtoolError(Exception):
31 """Exception for handling devtool errors"""
32 pass
33
34
35def exec_build_env_command(init_path, builddir, cmd, watch=False, **options):
36 """Run a program in bitbake build context"""
37 import bb
38 if not 'cwd' in options:
39 options["cwd"] = builddir
40 if init_path:
41 # As the OE init script makes use of BASH_SOURCE to determine OEROOT,
42 # and can't determine it when running under dash, we need to set
43 # the executable to bash to correctly set things up
44 if not 'executable' in options:
45 options['executable'] = 'bash'
46 logger.debug('Executing command: "%s" using init path %s' % (cmd, init_path))
47 init_prefix = '. %s %s > /dev/null && ' % (init_path, builddir)
48 else:
49 logger.debug('Executing command "%s"' % cmd)
50 init_prefix = ''
51 if watch:
52 if sys.stdout.isatty():
53 # Fool bitbake into thinking it's outputting to a terminal (because it is, indirectly)
54 cmd = 'script -e -q -c "%s" /dev/null' % cmd
55 return exec_watch('%s%s' % (init_prefix, cmd), **options)
56 else:
57 return bb.process.run('%s%s' % (init_prefix, cmd), **options)
58
59def exec_watch(cmd, **options):
60 """Run program with stdout shown on sys.stdout"""
61 import bb
62 if isinstance(cmd, basestring) and not "shell" in options:
63 options["shell"] = True
64
65 process = subprocess.Popen(
66 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **options
67 )
68
69 buf = ''
70 while True:
71 out = process.stdout.read(1)
72 if out:
73 sys.stdout.write(out)
74 sys.stdout.flush()
75 buf += out
76 elif out == '' and process.poll() != None:
77 break
78
79 if process.returncode != 0:
80 raise bb.process.ExecutionError(cmd, process.returncode, buf, None)
81
82 return buf, None
83
84def exec_fakeroot(d, cmd, **kwargs):
85 """Run a command under fakeroot (pseudo, in fact) so that it picks up the appropriate file permissions"""
86 # Grab the command and check it actually exists
87 fakerootcmd = d.getVar('FAKEROOTCMD', True)
88 if not os.path.exists(fakerootcmd):
89 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')
90 return 2
91 # Set up the appropriate environment
92 newenv = dict(os.environ)
93 fakerootenv = d.getVar('FAKEROOTENV', True)
94 for varvalue in fakerootenv.split():
95 if '=' in varvalue:
96 splitval = varvalue.split('=', 1)
97 newenv[splitval[0]] = splitval[1]
98 return subprocess.call("%s %s" % (fakerootcmd, cmd), env=newenv, **kwargs)
99
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500100def setup_tinfoil(config_only=False, basepath=None, tracking=False):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500101 """Initialize tinfoil api from bitbake"""
102 import scriptpath
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500103 orig_cwd = os.path.abspath(os.curdir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500104 try:
105 if basepath:
106 os.chdir(basepath)
107 bitbakepath = scriptpath.add_bitbake_lib_path()
108 if not bitbakepath:
109 logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
110 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500111
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500112 import bb.tinfoil
113 tinfoil = bb.tinfoil.Tinfoil(tracking=tracking)
114 tinfoil.prepare(config_only)
115 tinfoil.logger.setLevel(logger.getEffectiveLevel())
116 finally:
117 os.chdir(orig_cwd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500118 return tinfoil
119
120def get_recipe_file(cooker, pn):
121 """Find recipe file corresponding a package name"""
122 import oe.recipeutils
123 recipefile = oe.recipeutils.pn_to_recipe(cooker, pn)
124 if not recipefile:
125 skipreasons = oe.recipeutils.get_unavailable_reasons(cooker, pn)
126 if skipreasons:
127 logger.error('\n'.join(skipreasons))
128 else:
129 logger.error("Unable to find any recipe file matching %s" % pn)
130 return recipefile
131
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500132def parse_recipe(config, tinfoil, pn, appends, filter_workspace=True):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500133 """Parse recipe of a package"""
134 import oe.recipeutils
135 recipefile = get_recipe_file(tinfoil.cooker, pn)
136 if not recipefile:
137 # Error already logged
138 return None
139 if appends:
140 append_files = tinfoil.cooker.collection.get_file_appends(recipefile)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500141 if filter_workspace:
142 # Filter out appends from the workspace
143 append_files = [path for path in append_files if
144 not path.startswith(config.workspace_path)]
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500145 else:
146 append_files = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500147 return oe.recipeutils.parse_recipe(recipefile, append_files,
148 tinfoil.config_data)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500149
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500150def check_workspace_recipe(workspace, pn, checksrc=True, bbclassextend=False):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500151 """
152 Check that a recipe is in the workspace and (optionally) that source
153 is present.
154 """
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500155
156 workspacepn = pn
157
158 for recipe, value in workspace.iteritems():
159 if recipe == pn:
160 break
161 if bbclassextend:
162 recipefile = value['recipefile']
163 if recipefile:
164 targets = get_bbclassextend_targets(recipefile, recipe)
165 if pn in targets:
166 workspacepn = recipe
167 break
168 else:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500169 raise DevtoolError("No recipe named '%s' in your workspace" % pn)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500170
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500171 if checksrc:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500172 srctree = workspace[workspacepn]['srctree']
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500173 if not os.path.exists(srctree):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500174 raise DevtoolError("Source tree %s for recipe %s does not exist" % (srctree, workspacepn))
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500175 if not os.listdir(srctree):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500176 raise DevtoolError("Source tree %s for recipe %s is empty" % (srctree, workspacepn))
177
178 return workspacepn
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500179
180def use_external_build(same_dir, no_same_dir, d):
181 """
182 Determine if we should use B!=S (separate build and source directories) or not
183 """
184 b_is_s = True
185 if no_same_dir:
186 logger.info('Using separate build directory since --no-same-dir specified')
187 b_is_s = False
188 elif same_dir:
189 logger.info('Using source tree as build directory since --same-dir specified')
190 elif bb.data.inherits_class('autotools-brokensep', d):
191 logger.info('Using source tree as build directory since recipe inherits autotools-brokensep')
192 elif d.getVar('B', True) == os.path.abspath(d.getVar('S', True)):
193 logger.info('Using source tree as build directory since that would be the default for this recipe')
194 else:
195 b_is_s = False
196 return b_is_s
197
198def setup_git_repo(repodir, version, devbranch, basetag='devtool-base'):
199 """
200 Set up the git repository for the source tree
201 """
202 import bb.process
203 if not os.path.exists(os.path.join(repodir, '.git')):
204 bb.process.run('git init', cwd=repodir)
205 bb.process.run('git add .', cwd=repodir)
206 commit_cmd = ['git', 'commit', '-q']
207 stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
208 if not stdout:
209 commit_cmd.append('--allow-empty')
210 commitmsg = "Initial empty commit with no upstream sources"
211 elif version:
212 commitmsg = "Initial commit from upstream at version %s" % version
213 else:
214 commitmsg = "Initial commit from upstream"
215 commit_cmd += ['-m', commitmsg]
216 bb.process.run(commit_cmd, cwd=repodir)
217
218 bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
219 bb.process.run('git tag -f %s' % basetag, cwd=repodir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500220
221def recipe_to_append(recipefile, config, wildcard=False):
222 """
223 Convert a recipe file to a bbappend file path within the workspace.
224 NOTE: if the bbappend already exists, you should be using
225 workspace[args.recipename]['bbappend'] instead of calling this
226 function.
227 """
228 appendname = os.path.splitext(os.path.basename(recipefile))[0]
229 if wildcard:
230 appendname = re.sub(r'_.*', '_%', appendname)
231 appendpath = os.path.join(config.workspace_path, 'appends')
232 appendfile = os.path.join(appendpath, appendname + '.bbappend')
233 return appendfile
234
235def get_bbclassextend_targets(recipefile, pn):
236 """
237 Cheap function to get BBCLASSEXTEND and then convert that to the
238 list of targets that would result.
239 """
240 import bb.utils
241
242 values = {}
243 def get_bbclassextend_varfunc(varname, origvalue, op, newlines):
244 values[varname] = origvalue
245 return origvalue, None, 0, True
246 with open(recipefile, 'r') as f:
247 bb.utils.edit_metadata(f, ['BBCLASSEXTEND'], get_bbclassextend_varfunc)
248
249 targets = []
250 bbclassextend = values.get('BBCLASSEXTEND', '').split()
251 if bbclassextend:
252 for variant in bbclassextend:
253 if variant == 'nativesdk':
254 targets.append('%s-%s' % (variant, pn))
255 elif variant in ['native', 'cross', 'crosssdk']:
256 targets.append('%s-%s' % (pn, variant))
257 return targets