blob: 89f098a912a682c6b42a9cd65e383e4dc69f9fb3 [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#!/usr/bin/env python3
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002
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
Brad Bishop6e60e8b2018-02-01 10:27:11 -050026import codecs
Patrick Williamsc124f4f2015-09-15 14:41:29 -050027
28logger = logging.getLogger('devtool')
29
Patrick Williamsc124f4f2015-09-15 14:41:29 -050030class DevtoolError(Exception):
31 """Exception for handling devtool errors"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -060032 def __init__(self, message, exitcode=1):
33 super(DevtoolError, self).__init__(message)
34 self.exitcode = exitcode
Patrick Williamsc124f4f2015-09-15 14:41:29 -050035
36
37def exec_build_env_command(init_path, builddir, cmd, watch=False, **options):
38 """Run a program in bitbake build context"""
39 import bb
40 if not 'cwd' in options:
41 options["cwd"] = builddir
42 if init_path:
43 # As the OE init script makes use of BASH_SOURCE to determine OEROOT,
44 # and can't determine it when running under dash, we need to set
45 # the executable to bash to correctly set things up
46 if not 'executable' in options:
47 options['executable'] = 'bash'
48 logger.debug('Executing command: "%s" using init path %s' % (cmd, init_path))
49 init_prefix = '. %s %s > /dev/null && ' % (init_path, builddir)
50 else:
51 logger.debug('Executing command "%s"' % cmd)
52 init_prefix = ''
53 if watch:
54 if sys.stdout.isatty():
55 # Fool bitbake into thinking it's outputting to a terminal (because it is, indirectly)
56 cmd = 'script -e -q -c "%s" /dev/null' % cmd
57 return exec_watch('%s%s' % (init_prefix, cmd), **options)
58 else:
59 return bb.process.run('%s%s' % (init_prefix, cmd), **options)
60
61def exec_watch(cmd, **options):
62 """Run program with stdout shown on sys.stdout"""
63 import bb
Patrick Williamsc0f7c042017-02-23 20:41:17 -060064 if isinstance(cmd, str) and not "shell" in options:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050065 options["shell"] = True
66
67 process = subprocess.Popen(
68 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **options
69 )
70
Brad Bishop6e60e8b2018-02-01 10:27:11 -050071 reader = codecs.getreader('utf-8')(process.stdout)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050072 buf = ''
73 while True:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050074 out = reader.read(1, 1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050075 if out:
76 sys.stdout.write(out)
77 sys.stdout.flush()
78 buf += out
79 elif out == '' and process.poll() != None:
80 break
81
82 if process.returncode != 0:
83 raise bb.process.ExecutionError(cmd, process.returncode, buf, None)
84
85 return buf, None
86
87def exec_fakeroot(d, cmd, **kwargs):
88 """Run a command under fakeroot (pseudo, in fact) so that it picks up the appropriate file permissions"""
89 # Grab the command and check it actually exists
Brad Bishop6e60e8b2018-02-01 10:27:11 -050090 fakerootcmd = d.getVar('FAKEROOTCMD')
Patrick Williamsc124f4f2015-09-15 14:41:29 -050091 if not os.path.exists(fakerootcmd):
92 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')
93 return 2
94 # Set up the appropriate environment
95 newenv = dict(os.environ)
Brad Bishop6e60e8b2018-02-01 10:27:11 -050096 fakerootenv = d.getVar('FAKEROOTENV')
Patrick Williamsc124f4f2015-09-15 14:41:29 -050097 for varvalue in fakerootenv.split():
98 if '=' in varvalue:
99 splitval = varvalue.split('=', 1)
100 newenv[splitval[0]] = splitval[1]
101 return subprocess.call("%s %s" % (fakerootcmd, cmd), env=newenv, **kwargs)
102
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500103def setup_tinfoil(config_only=False, basepath=None, tracking=False):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500104 """Initialize tinfoil api from bitbake"""
105 import scriptpath
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500106 orig_cwd = os.path.abspath(os.curdir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500107 try:
108 if basepath:
109 os.chdir(basepath)
110 bitbakepath = scriptpath.add_bitbake_lib_path()
111 if not bitbakepath:
112 logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
113 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500115 import bb.tinfoil
116 tinfoil = bb.tinfoil.Tinfoil(tracking=tracking)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500117 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500118 tinfoil.logger.setLevel(logger.getEffectiveLevel())
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500119 tinfoil.prepare(config_only)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500120 except bb.tinfoil.TinfoilUIException:
121 tinfoil.shutdown()
122 raise DevtoolError('Failed to start bitbake environment')
123 except:
124 tinfoil.shutdown()
125 raise
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500126 finally:
127 os.chdir(orig_cwd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500128 return tinfoil
129
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500130def parse_recipe(config, tinfoil, pn, appends, filter_workspace=True):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500131 """Parse the specified recipe"""
132 try:
133 recipefile = tinfoil.get_recipe_file(pn)
134 except bb.providers.NoProvider as e:
135 logger.error(str(e))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500136 return None
137 if appends:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500138 append_files = tinfoil.get_file_appends(recipefile)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500139 if filter_workspace:
140 # Filter out appends from the workspace
141 append_files = [path for path in append_files if
142 not path.startswith(config.workspace_path)]
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500143 else:
144 append_files = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500145 try:
146 rd = tinfoil.parse_recipe_file(recipefile, appends, append_files)
147 except Exception as e:
148 logger.error(str(e))
149 return None
150 return rd
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500151
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500152def check_workspace_recipe(workspace, pn, checksrc=True, bbclassextend=False):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500153 """
154 Check that a recipe is in the workspace and (optionally) that source
155 is present.
156 """
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500157
158 workspacepn = pn
159
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600160 for recipe, value in workspace.items():
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500161 if recipe == pn:
162 break
163 if bbclassextend:
164 recipefile = value['recipefile']
165 if recipefile:
166 targets = get_bbclassextend_targets(recipefile, recipe)
167 if pn in targets:
168 workspacepn = recipe
169 break
170 else:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500171 raise DevtoolError("No recipe named '%s' in your workspace" % pn)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500172
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500173 if checksrc:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500174 srctree = workspace[workspacepn]['srctree']
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500175 if not os.path.exists(srctree):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500176 raise DevtoolError("Source tree %s for recipe %s does not exist" % (srctree, workspacepn))
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500177 if not os.listdir(srctree):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500178 raise DevtoolError("Source tree %s for recipe %s is empty" % (srctree, workspacepn))
179
180 return workspacepn
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500181
182def use_external_build(same_dir, no_same_dir, d):
183 """
184 Determine if we should use B!=S (separate build and source directories) or not
185 """
186 b_is_s = True
187 if no_same_dir:
188 logger.info('Using separate build directory since --no-same-dir specified')
189 b_is_s = False
190 elif same_dir:
191 logger.info('Using source tree as build directory since --same-dir specified')
192 elif bb.data.inherits_class('autotools-brokensep', d):
193 logger.info('Using source tree as build directory since recipe inherits autotools-brokensep')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500194 elif os.path.abspath(d.getVar('B')) == os.path.abspath(d.getVar('S')):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500195 logger.info('Using source tree as build directory since that would be the default for this recipe')
196 else:
197 b_is_s = False
198 return b_is_s
199
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600200def setup_git_repo(repodir, version, devbranch, basetag='devtool-base', d=None):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500201 """
202 Set up the git repository for the source tree
203 """
204 import bb.process
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600205 import oe.patch
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500206 if not os.path.exists(os.path.join(repodir, '.git')):
207 bb.process.run('git init', cwd=repodir)
208 bb.process.run('git add .', cwd=repodir)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600209 commit_cmd = ['git']
210 oe.patch.GitApplyTree.gitCommandUserOptions(commit_cmd, d=d)
211 commit_cmd += ['commit', '-q']
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500212 stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
213 if not stdout:
214 commit_cmd.append('--allow-empty')
215 commitmsg = "Initial empty commit with no upstream sources"
216 elif version:
217 commitmsg = "Initial commit from upstream at version %s" % version
218 else:
219 commitmsg = "Initial commit from upstream"
220 commit_cmd += ['-m', commitmsg]
221 bb.process.run(commit_cmd, cwd=repodir)
222
Brad Bishop316dfdd2018-06-25 12:45:53 -0400223 # Ensure singletask.lock (as used by externalsrc.bbclass) is ignored by git
224 excludes = []
225 excludefile = os.path.join(repodir, '.git', 'info', 'exclude')
226 try:
227 with open(excludefile, 'r') as f:
228 excludes = f.readlines()
229 except FileNotFoundError:
230 pass
231 if 'singletask.lock\n' not in excludes:
232 excludes.append('singletask.lock\n')
233 with open(excludefile, 'w') as f:
234 for line in excludes:
235 f.write(line)
236
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500237 bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
238 bb.process.run('git tag -f %s' % basetag, cwd=repodir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500239
240def recipe_to_append(recipefile, config, wildcard=False):
241 """
242 Convert a recipe file to a bbappend file path within the workspace.
243 NOTE: if the bbappend already exists, you should be using
244 workspace[args.recipename]['bbappend'] instead of calling this
245 function.
246 """
247 appendname = os.path.splitext(os.path.basename(recipefile))[0]
248 if wildcard:
249 appendname = re.sub(r'_.*', '_%', appendname)
250 appendpath = os.path.join(config.workspace_path, 'appends')
251 appendfile = os.path.join(appendpath, appendname + '.bbappend')
252 return appendfile
253
254def get_bbclassextend_targets(recipefile, pn):
255 """
256 Cheap function to get BBCLASSEXTEND and then convert that to the
257 list of targets that would result.
258 """
259 import bb.utils
260
261 values = {}
262 def get_bbclassextend_varfunc(varname, origvalue, op, newlines):
263 values[varname] = origvalue
264 return origvalue, None, 0, True
265 with open(recipefile, 'r') as f:
266 bb.utils.edit_metadata(f, ['BBCLASSEXTEND'], get_bbclassextend_varfunc)
267
268 targets = []
269 bbclassextend = values.get('BBCLASSEXTEND', '').split()
270 if bbclassextend:
271 for variant in bbclassextend:
272 if variant == 'nativesdk':
273 targets.append('%s-%s' % (variant, pn))
274 elif variant in ['native', 'cross', 'crosssdk']:
275 targets.append('%s-%s' % (pn, variant))
276 return targets
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600277
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500278def replace_from_file(path, old, new):
279 """Replace strings on a file"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600280
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500281 def read_file(path):
282 data = None
283 with open(path) as f:
284 data = f.read()
285 return data
286
287 def write_file(path, data):
288 if data is None:
289 return
290 wdata = data.rstrip() + "\n"
291 with open(path, "w") as f:
292 f.write(wdata)
293
294 # In case old is None, return immediately
295 if old is None:
296 return
297 try:
298 rdata = read_file(path)
299 except IOError as e:
300 # if file does not exit, just quit, otherwise raise an exception
301 if e.errno == errno.ENOENT:
302 return
303 else:
304 raise
305
306 old_contents = rdata.splitlines()
307 new_contents = []
308 for old_content in old_contents:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600309 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500310 new_contents.append(old_content.replace(old, new))
311 except ValueError:
312 pass
313 write_file(path, "\n".join(new_contents))
314
315
316def update_unlockedsigs(basepath, workspace, fixed_setup, extra=None):
317 """ This function will make unlocked-sigs.inc match the recipes in the
318 workspace plus any extras we want unlocked. """
319
320 if not fixed_setup:
321 # Only need to write this out within the eSDK
322 return
323
324 if not extra:
325 extra = []
326
327 confdir = os.path.join(basepath, 'conf')
328 unlockedsigs = os.path.join(confdir, 'unlocked-sigs.inc')
329
330 # Get current unlocked list if any
331 values = {}
332 def get_unlockedsigs_varfunc(varname, origvalue, op, newlines):
333 values[varname] = origvalue
334 return origvalue, None, 0, True
335 if os.path.exists(unlockedsigs):
336 with open(unlockedsigs, 'r') as f:
337 bb.utils.edit_metadata(f, ['SIGGEN_UNLOCKED_RECIPES'], get_unlockedsigs_varfunc)
338 unlocked = sorted(values.get('SIGGEN_UNLOCKED_RECIPES', []))
339
340 # If the new list is different to the current list, write it out
341 newunlocked = sorted(list(workspace.keys()) + extra)
342 if unlocked != newunlocked:
343 bb.utils.mkdirhier(confdir)
344 with open(unlockedsigs, 'w') as f:
345 f.write("# DO NOT MODIFY! YOUR CHANGES WILL BE LOST.\n" +
346 "# This layer was created by the OpenEmbedded devtool" +
347 " utility in order to\n" +
348 "# contain recipes that are unlocked.\n")
349
350 f.write('SIGGEN_UNLOCKED_RECIPES += "\\\n')
351 for pn in newunlocked:
352 f.write(' ' + pn)
353 f.write('"')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400354
355def check_prerelease_version(ver, operation):
356 if 'pre' in ver or 'rc' in ver:
357 logger.warning('Version "%s" looks like a pre-release version. '
358 'If that is the case, in order to ensure that the '
359 'version doesn\'t appear to go backwards when you '
360 'later upgrade to the final release version, it is '
361 'recommmended that instead you use '
362 '<current version>+<pre-release version> e.g. if '
363 'upgrading from 1.9 to 2.0-rc2 use "1.9+2.0-rc2". '
364 'If you prefer not to reset and re-try, you can change '
365 'the version after %s succeeds using "devtool rename" '
366 'with -V/--version.' % (ver, operation))
367
368def check_git_repo_dirty(repodir):
369 """Check if a git repository is clean or not"""
370 stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
371 return stdout
372
373def check_git_repo_op(srctree, ignoredirs=None):
374 """Check if a git repository is in the middle of a rebase"""
375 stdout, _ = bb.process.run('git rev-parse --show-toplevel', cwd=srctree)
376 topleveldir = stdout.strip()
377 if ignoredirs and topleveldir in ignoredirs:
378 return
379 gitdir = os.path.join(topleveldir, '.git')
380 if os.path.exists(os.path.join(gitdir, 'rebase-merge')):
381 raise DevtoolError("Source tree %s appears to be in the middle of a rebase - please resolve this first" % srctree)
382 if os.path.exists(os.path.join(gitdir, 'rebase-apply')):
383 raise DevtoolError("Source tree %s appears to be in the middle of 'git am' or 'git apply' - please resolve this first" % srctree)