PackageVariable now returns the default on "true"
[scons.git] / SCons / Variables / PackageVariable.py
blob7271cfbf8fd72c7a638d6f150d9071f8cf7275d0
1 # MIT License
3 # Copyright The SCons Foundation
5 # Permission is hereby granted, free of charge, to any person obtaining
6 # a copy of this software and associated documentation files (the
7 # "Software"), to deal in the Software without restriction, including
8 # without limitation the rights to use, copy, modify, merge, publish,
9 # distribute, sublicense, and/or sell copies of the Software, and to
10 # permit persons to whom the Software is furnished to do so, subject to
11 # the following conditions:
13 # The above copyright notice and this permission notice shall be included
14 # in all copies or substantial portions of the Software.
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
17 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
18 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 """Variable type for package Variables.
26 To be used whenever a 'package' may be enabled/disabled and the
27 package path may be specified.
29 Given these options ::
31 x11=no (disables X11 support)
32 x11=yes (will search for the package installation dir)
33 x11=/usr/local/X11 (will check this path for existence)
35 Can be used as a replacement for autoconf's ``--with-xxx=yyy`` ::
37 opts = Variables()
38 opts.Add(
39 PackageVariable(
40 key='x11',
41 help='use X11 installed here (yes = search some places)',
42 default='yes'
45 env = Environment(variables=opts)
46 if env['x11'] is True:
47 dir = ... # search X11 in some standard places ...
48 env['x11'] = dir
49 if env['x11']:
50 ... # build with x11 ...
51 """
53 import os
54 import functools
55 from typing import Callable, Optional, Tuple, Union
57 import SCons.Errors
59 __all__ = ['PackageVariable',]
61 ENABLE_STRINGS = ('1', 'yes', 'true', 'on', 'enable', 'search')
62 DISABLE_STRINGS = ('0', 'no', 'false', 'off', 'disable')
64 def _converter(val: Union[str, bool], default: str) -> Union[str, bool]:
65 """Convert a package variable.
67 Returns *val* if it looks like a path string, and ``False`` if it
68 is a disabling string. If *val* is an enabling string, returns
69 *default* unless *default* is an enabling or disabling string,
70 in which case ignore *default* and return ``True``.
72 .. versionchanged: NEXT_RELEASE
73 Now returns the default in case of a truthy value, matching what the
74 public documentation always claimed, except if the default looks
75 like one of the true/false strings.
76 """
77 if isinstance(val, bool):
78 # check for non-subst case, so we don't lower() a bool.
79 lval = str(val).lower()
80 else:
81 lval = val.lower()
82 if lval in DISABLE_STRINGS:
83 return False
84 if lval in ENABLE_STRINGS:
85 # Can't return the default if it is one of the enable/disable strings;
86 # test code expects a bool.
87 if default in ENABLE_STRINGS:
88 return True
89 else:
90 return default
91 return val
94 def _validator(key: str, val, env, searchfunc) -> None:
95 """Validate package variable for valid path.
97 Checks that if a path is given as the value, that pathname actually exists.
98 """
99 if env[key] is True:
100 # NOTE: searchfunc is not in the documentation.
101 if searchfunc:
102 env[key] = searchfunc(key, val)
103 # TODO: need to check path, or be sure searchfunc raises.
104 elif env[key] and not os.path.exists(val):
105 msg = f'Path does not exist for variable {key!r}: {val!r}'
106 raise SCons.Errors.UserError(msg) from None
109 # lint: W0622: Redefining built-in 'help' (redefined-builtin)
110 def PackageVariable(
111 key: str, help: str, default, searchfunc: Optional[Callable] = None
112 ) -> Tuple[str, str, str, Callable, Callable]:
113 """Return a tuple describing a package list SCons Variable.
115 The input parameters describe a 'package list' variable. Returns
116 a tuple with the correct converter and validator appended.
117 The result is usable as input to :meth:`~SCons.Variables.Variables.Add`.
119 A 'package list' variable may be specified as a truthy string from
120 :const:`ENABLE_STRINGS`, a falsy string from
121 :const:`DISABLE_STRINGS`, or as a pathname string.
122 This information is appended to *help* using only one string
123 each for truthy/falsy.
125 help = '\n '.join((help, f'( yes | no | /path/to/{key} )'))
126 validator = functools.partial(_validator, searchfunc=searchfunc)
127 converter = functools.partial(_converter, default=default)
128 return key, help, default, validator, converter
130 # Local Variables:
131 # tab-width:4
132 # indent-tabs-mode:nil
133 # End:
134 # vim: set expandtab tabstop=4 shiftwidth=4: