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