8 # Copyright (c) 2001, 2002 Steven Knight
10 # Permission is hereby granted, free of charge, to any person obtaining
11 # a copy of this software and associated documentation files (the
12 # "Software"), to deal in the Software without restriction, including
13 # without limitation the rights to use, copy, modify, merge, publish,
14 # distribute, sublicense, and/or sell copies of the Software, and to
15 # permit persons to whom the Software is furnished to do so, subject to
16 # the following conditions:
18 # The above copyright notice and this permission notice shall be included
19 # in all copies or substantial portions of the Software.
21 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
22 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
23 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
48 if os.name == 'posix':
50 def defaultSpawn(cmd, args, env):
55 args = [ 'sh', '-c' ] + \
56 [ string.join(map(lambda x: string.replace(str(x),
61 os.execvpe('sh', args, env)
63 exitval = exitvalmap[e[0]]
64 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
68 pid, stat = os.waitpid(pid, 0)
74 def pathsearch(cmd, env):
75 # In order to deal with the fact that 1.5.2 doesn't have
76 # os.spawnvpe(), roll our own PATH search.
77 if os.path.isabs(cmd):
78 if not os.path.exists(cmd):
80 if not SCons.Util.is_List(exts):
81 exts = string.split(exts, os.pathsep)
90 if not SCons.Util.is_List(path):
91 path = string.split(path, os.pathsep)
93 if not SCons.Util.is_List(exts):
94 exts = string.split(exts, os.pathsep)
98 pairs.append((dir, e))
99 for dir, ext in pairs:
100 f = os.path.join(dir, cmd)
103 if os.path.exists(f):
107 # Attempt to find cmd.exe (for WinNT/2k/XP) or
108 # command.com for Win9x
111 # First see if we can look in the registry...
112 if SCons.Util.can_read_reg:
114 # Look for Windows NT system root
115 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
116 'Software\\Microsoft\\Windows NT\\CurrentVersion')
117 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
118 cmd_interp = os.path.join(val, 'System32\\cmd.exe')
119 except SCons.Util.RegError:
121 # Okay, try the Windows 9x system root
122 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
123 'Software\\Microsoft\\Windows\\CurrentVersion')
124 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
125 cmd_interp = os.path.join(val, 'command.com')
129 cmd_interp = pathsearch('cmd', os.environ)
131 cmd_interp = pathsearch('command', os.environ)
133 # The upshot of all this is that, if you are using Python 1.5.2,
134 # you had better have cmd or command.com in your PATH when you run
137 def defaultSpawn(cmd, args, env):
139 sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
144 a = [ cmd_interp, '/C', args[0] ]
146 if ' ' in arg or '\t' in arg:
147 arg = '"' + arg + '"'
149 ret = os.spawnve(os.P_WAIT, cmd_interp, a, env)
151 ret = exitvalmap[e[0]]
152 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
155 def defaultSpawn(cmd, args, env):
156 sys.stderr.write("scons: Unknown os '%s', cannot spawn command interpreter.\n" % os.name)
157 sys.stderr.write("scons: Set your command handler with SetCommandHandler().\n")
162 def SetCommandHandler(func):
166 def GetCommandHandler():
170 class CommandGenerator:
172 Wrappes a command generator function so the Action() factory
173 function can tell a generator function from a function action.
175 def __init__(self, generator):
176 self.generator = generator
180 """A factory for action objects."""
181 if isinstance(act, ActionBase):
183 elif isinstance(act, CommandGenerator):
184 return CommandGeneratorAction(act.generator)
186 return FunctionAction(act)
187 elif SCons.Util.is_String(act):
188 return CommandAction(act)
189 elif SCons.Util.is_List(act):
190 return ListAction(act)
195 """Base class for actions that create output objects."""
196 def __cmp__(self, other):
197 return cmp(self.__dict__, other.__dict__)
199 def show(self, string):
202 def subst_dict(self, **kw):
203 """Create a dictionary for substitution of construction
206 This translates the following special arguments:
208 env - the construction environment itself,
209 the values of which (CC, CCFLAGS, etc.)
210 are copied straight into the dictionary
212 target - the target (object or array of objects),
213 used to generate the TARGET and TARGETS
214 construction variables
216 source - the source (object or array of objects),
217 used to generate the SOURCES construction
220 Any other keyword arguments are copied into the
224 if kw.has_key('env'):
225 dict.update(kw['env'])
235 if kw.has_key('target'):
238 if not SCons.Util.is_List(t):
242 except AttributeError:
244 dict['TARGETS'] = SCons.Util.PathList(map(os.path.normpath, map(str, t)))
246 dict['TARGET'] = dict['TARGETS'][0]
248 if kw.has_key('source'):
251 if not SCons.Util.is_List(s):
253 dict['SOURCES'] = SCons.Util.PathList(map(os.path.normpath, map(str, s)))
257 # Autogenerate necessary construction variables.
258 SCons.Util.autogenerate(dict, dir = cwd)
262 _rm = re.compile(r'\$[()]')
263 _remove = re.compile(r'\$\(([^\$]|\$[^\(])*?\$\)')
265 class CommandAction(ActionBase):
266 """Class for command-execution actions."""
267 def __init__(self, string):
268 self.command = string
270 def execute(self, **kw):
271 dict = apply(self.subst_dict, (), kw)
273 cmd_list = SCons.Util.scons_subst_list(self.command, dict, {}, _rm)
274 for cmd_line in cmd_list:
279 if ' ' in arg or '\t' in arg:
280 arg = '"' + arg + '"'
282 self.show(string.join(cl))
285 ENV = kw['env']['ENV']
287 import SCons.Defaults
288 ENV = SCons.Defaults.ConstructionEnvironment['ENV']
289 ret = spawn(cmd_line[0], cmd_line, ENV)
294 def _sig_dict(self, kw):
295 """Supply a dictionary for use in computing signatures.
297 For signature purposes, it doesn't matter what targets or
298 sources we use, so long as we use the same ones every time
299 so the signature stays the same. We supply an array of two
300 of each to allow for distinction between TARGET and TARGETS.
302 kw['target'] = ['__t1__', '__t2__']
303 kw['source'] = ['__s1__', '__s2__']
304 return apply(self.subst_dict, (), kw)
306 def get_raw_contents(self, **kw):
307 """Return the complete contents of this action's command line.
309 return SCons.Util.scons_subst(self.command, self._sig_dict(kw), {})
311 def get_contents(self, **kw):
312 """Return the signature contents of this action's command line.
314 This strips $(-$) and everything in between the string,
315 since those parts don't affect signatures.
317 return SCons.Util.scons_subst(self.command, self._sig_dict(kw), {}, _remove)
319 class CommandGeneratorAction(ActionBase):
320 """Class for command-generator actions."""
321 def __init__(self, generator):
322 self.generator = generator
324 def execute(self, **kw):
325 # ensure that target is a list, to make it easier to write
326 # generator functions:
328 if kw.has_key("target") and not SCons.Util.is_List(kw["target"]):
329 kw["target"] = [kw["target"]]
331 gen_list = apply(self.generator, (), kw)
332 gen_list = map(lambda x: map(str, x), gen_list)
334 # Do environment variable substitution on returned command list
335 dict = apply(self.subst_dict, (), kw)
337 for gen_line in gen_list:
339 curr_line = cmd_list[-1]
340 for gen_arg in gen_line:
341 arg_list = SCons.Util.scons_subst_list(gen_arg, dict, {})
342 curr_line.extend(arg_list[0])
343 if(len(arg_list) > 1):
344 cmd_list.extend(arg_list[1:])
345 curr_line = cmd_list[-1]
347 for cmd_line in filter(lambda x: x, cmd_list):
352 ENV = kw['env']['ENV']
354 import SCons.Defaults
355 ENV = SCons.Defaults.ConstructionEnvironment['ENV']
356 ret = spawn(cmd_line[0], cmd_line, ENV)
362 def get_contents(self, **kw):
363 """Return the signature contents of this action's command line.
365 This strips $(-$) and everything in between the string,
366 since those parts don't affect signatures.
368 kw['source'] = ["__s1__", "__s2__"]
369 kw['target'] = ["__t1__", "__t2__"]
370 cmd_list = apply(self.generator, (), kw)
371 cmd_list = map(lambda x: map(str, x), cmd_list)
372 cmd_list = map(lambda x: string.join(x, "\0"), cmd_list)
373 cmd_list = map(lambda x: _remove.sub('', x), cmd_list)
374 cmd_list = map(lambda x: filter(lambda y: y, string.split(x, "\0")), cmd_list)
377 class FunctionAction(ActionBase):
378 """Class for Python function actions."""
379 def __init__(self, function):
380 self.function = function
382 def execute(self, **kw):
384 # XXX: WHAT SHOULD WE PRINT HERE?
386 if kw.has_key('target'):
387 if SCons.Util.is_List(kw['target']):
388 kw['target'] = map(str, kw['target'])
390 kw['target'] = str(kw['target'])
391 if kw.has_key('source'):
392 kw['source'] = map(str, kw['source'])
393 return apply(self.function, (), kw)
395 def get_contents(self, **kw):
396 """Return the signature contents of this callable action.
398 By providing direct access to the code object of the
399 function, Python makes this extremely easy. Hooray!
401 #XXX DOES NOT ACCOUNT FOR CHANGES IN ENVIRONMENT VARIABLES
402 #THE FUNCTION MAY USE
404 # "self.function" is a function.
405 code = self.function.func_code.co_code
407 # "self.function" is a callable object.
408 code = self.function.__call__.im_func.func_code.co_code
411 class ListAction(ActionBase):
412 """Class for lists of other actions."""
413 def __init__(self, list):
414 self.list = map(lambda x: Action(x), list)
416 def execute(self, **kw):
418 r = apply(l.execute, (), kw)
423 def get_contents(self, **kw):
424 """Return the signature contents of this action list.
426 Simple concatenation of the signatures of the elements.
429 return reduce(lambda x, y: x + str(y.get_contents()), self.list, "")