blob: 39a1910a494c7a02819ff590d64cadc35a58d0a6 [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
Brad Bishop6dbb3162019-11-25 09:41:34 -050035 dirs = scriptutils.filter_src_subdirs(tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050036 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:
Andrew Geisslerc926e172021-05-07 16:11:35 -050074 bb.utils.rename(os.path.join(path, oldfile),
75 os.path.join(path, newfile))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050076
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050077def _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path):
78 oldrecipe = os.path.basename(oldrecipe)
79 if oldrecipe.endswith('_%s.bb' % oldpv):
80 newrecipe = '%s_%s.bb' % (bpn, newpv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050081 if oldrecipe != newrecipe:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050082 shutil.move(os.path.join(path, oldrecipe), os.path.join(path, newrecipe))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050083 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050084 newrecipe = oldrecipe
Patrick Williamsc124f4f2015-09-15 14:41:29 -050085 return os.path.join(path, newrecipe)
86
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050087def _rename_recipe_files(oldrecipe, bpn, oldpv, newpv, path):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050088 _rename_recipe_dirs(oldpv, newpv, path)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050089 return _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050090
Patrick Williamsc0f7c042017-02-23 20:41:17 -060091def _write_append(rc, srctree, same_dir, no_same_dir, rev, copied, workspace, d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050092 """Writes an append file"""
93 if not os.path.exists(rc):
94 raise DevtoolError("bbappend not created because %s does not exist" % rc)
95
96 appendpath = os.path.join(workspace, 'appends')
97 if not os.path.exists(appendpath):
98 bb.utils.mkdirhier(appendpath)
99
100 brf = os.path.basename(os.path.splitext(rc)[0]) # rc basename
101
102 srctree = os.path.abspath(srctree)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500103 pn = d.getVar('PN')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500104 af = os.path.join(appendpath, '%s.bbappend' % brf)
105 with open(af, 'w') as f:
Patrick Williams213cb262021-08-07 19:21:33 -0500106 f.write('FILESEXTRAPATHS:prepend := "${THISDIR}/${PN}:"\n\n')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500107 f.write('inherit externalsrc\n')
108 f.write(('# NOTE: We use pn- overrides here to avoid affecting'
109 'multiple variants in the case where the recipe uses BBCLASSEXTEND\n'))
Patrick Williams213cb262021-08-07 19:21:33 -0500110 f.write('EXTERNALSRC:pn-%s = "%s"\n' % (pn, srctree))
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500111 b_is_s = use_external_build(same_dir, no_same_dir, d)
112 if b_is_s:
Patrick Williams213cb262021-08-07 19:21:33 -0500113 f.write('EXTERNALSRC_BUILD:pn-%s = "%s"\n' % (pn, srctree))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600114 f.write('\n')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500115 if rev:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600116 f.write('# initial_rev: %s\n' % rev)
117 if copied:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500118 f.write('# original_path: %s\n' % os.path.dirname(d.getVar('FILE')))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600119 f.write('# original_files: %s\n' % ' '.join(copied))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500120 return af
121
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500122def _cleanup_on_error(rd, srctree):
123 rdp = os.path.split(rd)[0] # recipes folder
124 if os.path.exists(rd):
125 shutil.rmtree(rd)
126 if not len(os.listdir(rdp)):
127 os.rmdir(rdp)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500128 srctree = os.path.abspath(srctree)
129 if os.path.exists(srctree):
130 shutil.rmtree(srctree)
131
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500132def _upgrade_error(e, rd, srctree, keep_failure=False, extramsg=None):
133 if not keep_failure:
134 _cleanup_on_error(rd, srctree)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500135 logger.error(e)
Brad Bishop96ff1982019-08-19 13:50:42 -0400136 if extramsg:
137 logger.error(extramsg)
138 if keep_failure:
139 logger.info('Preserving failed upgrade files (--keep-failure)')
140 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500141
142def _get_uri(rd):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500143 srcuris = rd.getVar('SRC_URI').split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500144 if not len(srcuris):
145 raise DevtoolError('SRC_URI not found on recipe')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500146 # Get first non-local entry in SRC_URI - usually by convention it's
147 # the first entry, but not always!
148 srcuri = None
149 for entry in srcuris:
150 if not entry.startswith('file://'):
151 srcuri = entry
152 break
153 if not srcuri:
154 raise DevtoolError('Unable to find non-local entry in SRC_URI')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500155 srcrev = '${AUTOREV}'
156 if '://' in srcuri:
157 # Fetch a URL
158 rev_re = re.compile(';rev=([^;]+)')
159 res = rev_re.search(srcuri)
160 if res:
161 srcrev = res.group(1)
162 srcuri = rev_re.sub('', srcuri)
163 return srcuri, srcrev
164
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500165def _extract_new_source(newpv, srctree, no_patch, srcrev, srcbranch, branch, keep_temp, tinfoil, rd):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500166 """Extract sources of a recipe with a new version"""
167
168 def __run(cmd):
169 """Simple wrapper which calls _run with srctree as cwd"""
170 return _run(cmd, srctree)
171
172 crd = rd.createCopy()
173
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500174 pv = crd.getVar('PV')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500175 crd.setVar('PV', newpv)
176
177 tmpsrctree = None
178 uri, rev = _get_uri(crd)
179 if srcrev:
180 rev = srcrev
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600181 if uri.startswith('git://') or uri.startswith('gitsm://'):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500182 __run('git fetch')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500183 __run('git checkout %s' % rev)
184 __run('git tag -f devtool-base-new')
185 md5 = None
186 sha256 = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400187 _, _, _, _, _, params = bb.fetch2.decodeurl(uri)
188 srcsubdir_rel = params.get('destsuffix', 'git')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500189 if not srcbranch:
190 check_branch, check_branch_err = __run('git branch -r --contains %s' % srcrev)
191 get_branch = [x.strip() for x in check_branch.splitlines()]
192 # Remove HEAD reference point and drop remote prefix
193 get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000194 if len(get_branch) == 1:
195 # If srcrev is on only ONE branch, then use that branch
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500196 srcbranch = get_branch[0]
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000197 elif 'main' in get_branch:
198 # If srcrev is on multiple branches, then choose 'main' if it is one of them
199 srcbranch = 'main'
200 elif 'master' in get_branch:
201 # Otherwise choose 'master' if it is one of the branches
202 srcbranch = 'master'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500203 else:
204 # If get_branch contains more than one objects, then display error and exit.
205 mbrch = '\n ' + '\n '.join(get_branch)
206 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 -0500207 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500208 __run('git checkout devtool-base -b devtool-%s' % newpv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500209
210 tmpdir = tempfile.mkdtemp(prefix='devtool')
211 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500212 checksums, ftmpdir = scriptutils.fetch_url(tinfoil, uri, rev, tmpdir, logger, preserve_tmp=keep_temp)
213 except scriptutils.FetchUrlFailure as e:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500214 raise DevtoolError(e)
215
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500216 if ftmpdir and keep_temp:
217 logger.info('Fetch temp directory is %s' % ftmpdir)
218
219 md5 = checksums['md5sum']
220 sha256 = checksums['sha256sum']
221
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500222 tmpsrctree = _get_srctree(tmpdir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500223 srctree = os.path.abspath(srctree)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400224 srcsubdir_rel = os.path.relpath(tmpsrctree, tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500225
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500226 # Delete all sources so we ensure no stray files are left over
227 for item in os.listdir(srctree):
228 if item in ['.git', 'oe-local-files']:
229 continue
230 itempath = os.path.join(srctree, item)
231 if os.path.isdir(itempath):
232 shutil.rmtree(itempath)
233 else:
234 os.remove(itempath)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500235
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500236 # Copy in new ones
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500237 _copy_source_code(tmpsrctree, srctree)
238
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500239 (stdout,_) = __run('git ls-files --modified --others')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400240 filelist = stdout.splitlines()
241 pbar = bb.ui.knotty.BBProgress('Adding changed files', len(filelist))
242 pbar.start()
243 batchsize = 100
244 for i in range(0, len(filelist), batchsize):
245 batch = filelist[i:i+batchsize]
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500246 __run('git add -f -A %s' % ' '.join(['"%s"' % item for item in batch]))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400247 pbar.update(i)
248 pbar.finish()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500249
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600250 useroptions = []
251 oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=rd)
252 __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 -0500253 __run('git tag -f devtool-base-%s' % newpv)
254
255 (stdout, _) = __run('git rev-parse HEAD')
256 rev = stdout.rstrip()
257
258 if no_patch:
259 patches = oe.recipeutils.get_recipe_patches(crd)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400260 if patches:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800261 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 -0500262 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600263 __run('git checkout devtool-patched -b %s' % branch)
Andrew Geissler5f350902021-07-23 13:09:54 -0400264 (stdout, _) = __run('git branch --list devtool-override-*')
265 branches_to_rebase = [branch] + stdout.split()
266 for b in branches_to_rebase:
267 logger.info("Rebasing {} onto {}".format(b, rev))
268 __run('git checkout %s' % b)
269 try:
270 __run('git rebase %s' % rev)
271 except bb.process.ExecutionError as e:
272 if 'conflict' in e.stdout:
273 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()))
274 __run('git rebase --abort')
275 else:
276 logger.warning('Command \'%s\' failed:\n%s' % (e.command, e.stdout))
277 __run('git checkout %s' % branch)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500278
279 if tmpsrctree:
280 if keep_temp:
281 logger.info('Preserving temporary directory %s' % tmpsrctree)
282 else:
283 shutil.rmtree(tmpsrctree)
Brad Bishop6dbb3162019-11-25 09:41:34 -0500284 if tmpdir != tmpsrctree:
285 shutil.rmtree(tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500286
Brad Bishop316dfdd2018-06-25 12:45:53 -0400287 return (rev, md5, sha256, srcbranch, srcsubdir_rel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500288
Brad Bishop316dfdd2018-06-25 12:45:53 -0400289def _add_license_diff_to_recipe(path, diff):
290 notice_text = """# FIXME: the LIC_FILES_CHKSUM values have been updated by 'devtool upgrade'.
291# The following is the difference between the old and the new license text.
292# Please update the LICENSE value if needed, and summarize the changes in
293# the commit message via 'License-Update:' tag.
294# (example: 'License-Update: copyright years updated.')
295#
296# The changes:
297#
298"""
299 commented_diff = "\n".join(["# {}".format(l) for l in diff.split('\n')])
300 with open(path, 'rb') as f:
301 orig_content = f.read()
302 with open(path, 'wb') as f:
303 f.write(notice_text.encode())
304 f.write(commented_diff.encode())
305 f.write("\n#\n\n".encode())
306 f.write(orig_content)
307
Brad Bishop96ff1982019-08-19 13:50:42 -0400308def _create_new_recipe(newpv, md5, sha256, srcrev, srcbranch, srcsubdir_old, srcsubdir_new, workspace, tinfoil, rd, license_diff, new_licenses, srctree, keep_failure):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500309 """Creates the new recipe under workspace"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500310
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500311 bpn = rd.getVar('BPN')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500312 path = os.path.join(workspace, 'recipes', bpn)
313 bb.utils.mkdirhier(path)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500314 copied, _ = oe.recipeutils.copy_recipe_files(rd, path, all_variants=True)
315 if not copied:
316 raise DevtoolError('Internal error - no files were copied for recipe %s' % bpn)
317 logger.debug('Copied %s to %s' % (copied, path))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500318
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500319 oldpv = rd.getVar('PV')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500320 if not newpv:
321 newpv = oldpv
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500322 origpath = rd.getVar('FILE')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500323 fullpath = _rename_recipe_files(origpath, bpn, oldpv, newpv, path)
324 logger.debug('Upgraded %s => %s' % (origpath, fullpath))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500325
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500326 newvalues = {}
327 if _recipe_contains(rd, 'PV') and newpv != oldpv:
328 newvalues['PV'] = newpv
329
330 if srcrev:
331 newvalues['SRCREV'] = srcrev
332
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500333 if srcbranch:
334 src_uri = oe.recipeutils.split_var_value(rd.getVar('SRC_URI', False) or '')
335 changed = False
336 replacing = True
337 new_src_uri = []
338 for entry in src_uri:
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500339 try:
340 scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(entry)
341 except bb.fetch2.MalformedUrl as e:
342 raise DevtoolError("Could not decode SRC_URI: {}".format(e))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500343 if replacing and scheme in ['git', 'gitsm']:
344 branch = params.get('branch', 'master')
345 if rd.expand(branch) != srcbranch:
346 # Handle case where branch is set through a variable
347 res = re.match(r'\$\{([^}@]+)\}', branch)
348 if res:
349 newvalues[res.group(1)] = srcbranch
350 # We know we won't change SRC_URI now, so break out
351 break
352 else:
353 params['branch'] = srcbranch
354 entry = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
355 changed = True
356 replacing = False
357 new_src_uri.append(entry)
358 if changed:
359 newvalues['SRC_URI'] = ' '.join(new_src_uri)
360
361 newvalues['PR'] = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500362
Brad Bishop316dfdd2018-06-25 12:45:53 -0400363 # Work out which SRC_URI entries have changed in case the entry uses a name
364 crd = rd.createCopy()
365 crd.setVar('PV', newpv)
366 for var, value in newvalues.items():
367 crd.setVar(var, value)
368 old_src_uri = (rd.getVar('SRC_URI') or '').split()
369 new_src_uri = (crd.getVar('SRC_URI') or '').split()
370 newnames = []
371 addnames = []
372 for newentry in new_src_uri:
373 _, _, _, _, _, params = bb.fetch2.decodeurl(newentry)
374 if 'name' in params:
375 newnames.append(params['name'])
376 if newentry not in old_src_uri:
377 addnames.append(params['name'])
378 # Find what's been set in the original recipe
379 oldnames = []
380 noname = False
381 for varflag in rd.getVarFlags('SRC_URI'):
382 if varflag.endswith(('.md5sum', '.sha256sum')):
383 name = varflag.rsplit('.', 1)[0]
384 if name not in oldnames:
385 oldnames.append(name)
386 elif varflag in ['md5sum', 'sha256sum']:
387 noname = True
388 # Even if SRC_URI has named entries it doesn't have to actually use the name
389 if noname and addnames and addnames[0] not in oldnames:
390 addnames = []
391 # Drop any old names (the name actually might include ${PV})
392 for name in oldnames:
393 if name not in newnames:
394 newvalues['SRC_URI[%s.md5sum]' % name] = None
395 newvalues['SRC_URI[%s.sha256sum]' % name] = None
396
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500397 if sha256:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400398 if addnames:
399 nameprefix = '%s.' % addnames[0]
400 else:
401 nameprefix = ''
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500402 newvalues['SRC_URI[%smd5sum]' % nameprefix] = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400403 newvalues['SRC_URI[%ssha256sum]' % nameprefix] = sha256
404
405 if srcsubdir_new != srcsubdir_old:
406 s_subdir_old = os.path.relpath(os.path.abspath(rd.getVar('S')), rd.getVar('WORKDIR'))
407 s_subdir_new = os.path.relpath(os.path.abspath(crd.getVar('S')), crd.getVar('WORKDIR'))
408 if srcsubdir_old == s_subdir_old and srcsubdir_new != s_subdir_new:
409 # Subdir for old extracted source matches what S points to (it should!)
410 # but subdir for new extracted source doesn't match what S will be
411 newvalues['S'] = '${WORKDIR}/%s' % srcsubdir_new.replace(newpv, '${PV}')
412 if crd.expand(newvalues['S']) == crd.expand('${WORKDIR}/${BP}'):
413 # It's the default, drop it
414 # FIXME what if S is being set in a .inc?
415 newvalues['S'] = None
416 logger.info('Source subdirectory has changed, dropping S value since it now matches the default ("${WORKDIR}/${BP}")')
417 else:
418 logger.info('Source subdirectory has changed, updating S value')
419
420 if license_diff:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800421 newlicchksum = " ".join(["file://{}".format(l['path']) +
422 (";beginline={}".format(l['beginline']) if l['beginline'] else "") +
423 (";endline={}".format(l['endline']) if l['endline'] else "") +
424 (";md5={}".format(l['actual_md5'])) for l in new_licenses])
Brad Bishop316dfdd2018-06-25 12:45:53 -0400425 newvalues["LIC_FILES_CHKSUM"] = newlicchksum
426 _add_license_diff_to_recipe(fullpath, license_diff)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500427
Brad Bishop96ff1982019-08-19 13:50:42 -0400428 try:
429 rd = tinfoil.parse_recipe_file(fullpath, False)
430 except bb.tinfoil.TinfoilCommandFailed as e:
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500431 _upgrade_error(e, os.path.dirname(fullpath), srctree, keep_failure, 'Parsing of upgraded recipe failed')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500432 oe.recipeutils.patch_recipe(rd, fullpath, newvalues)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500433
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600434 return fullpath, copied
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500435
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500436
437def _check_git_config():
438 def getconfig(name):
439 try:
440 value = bb.process.run('git config --global %s' % name)[0].strip()
441 except bb.process.ExecutionError as e:
442 if e.exitcode == 1:
443 value = None
444 else:
445 raise
446 return value
447
448 username = getconfig('user.name')
449 useremail = getconfig('user.email')
450 configerr = []
451 if not username:
452 configerr.append('Please set your name using:\n git config --global user.name')
453 if not useremail:
454 configerr.append('Please set your email using:\n git config --global user.email')
455 if configerr:
456 raise DevtoolError('Your git configuration is incomplete which will prevent rebases from working:\n' + '\n'.join(configerr))
457
Brad Bishop316dfdd2018-06-25 12:45:53 -0400458def _extract_licenses(srcpath, recipe_licenses):
459 licenses = []
460 for url in recipe_licenses.split():
461 license = {}
462 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
463 license['path'] = path
464 license['md5'] = parm.get('md5', '')
465 license['beginline'], license['endline'] = 0, 0
466 if 'beginline' in parm:
467 license['beginline'] = int(parm['beginline'])
468 if 'endline' in parm:
469 license['endline'] = int(parm['endline'])
470 license['text'] = []
471 with open(os.path.join(srcpath, path), 'rb') as f:
472 import hashlib
473 actual_md5 = hashlib.md5()
474 lineno = 0
475 for line in f:
476 lineno += 1
477 if (lineno >= license['beginline']) and ((lineno <= license['endline']) or not license['endline']):
478 license['text'].append(line.decode(errors='ignore'))
479 actual_md5.update(line)
480 license['actual_md5'] = actual_md5.hexdigest()
481 licenses.append(license)
482 return licenses
483
484def _generate_license_diff(old_licenses, new_licenses):
485 need_diff = False
486 for l in new_licenses:
487 if l['md5'] != l['actual_md5']:
488 need_diff = True
489 break
490 if need_diff == False:
491 return None
492
493 import difflib
494 diff = ''
495 for old, new in zip(old_licenses, new_licenses):
496 for line in difflib.unified_diff(old['text'], new['text'], old['path'], new['path']):
497 diff = diff + line
498 return diff
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500499
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500500def upgrade(args, config, basepath, workspace):
501 """Entry point for the devtool 'upgrade' subcommand"""
502
503 if args.recipename in workspace:
504 raise DevtoolError("recipe %s is already in your workspace" % args.recipename)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500505 if args.srcbranch and not args.srcrev:
506 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 -0500507
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500508 _check_git_config()
509
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500510 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500511 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600512 rd = parse_recipe(config, tinfoil, args.recipename, True)
513 if not rd:
514 return 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500515
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500516 pn = rd.getVar('PN')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600517 if pn != args.recipename:
518 logger.info('Mapping %s to %s' % (args.recipename, pn))
519 if pn in workspace:
520 raise DevtoolError("recipe %s is already in your workspace" % pn)
521
522 if args.srctree:
523 srctree = os.path.abspath(args.srctree)
524 else:
525 srctree = standard.get_default_srctree(config, pn)
526
Andrew Geissler5f350902021-07-23 13:09:54 -0400527 # Check that recipe isn't using a shared workdir
528 s = os.path.abspath(rd.getVar('S'))
529 workdir = os.path.abspath(rd.getVar('WORKDIR'))
530 srctree_s = srctree
531 if s.startswith(workdir) and s != workdir and os.path.dirname(s) != workdir:
532 # Handle if S is set to a subdirectory of the source
533 srcsubdir = os.path.relpath(s, workdir).split(os.sep, 1)[1]
534 srctree_s = os.path.join(srctree, srcsubdir)
535
Brad Bishop316dfdd2018-06-25 12:45:53 -0400536 # try to automatically discover latest version and revision if not provided on command line
537 if not args.version and not args.srcrev:
538 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
539 if version_info['version'] and not version_info['version'].endswith("new-commits-available"):
540 args.version = version_info['version']
541 if version_info['revision']:
542 args.srcrev = version_info['revision']
543 if not args.version and not args.srcrev:
544 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.")
545
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600546 standard._check_compatible_recipe(pn, rd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500547 old_srcrev = rd.getVar('SRCREV')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600548 if old_srcrev == 'INVALID':
549 old_srcrev = None
550 if old_srcrev and not args.srcrev:
551 raise DevtoolError("Recipe specifies a SRCREV value; you must specify a new one when upgrading")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400552 old_ver = rd.getVar('PV')
553 if old_ver == args.version and old_srcrev == args.srcrev:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600554 raise DevtoolError("Current and upgrade versions are the same version")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400555 if args.version:
556 if bb.utils.vercmp_string(args.version, old_ver) < 0:
557 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))
558 check_prerelease_version(args.version, 'devtool upgrade')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600559
560 rf = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400561 license_diff = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600562 try:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400563 logger.info('Extracting current version source...')
564 rev1, srcsubdir1 = standard._extract_source(srctree, False, 'devtool-orig', False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
Andrew Geissler5f350902021-07-23 13:09:54 -0400565 old_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400566 logger.info('Extracting upgraded version source...')
567 rev2, md5, sha256, srcbranch, srcsubdir2 = _extract_new_source(args.version, srctree, args.no_patch,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500568 args.srcrev, args.srcbranch, args.branch, args.keep_temp,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600569 tinfoil, rd)
Andrew Geissler5f350902021-07-23 13:09:54 -0400570 new_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400571 license_diff = _generate_license_diff(old_licenses, new_licenses)
Brad Bishop96ff1982019-08-19 13:50:42 -0400572 rf, copied = _create_new_recipe(args.version, md5, sha256, args.srcrev, srcbranch, srcsubdir1, srcsubdir2, config.workspace_path, tinfoil, rd, license_diff, new_licenses, srctree, args.keep_failure)
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500573 except (bb.process.CmdError, DevtoolError) as e:
574 recipedir = os.path.join(config.workspace_path, 'recipes', rd.getVar('BPN'))
575 _upgrade_error(e, recipedir, srctree, args.keep_failure)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600576 standard._add_md5(config, pn, os.path.dirname(rf))
577
Andrew Geissler5f350902021-07-23 13:09:54 -0400578 af = _write_append(rf, srctree_s, args.same_dir, args.no_same_dir, rev2,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600579 copied, config.workspace_path, rd)
580 standard._add_md5(config, pn, af)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500581
Brad Bishop316dfdd2018-06-25 12:45:53 -0400582 update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500583
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600584 logger.info('Upgraded source extracted to %s' % srctree)
585 logger.info('New recipe is %s' % rf)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400586 if license_diff:
587 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.')
Patrick Williams213cb262021-08-07 19:21:33 -0500588 preferred_version = rd.getVar('PREFERRED_VERSION_%s' % rd.getVar('PN'))
589 if preferred_version:
590 logger.warning('Version is pinned to %s via PREFERRED_VERSION; it may need adjustment to match the new version before any further steps are taken' % preferred_version)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400591 finally:
592 tinfoil.shutdown()
593 return 0
594
595def latest_version(args, config, basepath, workspace):
596 """Entry point for the devtool 'latest_version' subcommand"""
597 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
598 try:
599 rd = parse_recipe(config, tinfoil, args.recipename, True)
600 if not rd:
601 return 1
602 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
603 # "new-commits-available" is an indication that upstream never issues version tags
604 if not version_info['version'].endswith("new-commits-available"):
605 logger.info("Current version: {}".format(version_info['current_version']))
606 logger.info("Latest version: {}".format(version_info['version']))
607 if version_info['revision']:
608 logger.info("Latest version's commit: {}".format(version_info['revision']))
609 else:
610 logger.info("Latest commit: {}".format(version_info['revision']))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600611 finally:
612 tinfoil.shutdown()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500613 return 0
614
Brad Bishop19323692019-04-05 15:28:33 -0400615def check_upgrade_status(args, config, basepath, workspace):
616 if not args.recipe:
617 logger.info("Checking the upstream status for all recipes may take a few minutes")
618 results = oe.recipeutils.get_recipe_upgrade_status(args.recipe)
619 for result in results:
620 # pn, update_status, current, latest, maintainer, latest_commit, no_update_reason
621 if args.all or result[1] != 'MATCH':
622 logger.info("{:25} {:15} {:15} {} {} {}".format( result[0],
623 result[2],
624 result[1] if result[1] != 'UPDATE' else (result[3] if not result[3].endswith("new-commits-available") else "new commits"),
625 result[4],
626 result[5] if result[5] != 'N/A' else "",
627 "cannot be updated due to: %s" %(result[6]) if result[6] else ""))
628
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500629def register_commands(subparsers, context):
630 """Register devtool subcommands from this plugin"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500631
632 defsrctree = standard.get_default_srctree(context.config)
633
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500634 parser_upgrade = subparsers.add_parser('upgrade', help='Upgrade an existing recipe',
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500635 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).',
636 group='starting')
637 parser_upgrade.add_argument('recipename', help='Name of recipe to upgrade (just name - no version, path or extension)')
638 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 -0400639 parser_upgrade.add_argument('--version', '-V', help='Version to upgrade to (PV). If omitted, latest upstream version will be determined and used, if possible.')
640 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 -0500641 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 -0500642 parser_upgrade.add_argument('--branch', '-b', default="devtool", help='Name for new development branch to checkout (default "%(default)s")')
643 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 -0400644 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 -0500645 group = parser_upgrade.add_mutually_exclusive_group()
646 group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
647 group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
648 parser_upgrade.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
Brad Bishop96ff1982019-08-19 13:50:42 -0400649 parser_upgrade.add_argument('--keep-failure', action="store_true", help='Keep failed upgrade recipe and associated files (for debugging)')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500650 parser_upgrade.set_defaults(func=upgrade, fixed_setup=context.fixed_setup)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400651
652 parser_latest_version = subparsers.add_parser('latest-version', help='Report the latest version of an existing recipe',
653 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)',
654 group='info')
655 parser_latest_version.add_argument('recipename', help='Name of recipe to query (just name - no version, path or extension)')
656 parser_latest_version.set_defaults(func=latest_version)
Brad Bishop19323692019-04-05 15:28:33 -0400657
658 parser_check_upgrade_status = subparsers.add_parser('check-upgrade-status', help="Report upgradability for multiple (or all) recipes",
659 description="Prints a table of recipes together with versions currently provided by recipes, and latest upstream versions, when there is a later version available",
660 group='info')
661 parser_check_upgrade_status.add_argument('recipe', help='Name of the recipe to report (omit to report upgrade info for all recipes)', nargs='*')
662 parser_check_upgrade_status.add_argument('--all', '-a', help='Show all recipes, not just recipes needing upgrade', action="store_true")
663 parser_check_upgrade_status.set_defaults(func=check_upgrade_status)