summaryrefslogtreecommitdiff
path: root/SCons/Util/types.py
blob: 2071217e9e02c82e3dcb7d72c3d7e2e388618be3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# SPDX-License-Identifier: MIT
#
# Copyright The SCons Foundation

"""Various SCons utility functions

Routines which check types and do type conversions.
"""

import os
import pprint
import re
from typing import Optional

from collections import UserDict, UserList, UserString, deque
from collections.abc import MappingView, Iterable

# Functions for deciding if things are like various types, mainly to
# handle UserDict, UserList and UserString like their underlying types.
#
# Yes, all of this manual testing breaks polymorphism, and the real
# Pythonic way to do all of this would be to just try it and handle the
# exception, but handling the exception when it's not the right type is
# often too slow.

# A trick is used to speed up these functions. Default arguments are
# used to take a snapshot of the global functions and constants used
# by these functions. This transforms accesses to global variables into
# local variable accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL).
# Since checkers dislike this, it's now annotated for pylint, to flag
# (mostly for other readers of this code) we're doing this intentionally.
# TODO: experts affirm this is still faster, but maybe check if worth it?

DictTypes = (dict, UserDict)
ListTypes = (list, UserList, deque)

# With Python 3, there are view types that are sequences. Other interesting
# sequences are range and bytearray.  What we don't want is strings: while
# they are iterable sequences, in SCons usage iterating over a string is
# almost never what we want. So basically iterable-but-not-string:
SequenceTypes = (list, tuple, deque, UserList, MappingView)

# Note that profiling data shows a speed-up when comparing
# explicitly with str instead of simply comparing
# with basestring. (at least on Python 2.5.1)
# TODO: PY3 check this benchmarking is still correct.
StringTypes = (str, UserString)

# Empirically, it is faster to check explicitly for str than for basestring.
BaseStringTypes = str


def is_Dict(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj, isinstance=isinstance, DictTypes=DictTypes
) -> bool:
    """Check if object is a dict."""
    return isinstance(obj, DictTypes)


def is_List(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj, isinstance=isinstance, ListTypes=ListTypes
) -> bool:
    """Check if object is a list."""
    return isinstance(obj, ListTypes)


def is_Sequence(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj, isinstance=isinstance, SequenceTypes=SequenceTypes
) -> bool:
    """Check if object is a sequence."""
    return isinstance(obj, SequenceTypes)


def is_Tuple(  # pylint: disable=redefined-builtin
    obj, isinstance=isinstance, tuple=tuple
) -> bool:
    """Check if object is a tuple."""
    return isinstance(obj, tuple)


def is_String(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj, isinstance=isinstance, StringTypes=StringTypes
) -> bool:
    """Check if object is a string."""
    return isinstance(obj, StringTypes)


def is_Scalar(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj, isinstance=isinstance, StringTypes=StringTypes, Iterable=Iterable,
) -> bool:
    """Check if object is a scalar: not a container or iterable."""
    # Profiling shows that there is an impressive speed-up of 2x
    # when explicitly checking for strings instead of just not
    # sequence when the argument (i.e. obj) is already a string.
    # But, if obj is a not string then it is twice as fast to
    # check only for 'not sequence'. The following code therefore
    # assumes that the obj argument is a string most of the time.
    # Update: now using collections.abc.Iterable for the 2nd check.
    # Note: None is considered a "scalar" for this check, which is correct
    # for the usage in SCons.Environment._add_cppdefines.
    return isinstance(obj, StringTypes) or not isinstance(obj, Iterable)


# From Dinu C. Gherman,
# Python Cookbook, second edition, recipe 6.17, p. 277.
# Also: https://code.activestate.com/recipes/68205
# ASPN: Python Cookbook: Null Object Design Pattern


class Null:
    """Null objects always and reliably 'do nothing'."""

    def __new__(cls, *args, **kwargs):
        if '_instance' not in vars(cls):
            cls._instance = super(Null, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self, *args, **kwargs):
        pass

    def __call__(self, *args, **kwargs):
        return self

    def __repr__(self):
        return f"Null(0x{id(self):08X})"

    def __bool__(self):
        return False

    def __getattr__(self, name):
        return self

    def __setattr__(self, name, value):
        return self

    def __delattr__(self, name):
        return self


