Remove redundant code
[scons.git] / SCons / Variables / PathVariable.py
bloba5bf6c59f286f9ea3468acef3a6f34836f697b68
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 path Variables.
26 To be used whenever a user-specified path override setting should be allowed.
28 Arguments to PathVariable are:
29 * *key* - name of this option on the command line (e.g. "prefix")
30 * *help* - help string for option
31 * *default* - default value for this option
32 * *validator* - [optional] validator for option value. Predefined are:
34 * *PathAccept* - accepts any path setting; no validation
35 * *PathIsDir* - path must be an existing directory
36 * *PathIsDirCreate* - path must be a dir; will create
37 * *PathIsFile* - path must be a file
38 * *PathExists* - path must exist (any type) [default]
40 The *validator* is a function that is called and which should return
41 True or False to indicate if the path is valid. The arguments
42 to the validator function are: (*key*, *val*, *env*). *key* is the
43 name of the option, *val* is the path specified for the option,
44 and *env* is the environment to which the Options have been added.
46 Usage example::
48 opts = Variables()
49 opts.Add(
50 PathVariable(
51 'qtdir',
52 help='where the root of Qt is installed',
53 default=qtdir,
54 validator=PathIsDir,
57 opts.Add(
58 PathVariable(
59 'qt_includes',
60 help='where the Qt includes are installed',
61 default='$qtdir/includes',
62 validator=PathIsDirCreate,
65 opts.Add(
66 PathVariable(
67 'qt_libraries',
68 help='where the Qt library is installed',
69 default='$qtdir/lib',
72 """
75 import os
76 import os.path
77 from typing import Tuple, Callable
79 import SCons.Errors
81 __all__ = ['PathVariable',]
83 class _PathVariableClass:
85 @staticmethod
86 def PathAccept(key, val, env) -> None:
87 """Accepts any path, no checking done."""
88 pass
90 @staticmethod
91 def PathIsDir(key, val, env) -> None:
92 """Validator to check if Path is a directory."""
93 if not os.path.isdir(val):
94 if os.path.isfile(val):
95 m = 'Directory path for option %s is a file: %s'
96 else:
97 m = 'Directory path for option %s does not exist: %s'
98 raise SCons.Errors.UserError(m % (key, val))
100 @staticmethod
101 def PathIsDirCreate(key, val, env) -> None:
102 """Validator to check if Path is a directory,
103 creating it if it does not exist."""
104 try:
105 os.makedirs(val, exist_ok=True)
106 except FileExistsError:
107 m = 'Path for option %s is a file, not a directory: %s'
108 raise SCons.Errors.UserError(m % (key, val))
109 except PermissionError:
110 m = 'Path for option %s could not be created: %s'
111 raise SCons.Errors.UserError(m % (key, val))
113 @staticmethod
114 def PathIsFile(key, val, env) -> None:
115 """Validator to check if Path is a file"""
116 if not os.path.isfile(val):
117 if os.path.isdir(val):
118 m = 'File path for option %s is a directory: %s'
119 else:
120 m = 'File path for option %s does not exist: %s'
121 raise SCons.Errors.UserError(m % (key, val))
123 @staticmethod
124 def PathExists(key, val, env) -> None:
125 """Validator to check if Path exists"""
126 if not os.path.exists(val):
127 m = 'Path for option %s does not exist: %s'
128 raise SCons.Errors.UserError(m % (key, val))
130 def __call__(self, key, help, default, validator=None) -> Tuple[str, str, str, Callable, None]:
131 """Return a tuple describing a path list SCons Variable.
133 The input parameters describe a 'path list' option. Returns
134 a tuple with the correct converter and validator appended. The
135 result is usable for input to :meth:`Add`.
137 The *default* option specifies the default path to use if the
138 user does not specify an override with this option.
140 *validator* is a validator, see this file for examples
142 if validator is None:
143 validator = self.PathExists
145 if SCons.Util.is_List(key) or SCons.Util.is_Tuple(key):
146 helpmsg = '%s ( /path/to/%s )' % (help, key[0])
147 else:
148 helpmsg = '%s ( /path/to/%s )' % (help, key)
149 return (key, helpmsg, default, validator, None)
152 PathVariable = _PathVariableClass()
154 # Local Variables:
155 # tab-width:4
156 # indent-tabs-mode:nil
157 # End:
158 # vim: set expandtab tabstop=4 shiftwidth=4: