xref: /OK3568_Linux_fs/yocto/poky/meta/lib/oe/types.py (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5import errno
6import re
7import os
8
9
10class OEList(list):
11    """OpenEmbedded 'list' type
12
13    Acts as an ordinary list, but is constructed from a string value and a
14    separator (optional), and re-joins itself when converted to a string with
15    str().  Set the variable type flag to 'list' to use this type, and the
16    'separator' flag may be specified (defaulting to whitespace)."""
17
18    name = "list"
19
20    def __init__(self, value, separator = None):
21        if value is not None:
22            list.__init__(self, value.split(separator))
23        else:
24            list.__init__(self)
25
26        if separator is None:
27            self.separator = " "
28        else:
29            self.separator = separator
30
31    def __str__(self):
32        return self.separator.join(self)
33
34def choice(value, choices):
35    """OpenEmbedded 'choice' type
36
37    Acts as a multiple choice for the user.  To use this, set the variable
38    type flag to 'choice', and set the 'choices' flag to a space separated
39    list of valid values."""
40    if not isinstance(value, str):
41        raise TypeError("choice accepts a string, not '%s'" % type(value))
42
43    value = value.lower()
44    choices = choices.lower()
45    if value not in choices.split():
46        raise ValueError("Invalid choice '%s'.  Valid choices: %s" %
47                         (value, choices))
48    return value
49
50class NoMatch(object):
51    """Stub python regex pattern object which never matches anything"""
52    def findall(self, string, flags=0):
53        return None
54
55    def finditer(self, string, flags=0):
56        return None
57
58    def match(self, flags=0):
59        return None
60
61    def search(self, string, flags=0):
62        return None
63
64    def split(self, string, maxsplit=0):
65        return None
66
67    def sub(pattern, repl, string, count=0):
68        return None
69
70    def subn(pattern, repl, string, count=0):
71        return None
72
73NoMatch = NoMatch()
74
75def regex(value, regexflags=None):
76    """OpenEmbedded 'regex' type
77
78    Acts as a regular expression, returning the pre-compiled regular
79    expression pattern object.  To use this type, set the variable type flag
80    to 'regex', and optionally, set the 'regexflags' type to a space separated
81    list of the flags to control the regular expression matching (e.g.
82    FOO[regexflags] += 'ignorecase').  See the python documentation on the
83    're' module for a list of valid flags."""
84
85    flagval = 0
86    if regexflags:
87        for flag in regexflags.split():
88            flag = flag.upper()
89            try:
90                flagval |= getattr(re, flag)
91            except AttributeError:
92                raise ValueError("Invalid regex flag '%s'" % flag)
93
94    if not value:
95        # Let's ensure that the default behavior for an undefined or empty
96        # variable is to match nothing. If the user explicitly wants to match
97        # anything, they can match '.*' instead.
98        return NoMatch
99
100    try:
101        return re.compile(value, flagval)
102    except re.error as exc:
103        raise ValueError("Invalid regex value '%s': %s" %
104                         (value, exc.args[0]))
105
106def boolean(value):
107    """OpenEmbedded 'boolean' type
108
109    Valid values for true: 'yes', 'y', 'true', 't', '1'
110    Valid values for false: 'no', 'n', 'false', 'f', '0', None
111    """
112    if value is None:
113        return False
114
115    if isinstance(value, bool):
116        return value
117
118    if not isinstance(value, str):
119        raise TypeError("boolean accepts a string, not '%s'" % type(value))
120
121    value = value.lower()
122    if value in ('yes', 'y', 'true', 't', '1'):
123        return True
124    elif value in ('no', 'n', 'false', 'f', '0'):
125        return False
126    raise ValueError("Invalid boolean value '%s'" % value)
127
128def integer(value, numberbase=10):
129    """OpenEmbedded 'integer' type
130
131    Defaults to base 10, but this can be specified using the optional
132    'numberbase' flag."""
133
134    return int(value, int(numberbase))
135
136_float = float
137def float(value, fromhex='false'):
138    """OpenEmbedded floating point type
139
140    To use this type, set the type flag to 'float', and optionally set the
141    'fromhex' flag to a true value (obeying the same rules as for the
142    'boolean' type) if the value is in base 16 rather than base 10."""
143
144    if boolean(fromhex):
145        return _float.fromhex(value)
146    else:
147        return _float(value)
148
149def path(value, relativeto='', normalize='true', mustexist='false'):
150    value = os.path.join(relativeto, value)
151
152    if boolean(normalize):
153        value = os.path.normpath(value)
154
155    if boolean(mustexist):
156        try:
157            with open(value, 'r'):
158                pass
159        except IOError as exc:
160            if exc.errno == errno.ENOENT:
161                raise ValueError("{0}: {1}".format(value, os.strerror(errno.ENOENT)))
162
163    return value
164
165def is_x86(arch):
166    """
167    Check whether arch is x86 or x86_64
168    """
169    if arch.startswith('x86_') or re.match('i.*86', arch):
170        return True
171    else:
172        return False
173
174def qemu_use_kvm(kvm, target_arch):
175    """
176    Enable kvm if target_arch == build_arch or both of them are x86 archs.
177    """
178
179    use_kvm = False
180    if kvm and boolean(kvm):
181        build_arch = os.uname()[4]
182        if is_x86(build_arch) and is_x86(target_arch):
183            use_kvm = True
184        elif build_arch == target_arch:
185            use_kvm = True
186    return use_kvm
187