class NullSeq(Null):
    """A Null object that can also be iterated over."""

    def __len__(self):
        return 0

    def __iter__(self):
        return iter(())

    def __getitem__(self, i):
        return self

    def __delitem__(self, i):
        return self

    def __setitem__(self, i, v):
        return self


def to_bytes(s) -> bytes:
    """Convert object to bytes."""
    if s is None:
        return b'None'
    if isinstance(s, (bytes, bytearray)):
        # if already bytes return.
        return s
    return bytes(s, 'utf-8')


def to_str(s) -> str:
    """Convert object to string."""
    if s is None:
        return 'None'
    if is_String(s):
        return s
    return str(s, 'utf-8')


# Generic convert-to-string functions.  The wrapper
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.


def to_String(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj,
    isinstance=isinstance,
    str=str,
    UserString=UserString,
    BaseStringTypes=BaseStringTypes,
) -> str:
    """Return a string version of obj."""
    if isinstance(obj, BaseStringTypes):
        # Early out when already a string!
        return obj

    if isinstance(obj, UserString):
        # obj.data can only be a regular string. Please see the UserString initializer.
        return obj.data

    return str(obj)


def to_String_for_subst(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj,
    isinstance=isinstance,
    str=str,
    BaseStringTypes=BaseStringTypes,
    SequenceTypes=SequenceTypes,
    UserString=UserString,
) -> str:
    """Return a string version of obj for subst usage."""
    # Note that the test cases are sorted by order of probability.
    if isinstance(obj, BaseStringTypes):
        return obj

    if isinstance(obj, SequenceTypes):
        return ' '.join([to_String_for_subst(e) for e in obj])

    if isinstance(obj, UserString):
        # obj.data can only a regular string. Please see the UserString initializer.
        return obj.data

    return str(obj)


def to_String_for_signature(  # pylint: disable=redefined-outer-name,redefined-builtin
    obj, to_String_for_subst=to_String_for_subst, AttributeError=AttributeError,
) -> str:
    """Return a string version of obj for signature usage.

    Like :func:`to_String_for_subst` but has special handling for
    scons objects that have a :meth:`for_signature` method, and for dicts.
    """
    try:
        f = obj.for_signature
    except AttributeError:
        if isinstance(obj, dict):
            # pprint will output dictionary in key sorted order
            # with py3.5 the order was randomized. Depending on dict order
            # which was undefined until py3.6 (where it's by insertion order)
            # was not wise.
            # TODO: Change code when floor is raised to PY36
            return pprint.pformat(obj, width=1000000)
        return to_String_for_subst(obj)
    else:
        return f()


def get_env_bool(env, name, default=False) -> bool:
    """Convert a construction variable to bool.

    If the value of *name* in *env* is 'true', 'yes', 'y', 'on' (case
    insensitive) or anything convertible to int that yields non-zero then
    return ``True``; if 'false', 'no', 'n', 'off' (case insensitive)
    or a number that converts to integer zero return ``False``.
    Otherwise, return `default`.

    Args:
        env: construction environment, or any dict-like object
        name: name of the variable
        default: value to return if *name* not in *env* or cannot
          be converted (default: False)

    Returns:
        the "truthiness" of `name`
    """
    try:
        var = env[name]
    except KeyError:
        return default
    try:
        return bool(int(var))
    except ValueError:
        if str(var).lower() in ('true', 'yes', 'y', 'on'):
            return True

        if str(var).lower() in ('false', 'no', 'n', 'off'):
            return False

        return default


def get_os_env_bool(name, default=False) -> bool:
    """Convert an environment variable to bool.

    Conversion is the same as for :func:`get_env_bool`.
    """
    return get_env_bool(os.environ, name, default)


_get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')


def get_environment_var(varstr) -> Optional[str]:
    """Return undecorated construction variable string.

    Determine if `varstr` looks like a reference
    to a single environment variable, like `"$FOO"` or `"${FOO}"`.
    If so, return that variable with no decorations, like `"FOO"`.
    If not, return `None`.
    """
    mo = _get_env_var.match(to_String(varstr))
    if mo:
        var = mo.group(1)
        if var[0] == '{':
            return var[1:-1]
        return var

    return None


# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: