]> git.ipfire.org Git - thirdparty/openembedded/openembedded-core.git/blame - scripts/lib/devtool/upgrade.py
kernelsrc/perf: clean up package version while using kernel source
[thirdparty/openembedded/openembedded-core.git] / scripts / lib / devtool / upgrade.py
CommitLineData
4020f5d9
LS
1# Development tool - upgrade command plugin
2#
802829f1 3# Copyright (C) 2014-2017 Intel Corporation
4020f5d9 4#
f8c9c511 5# SPDX-License-Identifier: GPL-2.0-only
4020f5d9
LS
6#
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
5f140359
LH
19
20devtool_path = os.path.dirname(os.path.realpath(__file__)) + '/../../../meta/lib'
21sys.path = sys.path + [devtool_path]
22
4020f5d9
LS
23import oe.recipeutils
24from devtool import standard
92c4d9be 25from devtool import exec_build_env_command, setup_tinfoil, DevtoolError, parse_recipe, use_external_build, update_unlockedsigs, check_prerelease_version
4020f5d9
LS
26
27logger = logging.getLogger('devtool')
28
4020f5d9
LS
29def _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
d2eeaa88 35 dirs = os.listdir(tmpdir)
4020f5d9
LS
36 if len(dirs) == 1:
37 srctree = os.path.join(tmpdir, dirs[0])
b25e922b
AK
38 else:
39 raise DevtoolError("Cannot determine where the source tree is after unpacking in {}: {}".format(tmpdir,dirs))
4020f5d9
LS
40 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)
479c8eb6 47 shutil.move(os.path.join(orig, path), dest_path)
4020f5d9 48
4020f5d9
LS
49def _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
8b8f0422 54def _recipe_contains(rd, var):
0a36bd96 55 rf = rd.getVar('FILE')
8b8f0422 56 varfiles = oe.recipeutils.get_var_files(rf, [var], rd)
25d4d827 57 for var, fn in varfiles.items():
8b8f0422
PE
58 if fn and fn.startswith(os.path.dirname(rf) + os.sep):
59 return True
60 return False
4020f5d9
LS
61
62def _rename_recipe_dirs(oldpv, newpv, path):
63 for root, dirs, files in os.walk(path):
3c623aac 64 # Rename directories with the version in their name
4020f5d9
LS
65 for olddir in dirs:
66 if olddir.find(oldpv) != -1:
67 newdir = olddir.replace(oldpv, newpv)
68 if olddir != newdir:
60454a0b 69 shutil.move(os.path.join(path, olddir), os.path.join(path, newdir))
3c623aac
PE
70 # 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:
656a65b2
DT
76 bb.utils.rename(os.path.join(path, oldfile),
77 os.path.join(path, newfile))
4020f5d9 78
e6343165 79def _rename_recipe_file(oldrecipe, pn, oldpv, newpv, path):
e144db36
PE
80 oldrecipe = os.path.basename(oldrecipe)
81 if oldrecipe.endswith('_%s.bb' % oldpv):
e6343165 82 newrecipe = '%s_%s.bb' % (pn, newpv)
4020f5d9 83 if oldrecipe != newrecipe:
e144db36 84 shutil.move(os.path.join(path, oldrecipe), os.path.join(path, newrecipe))
4020f5d9 85 else:
e144db36 86 newrecipe = oldrecipe
4020f5d9
LS
87 return os.path.join(path, newrecipe)
88
e6343165 89def _rename_recipe_files(oldrecipe, pn, oldpv, newpv, path):
4020f5d9 90 _rename_recipe_dirs(oldpv, newpv, path)
e6343165 91 return _rename_recipe_file(oldrecipe, pn, oldpv, newpv, path)
4020f5d9 92
900129cb 93def _write_append(rc, srctreebase, srctree, same_dir, no_same_dir, revs, copied, workspace, d):
4020f5d9
LS
94 """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)
688f7a64 105 pn = d.getVar('PN')
4020f5d9
LS
106 af = os.path.join(appendpath, '%s.bbappend' % brf)
107 with open(af, 'w') as f:
42344347 108 f.write('FILESEXTRAPATHS:prepend := "${THISDIR}/${PN}:"\n\n')
0817aa55
AK
109 # 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)
4020f5d9
LS
114 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'))
42344347 117 f.write('EXTERNALSRC:pn-%s = "%s"\n' % (pn, srctree))
320585b7
PE
118 b_is_s = use_external_build(same_dir, no_same_dir, d)
119 if b_is_s:
42344347 120 f.write('EXTERNALSRC_BUILD:pn-%s = "%s"\n' % (pn, srctree))
92eb42c3 121 f.write('\n')
900129cb
JS
122 if revs:
123 for name, rev in revs.items():
124 f.write('# initial_rev %s: %s\n' % (name, rev))
92eb42c3 125 if copied:
0a36bd96 126 f.write('# original_path: %s\n' % os.path.dirname(d.getVar('FILE')))
92eb42c3 127 f.write('# original_files: %s\n' % ' '.join(copied))
4020f5d9
LS
128 return af
129
e6539963 130def _cleanup_on_error(rd, srctree):
e6539963
AK
131 if os.path.exists(rd):
132 shutil.rmtree(rd)
4020f5d9
LS
133 srctree = os.path.abspath(srctree)
134 if os.path.exists(srctree):
135 shutil.rmtree(srctree)
136
e6539963
AK
137def _upgrade_error(e, rd, srctree, keep_failure=False, extramsg=None):
138 if not keep_failure:
139 _cleanup_on_error(rd, srctree)
4020f5d9 140 logger.error(e)
c519ac36
PE
141 if extramsg:
142 logger.error(extramsg)
143 if keep_failure:
144 logger.info('Preserving failed upgrade files (--keep-failure)')
145 sys.exit(1)
4020f5d9
LS
146
147def _get_uri(rd):
0a36bd96 148 srcuris = rd.getVar('SRC_URI').split()
4020f5d9
LS
149 if not len(srcuris):
150 raise DevtoolError('SRC_URI not found on recipe')
c868198c
PE
151 # Get first non-local entry in SRC_URI - usually by convention it's
152 # the first entry, but not always!
153 srcuri = None
154 for entry in srcuris:
155 if not entry.startswith('file://'):
156 srcuri = entry
157 break
158 if not srcuri:
159 raise DevtoolError('Unable to find non-local entry in SRC_URI')
4020f5d9
LS
160 srcrev = '${AUTOREV}'
161 if '://' in srcuri:
162 # Fetch a URL
163 rev_re = re.compile(';rev=([^;]+)')
164 res = rev_re.search(srcuri)
165 if res:
166 srcrev = res.group(1)
167 srcuri = rev_re.sub('', srcuri)
168 return srcuri, srcrev
169
29ced738 170def _extract_new_source(newpv, srctree, no_patch, srcrev, srcbranch, branch, keep_temp, tinfoil, rd):
4020f5d9 171 """Extract sources of a recipe with a new version"""
8457e24f 172 import oe.patch
4020f5d9
LS
173
174 def __run(cmd):
175 """Simple wrapper which calls _run with srctree as cwd"""
176 return _run(cmd, srctree)
177
178 crd = rd.createCopy()
179
0a36bd96 180 pv = crd.getVar('PV')
4020f5d9
LS
181 crd.setVar('PV', newpv)
182
183 tmpsrctree = None
184 uri, rev = _get_uri(crd)
185 if srcrev:
186 rev = srcrev
900129cb 187 paths = [srctree]
e7076f17 188 if uri.startswith('git://') or uri.startswith('gitsm://'):
c4daebf3 189 __run('git fetch')
4020f5d9 190 __run('git checkout %s' % rev)
f96e955b 191 __run('git tag -f --no-sign devtool-base-new')
900129cb 192 __run('git submodule update --recursive')
f96e955b 193 __run('git submodule foreach \'git tag -f --no-sign devtool-base-new\'')
900129cb
JS
194 (stdout, _) = __run('git submodule --quiet foreach \'echo $sm_path\'')
195 paths += [os.path.join(srctree, p) for p in stdout.splitlines()]
8ea8827e 196 checksums = {}
d29881a6
PE
197 _, _, _, _, _, params = bb.fetch2.decodeurl(uri)
198 srcsubdir_rel = params.get('destsuffix', 'git')
29ced738
CRSF
199 if not srcbranch:
200 check_branch, check_branch_err = __run('git branch -r --contains %s' % srcrev)
201 get_branch = [x.strip() for x in check_branch.splitlines()]
202 # Remove HEAD reference point and drop remote prefix
203 get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
bcb21ee2
AK
204 if len(get_branch) == 1:
205 # If srcrev is on only ONE branch, then use that branch
29ced738 206 srcbranch = get_branch[0]
bcb21ee2
AK
207 elif 'main' in get_branch:
208 # If srcrev is on multiple branches, then choose 'main' if it is one of them
209 srcbranch = 'main'
210 elif 'master' in get_branch:
211 # Otherwise choose 'master' if it is one of the branches
212 srcbranch = 'master'
29ced738
CRSF
213 else:
214 # If get_branch contains more than one objects, then display error and exit.
215 mbrch = '\n ' + '\n '.join(get_branch)
216 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))
4020f5d9 217 else:
a4f3e6d5 218 __run('git checkout devtool-base -b devtool-%s' % newpv)
4020f5d9
LS
219
220 tmpdir = tempfile.mkdtemp(prefix='devtool')
221 try:
9a47a669
PE
222 checksums, ftmpdir = scriptutils.fetch_url(tinfoil, uri, rev, tmpdir, logger, preserve_tmp=keep_temp)
223 except scriptutils.FetchUrlFailure as e:
4020f5d9
LS
224 raise DevtoolError(e)
225
9a47a669
PE
226 if ftmpdir and keep_temp:
227 logger.info('Fetch temp directory is %s' % ftmpdir)
228
4020f5d9 229 tmpsrctree = _get_srctree(tmpdir)
4f7595a5 230 srctree = os.path.abspath(srctree)
d29881a6 231 srcsubdir_rel = os.path.relpath(tmpsrctree, tmpdir)
4f7595a5
PE
232
233 # Delete all sources so we ensure no stray files are left over
234 for item in os.listdir(srctree):
235 if item in ['.git', 'oe-local-files']:
236 continue
237 itempath = os.path.join(srctree, item)
238 if os.path.isdir(itempath):
239 shutil.rmtree(itempath)
240 else:
241 os.remove(itempath)
242
243 # Copy in new ones
4020f5d9
LS
244 _copy_source_code(tmpsrctree, srctree)
245
06a24a61 246 (stdout,_) = __run('git ls-files --modified --others')
8b184f6c
PE
247 filelist = stdout.splitlines()
248 pbar = bb.ui.knotty.BBProgress('Adding changed files', len(filelist))
249 pbar.start()
250 batchsize = 100
251 for i in range(0, len(filelist), batchsize):
252 batch = filelist[i:i+batchsize]
06a24a61 253 __run('git add -f -A %s' % ' '.join(['"%s"' % item for item in batch]))
8b184f6c
PE
254 pbar.update(i)
255 pbar.finish()
4020f5d9 256
765a9017
PE
257 useroptions = []
258 oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=rd)
259 __run('git %s commit -q -m "Commit of upstream changes at version %s" --allow-empty' % (' '.join(useroptions), newpv))
f96e955b 260 __run('git tag -f --no-sign devtool-base-%s' % newpv)
4020f5d9 261
900129cb
JS
262 revs = {}
263 for path in paths:
264 (stdout, _) = _run('git rev-parse HEAD', cwd=path)
f5e6183b 265 revs[os.path.relpath(path, srctree)] = stdout.rstrip()
4020f5d9
LS
266
267 if no_patch:
268 patches = oe.recipeutils.get_recipe_patches(crd)
2d11e9e6 269 if patches:
f467fd27 270 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]))
4020f5d9 271 else:
900129cb
JS
272 for path in paths:
273 _run('git checkout devtool-patched -b %s' % branch, cwd=path)
274 (stdout, _) = _run('git branch --list devtool-override-*', cwd=path)
275 branches_to_rebase = [branch] + stdout.split()
f5e6183b
PK
276 target_branch = revs[os.path.relpath(path, srctree)]
277
278 # There is a bug (or feature?) in git rebase where if a commit with
279 # a note is fully rebased away by being part of an old commit, the
280 # note is still attached to the old commit. Avoid this by making
281 # sure all old devtool related commits have a note attached to them
282 # (this assumes git config notes.rewriteMode is set to ignore).
283 (stdout, _) = __run('git rev-list devtool-base..%s' % target_branch)
284 for rev in stdout.splitlines():
285 if not oe.patch.GitApplyTree.getNotes(path, rev):
286 oe.patch.GitApplyTree.addNote(path, rev, "dummy")
287
900129cb 288 for b in branches_to_rebase:
f5e6183b 289 logger.info("Rebasing {} onto {}".format(b, target_branch))
900129cb
JS
290 _run('git checkout %s' % b, cwd=path)
291 try:
f5e6183b 292 _run('git rebase %s' % target_branch, cwd=path)
900129cb
JS
293 except bb.process.ExecutionError as e:
294 if 'conflict' in e.stdout:
295 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()))
296 _run('git rebase --abort', cwd=path)
297 else:
298 logger.warning('Command \'%s\' failed:\n%s' % (e.command, e.stdout))
f5e6183b
PK
299
300 # Remove any dummy notes added above.
301 (stdout, _) = __run('git rev-list devtool-base..%s' % target_branch)
302 for rev in stdout.splitlines():
303 oe.patch.GitApplyTree.removeNote(path, rev, "dummy")
304
900129cb 305 _run('git checkout %s' % branch, cwd=path)
4020f5d9
LS
306
307 if tmpsrctree:
308 if keep_temp:
309 logger.info('Preserving temporary directory %s' % tmpsrctree)
310 else:
311 shutil.rmtree(tmpsrctree)
0d642861
PE
312 if tmpdir != tmpsrctree:
313 shutil.rmtree(tmpdir)
4020f5d9 314
8ea8827e 315 return (revs, checksums, srcbranch, srcsubdir_rel)
4020f5d9 316
ccb37f9e
AK
317def _add_license_diff_to_recipe(path, diff):
318 notice_text = """# FIXME: the LIC_FILES_CHKSUM values have been updated by 'devtool upgrade'.
319# The following is the difference between the old and the new license text.
320# Please update the LICENSE value if needed, and summarize the changes in
3905ae20
AK
321# the commit message via 'License-Update:' tag.
322# (example: 'License-Update: copyright years updated.')
ccb37f9e
AK
323#
324# The changes:
325#
326"""
327 commented_diff = "\n".join(["# {}".format(l) for l in diff.split('\n')])
328 with open(path, 'rb') as f:
329 orig_content = f.read()
330 with open(path, 'wb') as f:
331 f.write(notice_text.encode())
332 f.write(commented_diff.encode())
333 f.write("\n#\n\n".encode())
334 f.write(orig_content)
335
8ea8827e 336def _create_new_recipe(newpv, checksums, srcrev, srcbranch, srcsubdir_old, srcsubdir_new, workspace, tinfoil, rd, license_diff, new_licenses, srctree, keep_failure):
4020f5d9 337 """Creates the new recipe under workspace"""
4020f5d9 338
e6343165
AK
339 pn = rd.getVar('PN')
340 path = os.path.join(workspace, 'recipes', pn)
4020f5d9 341 bb.utils.mkdirhier(path)
56bf5e93 342 copied, _ = oe.recipeutils.copy_recipe_files(rd, path, all_variants=True)
3861486a 343 if not copied:
e6343165 344 raise DevtoolError('Internal error - no files were copied for recipe %s' % pn)
3861486a 345 logger.debug('Copied %s to %s' % (copied, path))
4020f5d9 346
0a36bd96 347 oldpv = rd.getVar('PV')
4020f5d9
LS
348 if not newpv:
349 newpv = oldpv
0a36bd96 350 origpath = rd.getVar('FILE')
e6343165 351 fullpath = _rename_recipe_files(origpath, pn, oldpv, newpv, path)
e144db36 352 logger.debug('Upgraded %s => %s' % (origpath, fullpath))
4020f5d9 353
8b8f0422
PE
354 newvalues = {}
355 if _recipe_contains(rd, 'PV') and newpv != oldpv:
356 newvalues['PV'] = newpv
357
358 if srcrev:
359 newvalues['SRCREV'] = srcrev
360
e49a66fd
PE
361 if srcbranch:
362 src_uri = oe.recipeutils.split_var_value(rd.getVar('SRC_URI', False) or '')
363 changed = False
364 replacing = True
365 new_src_uri = []
366 for entry in src_uri:
74774f9b
AK
367 try:
368 scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(entry)
369 except bb.fetch2.MalformedUrl as e:
370 raise DevtoolError("Could not decode SRC_URI: {}".format(e))
e49a66fd
PE
371 if replacing and scheme in ['git', 'gitsm']:
372 branch = params.get('branch', 'master')
373 if rd.expand(branch) != srcbranch:
374 # Handle case where branch is set through a variable
375 res = re.match(r'\$\{([^}@]+)\}', branch)
376 if res:
377 newvalues[res.group(1)] = srcbranch
378 # We know we won't change SRC_URI now, so break out
379 break
380 else:
381 params['branch'] = srcbranch
382 entry = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
383 changed = True
384 replacing = False
385 new_src_uri.append(entry)
386 if changed:
387 newvalues['SRC_URI'] = ' '.join(new_src_uri)
388
4acf8a69
PE
389 newvalues['PR'] = None
390
c914a5e1
PE
391 # Work out which SRC_URI entries have changed in case the entry uses a name
392 crd = rd.createCopy()
393 crd.setVar('PV', newpv)
394 for var, value in newvalues.items():
395 crd.setVar(var, value)
396 old_src_uri = (rd.getVar('SRC_URI') or '').split()
397 new_src_uri = (crd.getVar('SRC_URI') or '').split()
398 newnames = []
399 addnames = []
400 for newentry in new_src_uri:
401 _, _, _, _, _, params = bb.fetch2.decodeurl(newentry)
402 if 'name' in params:
403 newnames.append(params['name'])
404 if newentry not in old_src_uri:
405 addnames.append(params['name'])
406 # Find what's been set in the original recipe
407 oldnames = []
8ea8827e 408 oldsums = []
c914a5e1
PE
409 noname = False
410 for varflag in rd.getVarFlags('SRC_URI'):
8ea8827e
PK
411 for checksum in checksums:
412 if varflag.endswith('.' + checksum):
413 name = varflag.rsplit('.', 1)[0]
414 if name not in oldnames:
415 oldnames.append(name)
416 oldsums.append(checksum)
417 elif varflag == checksum:
418 noname = True
419 oldsums.append(checksum)
c914a5e1
PE
420 # Even if SRC_URI has named entries it doesn't have to actually use the name
421 if noname and addnames and addnames[0] not in oldnames:
422 addnames = []
423 # Drop any old names (the name actually might include ${PV})
424 for name in oldnames:
425 if name not in newnames:
8ea8827e
PK
426 for checksum in oldsums:
427 newvalues['SRC_URI[%s.%s]' % (name, checksum)] = None
c914a5e1 428
8ea8827e
PK
429 nameprefix = '%s.' % addnames[0] if addnames else ''
430
431 # md5sum is deprecated, remove any traces of it. If it was the only old
432 # checksum, then replace it with the default checksums.
433 if 'md5sum' in oldsums:
1609e77a 434 newvalues['SRC_URI[%smd5sum]' % nameprefix] = None
8ea8827e
PK
435 oldsums.remove('md5sum')
436 if not oldsums:
437 oldsums = ["%ssum" % s for s in bb.fetch2.SHOWN_CHECKSUM_LIST]
438
439 for checksum in oldsums:
440 newvalues['SRC_URI[%s%s]' % (nameprefix, checksum)] = checksums[checksum]
0f81b83f 441
d29881a6
PE
442 if srcsubdir_new != srcsubdir_old:
443 s_subdir_old = os.path.relpath(os.path.abspath(rd.getVar('S')), rd.getVar('WORKDIR'))
444 s_subdir_new = os.path.relpath(os.path.abspath(crd.getVar('S')), crd.getVar('WORKDIR'))
445 if srcsubdir_old == s_subdir_old and srcsubdir_new != s_subdir_new:
446 # Subdir for old extracted source matches what S points to (it should!)
447 # but subdir for new extracted source doesn't match what S will be
448 newvalues['S'] = '${WORKDIR}/%s' % srcsubdir_new.replace(newpv, '${PV}')
449 if crd.expand(newvalues['S']) == crd.expand('${WORKDIR}/${BP}'):
450 # It's the default, drop it
451 # FIXME what if S is being set in a .inc?
452 newvalues['S'] = None
453 logger.info('Source subdirectory has changed, dropping S value since it now matches the default ("${WORKDIR}/${BP}")')
454 else:
455 logger.info('Source subdirectory has changed, updating S value')
456
ccb37f9e 457 if license_diff:
6c5cc1b2
CQ
458 newlicchksum = " ".join(["file://{}".format(l['path']) +
459 (";beginline={}".format(l['beginline']) if l['beginline'] else "") +
460 (";endline={}".format(l['endline']) if l['endline'] else "") +
461 (";md5={}".format(l['actual_md5'])) for l in new_licenses])
ccb37f9e
AK
462 newvalues["LIC_FILES_CHKSUM"] = newlicchksum
463 _add_license_diff_to_recipe(fullpath, license_diff)
464
e5574163 465 tinfoil.modified_files()
c519ac36
PE
466 try:
467 rd = tinfoil.parse_recipe_file(fullpath, False)
468 except bb.tinfoil.TinfoilCommandFailed as e:
e6539963 469 _upgrade_error(e, os.path.dirname(fullpath), srctree, keep_failure, 'Parsing of upgraded recipe failed')
4acf8a69 470 oe.recipeutils.patch_recipe(rd, fullpath, newvalues)
4020f5d9 471
92eb42c3 472 return fullpath, copied
4020f5d9 473
802829f1
PE
474
475def _check_git_config():
476 def getconfig(name):
477 try:
30a9f7de 478 value = bb.process.run('git config %s' % name)[0].strip()
802829f1
PE
479 except bb.process.ExecutionError as e:
480 if e.exitcode == 1:
481 value = None
482 else:
483 raise
484 return value
485
486 username = getconfig('user.name')
487 useremail = getconfig('user.email')
488 configerr = []
489 if not username:
490 configerr.append('Please set your name using:\n git config --global user.name')
491 if not useremail:
492 configerr.append('Please set your email using:\n git config --global user.email')
493 if configerr:
494 raise DevtoolError('Your git configuration is incomplete which will prevent rebases from working:\n' + '\n'.join(configerr))
495
ccb37f9e
AK
496def _extract_licenses(srcpath, recipe_licenses):
497 licenses = []
498 for url in recipe_licenses.split():
499 license = {}
500 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
501 license['path'] = path
502 license['md5'] = parm.get('md5', '')
503 license['beginline'], license['endline'] = 0, 0
504 if 'beginline' in parm:
505 license['beginline'] = int(parm['beginline'])
506 if 'endline' in parm:
507 license['endline'] = int(parm['endline'])
508 license['text'] = []
509 with open(os.path.join(srcpath, path), 'rb') as f:
510 import hashlib
511 actual_md5 = hashlib.md5()
512 lineno = 0
513 for line in f:
514 lineno += 1
515 if (lineno >= license['beginline']) and ((lineno <= license['endline']) or not license['endline']):
516 license['text'].append(line.decode(errors='ignore'))
517 actual_md5.update(line)
518 license['actual_md5'] = actual_md5.hexdigest()
519 licenses.append(license)
520 return licenses
521
522def _generate_license_diff(old_licenses, new_licenses):
523 need_diff = False
524 for l in new_licenses:
525 if l['md5'] != l['actual_md5']:
526 need_diff = True
527 break
528 if need_diff == False:
529 return None
530
531 import difflib
532 diff = ''
533 for old, new in zip(old_licenses, new_licenses):
534 for line in difflib.unified_diff(old['text'], new['text'], old['path'], new['path']):
535 diff = diff + line
536 return diff
802829f1 537
4467aa06 538def _run_recipe_upgrade_extra_tasks(pn, rd, tinfoil):
59894f3b 539 tasks = []
4467aa06
AK
540 for task in (rd.getVar('RECIPE_UPGRADE_EXTRA_TASKS') or '').split():
541 logger.info('Running extra recipe upgrade task: %s' % task)
59894f3b
TO
542 res = tinfoil.build_targets(pn, task, handle_events=True)
543
544 if not res:
4467aa06 545 raise DevtoolError('Running extra recipe upgrade task %s for %s failed' % (task, pn))
59894f3b 546
4020f5d9
LS
547def upgrade(args, config, basepath, workspace):
548 """Entry point for the devtool 'upgrade' subcommand"""
549
550 if args.recipename in workspace:
551 raise DevtoolError("recipe %s is already in your workspace" % args.recipename)
e49a66fd
PE
552 if args.srcbranch and not args.srcrev:
553 raise DevtoolError("If you specify --srcbranch/-B then you must use --srcrev/-S to specify the revision" % args.recipename)
4020f5d9 554
802829f1
PE
555 _check_git_config()
556
8b8f0422 557 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
4020f5d9 558 try:
5ec6d9ef
PE
559 rd = parse_recipe(config, tinfoil, args.recipename, True)
560 if not rd:
561 return 1
562
0a36bd96 563 pn = rd.getVar('PN')
5ec6d9ef
PE
564 if pn != args.recipename:
565 logger.info('Mapping %s to %s' % (args.recipename, pn))
566 if pn in workspace:
567 raise DevtoolError("recipe %s is already in your workspace" % pn)
568
569 if args.srctree:
570 srctree = os.path.abspath(args.srctree)
571 else:
572 srctree = standard.get_default_srctree(config, pn)
573
c326ca8a 574 srctree_s = standard.get_real_srctree(srctree, rd.getVar('S'), rd.getVar('UNPACKDIR'))
fd77e356 575
45b4242b
AK
576 # try to automatically discover latest version and revision if not provided on command line
577 if not args.version and not args.srcrev:
578 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
579 if version_info['version'] and not version_info['version'].endswith("new-commits-available"):
580 args.version = version_info['version']
581 if version_info['revision']:
582 args.srcrev = version_info['revision']
583 if not args.version and not args.srcrev:
584 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.")
585
5ec6d9ef 586 standard._check_compatible_recipe(pn, rd)
0a36bd96 587 old_srcrev = rd.getVar('SRCREV')
5ec6d9ef
PE
588 if old_srcrev == 'INVALID':
589 old_srcrev = None
590 if old_srcrev and not args.srcrev:
591 raise DevtoolError("Recipe specifies a SRCREV value; you must specify a new one when upgrading")
92c4d9be
PE
592 old_ver = rd.getVar('PV')
593 if old_ver == args.version and old_srcrev == args.srcrev:
5ec6d9ef 594 raise DevtoolError("Current and upgrade versions are the same version")
92c4d9be
PE
595 if args.version:
596 if bb.utils.vercmp_string(args.version, old_ver) < 0:
597 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))
598 check_prerelease_version(args.version, 'devtool upgrade')
5ec6d9ef
PE
599
600 rf = None
ccb37f9e 601 license_diff = None
5ec6d9ef 602 try:
9cf2089b 603 logger.info('Extracting current version source...')
aa87603d 604 rev1, srcsubdir1 = standard._extract_source(srctree, False, 'devtool-orig', False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
fd77e356 605 old_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
9cf2089b 606 logger.info('Extracting upgraded version source...')
8ea8827e 607 rev2, checksums, srcbranch, srcsubdir2 = _extract_new_source(args.version, srctree, args.no_patch,
29ced738 608 args.srcrev, args.srcbranch, args.branch, args.keep_temp,
5ec6d9ef 609 tinfoil, rd)
fd77e356 610 new_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
ccb37f9e 611 license_diff = _generate_license_diff(old_licenses, new_licenses)
8ea8827e 612 rf, copied = _create_new_recipe(args.version, checksums, args.srcrev, srcbranch, srcsubdir1, srcsubdir2, config.workspace_path, tinfoil, rd, license_diff, new_licenses, srctree, args.keep_failure)
e6539963 613 except (bb.process.CmdError, DevtoolError) as e:
e6343165 614 recipedir = os.path.join(config.workspace_path, 'recipes', rd.getVar('PN'))
e6539963 615 _upgrade_error(e, recipedir, srctree, args.keep_failure)
5ec6d9ef
PE
616 standard._add_md5(config, pn, os.path.dirname(rf))
617
0817aa55 618 af = _write_append(rf, srctree, srctree_s, args.same_dir, args.no_same_dir, rev2,
5ec6d9ef
PE
619 copied, config.workspace_path, rd)
620 standard._add_md5(config, pn, af)
4e9a0be3 621
4467aa06 622 _run_recipe_upgrade_extra_tasks(pn, rd, tinfoil)
59894f3b 623
05e2c4ad 624 update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
4e9a0be3 625
5ec6d9ef
PE
626 logger.info('Upgraded source extracted to %s' % srctree)
627 logger.info('New recipe is %s' % rf)
ccb37f9e
AK
628 if license_diff:
629 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.')
0b0f53ee
AK
630 preferred_version = rd.getVar('PREFERRED_VERSION_%s' % rd.getVar('PN'))
631 if preferred_version:
632 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)
5ec6d9ef
PE
633 finally:
634 tinfoil.shutdown()
4020f5d9
LS
635 return 0
636
e8f5b5cc
AK
637def latest_version(args, config, basepath, workspace):
638 """Entry point for the devtool 'latest_version' subcommand"""
639 tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
640 try:
641 rd = parse_recipe(config, tinfoil, args.recipename, True)
642 if not rd:
643 return 1
644 version_info = oe.recipeutils.get_recipe_upstream_version(rd)
645 # "new-commits-available" is an indication that upstream never issues version tags
646 if not version_info['version'].endswith("new-commits-available"):
647 logger.info("Current version: {}".format(version_info['current_version']))
648 logger.info("Latest version: {}".format(version_info['version']))
649 if version_info['revision']:
650 logger.info("Latest version's commit: {}".format(version_info['revision']))
651 else:
652 logger.info("Latest commit: {}".format(version_info['revision']))
653 finally:
654 tinfoil.shutdown()
655 return 0
656
02284423 657def check_upgrade_status(args, config, basepath, workspace):
7874aea5
AK
658 def _print_status(recipe):
659 print("{:25} {:15} {:15} {} {} {}".format( recipe['pn'],
660 recipe['cur_ver'],
661 recipe['status'] if recipe['status'] != 'UPDATE' else (recipe['next_ver'] if not recipe['next_ver'].endswith("new-commits-available") else "new commits"),
662 recipe['maintainer'],
663 recipe['revision'] if recipe['revision'] != 'N/A' else "",
664 "cannot be updated due to: %s" %(recipe['no_upgrade_reason']) if recipe['no_upgrade_reason'] else ""))
02284423
AK
665 if not args.recipe:
666 logger.info("Checking the upstream status for all recipes may take a few minutes")
667 results = oe.recipeutils.get_recipe_upgrade_status(args.recipe)
7874aea5
AK
668 for recipegroup in results:
669 upgrades = [r for r in recipegroup if r['status'] != 'MATCH']
670 currents = [r for r in recipegroup if r['status'] == 'MATCH']
671 if len(upgrades) > 1:
672 print("These recipes need to be upgraded together {")
561e1996 673 for r in sorted(upgrades, key=lambda r:r['pn']):
7874aea5
AK
674 _print_status(r)
675 if len(upgrades) > 1:
676 print("}")
677 for r in currents:
678 if args.all:
679 _print_status(r)
02284423 680
4020f5d9
LS
681def register_commands(subparsers, context):
682 """Register devtool subcommands from this plugin"""
8a952407
PE
683
684 defsrctree = standard.get_default_srctree(context.config)
685
4020f5d9 686 parser_upgrade = subparsers.add_parser('upgrade', help='Upgrade an existing recipe',
e1b9d31e
PE
687 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).',
688 group='starting')
a90ffea3 689 parser_upgrade.add_argument('recipename', help='Name of recipe to upgrade (just name - no version, path or extension)')
8a952407 690 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)
45b4242b
AK
691 parser_upgrade.add_argument('--version', '-V', help='Version to upgrade to (PV). If omitted, latest upstream version will be determined and used, if possible.')
692 parser_upgrade.add_argument('--srcrev', '-S', help='Source revision to upgrade to (useful when fetching from an SCM such as git)')
e49a66fd 693 parser_upgrade.add_argument('--srcbranch', '-B', help='Branch in source repository containing the revision to use (if fetching from an SCM such as git)')
4020f5d9
LS
694 parser_upgrade.add_argument('--branch', '-b', default="devtool", help='Name for new development branch to checkout (default "%(default)s")')
695 parser_upgrade.add_argument('--no-patch', action="store_true", help='Do not apply patches from the recipe to the new source code')
aa87603d 696 parser_upgrade.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
4020f5d9
LS
697 group = parser_upgrade.add_mutually_exclusive_group()
698 group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
699 group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
700 parser_upgrade.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
c519ac36 701 parser_upgrade.add_argument('--keep-failure', action="store_true", help='Keep failed upgrade recipe and associated files (for debugging)')
4e9a0be3 702 parser_upgrade.set_defaults(func=upgrade, fixed_setup=context.fixed_setup)
e8f5b5cc
AK
703
704 parser_latest_version = subparsers.add_parser('latest-version', help='Report the latest version of an existing recipe',
705 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)',
706 group='info')
707 parser_latest_version.add_argument('recipename', help='Name of recipe to query (just name - no version, path or extension)')
708 parser_latest_version.set_defaults(func=latest_version)
02284423
AK
709
710 parser_check_upgrade_status = subparsers.add_parser('check-upgrade-status', help="Report upgradability for multiple (or all) recipes",
711 description="Prints a table of recipes together with versions currently provided by recipes, and latest upstream versions, when there is a later version available",
712 group='info')
713 parser_check_upgrade_status.add_argument('recipe', help='Name of the recipe to report (omit to report upgrade info for all recipes)', nargs='*')
29e064ac 714 parser_check_upgrade_status.add_argument('--all', '-a', help='Show all recipes, not just recipes needing upgrade', action="store_true")
02284423 715 parser_check_upgrade_status.set_defaults(func=check_upgrade_status)