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