xref: /OK3568_Linux_fs/yocto/poky/meta/lib/oe/recipeutils.py (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun# Utility functions for reading and modifying recipes
2*4882a593Smuzhiyun#
3*4882a593Smuzhiyun# Some code borrowed from the OE layer index
4*4882a593Smuzhiyun#
5*4882a593Smuzhiyun# Copyright (C) 2013-2017 Intel Corporation
6*4882a593Smuzhiyun#
7*4882a593Smuzhiyun# SPDX-License-Identifier: GPL-2.0-only
8*4882a593Smuzhiyun#
9*4882a593Smuzhiyun
10*4882a593Smuzhiyunimport sys
11*4882a593Smuzhiyunimport os
12*4882a593Smuzhiyunimport os.path
13*4882a593Smuzhiyunimport tempfile
14*4882a593Smuzhiyunimport textwrap
15*4882a593Smuzhiyunimport difflib
16*4882a593Smuzhiyunfrom . import utils
17*4882a593Smuzhiyunimport shutil
18*4882a593Smuzhiyunimport re
19*4882a593Smuzhiyunimport fnmatch
20*4882a593Smuzhiyunimport glob
21*4882a593Smuzhiyunimport bb.tinfoil
22*4882a593Smuzhiyun
23*4882a593Smuzhiyunfrom collections import OrderedDict, defaultdict
24*4882a593Smuzhiyunfrom bb.utils import vercmp_string
25*4882a593Smuzhiyun
26*4882a593Smuzhiyun# Help us to find places to insert values
27*4882a593Smuzhiyunrecipe_progression = ['SUMMARY', 'DESCRIPTION', 'AUTHOR', 'HOMEPAGE', 'BUGTRACKER', 'SECTION', 'LICENSE', 'LICENSE_FLAGS', 'LIC_FILES_CHKSUM', 'PROVIDES', 'DEPENDS', 'PR', 'PV', 'SRCREV', 'SRCPV', 'SRC_URI', 'S', 'do_fetch()', 'do_unpack()', 'do_patch()', 'EXTRA_OECONF', 'EXTRA_OECMAKE', 'EXTRA_OESCONS', 'do_configure()', 'EXTRA_OEMAKE', 'do_compile()', 'do_install()', 'do_populate_sysroot()', 'INITSCRIPT', 'USERADD', 'GROUPADD', 'PACKAGES', 'FILES', 'RDEPENDS', 'RRECOMMENDS', 'RSUGGESTS', 'RPROVIDES', 'RREPLACES', 'RCONFLICTS', 'ALLOW_EMPTY', 'populate_packages()', 'do_package()', 'do_deploy()', 'BBCLASSEXTEND']
28*4882a593Smuzhiyun# Variables that sometimes are a bit long but shouldn't be wrapped
29*4882a593Smuzhiyunnowrap_vars = ['SUMMARY', 'HOMEPAGE', 'BUGTRACKER', r'SRC_URI\[(.+\.)?md5sum\]', r'SRC_URI\[(.+\.)?sha256sum\]']
30*4882a593Smuzhiyunlist_vars = ['SRC_URI', 'LIC_FILES_CHKSUM']
31*4882a593Smuzhiyunmeta_vars = ['SUMMARY', 'DESCRIPTION', 'HOMEPAGE', 'BUGTRACKER', 'SECTION']
32*4882a593Smuzhiyun
33*4882a593Smuzhiyun
34*4882a593Smuzhiyundef simplify_history(history, d):
35*4882a593Smuzhiyun    """
36*4882a593Smuzhiyun    Eliminate any irrelevant events from a variable history
37*4882a593Smuzhiyun    """
38*4882a593Smuzhiyun    ret_history = []
39*4882a593Smuzhiyun    has_set = False
40*4882a593Smuzhiyun    # Go backwards through the history and remove any immediate operations
41*4882a593Smuzhiyun    # before the most recent set
42*4882a593Smuzhiyun    for event in reversed(history):
43*4882a593Smuzhiyun        if 'flag' in event or not 'file' in event:
44*4882a593Smuzhiyun            continue
45*4882a593Smuzhiyun        if event['op'] == 'set':
46*4882a593Smuzhiyun            if has_set:
47*4882a593Smuzhiyun                continue
48*4882a593Smuzhiyun            has_set = True
49*4882a593Smuzhiyun        elif event['op'] in ('append', 'prepend', 'postdot', 'predot'):
50*4882a593Smuzhiyun            # Reminder: "append" and "prepend" mean += and =+ respectively, NOT :append / :prepend
51*4882a593Smuzhiyun            if has_set:
52*4882a593Smuzhiyun                continue
53*4882a593Smuzhiyun        ret_history.insert(0, event)
54*4882a593Smuzhiyun    return ret_history
55*4882a593Smuzhiyun
56*4882a593Smuzhiyun
57*4882a593Smuzhiyundef get_var_files(fn, varlist, d):
58*4882a593Smuzhiyun    """Find the file in which each of a list of variables is set.
59*4882a593Smuzhiyun    Note: requires variable history to be enabled when parsing.
60*4882a593Smuzhiyun    """
61*4882a593Smuzhiyun    varfiles = {}
62*4882a593Smuzhiyun    for v in varlist:
63*4882a593Smuzhiyun        files = []
64*4882a593Smuzhiyun        if '[' in v:
65*4882a593Smuzhiyun            varsplit = v.split('[')
66*4882a593Smuzhiyun            varflag = varsplit[1].split(']')[0]
67*4882a593Smuzhiyun            history = d.varhistory.variable(varsplit[0])
68*4882a593Smuzhiyun            for event in history:
69*4882a593Smuzhiyun                if 'file' in event and event.get('flag', '') == varflag:
70*4882a593Smuzhiyun                    files.append(event['file'])
71*4882a593Smuzhiyun        else:
72*4882a593Smuzhiyun            history = d.varhistory.variable(v)
73*4882a593Smuzhiyun            for event in history:
74*4882a593Smuzhiyun                if 'file' in event and not 'flag' in event:
75*4882a593Smuzhiyun                    files.append(event['file'])
76*4882a593Smuzhiyun        if files:
77*4882a593Smuzhiyun            actualfile = files[-1]
78*4882a593Smuzhiyun        else:
79*4882a593Smuzhiyun            actualfile = None
80*4882a593Smuzhiyun        varfiles[v] = actualfile
81*4882a593Smuzhiyun
82*4882a593Smuzhiyun    return varfiles
83*4882a593Smuzhiyun
84*4882a593Smuzhiyun
85*4882a593Smuzhiyundef split_var_value(value, assignment=True):
86*4882a593Smuzhiyun    """
87*4882a593Smuzhiyun    Split a space-separated variable's value into a list of items,
88*4882a593Smuzhiyun    taking into account that some of the items might be made up of
89*4882a593Smuzhiyun    expressions containing spaces that should not be split.
90*4882a593Smuzhiyun    Parameters:
91*4882a593Smuzhiyun        value:
92*4882a593Smuzhiyun            The string value to split
93*4882a593Smuzhiyun        assignment:
94*4882a593Smuzhiyun            True to assume that the value represents an assignment
95*4882a593Smuzhiyun            statement, False otherwise. If True, and an assignment
96*4882a593Smuzhiyun            statement is passed in the first item in
97*4882a593Smuzhiyun            the returned list will be the part of the assignment
98*4882a593Smuzhiyun            statement up to and including the opening quote character,
99*4882a593Smuzhiyun            and the last item will be the closing quote.
100*4882a593Smuzhiyun    """
101*4882a593Smuzhiyun    inexpr = 0
102*4882a593Smuzhiyun    lastchar = None
103*4882a593Smuzhiyun    out = []
104*4882a593Smuzhiyun    buf = ''
105*4882a593Smuzhiyun    for char in value:
106*4882a593Smuzhiyun        if char == '{':
107*4882a593Smuzhiyun            if lastchar == '$':
108*4882a593Smuzhiyun                inexpr += 1
109*4882a593Smuzhiyun        elif char == '}':
110*4882a593Smuzhiyun            inexpr -= 1
111*4882a593Smuzhiyun        elif assignment and char in '"\'' and inexpr == 0:
112*4882a593Smuzhiyun            if buf:
113*4882a593Smuzhiyun                out.append(buf)
114*4882a593Smuzhiyun            out.append(char)
115*4882a593Smuzhiyun            char = ''
116*4882a593Smuzhiyun            buf = ''
117*4882a593Smuzhiyun        elif char.isspace() and inexpr == 0:
118*4882a593Smuzhiyun            char = ''
119*4882a593Smuzhiyun            if buf:
120*4882a593Smuzhiyun                out.append(buf)
121*4882a593Smuzhiyun            buf = ''
122*4882a593Smuzhiyun        buf += char
123*4882a593Smuzhiyun        lastchar = char
124*4882a593Smuzhiyun    if buf:
125*4882a593Smuzhiyun        out.append(buf)
126*4882a593Smuzhiyun
127*4882a593Smuzhiyun    # Join together assignment statement and opening quote
128*4882a593Smuzhiyun    outlist = out
129*4882a593Smuzhiyun    if assignment:
130*4882a593Smuzhiyun        assigfound = False
131*4882a593Smuzhiyun        for idx, item in enumerate(out):
132*4882a593Smuzhiyun            if '=' in item:
133*4882a593Smuzhiyun                assigfound = True
134*4882a593Smuzhiyun            if assigfound:
135*4882a593Smuzhiyun                if '"' in item or "'" in item:
136*4882a593Smuzhiyun                    outlist = [' '.join(out[:idx+1])]
137*4882a593Smuzhiyun                    outlist.extend(out[idx+1:])
138*4882a593Smuzhiyun                    break
139*4882a593Smuzhiyun    return outlist
140*4882a593Smuzhiyun
141*4882a593Smuzhiyun
142*4882a593Smuzhiyundef patch_recipe_lines(fromlines, values, trailing_newline=True):
143*4882a593Smuzhiyun    """Update or insert variable values into lines from a recipe.
144*4882a593Smuzhiyun       Note that some manual inspection/intervention may be required
145*4882a593Smuzhiyun       since this cannot handle all situations.
146*4882a593Smuzhiyun    """
147*4882a593Smuzhiyun
148*4882a593Smuzhiyun    import bb.utils
149*4882a593Smuzhiyun
150*4882a593Smuzhiyun    if trailing_newline:
151*4882a593Smuzhiyun        newline = '\n'
152*4882a593Smuzhiyun    else:
153*4882a593Smuzhiyun        newline = ''
154*4882a593Smuzhiyun
155*4882a593Smuzhiyun    nowrap_vars_res = []
156*4882a593Smuzhiyun    for item in nowrap_vars:
157*4882a593Smuzhiyun        nowrap_vars_res.append(re.compile('^%s$' % item))
158*4882a593Smuzhiyun
159*4882a593Smuzhiyun    recipe_progression_res = []
160*4882a593Smuzhiyun    recipe_progression_restrs = []
161*4882a593Smuzhiyun    for item in recipe_progression:
162*4882a593Smuzhiyun        if item.endswith('()'):
163*4882a593Smuzhiyun            key = item[:-2]
164*4882a593Smuzhiyun        else:
165*4882a593Smuzhiyun            key = item
166*4882a593Smuzhiyun        restr = r'%s(_[a-zA-Z0-9-_$(){}]+|\[[^\]]*\])?' % key
167*4882a593Smuzhiyun        if item.endswith('()'):
168*4882a593Smuzhiyun            recipe_progression_restrs.append(restr + '()')
169*4882a593Smuzhiyun        else:
170*4882a593Smuzhiyun            recipe_progression_restrs.append(restr)
171*4882a593Smuzhiyun        recipe_progression_res.append(re.compile('^%s$' % restr))
172*4882a593Smuzhiyun
173*4882a593Smuzhiyun    def get_recipe_pos(variable):
174*4882a593Smuzhiyun        for i, p in enumerate(recipe_progression_res):
175*4882a593Smuzhiyun            if p.match(variable):
176*4882a593Smuzhiyun                return i
177*4882a593Smuzhiyun        return -1
178*4882a593Smuzhiyun
179*4882a593Smuzhiyun    remainingnames = {}
180*4882a593Smuzhiyun    for k in values.keys():
181*4882a593Smuzhiyun        remainingnames[k] = get_recipe_pos(k)
182*4882a593Smuzhiyun    remainingnames = OrderedDict(sorted(remainingnames.items(), key=lambda x: x[1]))
183*4882a593Smuzhiyun
184*4882a593Smuzhiyun    modifying = False
185*4882a593Smuzhiyun
186*4882a593Smuzhiyun    def outputvalue(name, lines, rewindcomments=False):
187*4882a593Smuzhiyun        if values[name] is None:
188*4882a593Smuzhiyun            return
189*4882a593Smuzhiyun        if isinstance(values[name], tuple):
190*4882a593Smuzhiyun            op, value = values[name]
191*4882a593Smuzhiyun            if op == '+=' and value.strip() == '':
192*4882a593Smuzhiyun                return
193*4882a593Smuzhiyun        else:
194*4882a593Smuzhiyun            value = values[name]
195*4882a593Smuzhiyun            op = '='
196*4882a593Smuzhiyun        rawtext = '%s %s "%s"%s' % (name, op, value, newline)
197*4882a593Smuzhiyun        addlines = []
198*4882a593Smuzhiyun        nowrap = False
199*4882a593Smuzhiyun        for nowrap_re in nowrap_vars_res:
200*4882a593Smuzhiyun            if nowrap_re.match(name):
201*4882a593Smuzhiyun                nowrap = True
202*4882a593Smuzhiyun                break
203*4882a593Smuzhiyun        if nowrap:
204*4882a593Smuzhiyun            addlines.append(rawtext)
205*4882a593Smuzhiyun        elif name in list_vars:
206*4882a593Smuzhiyun            splitvalue = split_var_value(value, assignment=False)
207*4882a593Smuzhiyun            if len(splitvalue) > 1:
208*4882a593Smuzhiyun                linesplit = ' \\\n' + (' ' * (len(name) + 4))
209*4882a593Smuzhiyun                addlines.append('%s %s "%s%s"%s' % (name, op, linesplit.join(splitvalue), linesplit, newline))
210*4882a593Smuzhiyun            else:
211*4882a593Smuzhiyun                addlines.append(rawtext)
212*4882a593Smuzhiyun        else:
213*4882a593Smuzhiyun            wrapped = textwrap.wrap(rawtext)
214*4882a593Smuzhiyun            for wrapline in wrapped[:-1]:
215*4882a593Smuzhiyun                addlines.append('%s \\%s' % (wrapline, newline))
216*4882a593Smuzhiyun            addlines.append('%s%s' % (wrapped[-1], newline))
217*4882a593Smuzhiyun
218*4882a593Smuzhiyun        # Split on newlines - this isn't strictly necessary if you are only
219*4882a593Smuzhiyun        # going to write the output to disk, but if you want to compare it
220*4882a593Smuzhiyun        # (as patch_recipe_file() will do if patch=True) then it's important.
221*4882a593Smuzhiyun        addlines = [line for l in addlines for line in l.splitlines(True)]
222*4882a593Smuzhiyun        if rewindcomments:
223*4882a593Smuzhiyun            # Ensure we insert the lines before any leading comments
224*4882a593Smuzhiyun            # (that we'd want to ensure remain leading the next value)
225*4882a593Smuzhiyun            for i, ln in reversed(list(enumerate(lines))):
226*4882a593Smuzhiyun                if not ln.startswith('#'):
227*4882a593Smuzhiyun                    lines[i+1:i+1] = addlines
228*4882a593Smuzhiyun                    break
229*4882a593Smuzhiyun            else:
230*4882a593Smuzhiyun                lines.extend(addlines)
231*4882a593Smuzhiyun        else:
232*4882a593Smuzhiyun            lines.extend(addlines)
233*4882a593Smuzhiyun
234*4882a593Smuzhiyun    existingnames = []
235*4882a593Smuzhiyun    def patch_recipe_varfunc(varname, origvalue, op, newlines):
236*4882a593Smuzhiyun        if modifying:
237*4882a593Smuzhiyun            # Insert anything that should come before this variable
238*4882a593Smuzhiyun            pos = get_recipe_pos(varname)
239*4882a593Smuzhiyun            for k in list(remainingnames):
240*4882a593Smuzhiyun                if remainingnames[k] > -1 and pos >= remainingnames[k] and not k in existingnames:
241*4882a593Smuzhiyun                    outputvalue(k, newlines, rewindcomments=True)
242*4882a593Smuzhiyun                    del remainingnames[k]
243*4882a593Smuzhiyun            # Now change this variable, if it needs to be changed
244*4882a593Smuzhiyun            if varname in existingnames and op in ['+=', '=', '=+']:
245*4882a593Smuzhiyun                if varname in remainingnames:
246*4882a593Smuzhiyun                    outputvalue(varname, newlines)
247*4882a593Smuzhiyun                    del remainingnames[varname]
248*4882a593Smuzhiyun                return None, None, 0, True
249*4882a593Smuzhiyun        else:
250*4882a593Smuzhiyun            if varname in values:
251*4882a593Smuzhiyun                existingnames.append(varname)
252*4882a593Smuzhiyun        return origvalue, None, 0, True
253*4882a593Smuzhiyun
254*4882a593Smuzhiyun    # First run - establish which values we want to set are already in the file
255*4882a593Smuzhiyun    varlist = [re.escape(item) for item in values.keys()]
256*4882a593Smuzhiyun    bb.utils.edit_metadata(fromlines, varlist, patch_recipe_varfunc)
257*4882a593Smuzhiyun    # Second run - actually set everything
258*4882a593Smuzhiyun    modifying = True
259*4882a593Smuzhiyun    varlist.extend(recipe_progression_restrs)
260*4882a593Smuzhiyun    changed, tolines = bb.utils.edit_metadata(fromlines, varlist, patch_recipe_varfunc, match_overrides=True)
261*4882a593Smuzhiyun
262*4882a593Smuzhiyun    if remainingnames:
263*4882a593Smuzhiyun        if tolines and tolines[-1].strip() != '':
264*4882a593Smuzhiyun            tolines.append('\n')
265*4882a593Smuzhiyun        for k in remainingnames.keys():
266*4882a593Smuzhiyun            outputvalue(k, tolines)
267*4882a593Smuzhiyun
268*4882a593Smuzhiyun    return changed, tolines
269*4882a593Smuzhiyun
270*4882a593Smuzhiyun
271*4882a593Smuzhiyundef patch_recipe_file(fn, values, patch=False, relpath='', redirect_output=None):
272*4882a593Smuzhiyun    """Update or insert variable values into a recipe file (assuming you
273*4882a593Smuzhiyun       have already identified the exact file you want to update.)
274*4882a593Smuzhiyun       Note that some manual inspection/intervention may be required
275*4882a593Smuzhiyun       since this cannot handle all situations.
276*4882a593Smuzhiyun    """
277*4882a593Smuzhiyun
278*4882a593Smuzhiyun    with open(fn, 'r') as f:
279*4882a593Smuzhiyun        fromlines = f.readlines()
280*4882a593Smuzhiyun
281*4882a593Smuzhiyun    _, tolines = patch_recipe_lines(fromlines, values)
282*4882a593Smuzhiyun
283*4882a593Smuzhiyun    if redirect_output:
284*4882a593Smuzhiyun        with open(os.path.join(redirect_output, os.path.basename(fn)), 'w') as f:
285*4882a593Smuzhiyun            f.writelines(tolines)
286*4882a593Smuzhiyun        return None
287*4882a593Smuzhiyun    elif patch:
288*4882a593Smuzhiyun        relfn = os.path.relpath(fn, relpath)
289*4882a593Smuzhiyun        diff = difflib.unified_diff(fromlines, tolines, 'a/%s' % relfn, 'b/%s' % relfn)
290*4882a593Smuzhiyun        return diff
291*4882a593Smuzhiyun    else:
292*4882a593Smuzhiyun        with open(fn, 'w') as f:
293*4882a593Smuzhiyun            f.writelines(tolines)
294*4882a593Smuzhiyun        return None
295*4882a593Smuzhiyun
296*4882a593Smuzhiyun
297*4882a593Smuzhiyundef localise_file_vars(fn, varfiles, varlist):
298*4882a593Smuzhiyun    """Given a list of variables and variable history (fetched with get_var_files())
299*4882a593Smuzhiyun    find where each variable should be set/changed. This handles for example where a
300*4882a593Smuzhiyun    recipe includes an inc file where variables might be changed - in most cases
301*4882a593Smuzhiyun    we want to update the inc file when changing the variable value rather than adding
302*4882a593Smuzhiyun    it to the recipe itself.
303*4882a593Smuzhiyun    """
304*4882a593Smuzhiyun    fndir = os.path.dirname(fn) + os.sep
305*4882a593Smuzhiyun
306*4882a593Smuzhiyun    first_meta_file = None
307*4882a593Smuzhiyun    for v in meta_vars:
308*4882a593Smuzhiyun        f = varfiles.get(v, None)
309*4882a593Smuzhiyun        if f:
310*4882a593Smuzhiyun            actualdir = os.path.dirname(f) + os.sep
311*4882a593Smuzhiyun            if actualdir.startswith(fndir):
312*4882a593Smuzhiyun                first_meta_file = f
313*4882a593Smuzhiyun                break
314*4882a593Smuzhiyun
315*4882a593Smuzhiyun    filevars = defaultdict(list)
316*4882a593Smuzhiyun    for v in varlist:
317*4882a593Smuzhiyun        f = varfiles[v]
318*4882a593Smuzhiyun        # Only return files that are in the same directory as the recipe or in some directory below there
319*4882a593Smuzhiyun        # (this excludes bbclass files and common inc files that wouldn't be appropriate to set the variable
320*4882a593Smuzhiyun        # in if we were going to set a value specific to this recipe)
321*4882a593Smuzhiyun        if f:
322*4882a593Smuzhiyun            actualfile = f
323*4882a593Smuzhiyun        else:
324*4882a593Smuzhiyun            # Variable isn't in a file, if it's one of the "meta" vars, use the first file with a meta var in it
325*4882a593Smuzhiyun            if first_meta_file:
326*4882a593Smuzhiyun                actualfile = first_meta_file
327*4882a593Smuzhiyun            else:
328*4882a593Smuzhiyun                actualfile = fn
329*4882a593Smuzhiyun
330*4882a593Smuzhiyun        actualdir = os.path.dirname(actualfile) + os.sep
331*4882a593Smuzhiyun        if not actualdir.startswith(fndir):
332*4882a593Smuzhiyun            actualfile = fn
333*4882a593Smuzhiyun        filevars[actualfile].append(v)
334*4882a593Smuzhiyun
335*4882a593Smuzhiyun    return filevars
336*4882a593Smuzhiyun
337*4882a593Smuzhiyundef patch_recipe(d, fn, varvalues, patch=False, relpath='', redirect_output=None):
338*4882a593Smuzhiyun    """Modify a list of variable values in the specified recipe. Handles inc files if
339*4882a593Smuzhiyun    used by the recipe.
340*4882a593Smuzhiyun    """
341*4882a593Smuzhiyun    overrides = d.getVar('OVERRIDES').split(':')
342*4882a593Smuzhiyun    def override_applicable(hevent):
343*4882a593Smuzhiyun        op = hevent['op']
344*4882a593Smuzhiyun        if '[' in op:
345*4882a593Smuzhiyun            opoverrides = op.split('[')[1].split(']')[0].split(':')
346*4882a593Smuzhiyun            for opoverride in opoverrides:
347*4882a593Smuzhiyun                if not opoverride in overrides:
348*4882a593Smuzhiyun                    return False
349*4882a593Smuzhiyun        return True
350*4882a593Smuzhiyun
351*4882a593Smuzhiyun    varlist = varvalues.keys()
352*4882a593Smuzhiyun    fn = os.path.abspath(fn)
353*4882a593Smuzhiyun    varfiles = get_var_files(fn, varlist, d)
354*4882a593Smuzhiyun    locs = localise_file_vars(fn, varfiles, varlist)
355*4882a593Smuzhiyun    patches = []
356*4882a593Smuzhiyun    for f,v in locs.items():
357*4882a593Smuzhiyun        vals = {k: varvalues[k] for k in v}
358*4882a593Smuzhiyun        f = os.path.abspath(f)
359*4882a593Smuzhiyun        if f == fn:
360*4882a593Smuzhiyun            extravals = {}
361*4882a593Smuzhiyun            for var, value in vals.items():
362*4882a593Smuzhiyun                if var in list_vars:
363*4882a593Smuzhiyun                    history = simplify_history(d.varhistory.variable(var), d)
364*4882a593Smuzhiyun                    recipe_set = False
365*4882a593Smuzhiyun                    for event in history:
366*4882a593Smuzhiyun                        if os.path.abspath(event['file']) == fn:
367*4882a593Smuzhiyun                            if event['op'] == 'set':
368*4882a593Smuzhiyun                                recipe_set = True
369*4882a593Smuzhiyun                    if not recipe_set:
370*4882a593Smuzhiyun                        for event in history:
371*4882a593Smuzhiyun                            if event['op'].startswith(':remove'):
372*4882a593Smuzhiyun                                continue
373*4882a593Smuzhiyun                            if not override_applicable(event):
374*4882a593Smuzhiyun                                continue
375*4882a593Smuzhiyun                            newvalue = value.replace(event['detail'], '')
376*4882a593Smuzhiyun                            if newvalue == value and os.path.abspath(event['file']) == fn and event['op'].startswith(':'):
377*4882a593Smuzhiyun                                op = event['op'].replace('[', ':').replace(']', '')
378*4882a593Smuzhiyun                                extravals[var + op] = None
379*4882a593Smuzhiyun                            value = newvalue
380*4882a593Smuzhiyun                            vals[var] = ('+=', value)
381*4882a593Smuzhiyun            vals.update(extravals)
382*4882a593Smuzhiyun        patchdata = patch_recipe_file(f, vals, patch, relpath, redirect_output)
383*4882a593Smuzhiyun        if patch:
384*4882a593Smuzhiyun            patches.append(patchdata)
385*4882a593Smuzhiyun
386*4882a593Smuzhiyun    if patch:
387*4882a593Smuzhiyun        return patches
388*4882a593Smuzhiyun    else:
389*4882a593Smuzhiyun        return None
390*4882a593Smuzhiyun
391*4882a593Smuzhiyun
392*4882a593Smuzhiyun
393*4882a593Smuzhiyundef copy_recipe_files(d, tgt_dir, whole_dir=False, download=True, all_variants=False):
394*4882a593Smuzhiyun    """Copy (local) recipe files, including both files included via include/require,
395*4882a593Smuzhiyun    and files referred to in the SRC_URI variable."""
396*4882a593Smuzhiyun    import bb.fetch2
397*4882a593Smuzhiyun    import oe.path
398*4882a593Smuzhiyun
399*4882a593Smuzhiyun    # FIXME need a warning if the unexpanded SRC_URI value contains variable references
400*4882a593Smuzhiyun
401*4882a593Smuzhiyun    uri_values = []
402*4882a593Smuzhiyun    localpaths = []
403*4882a593Smuzhiyun    def fetch_urls(rdata):
404*4882a593Smuzhiyun        # Collect the local paths from SRC_URI
405*4882a593Smuzhiyun        srcuri = rdata.getVar('SRC_URI') or ""
406*4882a593Smuzhiyun        if srcuri not in uri_values:
407*4882a593Smuzhiyun            fetch = bb.fetch2.Fetch(srcuri.split(), rdata)
408*4882a593Smuzhiyun            if download:
409*4882a593Smuzhiyun                fetch.download()
410*4882a593Smuzhiyun            for pth in fetch.localpaths():
411*4882a593Smuzhiyun                if pth not in localpaths:
412*4882a593Smuzhiyun                    localpaths.append(os.path.abspath(pth))
413*4882a593Smuzhiyun            uri_values.append(srcuri)
414*4882a593Smuzhiyun
415*4882a593Smuzhiyun    fetch_urls(d)
416*4882a593Smuzhiyun    if all_variants:
417*4882a593Smuzhiyun        # Get files for other variants e.g. in the case of a SRC_URI:append
418*4882a593Smuzhiyun        localdata = bb.data.createCopy(d)
419*4882a593Smuzhiyun        variants = (localdata.getVar('BBCLASSEXTEND') or '').split()
420*4882a593Smuzhiyun        if variants:
421*4882a593Smuzhiyun            # Ensure we handle class-target if we're dealing with one of the variants
422*4882a593Smuzhiyun            variants.append('target')
423*4882a593Smuzhiyun            for variant in variants:
424*4882a593Smuzhiyun                if variant.startswith("devupstream"):
425*4882a593Smuzhiyun                    localdata.setVar('SRCPV', 'git')
426*4882a593Smuzhiyun                localdata.setVar('CLASSOVERRIDE', 'class-%s' % variant)
427*4882a593Smuzhiyun                fetch_urls(localdata)
428*4882a593Smuzhiyun
429*4882a593Smuzhiyun    # Copy local files to target directory and gather any remote files
430*4882a593Smuzhiyun    bb_dir = os.path.abspath(os.path.dirname(d.getVar('FILE'))) + os.sep
431*4882a593Smuzhiyun    remotes = []
432*4882a593Smuzhiyun    copied = []
433*4882a593Smuzhiyun    # Need to do this in two steps since we want to check against the absolute path
434*4882a593Smuzhiyun    includes = [os.path.abspath(path) for path in d.getVar('BBINCLUDED').split() if os.path.exists(path)]
435*4882a593Smuzhiyun    # We also check this below, but we don't want any items in this list being considered remotes
436*4882a593Smuzhiyun    includes = [path for path in includes if path.startswith(bb_dir)]
437*4882a593Smuzhiyun    for path in localpaths + includes:
438*4882a593Smuzhiyun        # Only import files that are under the meta directory
439*4882a593Smuzhiyun        if path.startswith(bb_dir):
440*4882a593Smuzhiyun            if not whole_dir:
441*4882a593Smuzhiyun                relpath = os.path.relpath(path, bb_dir)
442*4882a593Smuzhiyun                subdir = os.path.join(tgt_dir, os.path.dirname(relpath))
443*4882a593Smuzhiyun                if not os.path.exists(subdir):
444*4882a593Smuzhiyun                    os.makedirs(subdir)
445*4882a593Smuzhiyun                shutil.copy2(path, os.path.join(tgt_dir, relpath))
446*4882a593Smuzhiyun                copied.append(relpath)
447*4882a593Smuzhiyun        else:
448*4882a593Smuzhiyun            remotes.append(path)
449*4882a593Smuzhiyun    # Simply copy whole meta dir, if requested
450*4882a593Smuzhiyun    if whole_dir:
451*4882a593Smuzhiyun        shutil.copytree(bb_dir, tgt_dir)
452*4882a593Smuzhiyun
453*4882a593Smuzhiyun    return copied, remotes
454*4882a593Smuzhiyun
455*4882a593Smuzhiyun
456*4882a593Smuzhiyundef get_recipe_local_files(d, patches=False, archives=False):
457*4882a593Smuzhiyun    """Get a list of local files in SRC_URI within a recipe."""
458*4882a593Smuzhiyun    import oe.patch
459*4882a593Smuzhiyun    uris = (d.getVar('SRC_URI') or "").split()
460*4882a593Smuzhiyun    fetch = bb.fetch2.Fetch(uris, d)
461*4882a593Smuzhiyun    # FIXME this list should be factored out somewhere else (such as the
462*4882a593Smuzhiyun    # fetcher) though note that this only encompasses actual container formats
463*4882a593Smuzhiyun    # i.e. that can contain multiple files as opposed to those that only
464*4882a593Smuzhiyun    # contain a compressed stream (i.e. .tar.gz as opposed to just .gz)
465*4882a593Smuzhiyun    archive_exts = ['.tar', '.tgz', '.tar.gz', '.tar.Z', '.tbz', '.tbz2', '.tar.bz2', '.txz', '.tar.xz', '.tar.lz', '.zip', '.jar', '.rpm', '.srpm', '.deb', '.ipk', '.tar.7z', '.7z']
466*4882a593Smuzhiyun    ret = {}
467*4882a593Smuzhiyun    for uri in uris:
468*4882a593Smuzhiyun        if fetch.ud[uri].type == 'file':
469*4882a593Smuzhiyun            if (not patches and
470*4882a593Smuzhiyun                    oe.patch.patch_path(uri, fetch, '', expand=False)):
471*4882a593Smuzhiyun                continue
472*4882a593Smuzhiyun            # Skip files that are referenced by absolute path
473*4882a593Smuzhiyun            fname = fetch.ud[uri].basepath
474*4882a593Smuzhiyun            if os.path.isabs(fname):
475*4882a593Smuzhiyun                continue
476*4882a593Smuzhiyun            # Handle subdir=
477*4882a593Smuzhiyun            subdir = fetch.ud[uri].parm.get('subdir', '')
478*4882a593Smuzhiyun            if subdir:
479*4882a593Smuzhiyun                if os.path.isabs(subdir):
480*4882a593Smuzhiyun                    continue
481*4882a593Smuzhiyun                fname = os.path.join(subdir, fname)
482*4882a593Smuzhiyun            localpath = fetch.localpath(uri)
483*4882a593Smuzhiyun            if not archives:
484*4882a593Smuzhiyun                # Ignore archives that will be unpacked
485*4882a593Smuzhiyun                if localpath.endswith(tuple(archive_exts)):
486*4882a593Smuzhiyun                    unpack = fetch.ud[uri].parm.get('unpack', True)
487*4882a593Smuzhiyun                    if unpack:
488*4882a593Smuzhiyun                        continue
489*4882a593Smuzhiyun            if os.path.isdir(localpath):
490*4882a593Smuzhiyun                for root, dirs, files in os.walk(localpath):
491*4882a593Smuzhiyun                    for fname in files:
492*4882a593Smuzhiyun                        fileabspath = os.path.join(root,fname)
493*4882a593Smuzhiyun                        srcdir = os.path.dirname(localpath)
494*4882a593Smuzhiyun                        ret[os.path.relpath(fileabspath,srcdir)] = fileabspath
495*4882a593Smuzhiyun            else:
496*4882a593Smuzhiyun                ret[fname] = localpath
497*4882a593Smuzhiyun    return ret
498*4882a593Smuzhiyun
499*4882a593Smuzhiyun
500*4882a593Smuzhiyundef get_recipe_patches(d):
501*4882a593Smuzhiyun    """Get a list of the patches included in SRC_URI within a recipe."""
502*4882a593Smuzhiyun    import oe.patch
503*4882a593Smuzhiyun    patches = oe.patch.src_patches(d, expand=False)
504*4882a593Smuzhiyun    patchfiles = []
505*4882a593Smuzhiyun    for patch in patches:
506*4882a593Smuzhiyun        _, _, local, _, _, parm = bb.fetch.decodeurl(patch)
507*4882a593Smuzhiyun        patchfiles.append(local)
508*4882a593Smuzhiyun    return patchfiles
509*4882a593Smuzhiyun
510*4882a593Smuzhiyun
511*4882a593Smuzhiyundef get_recipe_patched_files(d):
512*4882a593Smuzhiyun    """
513*4882a593Smuzhiyun    Get the list of patches for a recipe along with the files each patch modifies.
514*4882a593Smuzhiyun    Params:
515*4882a593Smuzhiyun        d: the datastore for the recipe
516*4882a593Smuzhiyun    Returns:
517*4882a593Smuzhiyun        a dict mapping patch file path to a list of tuples of changed files and
518*4882a593Smuzhiyun        change mode ('A' for add, 'D' for delete or 'M' for modify)
519*4882a593Smuzhiyun    """
520*4882a593Smuzhiyun    import oe.patch
521*4882a593Smuzhiyun    patches = oe.patch.src_patches(d, expand=False)
522*4882a593Smuzhiyun    patchedfiles = {}
523*4882a593Smuzhiyun    for patch in patches:
524*4882a593Smuzhiyun        _, _, patchfile, _, _, parm = bb.fetch.decodeurl(patch)
525*4882a593Smuzhiyun        striplevel = int(parm['striplevel'])
526*4882a593Smuzhiyun        patchedfiles[patchfile] = oe.patch.PatchSet.getPatchedFiles(patchfile, striplevel, os.path.join(d.getVar('S'), parm.get('patchdir', '')))
527*4882a593Smuzhiyun    return patchedfiles
528*4882a593Smuzhiyun
529*4882a593Smuzhiyun
530*4882a593Smuzhiyundef validate_pn(pn):
531*4882a593Smuzhiyun    """Perform validation on a recipe name (PN) for a new recipe."""
532*4882a593Smuzhiyun    reserved_names = ['forcevariable', 'append', 'prepend', 'remove']
533*4882a593Smuzhiyun    if not re.match('^[0-9a-z-.+]+$', pn):
534*4882a593Smuzhiyun        return 'Recipe name "%s" is invalid: only characters 0-9, a-z, -, + and . are allowed' % pn
535*4882a593Smuzhiyun    elif pn in reserved_names:
536*4882a593Smuzhiyun        return 'Recipe name "%s" is invalid: is a reserved keyword' % pn
537*4882a593Smuzhiyun    elif pn.startswith('pn-'):
538*4882a593Smuzhiyun        return 'Recipe name "%s" is invalid: names starting with "pn-" are reserved' % pn
539*4882a593Smuzhiyun    elif pn.endswith(('.bb', '.bbappend', '.bbclass', '.inc', '.conf')):
540*4882a593Smuzhiyun        return 'Recipe name "%s" is invalid: should be just a name, not a file name' % pn
541*4882a593Smuzhiyun    return ''
542*4882a593Smuzhiyun
543*4882a593Smuzhiyun
544*4882a593Smuzhiyundef get_bbfile_path(d, destdir, extrapathhint=None):
545*4882a593Smuzhiyun    """
546*4882a593Smuzhiyun    Determine the correct path for a recipe within a layer
547*4882a593Smuzhiyun    Parameters:
548*4882a593Smuzhiyun        d: Recipe-specific datastore
549*4882a593Smuzhiyun        destdir: destination directory. Can be the path to the base of the layer or a
550*4882a593Smuzhiyun            partial path somewhere within the layer.
551*4882a593Smuzhiyun        extrapathhint: a path relative to the base of the layer to try
552*4882a593Smuzhiyun    """
553*4882a593Smuzhiyun    import bb.cookerdata
554*4882a593Smuzhiyun
555*4882a593Smuzhiyun    destdir = os.path.abspath(destdir)
556*4882a593Smuzhiyun    destlayerdir = find_layerdir(destdir)
557*4882a593Smuzhiyun
558*4882a593Smuzhiyun    # Parse the specified layer's layer.conf file directly, in case the layer isn't in bblayers.conf
559*4882a593Smuzhiyun    confdata = d.createCopy()
560*4882a593Smuzhiyun    confdata.setVar('BBFILES', '')
561*4882a593Smuzhiyun    confdata.setVar('LAYERDIR', destlayerdir)
562*4882a593Smuzhiyun    destlayerconf = os.path.join(destlayerdir, "conf", "layer.conf")
563*4882a593Smuzhiyun    confdata = bb.cookerdata.parse_config_file(destlayerconf, confdata)
564*4882a593Smuzhiyun    pn = d.getVar('PN')
565*4882a593Smuzhiyun
566*4882a593Smuzhiyun    # Parse BBFILES_DYNAMIC and append to BBFILES
567*4882a593Smuzhiyun    bbfiles_dynamic = (confdata.getVar('BBFILES_DYNAMIC') or "").split()
568*4882a593Smuzhiyun    collections = (confdata.getVar('BBFILE_COLLECTIONS') or "").split()
569*4882a593Smuzhiyun    invalid = []
570*4882a593Smuzhiyun    for entry in bbfiles_dynamic:
571*4882a593Smuzhiyun        parts = entry.split(":", 1)
572*4882a593Smuzhiyun        if len(parts) != 2:
573*4882a593Smuzhiyun            invalid.append(entry)
574*4882a593Smuzhiyun            continue
575*4882a593Smuzhiyun        l, f = parts
576*4882a593Smuzhiyun        invert = l[0] == "!"
577*4882a593Smuzhiyun        if invert:
578*4882a593Smuzhiyun            l = l[1:]
579*4882a593Smuzhiyun        if (l in collections and not invert) or (l not in collections and invert):
580*4882a593Smuzhiyun            confdata.appendVar("BBFILES", " " + f)
581*4882a593Smuzhiyun    if invalid:
582*4882a593Smuzhiyun        return None
583*4882a593Smuzhiyun    bbfilespecs = (confdata.getVar('BBFILES') or '').split()
584*4882a593Smuzhiyun    if destdir == destlayerdir:
585*4882a593Smuzhiyun        for bbfilespec in bbfilespecs:
586*4882a593Smuzhiyun            if not bbfilespec.endswith('.bbappend'):
587*4882a593Smuzhiyun                for match in glob.glob(bbfilespec):
588*4882a593Smuzhiyun                    splitext = os.path.splitext(os.path.basename(match))
589*4882a593Smuzhiyun                    if splitext[1] == '.bb':
590*4882a593Smuzhiyun                        mpn = splitext[0].split('_')[0]
591*4882a593Smuzhiyun                        if mpn == pn:
592*4882a593Smuzhiyun                            return os.path.dirname(match)
593*4882a593Smuzhiyun
594*4882a593Smuzhiyun    # Try to make up a path that matches BBFILES
595*4882a593Smuzhiyun    # this is a little crude, but better than nothing
596*4882a593Smuzhiyun    bpn = d.getVar('BPN')
597*4882a593Smuzhiyun    recipefn = os.path.basename(d.getVar('FILE'))
598*4882a593Smuzhiyun    pathoptions = [destdir]
599*4882a593Smuzhiyun    if extrapathhint:
600*4882a593Smuzhiyun        pathoptions.append(os.path.join(destdir, extrapathhint))
601*4882a593Smuzhiyun    if destdir == destlayerdir:
602*4882a593Smuzhiyun        pathoptions.append(os.path.join(destdir, 'recipes-%s' % bpn, bpn))
603*4882a593Smuzhiyun        pathoptions.append(os.path.join(destdir, 'recipes', bpn))
604*4882a593Smuzhiyun        pathoptions.append(os.path.join(destdir, bpn))
605*4882a593Smuzhiyun    elif not destdir.endswith(('/' + pn, '/' + bpn)):
606*4882a593Smuzhiyun        pathoptions.append(os.path.join(destdir, bpn))
607*4882a593Smuzhiyun    closepath = ''
608*4882a593Smuzhiyun    for pathoption in pathoptions:
609*4882a593Smuzhiyun        bbfilepath = os.path.join(pathoption, 'test.bb')
610*4882a593Smuzhiyun        for bbfilespec in bbfilespecs:
611*4882a593Smuzhiyun            if fnmatch.fnmatchcase(bbfilepath, bbfilespec):
612*4882a593Smuzhiyun                return pathoption
613*4882a593Smuzhiyun    return None
614*4882a593Smuzhiyun
615*4882a593Smuzhiyundef get_bbappend_path(d, destlayerdir, wildcardver=False):
616*4882a593Smuzhiyun    """Determine how a bbappend for a recipe should be named and located within another layer"""
617*4882a593Smuzhiyun
618*4882a593Smuzhiyun    import bb.cookerdata
619*4882a593Smuzhiyun
620*4882a593Smuzhiyun    destlayerdir = os.path.abspath(destlayerdir)
621*4882a593Smuzhiyun    recipefile = d.getVar('FILE')
622*4882a593Smuzhiyun    recipefn = os.path.splitext(os.path.basename(recipefile))[0]
623*4882a593Smuzhiyun    if wildcardver and '_' in recipefn:
624*4882a593Smuzhiyun        recipefn = recipefn.split('_', 1)[0] + '_%'
625*4882a593Smuzhiyun    appendfn = recipefn + '.bbappend'
626*4882a593Smuzhiyun
627*4882a593Smuzhiyun    # Parse the specified layer's layer.conf file directly, in case the layer isn't in bblayers.conf
628*4882a593Smuzhiyun    confdata = d.createCopy()
629*4882a593Smuzhiyun    confdata.setVar('BBFILES', '')
630*4882a593Smuzhiyun    confdata.setVar('LAYERDIR', destlayerdir)
631*4882a593Smuzhiyun    destlayerconf = os.path.join(destlayerdir, "conf", "layer.conf")
632*4882a593Smuzhiyun    confdata = bb.cookerdata.parse_config_file(destlayerconf, confdata)
633*4882a593Smuzhiyun
634*4882a593Smuzhiyun    origlayerdir = find_layerdir(recipefile)
635*4882a593Smuzhiyun    if not origlayerdir:
636*4882a593Smuzhiyun        return (None, False)
637*4882a593Smuzhiyun    # Now join this to the path where the bbappend is going and check if it is covered by BBFILES
638*4882a593Smuzhiyun    appendpath = os.path.join(destlayerdir, os.path.relpath(os.path.dirname(recipefile), origlayerdir), appendfn)
639*4882a593Smuzhiyun    closepath = ''
640*4882a593Smuzhiyun    pathok = True
641*4882a593Smuzhiyun    for bbfilespec in confdata.getVar('BBFILES').split():
642*4882a593Smuzhiyun        if fnmatch.fnmatchcase(appendpath, bbfilespec):
643*4882a593Smuzhiyun            # Our append path works, we're done
644*4882a593Smuzhiyun            break
645*4882a593Smuzhiyun        elif bbfilespec.startswith(destlayerdir) and fnmatch.fnmatchcase('test.bbappend', os.path.basename(bbfilespec)):
646*4882a593Smuzhiyun            # Try to find the longest matching path
647*4882a593Smuzhiyun            if len(bbfilespec) > len(closepath):
648*4882a593Smuzhiyun                closepath = bbfilespec
649*4882a593Smuzhiyun    else:
650*4882a593Smuzhiyun        # Unfortunately the bbappend layer and the original recipe's layer don't have the same structure
651*4882a593Smuzhiyun        if closepath:
652*4882a593Smuzhiyun            # bbappend layer's layer.conf at least has a spec that picks up .bbappend files
653*4882a593Smuzhiyun            # Now we just need to substitute out any wildcards
654*4882a593Smuzhiyun            appendsubdir = os.path.relpath(os.path.dirname(closepath), destlayerdir)
655*4882a593Smuzhiyun            if 'recipes-*' in appendsubdir:
656*4882a593Smuzhiyun                # Try to copy this part from the original recipe path
657*4882a593Smuzhiyun                res = re.search('/recipes-[^/]+/', recipefile)
658*4882a593Smuzhiyun                if res:
659*4882a593Smuzhiyun                    appendsubdir = appendsubdir.replace('/recipes-*/', res.group(0))
660*4882a593Smuzhiyun            # This is crude, but we have to do something
661*4882a593Smuzhiyun            appendsubdir = appendsubdir.replace('*', recipefn.split('_')[0])
662*4882a593Smuzhiyun            appendsubdir = appendsubdir.replace('?', 'a')
663*4882a593Smuzhiyun            appendpath = os.path.join(destlayerdir, appendsubdir, appendfn)
664*4882a593Smuzhiyun        else:
665*4882a593Smuzhiyun            pathok = False
666*4882a593Smuzhiyun    return (appendpath, pathok)
667*4882a593Smuzhiyun
668*4882a593Smuzhiyun
669*4882a593Smuzhiyundef bbappend_recipe(rd, destlayerdir, srcfiles, install=None, wildcardver=False, machine=None, extralines=None, removevalues=None, redirect_output=None, params=None):
670*4882a593Smuzhiyun    """
671*4882a593Smuzhiyun    Writes a bbappend file for a recipe
672*4882a593Smuzhiyun    Parameters:
673*4882a593Smuzhiyun        rd: data dictionary for the recipe
674*4882a593Smuzhiyun        destlayerdir: base directory of the layer to place the bbappend in
675*4882a593Smuzhiyun            (subdirectory path from there will be determined automatically)
676*4882a593Smuzhiyun        srcfiles: dict of source files to add to SRC_URI, where the value
677*4882a593Smuzhiyun            is the full path to the file to be added, and the value is the
678*4882a593Smuzhiyun            original filename as it would appear in SRC_URI or None if it
679*4882a593Smuzhiyun            isn't already present. You may pass None for this parameter if
680*4882a593Smuzhiyun            you simply want to specify your own content via the extralines
681*4882a593Smuzhiyun            parameter.
682*4882a593Smuzhiyun        install: dict mapping entries in srcfiles to a tuple of two elements:
683*4882a593Smuzhiyun            install path (*without* ${D} prefix) and permission value (as a
684*4882a593Smuzhiyun            string, e.g. '0644').
685*4882a593Smuzhiyun        wildcardver: True to use a % wildcard in the bbappend filename, or
686*4882a593Smuzhiyun            False to make the bbappend specific to the recipe version.
687*4882a593Smuzhiyun        machine:
688*4882a593Smuzhiyun            If specified, make the changes in the bbappend specific to this
689*4882a593Smuzhiyun            machine. This will also cause PACKAGE_ARCH = "${MACHINE_ARCH}"
690*4882a593Smuzhiyun            to be added to the bbappend.
691*4882a593Smuzhiyun        extralines:
692*4882a593Smuzhiyun            Extra lines to add to the bbappend. This may be a dict of name
693*4882a593Smuzhiyun            value pairs, or simply a list of the lines.
694*4882a593Smuzhiyun        removevalues:
695*4882a593Smuzhiyun            Variable values to remove - a dict of names/values.
696*4882a593Smuzhiyun        redirect_output:
697*4882a593Smuzhiyun            If specified, redirects writing the output file to the
698*4882a593Smuzhiyun            specified directory (for dry-run purposes)
699*4882a593Smuzhiyun        params:
700*4882a593Smuzhiyun            Parameters to use when adding entries to SRC_URI. If specified,
701*4882a593Smuzhiyun            should be a list of dicts with the same length as srcfiles.
702*4882a593Smuzhiyun    """
703*4882a593Smuzhiyun
704*4882a593Smuzhiyun    if not removevalues:
705*4882a593Smuzhiyun        removevalues = {}
706*4882a593Smuzhiyun
707*4882a593Smuzhiyun    # Determine how the bbappend should be named
708*4882a593Smuzhiyun    appendpath, pathok = get_bbappend_path(rd, destlayerdir, wildcardver)
709*4882a593Smuzhiyun    if not appendpath:
710*4882a593Smuzhiyun        bb.error('Unable to determine layer directory containing %s' % recipefile)
711*4882a593Smuzhiyun        return (None, None)
712*4882a593Smuzhiyun    if not pathok:
713*4882a593Smuzhiyun        bb.warn('Unable to determine correct subdirectory path for bbappend file - check that what %s adds to BBFILES also matches .bbappend files. Using %s for now, but until you fix this the bbappend will not be applied.' % (os.path.join(destlayerdir, 'conf', 'layer.conf'), os.path.dirname(appendpath)))
714*4882a593Smuzhiyun
715*4882a593Smuzhiyun    appenddir = os.path.dirname(appendpath)
716*4882a593Smuzhiyun    if not redirect_output:
717*4882a593Smuzhiyun        bb.utils.mkdirhier(appenddir)
718*4882a593Smuzhiyun
719*4882a593Smuzhiyun    # FIXME check if the bbappend doesn't get overridden by a higher priority layer?
720*4882a593Smuzhiyun
721*4882a593Smuzhiyun    layerdirs = [os.path.abspath(layerdir) for layerdir in rd.getVar('BBLAYERS').split()]
722*4882a593Smuzhiyun    if not os.path.abspath(destlayerdir) in layerdirs:
723*4882a593Smuzhiyun        bb.warn('Specified layer is not currently enabled in bblayers.conf, you will need to add it before this bbappend will be active')
724*4882a593Smuzhiyun
725*4882a593Smuzhiyun    bbappendlines = []
726*4882a593Smuzhiyun    if extralines:
727*4882a593Smuzhiyun        if isinstance(extralines, dict):
728*4882a593Smuzhiyun            for name, value in extralines.items():
729*4882a593Smuzhiyun                bbappendlines.append((name, '=', value))
730*4882a593Smuzhiyun        else:
731*4882a593Smuzhiyun            # Do our best to split it
732*4882a593Smuzhiyun            for line in extralines:
733*4882a593Smuzhiyun                if line[-1] == '\n':
734*4882a593Smuzhiyun                    line = line[:-1]
735*4882a593Smuzhiyun                splitline = line.split(None, 2)
736*4882a593Smuzhiyun                if len(splitline) == 3:
737*4882a593Smuzhiyun                    bbappendlines.append(tuple(splitline))
738*4882a593Smuzhiyun                else:
739*4882a593Smuzhiyun                    raise Exception('Invalid extralines value passed')
740*4882a593Smuzhiyun
741*4882a593Smuzhiyun    def popline(varname):
742*4882a593Smuzhiyun        for i in range(0, len(bbappendlines)):
743*4882a593Smuzhiyun            if bbappendlines[i][0] == varname:
744*4882a593Smuzhiyun                line = bbappendlines.pop(i)
745*4882a593Smuzhiyun                return line
746*4882a593Smuzhiyun        return None
747*4882a593Smuzhiyun
748*4882a593Smuzhiyun    def appendline(varname, op, value):
749*4882a593Smuzhiyun        for i in range(0, len(bbappendlines)):
750*4882a593Smuzhiyun            item = bbappendlines[i]
751*4882a593Smuzhiyun            if item[0] == varname:
752*4882a593Smuzhiyun                bbappendlines[i] = (item[0], item[1], item[2] + ' ' + value)
753*4882a593Smuzhiyun                break
754*4882a593Smuzhiyun        else:
755*4882a593Smuzhiyun            bbappendlines.append((varname, op, value))
756*4882a593Smuzhiyun
757*4882a593Smuzhiyun    destsubdir = rd.getVar('PN')
758*4882a593Smuzhiyun    if srcfiles:
759*4882a593Smuzhiyun        bbappendlines.append(('FILESEXTRAPATHS:prepend', ':=', '${THISDIR}/${PN}:'))
760*4882a593Smuzhiyun
761*4882a593Smuzhiyun    appendoverride = ''
762*4882a593Smuzhiyun    if machine:
763*4882a593Smuzhiyun        bbappendlines.append(('PACKAGE_ARCH', '=', '${MACHINE_ARCH}'))
764*4882a593Smuzhiyun        appendoverride = ':%s' % machine
765*4882a593Smuzhiyun    copyfiles = {}
766*4882a593Smuzhiyun    if srcfiles:
767*4882a593Smuzhiyun        instfunclines = []
768*4882a593Smuzhiyun        for i, (newfile, origsrcfile) in enumerate(srcfiles.items()):
769*4882a593Smuzhiyun            srcfile = origsrcfile
770*4882a593Smuzhiyun            srcurientry = None
771*4882a593Smuzhiyun            if not srcfile:
772*4882a593Smuzhiyun                srcfile = os.path.basename(newfile)
773*4882a593Smuzhiyun                srcurientry = 'file://%s' % srcfile
774*4882a593Smuzhiyun                if params and params[i]:
775*4882a593Smuzhiyun                    srcurientry = '%s;%s' % (srcurientry, ';'.join('%s=%s' % (k,v) for k,v in params[i].items()))
776*4882a593Smuzhiyun                # Double-check it's not there already
777*4882a593Smuzhiyun                # FIXME do we care if the entry is added by another bbappend that might go away?
778*4882a593Smuzhiyun                if not srcurientry in rd.getVar('SRC_URI').split():
779*4882a593Smuzhiyun                    if machine:
780*4882a593Smuzhiyun                        appendline('SRC_URI:append%s' % appendoverride, '=', ' ' + srcurientry)
781*4882a593Smuzhiyun                    else:
782*4882a593Smuzhiyun                        appendline('SRC_URI', '+=', srcurientry)
783*4882a593Smuzhiyun            copyfiles[newfile] = srcfile
784*4882a593Smuzhiyun            if install:
785*4882a593Smuzhiyun                institem = install.pop(newfile, None)
786*4882a593Smuzhiyun                if institem:
787*4882a593Smuzhiyun                    (destpath, perms) = institem
788*4882a593Smuzhiyun                    instdestpath = replace_dir_vars(destpath, rd)
789*4882a593Smuzhiyun                    instdirline = 'install -d ${D}%s' % os.path.dirname(instdestpath)
790*4882a593Smuzhiyun                    if not instdirline in instfunclines:
791*4882a593Smuzhiyun                        instfunclines.append(instdirline)
792*4882a593Smuzhiyun                    instfunclines.append('install -m %s ${WORKDIR}/%s ${D}%s' % (perms, os.path.basename(srcfile), instdestpath))
793*4882a593Smuzhiyun        if instfunclines:
794*4882a593Smuzhiyun            bbappendlines.append(('do_install:append%s()' % appendoverride, '', instfunclines))
795*4882a593Smuzhiyun
796*4882a593Smuzhiyun    if redirect_output:
797*4882a593Smuzhiyun        bb.note('Writing append file %s (dry-run)' % appendpath)
798*4882a593Smuzhiyun        outfile = os.path.join(redirect_output, os.path.basename(appendpath))
799*4882a593Smuzhiyun        # Only take a copy if the file isn't already there (this function may be called
800*4882a593Smuzhiyun        # multiple times per operation when we're handling overrides)
801*4882a593Smuzhiyun        if os.path.exists(appendpath) and not os.path.exists(outfile):
802*4882a593Smuzhiyun            shutil.copy2(appendpath, outfile)
803*4882a593Smuzhiyun    else:
804*4882a593Smuzhiyun        bb.note('Writing append file %s' % appendpath)
805*4882a593Smuzhiyun        outfile = appendpath
806*4882a593Smuzhiyun
807*4882a593Smuzhiyun    if os.path.exists(outfile):
808*4882a593Smuzhiyun        # Work around lack of nonlocal in python 2
809*4882a593Smuzhiyun        extvars = {'destsubdir': destsubdir}
810*4882a593Smuzhiyun
811*4882a593Smuzhiyun        def appendfile_varfunc(varname, origvalue, op, newlines):
812*4882a593Smuzhiyun            if varname == 'FILESEXTRAPATHS:prepend':
813*4882a593Smuzhiyun                if origvalue.startswith('${THISDIR}/'):
814*4882a593Smuzhiyun                    popline('FILESEXTRAPATHS:prepend')
815*4882a593Smuzhiyun                    extvars['destsubdir'] = rd.expand(origvalue.split('${THISDIR}/', 1)[1].rstrip(':'))
816*4882a593Smuzhiyun            elif varname == 'PACKAGE_ARCH':
817*4882a593Smuzhiyun                if machine:
818*4882a593Smuzhiyun                    popline('PACKAGE_ARCH')
819*4882a593Smuzhiyun                    return (machine, None, 4, False)
820*4882a593Smuzhiyun            elif varname.startswith('do_install:append'):
821*4882a593Smuzhiyun                func = popline(varname)
822*4882a593Smuzhiyun                if func:
823*4882a593Smuzhiyun                    instfunclines = [line.strip() for line in origvalue.strip('\n').splitlines()]
824*4882a593Smuzhiyun                    for line in func[2]:
825*4882a593Smuzhiyun                        if not line in instfunclines:
826*4882a593Smuzhiyun                            instfunclines.append(line)
827*4882a593Smuzhiyun                    return (instfunclines, None, 4, False)
828*4882a593Smuzhiyun            else:
829*4882a593Smuzhiyun                splitval = split_var_value(origvalue, assignment=False)
830*4882a593Smuzhiyun                changed = False
831*4882a593Smuzhiyun                removevar = varname
832*4882a593Smuzhiyun                if varname in ['SRC_URI', 'SRC_URI:append%s' % appendoverride]:
833*4882a593Smuzhiyun                    removevar = 'SRC_URI'
834*4882a593Smuzhiyun                    line = popline(varname)
835*4882a593Smuzhiyun                    if line:
836*4882a593Smuzhiyun                        if line[2] not in splitval:
837*4882a593Smuzhiyun                            splitval.append(line[2])
838*4882a593Smuzhiyun                            changed = True
839*4882a593Smuzhiyun                else:
840*4882a593Smuzhiyun                    line = popline(varname)
841*4882a593Smuzhiyun                    if line:
842*4882a593Smuzhiyun                        splitval = [line[2]]
843*4882a593Smuzhiyun                        changed = True
844*4882a593Smuzhiyun
845*4882a593Smuzhiyun                if removevar in removevalues:
846*4882a593Smuzhiyun                    remove = removevalues[removevar]
847*4882a593Smuzhiyun                    if isinstance(remove, str):
848*4882a593Smuzhiyun                        if remove in splitval:
849*4882a593Smuzhiyun                            splitval.remove(remove)
850*4882a593Smuzhiyun                            changed = True
851*4882a593Smuzhiyun                    else:
852*4882a593Smuzhiyun                        for removeitem in remove:
853*4882a593Smuzhiyun                            if removeitem in splitval:
854*4882a593Smuzhiyun                                splitval.remove(removeitem)
855*4882a593Smuzhiyun                                changed = True
856*4882a593Smuzhiyun
857*4882a593Smuzhiyun                if changed:
858*4882a593Smuzhiyun                    newvalue = splitval
859*4882a593Smuzhiyun                    if len(newvalue) == 1:
860*4882a593Smuzhiyun                        # Ensure it's written out as one line
861*4882a593Smuzhiyun                        if ':append' in varname:
862*4882a593Smuzhiyun                            newvalue = ' ' + newvalue[0]
863*4882a593Smuzhiyun                        else:
864*4882a593Smuzhiyun                            newvalue = newvalue[0]
865*4882a593Smuzhiyun                    if not newvalue and (op in ['+=', '.='] or ':append' in varname):
866*4882a593Smuzhiyun                        # There's no point appending nothing
867*4882a593Smuzhiyun                        newvalue = None
868*4882a593Smuzhiyun                    if varname.endswith('()'):
869*4882a593Smuzhiyun                        indent = 4
870*4882a593Smuzhiyun                    else:
871*4882a593Smuzhiyun                        indent = -1
872*4882a593Smuzhiyun                    return (newvalue, None, indent, True)
873*4882a593Smuzhiyun            return (origvalue, None, 4, False)
874*4882a593Smuzhiyun
875*4882a593Smuzhiyun        varnames = [item[0] for item in bbappendlines]
876*4882a593Smuzhiyun        if removevalues:
877*4882a593Smuzhiyun            varnames.extend(list(removevalues.keys()))
878*4882a593Smuzhiyun
879*4882a593Smuzhiyun        with open(outfile, 'r') as f:
880*4882a593Smuzhiyun            (updated, newlines) = bb.utils.edit_metadata(f, varnames, appendfile_varfunc)
881*4882a593Smuzhiyun
882*4882a593Smuzhiyun        destsubdir = extvars['destsubdir']
883*4882a593Smuzhiyun    else:
884*4882a593Smuzhiyun        updated = False
885*4882a593Smuzhiyun        newlines = []
886*4882a593Smuzhiyun
887*4882a593Smuzhiyun    if bbappendlines:
888*4882a593Smuzhiyun        for line in bbappendlines:
889*4882a593Smuzhiyun            if line[0].endswith('()'):
890*4882a593Smuzhiyun                newlines.append('%s {\n    %s\n}\n' % (line[0], '\n    '.join(line[2])))
891*4882a593Smuzhiyun            else:
892*4882a593Smuzhiyun                newlines.append('%s %s "%s"\n\n' % line)
893*4882a593Smuzhiyun        updated = True
894*4882a593Smuzhiyun
895*4882a593Smuzhiyun    if updated:
896*4882a593Smuzhiyun        with open(outfile, 'w') as f:
897*4882a593Smuzhiyun            f.writelines(newlines)
898*4882a593Smuzhiyun
899*4882a593Smuzhiyun    if copyfiles:
900*4882a593Smuzhiyun        if machine:
901*4882a593Smuzhiyun            destsubdir = os.path.join(destsubdir, machine)
902*4882a593Smuzhiyun        if redirect_output:
903*4882a593Smuzhiyun            outdir = redirect_output
904*4882a593Smuzhiyun        else:
905*4882a593Smuzhiyun            outdir = appenddir
906*4882a593Smuzhiyun        for newfile, srcfile in copyfiles.items():
907*4882a593Smuzhiyun            filedest = os.path.join(outdir, destsubdir, os.path.basename(srcfile))
908*4882a593Smuzhiyun            if os.path.abspath(newfile) != os.path.abspath(filedest):
909*4882a593Smuzhiyun                if newfile.startswith(tempfile.gettempdir()):
910*4882a593Smuzhiyun                    newfiledisp = os.path.basename(newfile)
911*4882a593Smuzhiyun                else:
912*4882a593Smuzhiyun                    newfiledisp = newfile
913*4882a593Smuzhiyun                if redirect_output:
914*4882a593Smuzhiyun                    bb.note('Copying %s to %s (dry-run)' % (newfiledisp, os.path.join(appenddir, destsubdir, os.path.basename(srcfile))))
915*4882a593Smuzhiyun                else:
916*4882a593Smuzhiyun                    bb.note('Copying %s to %s' % (newfiledisp, filedest))
917*4882a593Smuzhiyun                bb.utils.mkdirhier(os.path.dirname(filedest))
918*4882a593Smuzhiyun                shutil.copyfile(newfile, filedest)
919*4882a593Smuzhiyun
920*4882a593Smuzhiyun    return (appendpath, os.path.join(appenddir, destsubdir))
921*4882a593Smuzhiyun
922*4882a593Smuzhiyun
923*4882a593Smuzhiyundef find_layerdir(fn):
924*4882a593Smuzhiyun    """ Figure out the path to the base of the layer containing a file (e.g. a recipe)"""
925*4882a593Smuzhiyun    pth = os.path.abspath(fn)
926*4882a593Smuzhiyun    layerdir = ''
927*4882a593Smuzhiyun    while pth:
928*4882a593Smuzhiyun        if os.path.exists(os.path.join(pth, 'conf', 'layer.conf')):
929*4882a593Smuzhiyun            layerdir = pth
930*4882a593Smuzhiyun            break
931*4882a593Smuzhiyun        pth = os.path.dirname(pth)
932*4882a593Smuzhiyun        if pth == '/':
933*4882a593Smuzhiyun            return None
934*4882a593Smuzhiyun    return layerdir
935*4882a593Smuzhiyun
936*4882a593Smuzhiyun
937*4882a593Smuzhiyundef replace_dir_vars(path, d):
938*4882a593Smuzhiyun    """Replace common directory paths with appropriate variable references (e.g. /etc becomes ${sysconfdir})"""
939*4882a593Smuzhiyun    dirvars = {}
940*4882a593Smuzhiyun    # Sort by length so we get the variables we're interested in first
941*4882a593Smuzhiyun    for var in sorted(list(d.keys()), key=len):
942*4882a593Smuzhiyun        if var.endswith('dir') and var.lower() == var:
943*4882a593Smuzhiyun            value = d.getVar(var)
944*4882a593Smuzhiyun            if value.startswith('/') and not '\n' in value and value not in dirvars:
945*4882a593Smuzhiyun                dirvars[value] = var
946*4882a593Smuzhiyun    for dirpath in sorted(list(dirvars.keys()), reverse=True):
947*4882a593Smuzhiyun        path = path.replace(dirpath, '${%s}' % dirvars[dirpath])
948*4882a593Smuzhiyun    return path
949*4882a593Smuzhiyun
950*4882a593Smuzhiyundef get_recipe_pv_without_srcpv(pv, uri_type):
951*4882a593Smuzhiyun    """
952*4882a593Smuzhiyun    Get PV without SRCPV common in SCM's for now only
953*4882a593Smuzhiyun    support git.
954*4882a593Smuzhiyun
955*4882a593Smuzhiyun    Returns tuple with pv, prefix and suffix.
956*4882a593Smuzhiyun    """
957*4882a593Smuzhiyun    pfx = ''
958*4882a593Smuzhiyun    sfx = ''
959*4882a593Smuzhiyun
960*4882a593Smuzhiyun    if uri_type == 'git':
961*4882a593Smuzhiyun        git_regex = re.compile(r"(?P<pfx>v?)(?P<ver>.*?)(?P<sfx>\+[^\+]*(git)?r?(AUTOINC\+))(?P<rev>.*)")
962*4882a593Smuzhiyun        m = git_regex.match(pv)
963*4882a593Smuzhiyun
964*4882a593Smuzhiyun        if m:
965*4882a593Smuzhiyun            pv = m.group('ver')
966*4882a593Smuzhiyun            pfx = m.group('pfx')
967*4882a593Smuzhiyun            sfx = m.group('sfx')
968*4882a593Smuzhiyun    else:
969*4882a593Smuzhiyun        regex = re.compile(r"(?P<pfx>(v|r)?)(?P<ver>.*)")
970*4882a593Smuzhiyun        m = regex.match(pv)
971*4882a593Smuzhiyun        if m:
972*4882a593Smuzhiyun            pv = m.group('ver')
973*4882a593Smuzhiyun            pfx = m.group('pfx')
974*4882a593Smuzhiyun
975*4882a593Smuzhiyun    return (pv, pfx, sfx)
976*4882a593Smuzhiyun
977*4882a593Smuzhiyundef get_recipe_upstream_version(rd):
978*4882a593Smuzhiyun    """
979*4882a593Smuzhiyun        Get upstream version of recipe using bb.fetch2 methods with support for
980*4882a593Smuzhiyun        http, https, ftp and git.
981*4882a593Smuzhiyun
982*4882a593Smuzhiyun        bb.fetch2 exceptions can be raised,
983*4882a593Smuzhiyun            FetchError when don't have network access or upstream site don't response.
984*4882a593Smuzhiyun            NoMethodError when uri latest_versionstring method isn't implemented.
985*4882a593Smuzhiyun
986*4882a593Smuzhiyun        Returns a dictonary with version, repository revision, current_version, type and datetime.
987*4882a593Smuzhiyun        Type can be A for Automatic, M for Manual and U for Unknown.
988*4882a593Smuzhiyun    """
989*4882a593Smuzhiyun    from bb.fetch2 import decodeurl
990*4882a593Smuzhiyun    from datetime import datetime
991*4882a593Smuzhiyun
992*4882a593Smuzhiyun    ru = {}
993*4882a593Smuzhiyun    ru['current_version'] = rd.getVar('PV')
994*4882a593Smuzhiyun    ru['version'] = ''
995*4882a593Smuzhiyun    ru['type'] = 'U'
996*4882a593Smuzhiyun    ru['datetime'] = ''
997*4882a593Smuzhiyun    ru['revision'] = ''
998*4882a593Smuzhiyun
999*4882a593Smuzhiyun    # XXX: If don't have SRC_URI means that don't have upstream sources so
1000*4882a593Smuzhiyun    # returns the current recipe version, so that upstream version check
1001*4882a593Smuzhiyun    # declares a match.
1002*4882a593Smuzhiyun    src_uris = rd.getVar('SRC_URI')
1003*4882a593Smuzhiyun    if not src_uris:
1004*4882a593Smuzhiyun        ru['version'] = ru['current_version']
1005*4882a593Smuzhiyun        ru['type'] = 'M'
1006*4882a593Smuzhiyun        ru['datetime'] = datetime.now()
1007*4882a593Smuzhiyun        return ru
1008*4882a593Smuzhiyun
1009*4882a593Smuzhiyun    # XXX: we suppose that the first entry points to the upstream sources
1010*4882a593Smuzhiyun    src_uri = src_uris.split()[0]
1011*4882a593Smuzhiyun    uri_type, _, _, _, _, _ =  decodeurl(src_uri)
1012*4882a593Smuzhiyun
1013*4882a593Smuzhiyun    (pv, pfx, sfx) = get_recipe_pv_without_srcpv(rd.getVar('PV'), uri_type)
1014*4882a593Smuzhiyun    ru['current_version'] = pv
1015*4882a593Smuzhiyun
1016*4882a593Smuzhiyun    manual_upstream_version = rd.getVar("RECIPE_UPSTREAM_VERSION")
1017*4882a593Smuzhiyun    if manual_upstream_version:
1018*4882a593Smuzhiyun        # manual tracking of upstream version.
1019*4882a593Smuzhiyun        ru['version'] = manual_upstream_version
1020*4882a593Smuzhiyun        ru['type'] = 'M'
1021*4882a593Smuzhiyun
1022*4882a593Smuzhiyun        manual_upstream_date = rd.getVar("CHECK_DATE")
1023*4882a593Smuzhiyun        if manual_upstream_date:
1024*4882a593Smuzhiyun            date = datetime.strptime(manual_upstream_date, "%b %d, %Y")
1025*4882a593Smuzhiyun        else:
1026*4882a593Smuzhiyun            date = datetime.now()
1027*4882a593Smuzhiyun        ru['datetime'] = date
1028*4882a593Smuzhiyun
1029*4882a593Smuzhiyun    elif uri_type == "file":
1030*4882a593Smuzhiyun        # files are always up-to-date
1031*4882a593Smuzhiyun        ru['version'] =  pv
1032*4882a593Smuzhiyun        ru['type'] = 'A'
1033*4882a593Smuzhiyun        ru['datetime'] = datetime.now()
1034*4882a593Smuzhiyun    else:
1035*4882a593Smuzhiyun        ud = bb.fetch2.FetchData(src_uri, rd)
1036*4882a593Smuzhiyun        if rd.getVar("UPSTREAM_CHECK_COMMITS") == "1":
1037*4882a593Smuzhiyun            bb.fetch2.get_srcrev(rd)
1038*4882a593Smuzhiyun            revision = ud.method.latest_revision(ud, rd, 'default')
1039*4882a593Smuzhiyun            upversion = pv
1040*4882a593Smuzhiyun            if revision != rd.getVar("SRCREV"):
1041*4882a593Smuzhiyun                upversion = upversion + "-new-commits-available"
1042*4882a593Smuzhiyun        else:
1043*4882a593Smuzhiyun            pupver = ud.method.latest_versionstring(ud, rd)
1044*4882a593Smuzhiyun            (upversion, revision) = pupver
1045*4882a593Smuzhiyun
1046*4882a593Smuzhiyun        if upversion:
1047*4882a593Smuzhiyun            ru['version'] = upversion
1048*4882a593Smuzhiyun            ru['type'] = 'A'
1049*4882a593Smuzhiyun
1050*4882a593Smuzhiyun        if revision:
1051*4882a593Smuzhiyun            ru['revision'] = revision
1052*4882a593Smuzhiyun
1053*4882a593Smuzhiyun        ru['datetime'] = datetime.now()
1054*4882a593Smuzhiyun
1055*4882a593Smuzhiyun    return ru
1056*4882a593Smuzhiyun
1057*4882a593Smuzhiyundef _get_recipe_upgrade_status(data):
1058*4882a593Smuzhiyun    uv = get_recipe_upstream_version(data)
1059*4882a593Smuzhiyun
1060*4882a593Smuzhiyun    pn = data.getVar('PN')
1061*4882a593Smuzhiyun    cur_ver = uv['current_version']
1062*4882a593Smuzhiyun
1063*4882a593Smuzhiyun    upstream_version_unknown = data.getVar('UPSTREAM_VERSION_UNKNOWN')
1064*4882a593Smuzhiyun    if not uv['version']:
1065*4882a593Smuzhiyun        status = "UNKNOWN" if upstream_version_unknown else "UNKNOWN_BROKEN"
1066*4882a593Smuzhiyun    else:
1067*4882a593Smuzhiyun        cmp = vercmp_string(uv['current_version'], uv['version'])
1068*4882a593Smuzhiyun        if cmp == -1:
1069*4882a593Smuzhiyun            status = "UPDATE" if not upstream_version_unknown else "KNOWN_BROKEN"
1070*4882a593Smuzhiyun        elif cmp == 0:
1071*4882a593Smuzhiyun            status = "MATCH" if not upstream_version_unknown else "KNOWN_BROKEN"
1072*4882a593Smuzhiyun        else:
1073*4882a593Smuzhiyun            status = "UNKNOWN" if upstream_version_unknown else "UNKNOWN_BROKEN"
1074*4882a593Smuzhiyun
1075*4882a593Smuzhiyun    next_ver = uv['version'] if uv['version'] else "N/A"
1076*4882a593Smuzhiyun    revision = uv['revision'] if uv['revision'] else "N/A"
1077*4882a593Smuzhiyun    maintainer = data.getVar('RECIPE_MAINTAINER')
1078*4882a593Smuzhiyun    no_upgrade_reason = data.getVar('RECIPE_NO_UPDATE_REASON')
1079*4882a593Smuzhiyun
1080*4882a593Smuzhiyun    return (pn, status, cur_ver, next_ver, maintainer, revision, no_upgrade_reason)
1081*4882a593Smuzhiyun
1082*4882a593Smuzhiyundef get_recipe_upgrade_status(recipes=None):
1083*4882a593Smuzhiyun    pkgs_list = []
1084*4882a593Smuzhiyun    data_copy_list = []
1085*4882a593Smuzhiyun    copy_vars = ('SRC_URI',
1086*4882a593Smuzhiyun                 'PV',
1087*4882a593Smuzhiyun                 'DL_DIR',
1088*4882a593Smuzhiyun                 'PN',
1089*4882a593Smuzhiyun                 'CACHE',
1090*4882a593Smuzhiyun                 'PERSISTENT_DIR',
1091*4882a593Smuzhiyun                 'BB_URI_HEADREVS',
1092*4882a593Smuzhiyun                 'UPSTREAM_CHECK_COMMITS',
1093*4882a593Smuzhiyun                 'UPSTREAM_CHECK_GITTAGREGEX',
1094*4882a593Smuzhiyun                 'UPSTREAM_CHECK_REGEX',
1095*4882a593Smuzhiyun                 'UPSTREAM_CHECK_URI',
1096*4882a593Smuzhiyun                 'UPSTREAM_VERSION_UNKNOWN',
1097*4882a593Smuzhiyun                 'RECIPE_MAINTAINER',
1098*4882a593Smuzhiyun                 'RECIPE_NO_UPDATE_REASON',
1099*4882a593Smuzhiyun                 'RECIPE_UPSTREAM_VERSION',
1100*4882a593Smuzhiyun                 'RECIPE_UPSTREAM_DATE',
1101*4882a593Smuzhiyun                 'CHECK_DATE',
1102*4882a593Smuzhiyun                 'FETCHCMD_bzr',
1103*4882a593Smuzhiyun                 'FETCHCMD_ccrc',
1104*4882a593Smuzhiyun                 'FETCHCMD_cvs',
1105*4882a593Smuzhiyun                 'FETCHCMD_git',
1106*4882a593Smuzhiyun                 'FETCHCMD_hg',
1107*4882a593Smuzhiyun                 'FETCHCMD_npm',
1108*4882a593Smuzhiyun                 'FETCHCMD_osc',
1109*4882a593Smuzhiyun                 'FETCHCMD_p4',
1110*4882a593Smuzhiyun                 'FETCHCMD_repo',
1111*4882a593Smuzhiyun                 'FETCHCMD_s3',
1112*4882a593Smuzhiyun                 'FETCHCMD_svn',
1113*4882a593Smuzhiyun                 'FETCHCMD_wget',
1114*4882a593Smuzhiyun            )
1115*4882a593Smuzhiyun
1116*4882a593Smuzhiyun    with bb.tinfoil.Tinfoil() as tinfoil:
1117*4882a593Smuzhiyun        tinfoil.prepare(config_only=False)
1118*4882a593Smuzhiyun
1119*4882a593Smuzhiyun        if not recipes:
1120*4882a593Smuzhiyun            recipes = tinfoil.all_recipe_files(variants=False)
1121*4882a593Smuzhiyun
1122*4882a593Smuzhiyun        for fn in recipes:
1123*4882a593Smuzhiyun            try:
1124*4882a593Smuzhiyun                if fn.startswith("/"):
1125*4882a593Smuzhiyun                    data = tinfoil.parse_recipe_file(fn)
1126*4882a593Smuzhiyun                else:
1127*4882a593Smuzhiyun                    data = tinfoil.parse_recipe(fn)
1128*4882a593Smuzhiyun            except bb.providers.NoProvider:
1129*4882a593Smuzhiyun                bb.note(" No provider for %s" % fn)
1130*4882a593Smuzhiyun                continue
1131*4882a593Smuzhiyun
1132*4882a593Smuzhiyun            unreliable = data.getVar('UPSTREAM_CHECK_UNRELIABLE')
1133*4882a593Smuzhiyun            if unreliable == "1":
1134*4882a593Smuzhiyun                bb.note(" Skip package %s as upstream check unreliable" % pn)
1135*4882a593Smuzhiyun                continue
1136*4882a593Smuzhiyun
1137*4882a593Smuzhiyun            data_copy = bb.data.init()
1138*4882a593Smuzhiyun            for var in copy_vars:
1139*4882a593Smuzhiyun                data_copy.setVar(var, data.getVar(var))
1140*4882a593Smuzhiyun            for k in data:
1141*4882a593Smuzhiyun                if k.startswith('SRCREV'):
1142*4882a593Smuzhiyun                    data_copy.setVar(k, data.getVar(k))
1143*4882a593Smuzhiyun
1144*4882a593Smuzhiyun            data_copy_list.append(data_copy)
1145*4882a593Smuzhiyun
1146*4882a593Smuzhiyun    from concurrent.futures import ProcessPoolExecutor
1147*4882a593Smuzhiyun    with ProcessPoolExecutor(max_workers=utils.cpu_count()) as executor:
1148*4882a593Smuzhiyun        pkgs_list = executor.map(_get_recipe_upgrade_status, data_copy_list)
1149*4882a593Smuzhiyun
1150*4882a593Smuzhiyun    return pkgs_list
1151