python: Delete authors lists from the python directory.
[gem5.git] / src / python / m5 / util / __init__.py
1 # Copyright (c) 2016 ARM Limited
2 # All rights reserved.
3 #
4 # The license below extends only to copyright in the software and shall
5 # not be construed as granting a license to any other intellectual
6 # property including but not limited to intellectual property relating
7 # to a hardware implementation of the functionality of the software
8 # licensed hereunder. You may use the software subject to the license
9 # terms below provided that you ensure that this notice is replicated
10 # unmodified and in its entirety in all distributions of the software,
11 # modified or unmodified, in source code or in binary form.
12 #
13 # Copyright (c) 2008-2009 The Hewlett-Packard Development Company
14 # Copyright (c) 2004-2006 The Regents of The University of Michigan
15 # All rights reserved.
16 #
17 # Redistribution and use in source and binary forms, with or without
18 # modification, are permitted provided that the following conditions are
19 # met: redistributions of source code must retain the above copyright
20 # notice, this list of conditions and the following disclaimer;
21 # redistributions in binary form must reproduce the above copyright
22 # notice, this list of conditions and the following disclaimer in the
23 # documentation and/or other materials provided with the distribution;
24 # neither the name of the copyright holders nor the names of its
25 # contributors may be used to endorse or promote products derived from
26 # this software without specific prior written permission.
27 #
28 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
40 from __future__ import print_function
41
42 import os
43 import re
44 import sys
45
46 from . import convert
47 from . import jobfile
48
49 from .attrdict import attrdict, multiattrdict, optiondict
50 from .code_formatter import code_formatter
51 from .multidict import multidict
52 from .smartdict import SmartDict
53 from .sorteddict import SortedDict
54
55 # panic() should be called when something happens that should never
56 # ever happen regardless of what the user does (i.e., an acutal m5
57 # bug).
58 def panic(fmt, *args):
59 print('panic:', fmt % args, file=sys.stderr)
60 sys.exit(1)
61
62 # fatal() should be called when the simulation cannot continue due to
63 # some condition that is the user's fault (bad configuration, invalid
64 # arguments, etc.) and not a simulator bug.
65 def fatal(fmt, *args):
66 print('fatal:', fmt % args, file=sys.stderr)
67 sys.exit(1)
68
69 # warn() should be called when the user should be warned about some condition
70 # that may or may not be the user's fault, but that they should be made aware
71 # of as it may affect the simulation or results.
72 def warn(fmt, *args):
73 print('warn:', fmt % args, file=sys.stderr)
74
75 # inform() should be called when the user should be informed about some
76 # condition that they may be interested in.
77 def inform(fmt, *args):
78 print('info:', fmt % args, file=sys.stdout)
79
80 class Singleton(type):
81 def __call__(cls, *args, **kwargs):
82 if hasattr(cls, '_instance'):
83 return cls._instance
84
85 cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
86 return cls._instance
87
88 def addToPath(path):
89 """Prepend given directory to system module search path. We may not
90 need this anymore if we can structure our config library more like a
91 Python package."""
92
93 # if it's a relative path and we know what directory the current
94 # python script is in, make the path relative to that directory.
95 if not os.path.isabs(path) and sys.path[0]:
96 path = os.path.join(sys.path[0], path)
97 path = os.path.realpath(path)
98 # sys.path[0] should always refer to the current script's directory,
99 # so place the new dir right after that.
100 sys.path.insert(1, path)
101
102 # Apply method to object.
103 # applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>)
104 def applyMethod(obj, meth, *args, **kwargs):
105 return getattr(obj, meth)(*args, **kwargs)
106
107 # If the first argument is an (non-sequence) object, apply the named
108 # method with the given arguments. If the first argument is a
109 # sequence, apply the method to each element of the sequence (a la
110 # 'map').
111 def applyOrMap(objOrSeq, meth, *args, **kwargs):
112 if not isinstance(objOrSeq, (list, tuple)):
113 return applyMethod(objOrSeq, meth, *args, **kwargs)
114 else:
115 return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq]
116
117 def compareVersions(v1, v2):
118 """helper function: compare arrays or strings of version numbers.
119 E.g., compare_version((1,3,25), (1,4,1)')
120 returns -1, 0, 1 if v1 is <, ==, > v2
121 """
122 def make_version_list(v):
123 if isinstance(v, (list,tuple)):
124 return v
125 elif isinstance(v, str):
126 return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
127 else:
128 raise TypeError()
129
130 v1 = make_version_list(v1)
131 v2 = make_version_list(v2)
132 # Compare corresponding elements of lists
133 for n1,n2 in zip(v1, v2):
134 if n1 < n2: return -1
135 if n1 > n2: return 1
136 # all corresponding values are equal... see if one has extra values
137 if len(v1) < len(v2): return -1
138 if len(v1) > len(v2): return 1
139 return 0
140
141 def crossproduct(items):
142 if len(items) == 1:
143 for i in items[0]:
144 yield (i,)
145 else:
146 for i in items[0]:
147 for j in crossproduct(items[1:]):
148 yield (i,) + j
149
150 def flatten(items):
151 while items:
152 item = items.pop(0)
153 if isinstance(item, (list, tuple)):
154 items[0:0] = item
155 else:
156 yield item
157
158 # force scalars to one-element lists for uniformity
159 def makeList(objOrList):
160 if isinstance(objOrList, list):
161 return objOrList
162 return [objOrList]
163
164 def printList(items, indent=4):
165 line = ' ' * indent
166 for i,item in enumerate(items):
167 if len(line) + len(item) > 76:
168 print(line)
169 line = ' ' * indent
170
171 if i < len(items) - 1:
172 line += '%s, ' % item
173 else:
174 line += item
175 print(line)
176
177 def readCommand(cmd, **kwargs):
178 """run the command cmd, read the results and return them
179 this is sorta like `cmd` in shell"""
180 from subprocess import Popen, PIPE, STDOUT
181
182 if isinstance(cmd, str):
183 cmd = cmd.split()
184
185 no_exception = 'exception' in kwargs
186 exception = kwargs.pop('exception', None)
187
188 kwargs.setdefault('shell', False)
189 kwargs.setdefault('stdout', PIPE)
190 kwargs.setdefault('stderr', STDOUT)
191 kwargs.setdefault('close_fds', True)
192 try:
193 subp = Popen(cmd, **kwargs)
194 except Exception as e:
195 if no_exception:
196 return exception
197 raise
198
199 return subp.communicate()[0]
200
201 def makeDir(path):
202 """Make a directory if it doesn't exist. If the path does exist,
203 ensure that it is a directory"""
204 if os.path.exists(path):
205 if not os.path.isdir(path):
206 raise AttributeError("%s exists but is not directory" % path)
207 else:
208 os.mkdir(path)
209
210 def isInteractive():
211 """Check if the simulator is run interactively or in a batch environment"""
212
213 return sys.__stdin__.isatty()