blob: 62ec2f94cbcbdd78f620bbef2daa3608432ad829 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Development tool - upgrade command plugin
2#
Brad Bishopd7bf8c12018-02-25 22:55:05 -05003# Copyright (C) 2014-2017 Intel Corporation
Patrick Williamsc124f4f2015-09-15 14:41:29 -05004#
Brad Bishopc342db32019-05-15 21:57:59 -04005# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006#
7"""Devtool upgrade plugin"""
8
9import os
10import sys
11import re
12import shutil
13import tempfile
14import logging
15import argparse
16import scriptutils
17import errno
18import bb
Brad Bishop6e60e8b2018-02-01 10:27:11 -050019
20devtool_path = os.path.dirname(os.path.realpath(__file__)) + '/../../../meta/lib'
21sys.path = sys.path + [devtool_path]
22
Patrick Williamsc124f4f2015-09-15 14:41:29 -050023import oe.recipeutils
24from devtool import standard
Brad Bishop316dfdd2018-06-25 12:45:53 -040025from devtool import exec_build_env_command, setup_tinfoil, DevtoolError, parse_recipe, use_external_build, update_unlockedsigs, check_prerelease_version
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026
27logger = logging.getLogger('devtool')
28
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029def _run(cmd, cwd=''):
30 logger.debug("Running command %s> %s" % (cwd,cmd))
31 return bb.process.run('%s' % cmd, cwd=cwd)
32
33def _get_srctree(tmpdir):
34 srctree = tmpdir
35 dirs = os.listdir(tmpdir)
36 if len(dirs) == 1:
37 srctree = os.path.join(tmpdir, dirs[0])
38 return srctree
39
40def _copy_source_code(orig, dest):
41 for path in standard._ls_tree(orig):
42 dest_dir = os.path.join(dest, os.path.dirname(path))
43 bb.utils.mkdirhier(dest_dir)
44 dest_path = os.path.join(dest, path)
Patrick Williamsf1e5d692016-03-30 15:21:19 -050045 shutil.move(os.path.join(orig, path), dest_path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046
Patrick Williamsc124f4f2015-09-15 14:41:29 -050047def _remove_patch_dirs(recipefolder):
48 for root, dirs, files in os.walk(recipefolder):
49 for d in dirs:
50 shutil.rmtree(os.path.join(root,d))
51
Patrick Williamsf1e5d692016-03-30 15:21:19 -050052def _recipe_contains(rd, var):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050053 rf = rd.getVar('FILE')
Patrick Williamsf1e5d692016-03-30 15:21:19 -050054 varfiles = oe.recipeutils.get_var_files(rf, [var], rd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060055 for var, fn in varfiles.items():
Patrick Williamsf1e5d692016-03-30 15:21:19 -050056 if fn and fn.startswith(os.path.dirname(rf) + os.sep):
57 return True
58 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050059
60def _rename_recipe_dirs(oldpv, newpv, path):
61 for root, dirs, files in os.walk(path):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060062 # Rename directories with the version in their name
Patrick Williamsc124f4f2015-09-15 14:41:29 -050063 for olddir in dirs:
64 if olddir.find(oldpv) != -1:
65 newdir = olddir.replace(oldpv, newpv)
66 if olddir != newdir:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050067 shutil.move(os.path.join(path, olddir), os.path.join(path, newdir))
Patrick Williamsc0f7c042017-02-23 20:41:17 -060068 # Rename any inc files with the version in their name (unusual, but possible)
69 for oldfile in files:
70 if oldfile.endswith('.inc'):
71 if oldfile.find(oldpv) != -1:
72 newfile = oldfile.replace(oldpv, newpv)
73 if oldfile != newfile:
74 os.rename(os.path.join(path, oldfile), os.path.join(path, newfile))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050075
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050076def _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path):
77 oldrecipe = os.path.basename(oldrecipe)
78 if oldrecipe.endswith('_%s.bb' % oldpv):
79 newrecipe = '%s_%s.bb' % (bpn, newpv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050080 if oldrecipe != newrecipe:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050081 shutil.move(os.path.join(path, oldrecipe), os.path.join(path, newrecipe))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050082 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050083 newrecipe = oldrecipe
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084 return os.path.join(path, newrecipe)
85
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050086def _rename_recipe_files(oldrecipe, bpn, oldpv, newpv, path):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050087 _rename_recipe_dirs(oldpv, newpv, path)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050088 return _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050089
Patrick Williamsc0f7c042017-02-23 20:41:17 -060090def _write_append(rc, srctree, same_dir, no_same_dir, rev, copied, workspace, d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050091 """Writes an append file"""
92 if not os.path.exists(rc):
93 raise DevtoolError("bbappend not created because %s does not exist" % rc)
94
95 appendpath = os.path.join(workspace, 'appends')
96 if not os.path.exists(appendpath):
97 bb.utils.mkdirhier(appendpath)
98
99 brf = os.path.basename(os.path.splitext(rc)[0]) # rc basename
100
101 srctree = os.path.abspath(srctree)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500102 pn = d.getVar('PN')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500103 af = os.path.join(appendpath, '%s.bbappend' % brf)
104 with open(af, 'w') as f:
105 f.write('FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"\n\n')
106 f.write('inherit externalsrc\n')
107 f.write(('# NOTE: We use pn- overrides here to avoid affecting'
108 'multiple variants in the case where the recipe uses BBCLASSEXTEND\n'))
109 f.write('EXTERNALSRC_pn-%s = "%s"\n' % (pn, srctree))
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500110 b_is_s = use_external_build(same_dir, no_same_dir, d)
111 if b_is_s:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500112 f.write('EXTERNALSRC_BUILD_pn-%s = "%s"\n' % (pn, srctree))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600113 f.write('\n')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114 if rev:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600115 f.write('# initial_rev: %s\n' % rev)
116 if copied:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500117 f.write('# original_path: %s\n' % os.path.dirname(d.getVar('FILE')))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600118 f.write('# original_files: %s\n' % ' '.join(copied))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500119 return af
120
121def _cleanup_on_error(rf, srctree):
122 rfp = os.path.split(rf)[0] # recipe folder
123 rfpp = os.path.split(rfp)[0] # recipes folder
124 if os.path.exists(rfp):
125 shutil.rmtree(b)
126 if not len(os.listdir(rfpp)):
127 os.rmdir(rfpp)
128 srctree = os.path.abspath(srctree)
129 if os.path.exists(srctree):
130 shutil.rmtree(srctree)
131
132def _upgrade_error(e, rf, srctree):
133 if rf:
134 cleanup_on_error(rf, srctree)
135 logger.error(e)
136 raise DevtoolError(e)
137
138def _get_uri(rd):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500139 srcuris = rd.getVar('SRC_URI').split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500140 if not len(srcuris):
141 raise DevtoolError('SRC_URI not found on recipe')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500142 # Get first non-local entry in SRC_URI - usually by convention it's
143 # the first entry, but not always!
144 srcuri = None
145 for entry in srcuris:
146 if not entry.startswith('file://'):
147 srcuri = entry
148 break
149 if not srcuri:
150 raise DevtoolError('Unable to find non-local entry in SRC_URI')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500151 srcrev = '${AUTOREV}'
152 if '://' in srcuri:
153 # Fetch a URL
154 rev_re = re.compile(';rev=([^;]+)')
155 res = rev_re.search(srcuri)
156 if res:
157 srcrev = res.group(1)
158 srcuri = rev_re.sub('', srcuri)
159 return srcuri, srcrev
160
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500161def _extract_new_source(newpv, srctree, no_patch, srcrev, srcbranch, branch, keep_temp, tinfoil, rd):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500162 """Extract sources of a recipe with a new version"""
163
164 def __run(cmd):
165 """Simple wrapper which calls _run with srctree as cwd"""
166 return _run(cmd, srctree)
167
168 crd = rd.createCopy()
169
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500170 pv = crd.getVar('PV')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500171 crd.setVar('PV', newpv)
172
173 tmpsrctree = None
174 uri, rev = _get_uri(crd)
175 if srcrev:
176 rev = srcrev
177 if uri.startswith('git://'):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500178 __run('git fetch')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500179 __run('git checkout %s' % rev)
180 __run('git tag -f devtool-base-new')
181 md5 = None
182 sha256 = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400183 _, _, _, _, _, params = bb.fetch2.decodeurl(uri)
184 srcsubdir_rel = params.get('destsuffix', 'git')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500185 if not srcbranch:
186 check_branch, check_branch_err = __run('git branch -r --contains %s' % srcrev)
187 get_branch = [x.strip() for x in check_branch.splitlines()]
188 # Remove HEAD reference point and drop remote prefix
189 get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
190 if 'master' in get_branch:
191 # If it is master, we do not need to append 'branch=master' as this is default.
192 # Even with the case where get_branch has multiple objects, if 'master' is one
193 # of them, we should default take from 'master'
194 srcbranch = ''
195 elif len(get_branch) == 1:
196 # If 'master' isn't in get_branch and get_branch contains only ONE object, then store result into 'srcbranch'
197 srcbranch = get_branch[0]
198 else:
199 # If get_branch contains more than one objects, then display error and exit.
200 mbrch = '\n ' + '\n '.join(get_branch)
201 raise DevtoolError('Revision %s was found on multiple branches: %s\nPlease provide the correct branch in the devtool command with "--srcbranch" or "-B" option.' % (srcrev, mbrch))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500202 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500203 __run('git checkout devtool-base -b devtool-%s' % newpv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500204
205 tmpdir = tempfile.mkdtemp(prefix='devtool')
206 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500207 checksums, ftmpdir = scriptutils.fetch_url(tinfoil, uri, rev, tmpdir, logger, preserve_tmp=keep_temp)
208 except scriptutils.FetchUrlFailure as e:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500209 raise DevtoolError(e)
210
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500211 if ftmpdir and keep_temp:
212 logger.info('Fetch temp directory is %s' % ftmpdir)
213
214 md5 = checksums['md5sum']
215 sha256 = checksums['sha256sum']
216
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500217 tmpsrctree = _get_srctree(tmpdir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500218 srctree = os.path.abspath(srctree)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400219 srcsubdir_rel = os.path.relpath(tmpsrctree, tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500220
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500221 # Delete all sources so we ensure no stray files are left over
222 for item in os.listdir(srctree):
223 if item in ['.git', 'oe-local-files']:
224 continue
225 itempath = os.path.join(srctree, item)
226 if os.path.isdir(itempath):
227 shutil.rmtree(itempath)
228 else:
229 os.remove(itempath)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500230
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500231 # Copy in new ones
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500232 _copy_source_code(tmpsrctree, srctree)
233
234 (stdout,_) = __run('git ls-files --modified --others --exclude-standard')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400235 filelist = stdout.splitlines()
236 pbar = bb.ui.knotty.BBProgress('Adding changed files', len(filelist))
237 pbar.start()
238 batchsize = 100
239 for i in range(0, len(filelist), batchsize):
240 batch = filelist[i:i+batchsize]
241 __run('git add -A %s' % ' '.join(['"%s"' % item for item in batch]))
242 pbar.update(i)
243 pbar.finish()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500244
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600245 useroptions = []
246 oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=rd)
247 __run('git %s commit -q -m "Commit of upstream changes at version %s" --allow-empty' % (' '.join(useroptions), newpv))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500248 __run('git tag -f devtool-base-%s' % newpv)
249
250 (stdout, _) = __run('git rev-parse HEAD')
251 rev = stdout.rstrip()
252
253 if no_patch:
254 patches = oe.recipeutils.get_recipe_patches(crd)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400255 if patches:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800256 logger.warning('By user choice, the following patches will NOT be applied to the new source tree:\n %s' % '\n '.join([os.path.basename(patch) for patch in patches]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500257 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600258 __run('git checkout devtool-patched -b %s' % branch)
259 skiptag = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500260 try:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500261 __run('git rebase %s' % rev)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600262 except bb.process.ExecutionError as e:
263 skiptag = True
264 if 'conflict' in e.stdout:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800265 logger.warning('Command \'%s\' failed:\n%s\n\nYou will need to resolve conflicts in order to complete the upgrade.' % (e.command, e.stdout.rstrip()))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600266 else:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800267 logger.warning('Command \'%s\' failed:\n%s' % (e.command, e.stdout))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600268 if not skiptag:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500269 if uri.startswith('git://'):
270 suffix = 'new'
271 else:
272 suffix = newpv
273 __run('git tag -f devtool-patched-%s' % suffix)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500274
275 if tmpsrctree:
276 if keep_temp:
277 logger.info('Preserving temporary directory %s' % tmpsrctree)
278 else:
279 shutil.rmtree(tmpsrctree)
280
Brad Bishop316dfdd2018-06-25 12:45:53 -0400281 return (rev, md5, sha256, srcbranch, srcsubdir_rel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500282
Brad Bishop316dfdd2018-06-25 12:45:53 -0400283def _add_license_diff_to_recipe(path, diff):
284 notice_text = """# FIXME: the LIC_FILES_CHKSUM values have been updated by 'devtool upgrade'.
285# The following is the difference between the old and the new license text.
286# Please update the LICENSE value if needed, and summarize the changes in
287# the commit message via 'License-Update:' tag.
288# (example: 'License-Update: copyright years updated.')
289#
290# The changes:
291#
292"""
293 commented_diff = "\n".join(["# {}".format(l) for l in diff.split('\n')])
294 with open(path, 'rb') as f:
295 orig_content = f.read()
296 with open(path, 'wb') as f:
297 f.write(notice_text.encode())
298 f.write(commented_diff.encode())
299 f.write("\n#\n\n".encode())
300 f.write(orig_content)
301
302def _create_new_recipe(newpv, md5, sha256, srcrev, srcbranch, srcsubdir_old, srcsubdir_new, workspace, tinfoil, rd, license_diff, new_licenses):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500303 """Creates the new recipe under workspace"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500304
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500305 bpn = rd.getVar('BPN')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500306 path = os.path.join(workspace, 'recipes', bpn)
307 bb.utils.mkdirhier(path)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500308 copied, _ = oe.recipeutils.copy_recipe_files(rd, path, all_variants=True)
309 if not copied:
310 raise DevtoolError('Internal error - no files were copied for recipe %s' % bpn)
311 logger.debug('Copied %s to %s' % (copied, path))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500312
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500313 oldpv = rd.getVar('PV')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500314 if not newpv:
315 newpv = oldpv
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500316 origpath = rd.getVar('FILE')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500317 fullpath = _rename_recipe_files(origpath, bpn, oldpv, newpv, path)
318 logger.debug('Upgraded %s => %s' % (origpath, fullpath))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500319
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500320 newvalues = {}
321 if _recipe_contains(rd, 'PV') and newpv != oldpv:
322 newvalues['PV'] = newpv
323
324 if srcrev:
325 newvalues['SRCREV'] = srcrev
326
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500327 if srcbranch:
328 src_uri = oe.recipeutils.split_var_value(rd.getVar('SRC_URI', False) or '')
329 changed = False
330 replacing = True
331 new_src_uri = []
332 for entry in src_uri:
333 scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(entry)
334 if replacing and scheme in ['git', 'gitsm']:
335 branch = params.get('branch', 'master')
336 if rd.expand(branch) != srcbranch:
337 # Handle case where branch is set through a variable
338 res = re.match(r'\$\{([^}@]+)\}', branch)
339 if res:
340 newvalues[res.group(1)] = srcbranch
341 # We know we won't change SRC_URI now, so break out
342 break
343 else:
344 params['branch'] = srcbranch
345 entry = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
346 changed = True
347 replacing = False
348 new_src_uri.append(entry)
349 if changed:
350 newvalues['SRC_URI'] = ' '.join(new_src_uri)
351
352 newvalues['PR'] = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500353
Brad Bishop316dfdd2018-06-25 12:45:53 -0400354 # Work out which SRC_URI entries have changed in case the entry uses a name
355 crd = rd.createCopy()
356 crd.setVar('PV', newpv)
357 for var, value in newvalues.items():
358 crd.setVar(var, value)
359 old_src_uri = (rd.getVar('SRC_URI') or '').split()
360 new_src_uri = (crd.getVar('SRC_URI') or '').split()
361 newnames = []
362 addnames = []
363 for newentry in new_src_uri:
364 _, _, _, _, _, params = bb.fetch2.decodeurl(newentry)
365 if 'name' in params:
366 newnames.append(params['name'])
367 if newentry not in old_src_uri:
368 addnames.append(params['name'])
369 # Find what's been set in the original recipe
370 oldnames = []
371 noname = False
372 for varflag in rd.getVarFlags('SRC_URI'):
373 if varflag.endswith(('.md5sum', '.sha256sum')):
374 name = varflag.rsplit('.', 1)[0]
375 if name not in oldnames:
376 oldnames.append(name)
377 elif varflag in ['md5sum', 'sha256sum']:
378 noname = True
379 # Even if SRC_URI has named entries it doesn't have to actually use the name
380 if noname and addnames and addnames[0] not in oldnames:
381 addnames = []
382 # Drop any old names (the name actually might include ${PV})
383 for name in oldnames:
384 if name not in newnames:
385 newvalues['SRC_URI[%s.md5sum]' % name] = None
386 newvalues['SRC_URI[%s.sha256sum]' % name] = None
387
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500388 if md5 and sha256:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400389 if addnames:
390 nameprefix = '%s.' % addnames[0]
391 else:
392 nameprefix = ''
393 newvalues['SRC_URI[%smd5sum]' % nameprefix] = md5
394 newvalues['SRC_URI[%ssha256sum]' % nameprefix] = sha256
395
396 if srcsubdir_new != srcsubdir_old:
397 s_subdir_old = os.path.relpath(os.path.abspath(rd.getVar('S')), rd.getVar('WORKDIR'))
398 s_subdir_new = os.path.relpath(os.path.abspath(crd.getVar('S')), crd.getVar('WORKDIR'))
399 if srcsubdir_old == s_subdir_old and srcsubdir_new != s_subdir_new:
400 # Subdir for old extracted source matches what S points to (it should!)
401 # but subdir for new extracted source doesn't match what S will be
402 newvalues['S'] = '${WORKDIR}/%s' % srcsubdir_new.replace(newpv, '${PV}')
403 if crd.expand(newvalues['S']) == crd.expand('${WORKDIR}/${BP}'):
404 # It's the default, drop it
405 # FIXME what if S is being set in a .inc?
406 newvalues['S'] = None
407 logger.info('Source subdirectory has changed, dropping S value since it now matches the default ("${WORKDIR}/${BP}")')
408 else:
409 logger.info('Source subdirectory has changed, updating S value')
410
411 if license_diff:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800412 newlicchksum = " ".join(["file://{}".format(l['path']) +
413 (";beginline={}".format(l['beginline']) if l['beginline'] else "") +
414 (";endline={}".format(l['endline']) if l['endline'] else "") +
415 (";md5={}".format(l['actual_md5'])) for l in new_licenses])
Brad Bishop316dfdd2018-06-25 12:45:53 -0400416 newvalues["LIC_FILES_CHKSUM"] = newlicchksum
417 _add_license_diff_to_recipe(fullpath, license_diff)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500418
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500419 rd = tinfoil.parse_recipe_file(fullpath, False)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500420 oe.recipeutils.patch_recipe(rd, fullpath, newvalues)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500421
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600422 return fullpath, copied
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500423
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500424
425def _check_git_config():
426 def getconfig(name):
427 try:
428 value = bb.process.run('git config --global %s' % name)[0].strip()
429 except bb.process.ExecutionError as e:
430 if e.exitcode == 1:
431 value = None
432 else:
433 raise
434 return value
435
436 username = getconfig('user.name')
437 useremail = getconfig('user.email')
438 configerr = []
439 if not username:
440 configerr.append('Please set your name using:\n git config --global user.name')
441 if not useremail:
442 configerr.append('Please set your email using:\n git config --global user.email')
443 if configerr:
444 raise DevtoolError('Your git configuration is incomplete which will prevent rebases from working:\n' + '\n'.join(configerr))
445
Brad Bishop316dfdd2018-06-25 12:45:53 -0400446def _extract_licenses(srcpath, recipe_licenses):
447 licenses = []
448 for url in recipe_licenses.split():
449 license = {}
450 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
451 license['path'] = path
452 license['md5'] = parm.get('md5', '')
453 license['beginline'], license['endline'] = 0, 0
454 if 'beginline' in parm:
455 license['beginline'] = int(parm['beginline'])
456 if 'endline' in parm:
457 license['endline'] = int(parm['endline'])
458 license['text'] = []
459 with open(os.path.join(srcpath, path), 'rb') as f:
460 import hashlib
461 actual_md5 = hashlib.md5()
462 lineno = 0
463 for line in f:
464 lineno += 1
465 if (lineno >= license['beginline']) and ((lineno <= license['endline']) or not license['endline']):
466 license['text'].append(line.decode(errors='ignore'))
467 actual_md5.update(line)
468 license['actual_md5'] = actual_md5.hexdigest()
469 licenses.append(license)
470 return licenses
471
472def _generate_license_diff(old_licenses, new_licenses):
473 need_diff = False
474 for l in new_licenses:
475 if l['md5'] != l['actual_md5']:
476 need_diff = True
477 break
478 if need_diff == False:
479 return None
480
481 import difflib
482 diff = ''
483 for old, new in zip(old_licenses, new_licenses):
484 for line in difflib.unified_diff(old['text'], new['text'], old['path'], new['path']):
485 diff = diff + line
486 return diff
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500487
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500488def upgrade(args, config, basepath, workspace):
489 """Entry point for the devtool 'upgrade' subcommand"""
490
491 if args.recipename in workspace:
492 raise DevtoolError("recipe %s is already in your workspace" % args.recipename)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500493 if args.srcbranch and not args.srcrev:
494 raise DevtoolError("If you specify --srcbranch/-B then you must use --srcrev/-S to specify the revision" % args.recipename)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500495
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500496 _check_git_config()
497
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500498 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500499 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600500 rd = parse_recipe(config, tinfoil, args.recipename, True)
501 if not rd:
502 return 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500503
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500504 pn = rd.getVar('PN')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600505 if pn != args.recipename:
506 logger.info('Mapping %s to %s' % (args.recipename, pn))
507 if pn in workspace:
508 raise DevtoolError("recipe %s is already in your workspace" % pn)
509
510 if args.srctree:
511 srctree = os.path.abspath(args.srctree)
512 else:
513 srctree = standard.get_default_srctree(config, pn)
514
Brad Bishop316dfdd2018-06-25 12:45:53 -0400515 # try to automatically discover latest version and revision if not provided on command line
516 if not args.version and not args.srcrev:
517 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
518 if version_info['version'] and not version_info['version'].endswith("new-commits-available"):
519 args.version = version_info['version']
520 if version_info['revision']:
521 args.srcrev = version_info['revision']
522 if not args.version and not args.srcrev:
523 raise DevtoolError("Automatic discovery of latest version/revision failed - you must provide a version using the --version/-V option, or for recipes that fetch from an SCM such as git, the --srcrev/-S option.")
524
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600525 standard._check_compatible_recipe(pn, rd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500526 old_srcrev = rd.getVar('SRCREV')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600527 if old_srcrev == 'INVALID':
528 old_srcrev = None
529 if old_srcrev and not args.srcrev:
530 raise DevtoolError("Recipe specifies a SRCREV value; you must specify a new one when upgrading")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400531 old_ver = rd.getVar('PV')
532 if old_ver == args.version and old_srcrev == args.srcrev:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600533 raise DevtoolError("Current and upgrade versions are the same version")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400534 if args.version:
535 if bb.utils.vercmp_string(args.version, old_ver) < 0:
536 logger.warning('Upgrade version %s compares as less than the current version %s. If you are using a package feed for on-target upgrades or providing this recipe for general consumption, then you should increment PE in the recipe (or if there is no current PE value set, set it to "1")' % (args.version, old_ver))
537 check_prerelease_version(args.version, 'devtool upgrade')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600538
539 rf = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400540 license_diff = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600541 try:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400542 logger.info('Extracting current version source...')
543 rev1, srcsubdir1 = standard._extract_source(srctree, False, 'devtool-orig', False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
544 old_licenses = _extract_licenses(srctree, rd.getVar('LIC_FILES_CHKSUM'))
545 logger.info('Extracting upgraded version source...')
546 rev2, md5, sha256, srcbranch, srcsubdir2 = _extract_new_source(args.version, srctree, args.no_patch,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500547 args.srcrev, args.srcbranch, args.branch, args.keep_temp,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600548 tinfoil, rd)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400549 new_licenses = _extract_licenses(srctree, rd.getVar('LIC_FILES_CHKSUM'))
550 license_diff = _generate_license_diff(old_licenses, new_licenses)
551 rf, copied = _create_new_recipe(args.version, md5, sha256, args.srcrev, srcbranch, srcsubdir1, srcsubdir2, config.workspace_path, tinfoil, rd, license_diff, new_licenses)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600552 except bb.process.CmdError as e:
553 _upgrade_error(e, rf, srctree)
554 except DevtoolError as e:
555 _upgrade_error(e, rf, srctree)
556 standard._add_md5(config, pn, os.path.dirname(rf))
557
558 af = _write_append(rf, srctree, args.same_dir, args.no_same_dir, rev2,
559 copied, config.workspace_path, rd)
560 standard._add_md5(config, pn, af)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500561
Brad Bishop316dfdd2018-06-25 12:45:53 -0400562 update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500563
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600564 logger.info('Upgraded source extracted to %s' % srctree)
565 logger.info('New recipe is %s' % rf)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400566 if license_diff:
567 logger.info('License checksums have been updated in the new recipe; please refer to it for the difference between the old and the new license texts.')
568 finally:
569 tinfoil.shutdown()
570 return 0
571
572def latest_version(args, config, basepath, workspace):
573 """Entry point for the devtool 'latest_version' subcommand"""
574 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
575 try:
576 rd = parse_recipe(config, tinfoil, args.recipename, True)
577 if not rd:
578 return 1
579 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
580 # "new-commits-available" is an indication that upstream never issues version tags
581 if not version_info['version'].endswith("new-commits-available"):
582 logger.info("Current version: {}".format(version_info['current_version']))
583 logger.info("Latest version: {}".format(version_info['version']))
584 if version_info['revision']:
585 logger.info("Latest version's commit: {}".format(version_info['revision']))
586 else:
587 logger.info("Latest commit: {}".format(version_info['revision']))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600588 finally:
589 tinfoil.shutdown()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500590 return 0
591
Brad Bishop19323692019-04-05 15:28:33 -0400592def check_upgrade_status(args, config, basepath, workspace):
593 if not args.recipe:
594 logger.info("Checking the upstream status for all recipes may take a few minutes")
595 results = oe.recipeutils.get_recipe_upgrade_status(args.recipe)
596 for result in results:
597 # pn, update_status, current, latest, maintainer, latest_commit, no_update_reason
598 if args.all or result[1] != 'MATCH':
599 logger.info("{:25} {:15} {:15} {} {} {}".format( result[0],
600 result[2],
601 result[1] if result[1] != 'UPDATE' else (result[3] if not result[3].endswith("new-commits-available") else "new commits"),
602 result[4],
603 result[5] if result[5] != 'N/A' else "",
604 "cannot be updated due to: %s" %(result[6]) if result[6] else ""))
605
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500606def register_commands(subparsers, context):
607 """Register devtool subcommands from this plugin"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500608
609 defsrctree = standard.get_default_srctree(context.config)
610
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500611 parser_upgrade = subparsers.add_parser('upgrade', help='Upgrade an existing recipe',
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500612 description='Upgrades an existing recipe to a new upstream version. Puts the upgraded recipe file into the workspace along with any associated files, and extracts the source tree to a specified location (in case patches need rebasing or adding to as a result of the upgrade).',
613 group='starting')
614 parser_upgrade.add_argument('recipename', help='Name of recipe to upgrade (just name - no version, path or extension)')
615 parser_upgrade.add_argument('srctree', nargs='?', help='Path to where to extract the source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400616 parser_upgrade.add_argument('--version', '-V', help='Version to upgrade to (PV). If omitted, latest upstream version will be determined and used, if possible.')
617 parser_upgrade.add_argument('--srcrev', '-S', help='Source revision to upgrade to (useful when fetching from an SCM such as git)')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500618 parser_upgrade.add_argument('--srcbranch', '-B', help='Branch in source repository containing the revision to use (if fetching from an SCM such as git)')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500619 parser_upgrade.add_argument('--branch', '-b', default="devtool", help='Name for new development branch to checkout (default "%(default)s")')
620 parser_upgrade.add_argument('--no-patch', action="store_true", help='Do not apply patches from the recipe to the new source code')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400621 parser_upgrade.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500622 group = parser_upgrade.add_mutually_exclusive_group()
623 group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
624 group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
625 parser_upgrade.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500626 parser_upgrade.set_defaults(func=upgrade, fixed_setup=context.fixed_setup)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400627
628 parser_latest_version = subparsers.add_parser('latest-version', help='Report the latest version of an existing recipe',
629 description='Queries the upstream server for what the latest upstream release is (for git, tags are checked, for tarballs, a list of them is obtained, and one with the highest version number is reported)',
630 group='info')
631 parser_latest_version.add_argument('recipename', help='Name of recipe to query (just name - no version, path or extension)')
632 parser_latest_version.set_defaults(func=latest_version)
Brad Bishop19323692019-04-05 15:28:33 -0400633
634 parser_check_upgrade_status = subparsers.add_parser('check-upgrade-status', help="Report upgradability for multiple (or all) recipes",
635 description="Prints a table of recipes together with versions currently provided by recipes, and latest upstream versions, when there is a later version available",
636 group='info')
637 parser_check_upgrade_status.add_argument('recipe', help='Name of the recipe to report (omit to report upgrade info for all recipes)', nargs='*')
638 parser_check_upgrade_status.add_argument('--all', '-a', help='Show all recipes, not just recipes needing upgrade', action="store_true")
639 parser_check_upgrade_status.set_defaults(func=check_upgrade_status)