1 # Copyright (c) 2014-2016 Intel Corporation
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 """A collection of various bits that don't seem to belong anywhere else.
23 This is the classic catchall "utils" module from most projects, that for
24 historically reasons is called "core" in piglit.
28 from __future__
import (
29 absolute_import
, division
, print_function
, unicode_literals
35 from six
.moves
import configparser
37 from framework
import exceptions
43 'collect_system_info',
47 PLATFORMS
= ["glx", "x11_egl", "wayland", "gbm", "mixed_glx_egl", "wgl"]
50 class PiglitConfig(configparser
.SafeConfigParser
):
51 """Custom Config parser that provides a few extra helpers."""
52 def __init__(self
, *args
, **kwargs
):
53 # In Python2 the ConfigParser classes are old style, you can't use
54 # super() on them. sigh
55 configparser
.SafeConfigParser
.__init
__(self
, *args
, **kwargs
)
58 def readfp(self
, fp
, filename
=None):
59 # In Python2 the ConfigParser classes are old style, you can't use
60 # super() on them. sigh
61 configparser
.SafeConfigParser
.readfp(self
, fp
, filename
)
62 self
.filename
= os
.path
.abspath(filename
or fp
.name
)
64 def safe_get(self
, section
, option
, fallback
=None, **kwargs
):
65 """A version of self.get that doesn't raise NoSectionError or
68 This is equivalent to passing if the option isn't found. It will return
69 None if an error is caught
73 return self
.get(section
, option
, **kwargs
)
74 except (configparser
.NoOptionError
, configparser
.NoSectionError
):
77 def required_get(self
, section
, option
, **kwargs
):
78 """A version fo self.get that raises PiglitFatalError.
80 If self.get returns NoSectionError or NoOptionError then this will
81 raise a PiglitFatalException, aborting the program.
85 return self
.get(section
, option
, **kwargs
)
86 except configparser
.NoSectionError
:
87 raise exceptions
.PiglitFatalError(
88 'No Section "{}" in file "{}".\n'
89 'This section is required.'.format(
90 section
, self
.filename
))
91 except configparser
.NoOptionError
:
92 raise exceptions
.PiglitFatalError(
93 'No option "{}" from section "{}" in file "{}".\n'
94 'This option is required.'.format(
95 option
, section
, self
.filename
))
98 PIGLIT_CONFIG
= PiglitConfig(allow_no_value
=True)
101 def get_config(arg
=None):
103 PIGLIT_CONFIG
.readfp(arg
)
105 # Load the piglit.conf. First try looking in the current directory,
106 # then trying the XDG_CONFIG_HOME, then $HOME/.config/, finally try the
109 os
.environ
.get('XDG_CONFIG_HOME',
110 os
.path
.expandvars('$HOME/.config')),
111 os
.path
.join(os
.path
.dirname(__file__
), '..')]:
113 with
open(os
.path
.join(d
, 'piglit.conf'), 'r') as f
:
114 PIGLIT_CONFIG
.readfp(f
)
120 def check_dir(dirname
, failifexists
=False, handler
=None):
121 """Check for the existence of a directory and create it if possible.
123 This function will check for the existance of a directory. If that
124 directory doesn't exist it will try to create it. If the directory does
125 exist than it does one of two things.
126 1) If "failifexists" is False (default): it will just return
127 2) If "failifexists" is True it will raise an PiglitException, it is the
128 job of the caller using failifexists=True to handle this exception
130 Both failifexists and handler can be passed, but failifexists will have
134 dirname -- the name of the directory to check
137 failifexists -- If True and the directory exists then PiglitException will
138 be raised (default: False)
139 handler -- a callable that is passed dirname if the thing to check exists.
145 # If the error is not "no file or directory" or "not a dir", then
146 # either raise an exception, call the handler function, or return
147 if e
.errno
not in [errno
.ENOENT
, errno
.ENOTDIR
]:
149 raise exceptions
.PiglitException
150 elif handler
is not None:
154 # makedirs is expensive, so check before # calling it.
155 if not os
.path
.exists(dirname
):
158 if e
.errno
!= errno
.EEXIST
:
162 def collect_system_info():
163 """ Get relavent information about the system running piglit
165 This method runs through a list of tuples, where element 1 is the name of
166 the program being run, and elemnt 2 is a command to run (in a form accepted
170 progs
= [('wglinfo', ['wglinfo']),
171 ('glxinfo', ['glxinfo']),
172 ('uname', ['uname', '-a']),
173 ('clinfo', ['clinfo']),
174 ('lspci', ['lspci', '-nn'])]
178 for name
, command
in progs
:
180 out
= subprocess
.check_output(command
, stderr
=subprocess
.STDOUT
)
181 result
[name
] = out
.decode('utf-8')
183 # If we get the 'no file or directory' error then pass, that means
184 # that the binary isn't installed or isn't relavent to the system.
185 # If it's any other OSError, then raise
186 if e
.errno
!= errno
.ENOENT
:
188 except subprocess
.CalledProcessError
:
189 # If the binary is installed by doesn't work on the window system
190 # (glxinfo) it will raise this error. go on
196 def parse_listfile(filename
):
198 Parses a newline-seperated list in a text file and returns a python list
199 object. It will expand tildes on Unix-like system to the users home
208 ['/home/user/tests1', '/home/users/tests2/main', '/tmp/test3']
210 with
open(filename
, 'r') as file:
211 return [os
.path
.expanduser(i
.strip()) for i
in file.readlines()]
214 class lazy_property(object): # pylint: disable=invalid-name,too-few-public-methods
215 """Descriptor that replaces the function it wraps with the value generated.
217 This makes a property that is truly lazy, it is calculated once on demand,
218 and stored. This makes this very useful for values that you might want to
219 calculate and reuse, but they cannot change.
221 This works by very cleverly shadowing itself with the calculated value. It
222 adds the value to the instance, which pushes itself up the MRO and will
223 never be queried again.
226 def __init__(self
, func
):
229 def __get__(self
, instance
, cls
):
230 value
= self
.__func
(instance
)
231 setattr(instance
, self
.__func
.__name
__, value
)