blob: 9cd50be3a25ec534c7275a256c4498380b060cf1 [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])
Patrick Williams2a254922023-08-11 09:48:11 -050038 else:
39 raise DevtoolError("Cannot determine where the source tree is after unpacking in {}: {}".format(tmpdir,dirs))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050040 return srctree
41
42def _copy_source_code(orig, dest):
43 for path in standard._ls_tree(orig):
44 dest_dir = os.path.join(dest, os.path.dirname(path))
45 bb.utils.mkdirhier(dest_dir)
46 dest_path = os.path.join(dest, path)
Patrick Williamsf1e5d692016-03-30 15:21:19 -050047 shutil.move(os.path.join(orig, path), dest_path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048
Patrick Williamsc124f4f2015-09-15 14:41:29 -050049def _remove_patch_dirs(recipefolder):
50 for root, dirs, files in os.walk(recipefolder):
51 for d in dirs:
52 shutil.rmtree(os.path.join(root,d))
53
Patrick Williamsf1e5d692016-03-30 15:21:19 -050054def _recipe_contains(rd, var):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050055 rf = rd.getVar('FILE')
Patrick Williamsf1e5d692016-03-30 15:21:19 -050056 varfiles = oe.recipeutils.get_var_files(rf, [var], rd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060057 for var, fn in varfiles.items():
Patrick Williamsf1e5d692016-03-30 15:21:19 -050058 if fn and fn.startswith(os.path.dirname(rf) + os.sep):
59 return True
60 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050061
62def _rename_recipe_dirs(oldpv, newpv, path):
63 for root, dirs, files in os.walk(path):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060064 # Rename directories with the version in their name
Patrick Williamsc124f4f2015-09-15 14:41:29 -050065 for olddir in dirs:
66 if olddir.find(oldpv) != -1:
67 newdir = olddir.replace(oldpv, newpv)
68 if olddir != newdir:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050069 shutil.move(os.path.join(path, olddir), os.path.join(path, newdir))
Patrick Williamsc0f7c042017-02-23 20:41:17 -060070 # Rename any inc files with the version in their name (unusual, but possible)
71 for oldfile in files:
72 if oldfile.endswith('.inc'):
73 if oldfile.find(oldpv) != -1:
74 newfile = oldfile.replace(oldpv, newpv)
75 if oldfile != newfile:
Andrew Geisslerc926e172021-05-07 16:11:35 -050076 bb.utils.rename(os.path.join(path, oldfile),
77 os.path.join(path, newfile))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050078
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050079def _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path):
80 oldrecipe = os.path.basename(oldrecipe)
81 if oldrecipe.endswith('_%s.bb' % oldpv):
82 newrecipe = '%s_%s.bb' % (bpn, newpv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050083 if oldrecipe != newrecipe:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050084 shutil.move(os.path.join(path, oldrecipe), os.path.join(path, newrecipe))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050085 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050086 newrecipe = oldrecipe
Patrick Williamsc124f4f2015-09-15 14:41:29 -050087 return os.path.join(path, newrecipe)
88
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050089def _rename_recipe_files(oldrecipe, bpn, oldpv, newpv, path):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050090 _rename_recipe_dirs(oldpv, newpv, path)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050091 return _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050092
Andrew Geissler517393d2023-01-13 08:55:19 -060093def _write_append(rc, srctreebase, srctree, same_dir, no_same_dir, rev, copied, workspace, d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050094 """Writes an append file"""
95 if not os.path.exists(rc):
96 raise DevtoolError("bbappend not created because %s does not exist" % rc)
97
98 appendpath = os.path.join(workspace, 'appends')
99 if not os.path.exists(appendpath):
100 bb.utils.mkdirhier(appendpath)
101
102 brf = os.path.basename(os.path.splitext(rc)[0]) # rc basename
103
104 srctree = os.path.abspath(srctree)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500105 pn = d.getVar('PN')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500106 af = os.path.join(appendpath, '%s.bbappend' % brf)
107 with open(af, 'w') as f:
Patrick Williams213cb262021-08-07 19:21:33 -0500108 f.write('FILESEXTRAPATHS:prepend := "${THISDIR}/${PN}:"\n\n')
Andrew Geissler517393d2023-01-13 08:55:19 -0600109 # Local files can be modified/tracked in separate subdir under srctree
110 # Mostly useful for packages with S != WORKDIR
111 f.write('FILESPATH:prepend := "%s:"\n' %
112 os.path.join(srctreebase, 'oe-local-files'))
113 f.write('# srctreebase: %s\n' % srctreebase)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114 f.write('inherit externalsrc\n')
115 f.write(('# NOTE: We use pn- overrides here to avoid affecting'
116 'multiple variants in the case where the recipe uses BBCLASSEXTEND\n'))
Patrick Williams213cb262021-08-07 19:21:33 -0500117 f.write('EXTERNALSRC:pn-%s = "%s"\n' % (pn, srctree))
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500118 b_is_s = use_external_build(same_dir, no_same_dir, d)
119 if b_is_s:
Patrick Williams213cb262021-08-07 19:21:33 -0500120 f.write('EXTERNALSRC_BUILD:pn-%s = "%s"\n' % (pn, srctree))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600121 f.write('\n')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500122 if rev:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600123 f.write('# initial_rev: %s\n' % rev)
124 if copied:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500125 f.write('# original_path: %s\n' % os.path.dirname(d.getVar('FILE')))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600126 f.write('# original_files: %s\n' % ' '.join(copied))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500127 return af
128
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500129def _cleanup_on_error(rd, srctree):
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500130 if os.path.exists(rd):
131 shutil.rmtree(rd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500132 srctree = os.path.abspath(srctree)
133 if os.path.exists(srctree):
134 shutil.rmtree(srctree)
135
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500136def _upgrade_error(e, rd, srctree, keep_failure=False, extramsg=None):
137 if not keep_failure:
138 _cleanup_on_error(rd, srctree)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500139 logger.error(e)
Brad Bishop96ff1982019-08-19 13:50:42 -0400140 if extramsg:
141 logger.error(extramsg)
142 if keep_failure:
143 logger.info('Preserving failed upgrade files (--keep-failure)')
144 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500145
146def _get_uri(rd):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500147 srcuris = rd.getVar('SRC_URI').split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500148 if not len(srcuris):
149 raise DevtoolError('SRC_URI not found on recipe')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500150 # Get first non-local entry in SRC_URI - usually by convention it's
151 # the first entry, but not always!
152 srcuri = None
153 for entry in srcuris:
154 if not entry.startswith('file://'):
155 srcuri = entry
156 break
157 if not srcuri:
158 raise DevtoolError('Unable to find non-local entry in SRC_URI')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500159 srcrev = '${AUTOREV}'
160 if '://' in srcuri:
161 # Fetch a URL
162 rev_re = re.compile(';rev=([^;]+)')
163 res = rev_re.search(srcuri)
164 if res:
165 srcrev = res.group(1)
166 srcuri = rev_re.sub('', srcuri)
167 return srcuri, srcrev
168
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500169def _extract_new_source(newpv, srctree, no_patch, srcrev, srcbranch, branch, keep_temp, tinfoil, rd):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500170 """Extract sources of a recipe with a new version"""
171
172 def __run(cmd):
173 """Simple wrapper which calls _run with srctree as cwd"""
174 return _run(cmd, srctree)
175
176 crd = rd.createCopy()
177
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500178 pv = crd.getVar('PV')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500179 crd.setVar('PV', newpv)
180
181 tmpsrctree = None
182 uri, rev = _get_uri(crd)
183 if srcrev:
184 rev = srcrev
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600185 if uri.startswith('git://') or uri.startswith('gitsm://'):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500186 __run('git fetch')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500187 __run('git checkout %s' % rev)
188 __run('git tag -f devtool-base-new')
189 md5 = None
190 sha256 = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400191 _, _, _, _, _, params = bb.fetch2.decodeurl(uri)
192 srcsubdir_rel = params.get('destsuffix', 'git')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500193 if not srcbranch:
194 check_branch, check_branch_err = __run('git branch -r --contains %s' % srcrev)
195 get_branch = [x.strip() for x in check_branch.splitlines()]
196 # Remove HEAD reference point and drop remote prefix
197 get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000198 if len(get_branch) == 1:
199 # If srcrev is on only ONE branch, then use that branch
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500200 srcbranch = get_branch[0]
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000201 elif 'main' in get_branch:
202 # If srcrev is on multiple branches, then choose 'main' if it is one of them
203 srcbranch = 'main'
204 elif 'master' in get_branch:
205 # Otherwise choose 'master' if it is one of the branches
206 srcbranch = 'master'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500207 else:
208 # If get_branch contains more than one objects, then display error and exit.
209 mbrch = '\n ' + '\n '.join(get_branch)
210 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 -0500211 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500212 __run('git checkout devtool-base -b devtool-%s' % newpv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500213
214 tmpdir = tempfile.mkdtemp(prefix='devtool')
215 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500216 checksums, ftmpdir = scriptutils.fetch_url(tinfoil, uri, rev, tmpdir, logger, preserve_tmp=keep_temp)
217 except scriptutils.FetchUrlFailure as e:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500218 raise DevtoolError(e)
219
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500220 if ftmpdir and keep_temp:
221 logger.info('Fetch temp directory is %s' % ftmpdir)
222
223 md5 = checksums['md5sum']
224 sha256 = checksums['sha256sum']
225
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500226 tmpsrctree = _get_srctree(tmpdir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500227 srctree = os.path.abspath(srctree)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400228 srcsubdir_rel = os.path.relpath(tmpsrctree, tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500229
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500230 # Delete all sources so we ensure no stray files are left over
231 for item in os.listdir(srctree):
232 if item in ['.git', 'oe-local-files']:
233 continue
234 itempath = os.path.join(srctree, item)
235 if os.path.isdir(itempath):
236 shutil.rmtree(itempath)
237 else:
238 os.remove(itempath)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500239
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500240 # Copy in new ones
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500241 _copy_source_code(tmpsrctree, srctree)
242
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500243 (stdout,_) = __run('git ls-files --modified --others')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400244 filelist = stdout.splitlines()
245 pbar = bb.ui.knotty.BBProgress('Adding changed files', len(filelist))
246 pbar.start()
247 batchsize = 100
248 for i in range(0, len(filelist), batchsize):
249 batch = filelist[i:i+batchsize]
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500250 __run('git add -f -A %s' % ' '.join(['"%s"' % item for item in batch]))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400251 pbar.update(i)
252 pbar.finish()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500253
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600254 useroptions = []
255 oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=rd)
256 __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 -0500257 __run('git tag -f devtool-base-%s' % newpv)
258
259 (stdout, _) = __run('git rev-parse HEAD')
260 rev = stdout.rstrip()
261
262 if no_patch:
263 patches = oe.recipeutils.get_recipe_patches(crd)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400264 if patches:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800265 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 -0500266 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 __run('git checkout devtool-patched -b %s' % branch)
Andrew Geissler5f350902021-07-23 13:09:54 -0400268 (stdout, _) = __run('git branch --list devtool-override-*')
269 branches_to_rebase = [branch] + stdout.split()
270 for b in branches_to_rebase:
271 logger.info("Rebasing {} onto {}".format(b, rev))
272 __run('git checkout %s' % b)
273 try:
274 __run('git rebase %s' % rev)
275 except bb.process.ExecutionError as e:
276 if 'conflict' in e.stdout:
277 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()))
278 __run('git rebase --abort')
279 else:
280 logger.warning('Command \'%s\' failed:\n%s' % (e.command, e.stdout))
281 __run('git checkout %s' % branch)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500282
283 if tmpsrctree:
284 if keep_temp:
285 logger.info('Preserving temporary directory %s' % tmpsrctree)
286 else:
287 shutil.rmtree(tmpsrctree)
Brad Bishop6dbb3162019-11-25 09:41:34 -0500288 if tmpdir != tmpsrctree:
289 shutil.rmtree(tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500290
Brad Bishop316dfdd2018-06-25 12:45:53 -0400291 return (rev, md5, sha256, srcbranch, srcsubdir_rel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500292
Brad Bishop316dfdd2018-06-25 12:45:53 -0400293def _add_license_diff_to_recipe(path, diff):
294 notice_text = """# FIXME: the LIC_FILES_CHKSUM values have been updated by 'devtool upgrade'.
295# The following is the difference between the old and the new license text.
296# Please update the LICENSE value if needed, and summarize the changes in
297# the commit message via 'License-Update:' tag.
298# (example: 'License-Update: copyright years updated.')
299#
300# The changes:
301#
302"""
303 commented_diff = "\n".join(["# {}".format(l) for l in diff.split('\n')])
304 with open(path, 'rb') as f:
305 orig_content = f.read()
306 with open(path, 'wb') as f:
307 f.write(notice_text.encode())
308 f.write(commented_diff.encode())
309 f.write("\n#\n\n".encode())
310 f.write(orig_content)
311
Brad Bishop96ff1982019-08-19 13:50:42 -0400312def _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 -0500313 """Creates the new recipe under workspace"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500314
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500315 bpn = rd.getVar('BPN')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500316 path = os.path.join(workspace, 'recipes', bpn)
317 bb.utils.mkdirhier(path)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500318 copied, _ = oe.recipeutils.copy_recipe_files(rd, path, all_variants=True)
319 if not copied:
320 raise DevtoolError('Internal error - no files were copied for recipe %s' % bpn)
321 logger.debug('Copied %s to %s' % (copied, path))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500322
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500323 oldpv = rd.getVar('PV')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500324 if not newpv:
325 newpv = oldpv
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500326 origpath = rd.getVar('FILE')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500327 fullpath = _rename_recipe_files(origpath, bpn, oldpv, newpv, path)
328 logger.debug('Upgraded %s => %s' % (origpath, fullpath))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500329
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500330 newvalues = {}
331 if _recipe_contains(rd, 'PV') and newpv != oldpv:
332 newvalues['PV'] = newpv
333
334 if srcrev:
335 newvalues['SRCREV'] = srcrev
336
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500337 if srcbranch:
338 src_uri = oe.recipeutils.split_var_value(rd.getVar('SRC_URI', False) or '')
339 changed = False
340 replacing = True
341 new_src_uri = []
342 for entry in src_uri:
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500343 try:
344 scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(entry)
345 except bb.fetch2.MalformedUrl as e:
346 raise DevtoolError("Could not decode SRC_URI: {}".format(e))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500347 if replacing and scheme in ['git', 'gitsm']:
348 branch = params.get('branch', 'master')
349 if rd.expand(branch) != srcbranch:
350 # Handle case where branch is set through a variable
351 res = re.match(r'\$\{([^}@]+)\}', branch)
352 if res:
353 newvalues[res.group(1)] = srcbranch
354 # We know we won't change SRC_URI now, so break out
355 break
356 else:
357 params['branch'] = srcbranch
358 entry = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
359 changed = True
360 replacing = False
361 new_src_uri.append(entry)
362 if changed:
363 newvalues['SRC_URI'] = ' '.join(new_src_uri)
364
365 newvalues['PR'] = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500366
Brad Bishop316dfdd2018-06-25 12:45:53 -0400367 # Work out which SRC_URI entries have changed in case the entry uses a name
368 crd = rd.createCopy()
369 crd.setVar('PV', newpv)
370 for var, value in newvalues.items():
371 crd.setVar(var, value)
372 old_src_uri = (rd.getVar('SRC_URI') or '').split()
373 new_src_uri = (crd.getVar('SRC_URI') or '').split()
374 newnames = []
375 addnames = []
376 for newentry in new_src_uri:
377 _, _, _, _, _, params = bb.fetch2.decodeurl(newentry)
378 if 'name' in params:
379 newnames.append(params['name'])
380 if newentry not in old_src_uri:
381 addnames.append(params['name'])
382 # Find what's been set in the original recipe
383 oldnames = []
384 noname = False
385 for varflag in rd.getVarFlags('SRC_URI'):
386 if varflag.endswith(('.md5sum', '.sha256sum')):
387 name = varflag.rsplit('.', 1)[0]
388 if name not in oldnames:
389 oldnames.append(name)
390 elif varflag in ['md5sum', 'sha256sum']:
391 noname = True
392 # Even if SRC_URI has named entries it doesn't have to actually use the name
393 if noname and addnames and addnames[0] not in oldnames:
394 addnames = []
395 # Drop any old names (the name actually might include ${PV})
396 for name in oldnames:
397 if name not in newnames:
398 newvalues['SRC_URI[%s.md5sum]' % name] = None
399 newvalues['SRC_URI[%s.sha256sum]' % name] = None
400
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500401 if sha256:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400402 if addnames:
403 nameprefix = '%s.' % addnames[0]
404 else:
405 nameprefix = ''
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500406 newvalues['SRC_URI[%smd5sum]' % nameprefix] = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400407 newvalues['SRC_URI[%ssha256sum]' % nameprefix] = sha256
408
409 if srcsubdir_new != srcsubdir_old:
410 s_subdir_old = os.path.relpath(os.path.abspath(rd.getVar('S')), rd.getVar('WORKDIR'))
411 s_subdir_new = os.path.relpath(os.path.abspath(crd.getVar('S')), crd.getVar('WORKDIR'))
412 if srcsubdir_old == s_subdir_old and srcsubdir_new != s_subdir_new:
413 # Subdir for old extracted source matches what S points to (it should!)
414 # but subdir for new extracted source doesn't match what S will be
415 newvalues['S'] = '${WORKDIR}/%s' % srcsubdir_new.replace(newpv, '${PV}')
416 if crd.expand(newvalues['S']) == crd.expand('${WORKDIR}/${BP}'):
417 # It's the default, drop it
418 # FIXME what if S is being set in a .inc?
419 newvalues['S'] = None
420 logger.info('Source subdirectory has changed, dropping S value since it now matches the default ("${WORKDIR}/${BP}")')
421 else:
422 logger.info('Source subdirectory has changed, updating S value')
423
424 if license_diff:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800425 newlicchksum = " ".join(["file://{}".format(l['path']) +
426 (";beginline={}".format(l['beginline']) if l['beginline'] else "") +
427 (";endline={}".format(l['endline']) if l['endline'] else "") +
428 (";md5={}".format(l['actual_md5'])) for l in new_licenses])
Brad Bishop316dfdd2018-06-25 12:45:53 -0400429 newvalues["LIC_FILES_CHKSUM"] = newlicchksum
430 _add_license_diff_to_recipe(fullpath, license_diff)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500431
Andrew Geissler220dafd2023-10-04 10:18:08 -0500432 tinfoil.modified_files()
Brad Bishop96ff1982019-08-19 13:50:42 -0400433 try:
434 rd = tinfoil.parse_recipe_file(fullpath, False)
435 except bb.tinfoil.TinfoilCommandFailed as e:
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500436 _upgrade_error(e, os.path.dirname(fullpath), srctree, keep_failure, 'Parsing of upgraded recipe failed')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500437 oe.recipeutils.patch_recipe(rd, fullpath, newvalues)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500438
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600439 return fullpath, copied
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500440
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500441
442def _check_git_config():
443 def getconfig(name):
444 try:
Andrew Geissler20137392023-10-12 04:59:14 -0600445 value = bb.process.run('git config %s' % name)[0].strip()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500446 except bb.process.ExecutionError as e:
447 if e.exitcode == 1:
448 value = None
449 else:
450 raise
451 return value
452
453 username = getconfig('user.name')
454 useremail = getconfig('user.email')
455 configerr = []
456 if not username:
457 configerr.append('Please set your name using:\n git config --global user.name')
458 if not useremail:
459 configerr.append('Please set your email using:\n git config --global user.email')
460 if configerr:
461 raise DevtoolError('Your git configuration is incomplete which will prevent rebases from working:\n' + '\n'.join(configerr))
462
Brad Bishop316dfdd2018-06-25 12:45:53 -0400463def _extract_licenses(srcpath, recipe_licenses):
464 licenses = []
465 for url in recipe_licenses.split():
466 license = {}
467 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
468 license['path'] = path
469 license['md5'] = parm.get('md5', '')
470 license['beginline'], license['endline'] = 0, 0
471 if 'beginline' in parm:
472 license['beginline'] = int(parm['beginline'])
473 if 'endline' in parm:
474 license['endline'] = int(parm['endline'])
475 license['text'] = []
476 with open(os.path.join(srcpath, path), 'rb') as f:
477 import hashlib
478 actual_md5 = hashlib.md5()
479 lineno = 0
480 for line in f:
481 lineno += 1
482 if (lineno >= license['beginline']) and ((lineno <= license['endline']) or not license['endline']):
483 license['text'].append(line.decode(errors='ignore'))
484 actual_md5.update(line)
485 license['actual_md5'] = actual_md5.hexdigest()
486 licenses.append(license)
487 return licenses
488
489def _generate_license_diff(old_licenses, new_licenses):
490 need_diff = False
491 for l in new_licenses:
492 if l['md5'] != l['actual_md5']:
493 need_diff = True
494 break
495 if need_diff == False:
496 return None
497
498 import difflib
499 diff = ''
500 for old, new in zip(old_licenses, new_licenses):
501 for line in difflib.unified_diff(old['text'], new['text'], old['path'], new['path']):
502 diff = diff + line
503 return diff
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500504
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500505def upgrade(args, config, basepath, workspace):
506 """Entry point for the devtool 'upgrade' subcommand"""
507
508 if args.recipename in workspace:
509 raise DevtoolError("recipe %s is already in your workspace" % args.recipename)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500510 if args.srcbranch and not args.srcrev:
511 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 -0500512
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500513 _check_git_config()
514
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500515 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500516 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600517 rd = parse_recipe(config, tinfoil, args.recipename, True)
518 if not rd:
519 return 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500520
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500521 pn = rd.getVar('PN')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600522 if pn != args.recipename:
523 logger.info('Mapping %s to %s' % (args.recipename, pn))
524 if pn in workspace:
525 raise DevtoolError("recipe %s is already in your workspace" % pn)
526
527 if args.srctree:
528 srctree = os.path.abspath(args.srctree)
529 else:
530 srctree = standard.get_default_srctree(config, pn)
531
Andrew Geissler517393d2023-01-13 08:55:19 -0600532 srctree_s = standard.get_real_srctree(srctree, rd.getVar('S'), rd.getVar('WORKDIR'))
Andrew Geissler5f350902021-07-23 13:09:54 -0400533
Brad Bishop316dfdd2018-06-25 12:45:53 -0400534 # try to automatically discover latest version and revision if not provided on command line
535 if not args.version and not args.srcrev:
536 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
537 if version_info['version'] and not version_info['version'].endswith("new-commits-available"):
538 args.version = version_info['version']
539 if version_info['revision']:
540 args.srcrev = version_info['revision']
541 if not args.version and not args.srcrev:
542 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.")
543
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600544 standard._check_compatible_recipe(pn, rd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500545 old_srcrev = rd.getVar('SRCREV')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600546 if old_srcrev == 'INVALID':
547 old_srcrev = None
548 if old_srcrev and not args.srcrev:
549 raise DevtoolError("Recipe specifies a SRCREV value; you must specify a new one when upgrading")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400550 old_ver = rd.getVar('PV')
551 if old_ver == args.version and old_srcrev == args.srcrev:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600552 raise DevtoolError("Current and upgrade versions are the same version")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400553 if args.version:
554 if bb.utils.vercmp_string(args.version, old_ver) < 0:
555 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))
556 check_prerelease_version(args.version, 'devtool upgrade')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600557
558 rf = None
Brad Bishop316dfdd2018-06-25 12:45:53 -0400559 license_diff = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600560 try:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400561 logger.info('Extracting current version source...')
562 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 -0400563 old_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400564 logger.info('Extracting upgraded version source...')
565 rev2, md5, sha256, srcbranch, srcsubdir2 = _extract_new_source(args.version, srctree, args.no_patch,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500566 args.srcrev, args.srcbranch, args.branch, args.keep_temp,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600567 tinfoil, rd)
Andrew Geissler5f350902021-07-23 13:09:54 -0400568 new_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400569 license_diff = _generate_license_diff(old_licenses, new_licenses)
Brad Bishop96ff1982019-08-19 13:50:42 -0400570 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 -0500571 except (bb.process.CmdError, DevtoolError) as e:
572 recipedir = os.path.join(config.workspace_path, 'recipes', rd.getVar('BPN'))
573 _upgrade_error(e, recipedir, srctree, args.keep_failure)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600574 standard._add_md5(config, pn, os.path.dirname(rf))
575
Andrew Geissler517393d2023-01-13 08:55:19 -0600576 af = _write_append(rf, srctree, srctree_s, args.same_dir, args.no_same_dir, rev2,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600577 copied, config.workspace_path, rd)
578 standard._add_md5(config, pn, af)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500579
Brad Bishop316dfdd2018-06-25 12:45:53 -0400580 update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500581
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600582 logger.info('Upgraded source extracted to %s' % srctree)
583 logger.info('New recipe is %s' % rf)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400584 if license_diff:
585 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 -0500586 preferred_version = rd.getVar('PREFERRED_VERSION_%s' % rd.getVar('PN'))
587 if preferred_version:
588 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 -0400589 finally:
590 tinfoil.shutdown()
591 return 0
592
593def latest_version(args, config, basepath, workspace):
594 """Entry point for the devtool 'latest_version' subcommand"""
595 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
596 try:
597 rd = parse_recipe(config, tinfoil, args.recipename, True)
598 if not rd:
599 return 1
600 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
601 # "new-commits-available" is an indication that upstream never issues version tags
602 if not version_info['version'].endswith("new-commits-available"):
603 logger.info("Current version: {}".format(version_info['current_version']))
604 logger.info("Latest version: {}".format(version_info['version']))
605 if version_info['revision']:
606 logger.info("Latest version's commit: {}".format(version_info['revision']))
607 else:
608 logger.info("Latest commit: {}".format(version_info['revision']))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600609 finally:
610 tinfoil.shutdown()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500611 return 0
612
Brad Bishop19323692019-04-05 15:28:33 -0400613def check_upgrade_status(args, config, basepath, workspace):
614 if not args.recipe:
615 logger.info("Checking the upstream status for all recipes may take a few minutes")
616 results = oe.recipeutils.get_recipe_upgrade_status(args.recipe)
617 for result in results:
618 # pn, update_status, current, latest, maintainer, latest_commit, no_update_reason
619 if args.all or result[1] != 'MATCH':
620 logger.info("{:25} {:15} {:15} {} {} {}".format( result[0],
621 result[2],
622 result[1] if result[1] != 'UPDATE' else (result[3] if not result[3].endswith("new-commits-available") else "new commits"),
623 result[4],
624 result[5] if result[5] != 'N/A' else "",
625 "cannot be updated due to: %s" %(result[6]) if result[6] else ""))
626
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500627def register_commands(subparsers, context):
628 """Register devtool subcommands from this plugin"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500629
630 defsrctree = standard.get_default_srctree(context.config)
631
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500632 parser_upgrade = subparsers.add_parser('upgrade', help='Upgrade an existing recipe',
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500633 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).',
634 group='starting')
635 parser_upgrade.add_argument('recipename', help='Name of recipe to upgrade (just name - no version, path or extension)')
636 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 -0400637 parser_upgrade.add_argument('--version', '-V', help='Version to upgrade to (PV). If omitted, latest upstream version will be determined and used, if possible.')
638 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 -0500639 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 -0500640 parser_upgrade.add_argument('--branch', '-b', default="devtool", help='Name for new development branch to checkout (default "%(default)s")')
641 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 -0400642 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 -0500643 group = parser_upgrade.add_mutually_exclusive_group()
644 group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
645 group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
646 parser_upgrade.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
Brad Bishop96ff1982019-08-19 13:50:42 -0400647 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 -0500648 parser_upgrade.set_defaults(func=upgrade, fixed_setup=context.fixed_setup)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400649
650 parser_latest_version = subparsers.add_parser('latest-version', help='Report the latest version of an existing recipe',
651 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)',
652 group='info')
653 parser_latest_version.add_argument('recipename', help='Name of recipe to query (just name - no version, path or extension)')
654 parser_latest_version.set_defaults(func=latest_version)
Brad Bishop19323692019-04-05 15:28:33 -0400655
656 parser_check_upgrade_status = subparsers.add_parser('check-upgrade-status', help="Report upgradability for multiple (or all) recipes",
657 description="Prints a table of recipes together with versions currently provided by recipes, and latest upstream versions, when there is a later version available",
658 group='info')
659 parser_check_upgrade_status.add_argument('recipe', help='Name of the recipe to report (omit to report upgrade info for all recipes)', nargs='*')
660 parser_check_upgrade_status.add_argument('--all', '-a', help='Show all recipes, not just recipes needing upgrade', action="store_true")
661 parser_check_upgrade_status.set_defaults(func=check_upgrade_status)