summaryrefslogtreecommitdiffstats
path: root/SCons/Variables/__init__.py
blob: ca18432153adb88809e0d68cf872000c4ce1f15b (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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# MIT License
#
# Copyright The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""Adds user-friendly customizable variables to an SCons build."""

from __future__ import annotations

import os.path
import sys
from contextlib import suppress
from dataclasses import dataclass
from functools import cmp_to_key
from typing import Any, Callable, Sequence

import SCons.Errors
import SCons.Util
import SCons.Warnings

# Note: imports are for the benefit of SCons.Main (and tests); since they
#   are not used here, the "as Foo" form is for checkers.
from .BoolVariable import BoolVariable
from .EnumVariable import EnumVariable
from .ListVariable import ListVariable
from .PackageVariable import PackageVariable
from .PathVariable import PathVariable

__all__ = [
    "Variable",
    "Variables",
    "BoolVariable",
    "EnumVariable",
    "ListVariable",
    "PackageVariable",
    "PathVariable",
]


@dataclass(order=True)
class Variable:
    """A Build Variable."""
    __slots__ = ('key', 'aliases', 'help', 'default', 'validator', 'converter', 'do_subst')
    key: str
    aliases: list[str]
    help: str
    default: Any
    validator: Callable | None
    converter: Callable | None
    do_subst: bool


class Variables:
    """A container for Build Variables.

    Includes a method to populate the variables with values into a
    construction envirionment, and methods to render the help text.

    Note that the pubic API for creating a ``Variables`` object is
    :func:`SCons.Script.Variables`, a kind of factory function, which
    defaults to supplying the contents of :attr:`~SCons.Script.ARGUMENTS`
    as the *args* parameter if it was not otherwise given. That is the
    behavior documented in the manpage for ``Variables`` - and different
    from the default if you instantiate this directly.

    Arguments:
      files: string or list of strings naming variable config scripts
         (default ``None``)
      args: dictionary to override values set from *files*.  (default ``None``)
      is_global: if true, return a global singleton :class:`Variables` object
         instead of a fresh instance. Currently inoperable (default ``False``)

    .. versionchanged:: 4.8.0
       The default for *is_global* changed to ``False`` (the previous
       default ``True`` had no effect due to an implementation error).

    .. deprecated:: 4.8.0
       *is_global* is deprecated.

    .. versionadded:: 4.9.0
       The :attr:`defaulted` attribute now lists those variables which
       were filled in from default values.
    """

    def __init__(
        self,
        files: str | Sequence[str | None] = None,
        args: dict | None = None,
        is_global: bool = False,
    ) -> None:
        self.options: list[Variable] = []
        self.args = args if args is not None else {}
        if not SCons.Util.is_Sequence(files):
            files = [files] if files else []
        self.files: Sequence[str] = files
        self.unknown: dict[str, str] = {}
        self.defaulted: list[str] = []

    def __str__(self) -> str:
        """Provide a way to "print" a :class:`Variables` object."""
        opts = ',\n'.join((f"    {option!s}" for option in self.options))
        return (
            f"Variables(\n  options=[\n{opts}\n  ],\n"
            f"  args={self.args},\n"
            f"  files={self.files},\n"
            f"  unknown={self.unknown},\n"
            f"  defaulted={self.defaulted},\n)"
        )

    # lint: W0622: Redefining built-in 'help'
    def _do_add(
        self,
        key: str | Sequence[str],
        help: str = "",
        default=None,
        validator: Callable | None = None,
        converter: Callable | None = None,
        **kwargs,
    ) -> None:
        """Create a :class:`Variable` and add it to the list.

        This is the internal implementation for :meth:`Add` and
        :meth:`AddVariables`. Not part of the public API.

        .. versionadded:: 4.8.0
              *subst* keyword argument is now recognized.
        """
        # aliases needs to be a list for later concatenation operations
        if SCons.Util.is_Sequence(key):
            name, aliases = key[0], list(key[1:])
        else:
            name, aliases = key, []
        if not name.isidentifier():
            raise SCons.Errors.UserError(f"Illegal Variables key {name!r}")
        do_subst = kwargs.pop("subst", True)
        option = Variable(name, aliases, help, default, validator, converter, do_subst)
        self.options.append(option)

        # options might be added after the 'unknown' dict has been set up:
        # look for and remove the key and all its aliases from that dict
        for alias in option.aliases + [option.key,]:
            if alias in self.unknown:
                del self.unknown[alias]

    def keys(self) -> list:
        """Return the variable names."""
        for option in self.options:
            yield option.key

    def Add(
        self, key: str | Sequence, *args, **kwargs,
    ) -> None:
        """Add a Build Variable.

        Arguments:
          key: the name of the variable, or a 5-tuple (or other sequence).
            If *key* is a tuple, and there are no additional arguments
            except the *help*, *default*, *validator* and *converter*
            keyword arguments, *key* is unpacked into the variable name
            plus the *help*, *default*, *validator* and *converter*
            arguments; if there are additional arguments, the first
            elements of *key* is taken as the variable name, and the
            remainder as aliases.
          args: optional positional arguments, corresponding to the
            *help*, *default*, *validator* and *converter* keyword args.
          kwargs: arbitrary keyword arguments used by the variable itself.

        Keyword Args:
          help: help text for the variable (default: empty string)
          default: default value for variable (default: ``None``)
          validator: function called to validate the value (default: ``None``)
          converter: function to be called to convert the variable's
            value before putting it in the environment. (default: ``None``)
          subst: perform substitution on the value before the converter
            and validator functions (if any) are called (default: ``True``)

        .. versionadded:: 4.8.0
              The *subst* keyword argument is now specially recognized.
        """
        if SCons.Util.is_Sequence(key):
            # If no other positional args (and no fundamental kwargs),
            # unpack key, and pass the kwargs on:
            known_kw = {'help', 'default', 'validator', 'converter'}
            if not args and not known_kw.intersection(kwargs.keys()):
                return self._do_add(*key, **kwargs)

        return self._do_add(key, *args, **kwargs)

    def AddVariables(self, *optlist) -> None:
        """Add Build Variables.

        Each *optlist* element is a sequence of arguments to be passed on
        to the underlying method for adding variables.

        Example::

            opt = Variables()
            opt.AddVariables(
                ('debug', '', 0),
                ('CC', 'The C compiler'),
                ('VALIDATE', 'An option for testing validation', 'notset', validator, None),
            )
        """
        for opt in optlist:
            self._do_add(*opt)

    def Update(self, env, args: dict | None = None) -> None:
        """Update an environment with the Build Variables.

        This is where the work of adding variables to the environment
        happens, The input sources saved at init time are scanned for
        variables to add, though if *args* is passed, then it is used
        instead of the saved one. If any variable description set up
        a callback for a validator and/or converter, those are called.
        Variables from the input sources which do not match a variable
        description in this object are ignored for purposes of adding
        to *env*, but are saved in the :attr:`unknown` dict attribute.
        Variables which are set in *env* from the default in a variable
        description and not from the input sources are saved in the
        :attr:`defaulted` list attribute.

        Args:
            env: the environment to update.
            args: a dictionary of keys and values to update in *env*.
               If omitted, uses the saved :attr:`args`
        """
        # first pull in the defaults, except any which are None.
        values = {opt.key: opt.default for opt in self.options if opt.default is not None}
        self.defaulted = list(values)

        # next set the values specified in any saved-variables script(s)
        for filename in self.files:
            # TODO: issue #816 use Node to access saved-variables file?
            if os.path.exists(filename):
                # issue #4645: don't exec directly into values,
                #   so we can iterate through for unknown variables.
                temp_values = {}
                dirname = os.path.split(os.path.abspath(filename))[0]
                if dirname:
                    sys.path.insert(0, dirname)
                try:
                    temp_values['__name__'] = filename
                    with open(filename) as f:
                        contents = f.read()
                    exec(contents, {}, temp_values)
                finally:
                    if dirname:
                        del sys.path[0]
                    del temp_values['__name__']

                for arg, value in temp_values.items():
                    added = False
                    for option in self.options:
                        if arg in option.aliases + [option.key,]:
                            values[option.key] = value
                            with suppress(ValueError):
                                self.defaulted.remove(option.key)
                            added = True
                    if not added:
                        self.unknown[arg] = value

        # set the values specified on the command line
        if args is None:
            args = self.args

        for arg, value in args.items():
            added = False
            for option in self.options:
                if arg in option.aliases + [option.key,]:
                    values[option.key] = value
                    with suppress(ValueError):
                        self.defaulted.remove(option.key)
                    added = True
            if not added:
                self.unknown[arg] = value

        # put the variables in the environment
        # (don't copy over variables that are not declared as options)
        #
        # Nitpicking: in OO terms, this method increases coupling as its
        #   main work is to update a different object (env), rather than
        #   the object it's bound to (although it does update self, too).
        #   It's tricky to decouple because the algorithm counts on directly
        #   setting a var in *env* first so it can call env.subst() on it
        #   to transform it.

        for option in self.options:
            try:
                env[option.key] = values[option.key]
            except KeyError:
                pass

        # apply converters
        for option in self.options:
            if option.converter and option.key in values:
                if option.do_subst:
                    value = env.subst('${%s}' % option.key)
                else:
                    value = env[option.key]
                try:
                    try:
                        env[option.key] = option.converter(value)
                    except TypeError:
                        env[option.key] = option.converter(value, env)
                except ValueError as exc:
                    # We usually want the converter not to fail and leave
                    # that to the validator, but in case, handle it.
                    msg = f'Error converting option: {option.key!r}\n{exc}'
                    raise SCons.Errors.UserError(msg) from exc

        # apply validators
        for option in self.options:
            if option.validator and option.key in values:
                if option.do_subst:
                    val = env[option.key]
                    if not SCons.Util.is_String(val):
                        # issue #4585: a _ListVariable should not be further
                        #    substituted, breaks on values with spaces.
                        value = val
                    else:
                        value = env.subst('${%s}' % option.key)
                else:
                    value = env[option.key]
                option.validator(option.key, value, env)

    def UnknownVariables(self) -> dict:
        """Return dict of unknown variables.

        Identifies variables that were not recognized in this object.
        """
        return self.unknown

    def Save(self, filename, env) -> None:
        """Save the variables to a script.

        Saves all the variables which have non-default settings
        to the given file as Python expressions.  This script can
        then be used to load the variables for a subsequent run.
        This can be used to create a build variable "cache" or
        capture different configurations for selection.

        Args:
            filename: Name of the file to save into
            env: the environment to get the option values from
        """
        # Create the file and write out the header
        try:
            # TODO: issue #816 use Node to access saved-variables file?
            with open(filename, 'w') as fh:
                # Make an assignment in the file for each option
                # within the environment that was assigned a value
                # other than the default. We don't want to save the
                # ones set to default: in case the SConscript settings
                # change you would then pick up old defaults.
                for option in self.options:
                    try:
                        value = env[option.key]
                        try:
                            prepare = value.prepare_to_store
                        except AttributeError:
                            try:
                                eval(repr(value))
                            except KeyboardInterrupt:
                                raise
                            except Exception:
                                # Convert stuff that has a repr() that
                                # cannot be evaluated into a string
                                value = SCons.Util.to_String(value)
                        else:
                            value = prepare()

                        defaultVal = env.subst(SCons.Util.to_String(option.default))
                        if option.converter:
                            try:
                                defaultVal = option.converter(defaultVal)
                            except TypeError:
                                defaultVal = option.converter(defaultVal, env)

                        if str(env.subst(f'${option.key}')) != str(defaultVal):
                            fh.write(f'{option.key} = {value!r}\n')
                    except KeyError:
                        pass
        except OSError as exc:
            msg = f'Error writing options to file: {filename}\n{exc}'
            raise SCons.Errors.UserError(msg) from exc

    def GenerateHelpText(self, env, sort: bool | Callable = False) -> str:
        """Generate the help text for the Variables object.

        Args:
            env: an environment that is used to get the current values
                of the variables.
            sort: Either a comparison function used for sorting
                (must take two arguments and return ``-1``, ``0`` or ``1``)
                or a boolean to indicate if it should be sorted.
        """
        # TODO this interface was designed when Python's sorted() took an
        #   optional comparison function (pre-3.0). Since it no longer does,
        #   we use functools.cmp_to_key() since can't really change the
        #   documented meaning of the "sort" argument. Maybe someday?
        if callable(sort):
            options = sorted(self.options, key=cmp_to_key(lambda x, y: sort(x.key, y.key)))
        elif sort is True:
            options = sorted(self.options)
        else:
            options = self.options

        def format_opt(opt, self=self, env=env) -> str:
            if opt.key in env:
                actual = env.subst(f'${opt.key}')
            else:
                actual = None
            return self.FormatVariableHelpText(
                env, opt.key, opt.help, opt.default, actual, opt.aliases
            )
        return ''.join(_f for _f in map(format_opt, options) if _f)

    fmt = '\n%s: %s\n    default: %s\n    actual: %s\n'
    aliasfmt = '\n%s: %s\n    default: %s\n    actual: %s\n    aliases: %s\n'

    # lint: W0622: Redefining built-in 'help'
    def FormatVariableHelpText(
        self,
        env,
        key: str,
        help: str,
        default,
        actual,
        aliases: list[str | None] = None,
    ) -> str:
        """Format the help text for a single variable.

        The caller is responsible for obtaining all the values,
        although now the :class:`Variable` class is more publicly exposed,
        this method could easily do most of that work - however
        that would change the existing published API.
        """
        if aliases is None:
            aliases = []
        # Don't display the key name itself as an alias.
        aliases = [a for a in aliases if a != key]
        if aliases:
            return self.aliasfmt % (key, help, default, actual, aliases)
        return self.fmt % (key, help, default, actual)

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