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