blob: 50604e6e0dabb1662ff36bbda7fe39a9e171f677 [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
25
26logger = logging.getLogger('devtool')
27
28
29class DevtoolError(Exception):
30 """Exception for handling devtool errors"""
31 pass
32
33
34def exec_build_env_command(init_path, builddir, cmd, watch=False, **options):
35 """Run a program in bitbake build context"""
36 import bb
37 if not 'cwd' in options:
38 options["cwd"] = builddir
39 if init_path:
40 # As the OE init script makes use of BASH_SOURCE to determine OEROOT,
41 # and can't determine it when running under dash, we need to set
42 # the executable to bash to correctly set things up
43 if not 'executable' in options:
44 options['executable'] = 'bash'
45 logger.debug('Executing command: "%s" using init path %s' % (cmd, init_path))
46 init_prefix = '. %s %s > /dev/null && ' % (init_path, builddir)
47 else:
48 logger.debug('Executing command "%s"' % cmd)
49 init_prefix = ''
50 if watch:
51 if sys.stdout.isatty():
52 # Fool bitbake into thinking it's outputting to a terminal (because it is, indirectly)
53 cmd = 'script -e -q -c "%s" /dev/null' % cmd
54 return exec_watch('%s%s' % (init_prefix, cmd), **options)
55 else:
56 return bb.process.run('%s%s' % (init_prefix, cmd), **options)
57
58def exec_watch(cmd, **options):
59 """Run program with stdout shown on sys.stdout"""
60 import bb
61 if isinstance(cmd, basestring) and not "shell" in options:
62 options["shell"] = True
63
64 process = subprocess.Popen(
65 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **options
66 )
67
68 buf = ''
69 while True:
70 out = process.stdout.read(1)
71 if out:
72 sys.stdout.write(out)
73 sys.stdout.flush()
74 buf += out
75 elif out == '' and process.poll() != None:
76 break
77
78 if process.returncode != 0:
79 raise bb.process.ExecutionError(cmd, process.returncode, buf, None)
80
81 return buf, None
82
83def exec_fakeroot(d, cmd, **kwargs):
84 """Run a command under fakeroot (pseudo, in fact) so that it picks up the appropriate file permissions"""
85 # Grab the command and check it actually exists
86 fakerootcmd = d.getVar('FAKEROOTCMD', True)
87 if not os.path.exists(fakerootcmd):
88 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')
89 return 2
90 # Set up the appropriate environment
91 newenv = dict(os.environ)
92 fakerootenv = d.getVar('FAKEROOTENV', True)
93 for varvalue in fakerootenv.split():
94 if '=' in varvalue:
95 splitval = varvalue.split('=', 1)
96 newenv[splitval[0]] = splitval[1]
97 return subprocess.call("%s %s" % (fakerootcmd, cmd), env=newenv, **kwargs)
98
Patrick Williamsf1e5d692016-03-30 15:21:19 -050099def setup_tinfoil(config_only=False, basepath=None, tracking=False):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500100 """Initialize tinfoil api from bitbake"""
101 import scriptpath
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500102 orig_cwd = os.path.abspath(os.curdir)
103 if basepath:
104 os.chdir(basepath)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500105 bitbakepath = scriptpath.add_bitbake_lib_path()
106 if not bitbakepath:
107 logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
108 sys.exit(1)
109
110 import bb.tinfoil
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500111 tinfoil = bb.tinfoil.Tinfoil(tracking=tracking)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500112 tinfoil.prepare(config_only)
113 tinfoil.logger.setLevel(logger.getEffectiveLevel())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500114 os.chdir(orig_cwd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500115 return tinfoil
116
117def get_recipe_file(cooker, pn):
118 """Find recipe file corresponding a package name"""
119 import oe.recipeutils
120 recipefile = oe.recipeutils.pn_to_recipe(cooker, pn)
121 if not recipefile:
122 skipreasons = oe.recipeutils.get_unavailable_reasons(cooker, pn)
123 if skipreasons:
124 logger.error('\n'.join(skipreasons))
125 else:
126 logger.error("Unable to find any recipe file matching %s" % pn)
127 return recipefile
128
129def parse_recipe(config, tinfoil, pn, appends):
130 """Parse recipe of a package"""
131 import oe.recipeutils
132 recipefile = get_recipe_file(tinfoil.cooker, pn)
133 if not recipefile:
134 # Error already logged
135 return None
136 if appends:
137 append_files = tinfoil.cooker.collection.get_file_appends(recipefile)
138 # Filter out appends from the workspace
139 append_files = [path for path in append_files if
140 not path.startswith(config.workspace_path)]
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500141 else:
142 append_files = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500143 return oe.recipeutils.parse_recipe(recipefile, append_files,
144 tinfoil.config_data)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500145
146def check_workspace_recipe(workspace, pn, checksrc=True):
147 """
148 Check that a recipe is in the workspace and (optionally) that source
149 is present.
150 """
151 if not pn in workspace:
152 raise DevtoolError("No recipe named '%s' in your workspace" % pn)
153 if checksrc:
154 srctree = workspace[pn]['srctree']
155 if not os.path.exists(srctree):
156 raise DevtoolError("Source tree %s for recipe %s does not exist" % (srctree, pn))
157 if not os.listdir(srctree):
158 raise DevtoolError("Source tree %s for recipe %s is empty" % (srctree, pn))
159
160def use_external_build(same_dir, no_same_dir, d):
161 """
162 Determine if we should use B!=S (separate build and source directories) or not
163 """
164 b_is_s = True
165 if no_same_dir:
166 logger.info('Using separate build directory since --no-same-dir specified')
167 b_is_s = False
168 elif same_dir:
169 logger.info('Using source tree as build directory since --same-dir specified')
170 elif bb.data.inherits_class('autotools-brokensep', d):
171 logger.info('Using source tree as build directory since recipe inherits autotools-brokensep')
172 elif d.getVar('B', True) == os.path.abspath(d.getVar('S', True)):
173 logger.info('Using source tree as build directory since that would be the default for this recipe')
174 else:
175 b_is_s = False
176 return b_is_s
177
178def setup_git_repo(repodir, version, devbranch, basetag='devtool-base'):
179 """
180 Set up the git repository for the source tree
181 """
182 import bb.process
183 if not os.path.exists(os.path.join(repodir, '.git')):
184 bb.process.run('git init', cwd=repodir)
185 bb.process.run('git add .', cwd=repodir)
186 commit_cmd = ['git', 'commit', '-q']
187 stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
188 if not stdout:
189 commit_cmd.append('--allow-empty')
190 commitmsg = "Initial empty commit with no upstream sources"
191 elif version:
192 commitmsg = "Initial commit from upstream at version %s" % version
193 else:
194 commitmsg = "Initial commit from upstream"
195 commit_cmd += ['-m', commitmsg]
196 bb.process.run(commit_cmd, cwd=repodir)
197
198 bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
199 bb.process.run('git tag -f %s' % basetag, cwd=repodir)