2 # Copyright (c) 2014-2016, 2019 Intel Corporation
4 # Permission is hereby granted, free of charge, to any person obtaining a copy
5 # of this software and associated documentation files (the "Software"), to deal
6 # in the Software without restriction, including without limitation the rights
7 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 # copies of the Software, and to permit persons to whom the Software is
9 # furnished to do so, subject to the following conditions:
11 # The above copyright notice and this permission notice shall be included in
12 # all copies or substantial portions of the Software.
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 """A collection of various bits that don't seem to belong anywhere else.
24 This is the classic catchall "utils" module from most projects, that for
25 historically reasons is called "core" in piglit.
34 from framework
import exceptions
40 'collect_system_info',
45 PLATFORMS
= ["glx", "x11_egl", "wayland", "gbm", "mixed_glx_egl", "wgl", "surfaceless_egl"]
48 class PiglitConfig(configparser
.ConfigParser
):
49 """Custom Config parser that provides a few extra helpers."""
50 def __init__(self
, *args
, **kwargs
):
51 super().__init
__(*args
, **kwargs
)
54 def read_file(self
, f
, source
=None):
55 super().read_file(f
, source
)
56 self
.filename
= os
.path
.abspath(source
or f
.name
)
58 def safe_get(self
, section
, option
, fallback
=None, **kwargs
):
59 """A version of self.get that doesn't raise NoSectionError or
62 This is equivalent to passing if the option isn't found. It will return
63 None if an error is caught
67 return self
.get(section
, option
, **kwargs
)
68 except (configparser
.NoOptionError
, configparser
.NoSectionError
):
71 def required_get(self
, section
, option
, **kwargs
):
72 """A version fo self.get that raises PiglitFatalError.
74 If self.get returns NoSectionError or NoOptionError then this will
75 raise a PiglitFatalException, aborting the program.
79 return self
.get(section
, option
, **kwargs
)
80 except configparser
.NoSectionError
:
81 raise exceptions
.PiglitFatalError(
82 'No Section "{}" in file "{}".\n'
83 'This section is required.'.format(
84 section
, self
.filename
))
85 except configparser
.NoOptionError
:
86 raise exceptions
.PiglitFatalError(
87 'No option "{}" from section "{}" in file "{}".\n'
88 'This option is required.'.format(
89 option
, section
, self
.filename
))
92 PIGLIT_CONFIG
= PiglitConfig(allow_no_value
=True)
95 def get_config(arg
=None):
97 PIGLIT_CONFIG
.read_file(arg
)
99 # Load the piglit.conf. First try looking in the current directory,
100 # then trying the XDG_CONFIG_HOME, then $HOME/.config/, finally try the
103 os
.environ
.get('XDG_CONFIG_HOME',
104 os
.path
.expandvars('$HOME/.config')),
105 os
.path
.join(os
.path
.dirname(__file__
), '..')]:
107 with
open(os
.path
.join(d
, 'piglit.conf'), 'r') as f
:
108 PIGLIT_CONFIG
.read_file(f
)
114 def get_option(env_varname
, config_option
, default
=None, required
=False):
115 """Query the given environment variable and then piglit.conf for the option.
117 Return the value of the default argument if opt is None.
120 opt
= os
.environ
.get(env_varname
, None)
124 opt
= PIGLIT_CONFIG
.safe_get(config_option
[0], config_option
[1])
126 if required
and not opt
:
127 raise exceptions
.PiglitFatalError(
128 'Cannot get env "{}" or conf value "{}:{}"'.format(
129 env_varname
, config_option
[0], config_option
[1]))
130 return opt
or default
133 def check_dir(dirname
, failifexists
=False, handler
=None):
134 """Check for the existence of a directory and create it if possible.
136 This function will check for the existance of a directory. If that
137 directory doesn't exist it will try to create it. If the directory does
138 exist than it does one of two things.
139 1) If "failifexists" is False (default): it will just return
140 2) If "failifexists" is True it will raise an PiglitException, it is the
141 job of the caller using failifexists=True to handle this exception
143 Both failifexists and handler can be passed, but failifexists will have
147 dirname -- the name of the directory to check
150 failifexists -- If True and the directory exists then PiglitException will
151 be raised (default: False)
152 handler -- a callable that is passed dirname if the thing to check exists.
158 # If the error is not "no file or directory" or "not a dir", then
159 # either raise an exception, call the handler function, or return
160 if e
.errno
not in [errno
.ENOENT
, errno
.ENOTDIR
]:
162 raise exceptions
.PiglitException
163 elif handler
is not None:
167 # makedirs is expensive, so check before # calling it.
168 if not os
.path
.exists(dirname
):
171 if e
.errno
!= errno
.EEXIST
:
175 def collect_system_info():
176 """ Get relavent information about the system running piglit
178 This method runs through a list of tuples, where element 1 is the name of
179 the program being run, and elemnt 2 is a command to run (in a form accepted
183 progs
= [('wglinfo', ['wglinfo']),
184 ('glxinfo', ['glxinfo']),
185 ('uname', ['uname', '-a']),
186 ('clinfo', ['clinfo']),
187 ('lspci', ['lspci', '-nn'])]
191 for name
, command
in progs
:
193 out
= subprocess
.check_output(command
, stderr
=subprocess
.STDOUT
)
194 result
[name
] = out
.decode('utf-8')
196 # If we get the 'no file or directory' error then pass, that means
197 # that the binary isn't installed or isn't relavent to the system.
198 # If it's any other OSError, then raise
199 if e
.errno
!= errno
.ENOENT
and e
.errno
!= errno
.EACCES
:
201 except subprocess
.CalledProcessError
:
202 # If the binary is installed by doesn't work on the window system
203 # (glxinfo) it will raise this error. go on
209 def parse_listfile(filename
):
211 Parses a newline-seperated list in a text file and returns a python list
212 object. It will expand tildes on Unix-like system to the users home
221 ['/home/user/tests1', '/home/users/tests2/main', '/tmp/test3']
223 with
open(filename
, 'r') as file:
224 return [os
.path
.expanduser(i
.strip()) for i
in file.readlines()]
227 class lazy_property(object): # pylint: disable=invalid-name,too-few-public-methods
228 """Descriptor that replaces the function it wraps with the value generated.
230 This makes a property that is truly lazy, it is calculated once on demand,
231 and stored. This makes this very useful for values that you might want to
232 calculate and reuse, but they cannot change.
234 This works by very cleverly shadowing itself with the calculated value. It
235 adds the value to the instance, which pushes itself up the MRO and will
236 never be queried again.
239 def __init__(self
, func
):
242 def __get__(self
, instance
, cls
):
243 value
= self
.__func
(instance
)
244 setattr(instance
, self
.__func
.__name
__, value
)