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__"
53 if os.name == 'posix':
55 def defaultSpawn(cmd, args, env):
60 args = [ 'sh', '-c' ] + \
61 [ string.join(map(lambda x: string.replace(str(x),
66 os.execvpe('sh', args, env)
68 exitval = exitvalmap[e[0]]
69 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
73 pid, stat = os.waitpid(pid, 0)
79 def pathsearch(cmd, env):
80 # In order to deal with the fact that 1.5.2 doesn't have
81 # os.spawnvpe(), roll our own PATH search.
82 if os.path.isabs(cmd):
83 if not os.path.exists(cmd):
85 if not SCons.Util.is_List(exts):
86 exts = string.split(exts, os.pathsep)
95 if not SCons.Util.is_List(path):
96 path = string.split(path, os.pathsep)
98 if not SCons.Util.is_List(exts):
99 exts = string.split(exts, os.pathsep)
103 pairs.append((dir, e))
104 for dir, ext in pairs:
105 f = os.path.join(dir, cmd)
108 if os.path.exists(f):
112 # Attempt to find cmd.exe (for WinNT/2k/XP) or
113 # command.com for Win9x
116 # First see if we can look in the registry...
117 if SCons.Util.can_read_reg:
119 # Look for Windows NT system root
120 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
121 'Software\\Microsoft\\Windows NT\\CurrentVersion')
122 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
123 cmd_interp = os.path.join(val, 'System32\\cmd.exe')
124 except SCons.Util.RegError:
126 # Okay, try the Windows 9x system root
127 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
128 'Software\\Microsoft\\Windows\\CurrentVersion')
129 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
130 cmd_interp = os.path.join(val, 'command.com')
134 cmd_interp = pathsearch('cmd', os.environ)
136 cmd_interp = pathsearch('command', os.environ)
138 # The upshot of all this is that, if you are using Python 1.5.2,
139 # you had better have cmd or command.com in your PATH when you run
142 def defaultSpawn(cmd, args, env):
144 sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
149 a = [ cmd_interp, '/C', args[0] ]
151 if ' ' in arg or '\t' in arg:
152 arg = '"' + arg + '"'
154 ret = os.spawnve(os.P_WAIT, cmd_interp, a, env)
156 ret = exitvalmap[e[0]]
157 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
160 def defaultSpawn(cmd, args, env):
161 sys.stderr.write("scons: Unknown os '%s', cannot spawn command interpreter.\n" % os.name)
162 sys.stderr.write("scons: Set your command handler with SetCommandHandler().\n")
167 def SetCommandHandler(func):
171 def GetCommandHandler():
175 class CommandGenerator:
177 Wraps a command generator function so the Action() factory
178 function can tell a generator function from a function action.
180 def __init__(self, generator):
181 self.generator = generator
183 def _do_create_action(act):
184 """This is the actual "implementation" for the
185 Action factory method, below. This handles the
186 fact that passing lists to Action() itself has
187 different semantics than passing lists as elements
190 The former will create a ListAction, the latter
191 will create a CommandAction by converting the inner
192 list elements to strings."""
194 if isinstance(act, ActionBase):
196 elif SCons.Util.is_List(act):
197 return CommandAction(act)
198 elif isinstance(act, CommandGenerator):
199 return CommandGeneratorAction(act.generator)
201 return FunctionAction(act)
202 elif SCons.Util.is_String(act):
203 var=SCons.Util.get_environment_var(act)
205 # This looks like a string that is purely an Environment
206 # variable reference, like "$FOO" or "${FOO}". We do
207 # something special here...we lazily evaluate the contents
208 # of that Environment variable, so a user could but something
209 # like a function or a CommandGenerator in that variable
210 # instead of a string.
211 return CommandGeneratorAction(LazyCmdGenerator(var))
212 listCmds = map(lambda x: CommandAction(string.split(x)),
213 string.split(act, '\n'))
214 if len(listCmds) == 1:
217 return ListAction(listCmds)
222 """A factory for action objects."""
223 if SCons.Util.is_List(act):
224 acts = filter(lambda x: not x is None,
225 map(_do_create_action, act))
229 return ListAction(acts)
231 return _do_create_action(act)
234 """Base class for actions that create output objects."""
235 def __cmp__(self, other):
236 return cmp(self.__dict__, other.__dict__)
238 def show(self, string):
241 def subst_dict(self, **kw):
242 """Create a dictionary for substitution of construction
245 This translates the following special arguments:
247 env - the construction environment itself,
248 the values of which (CC, CCFLAGS, etc.)
249 are copied straight into the dictionary
251 target - the target (object or array of objects),
252 used to generate the TARGET and TARGETS
253 construction variables
255 source - the source (object or array of objects),
256 used to generate the SOURCES and SOURCE
257 construction variables
259 Any other keyword arguments are copied into the
263 if kw.has_key('env'):
264 dict.update(kw['env'])
274 if kw.has_key('target'):
277 if not SCons.Util.is_List(t):
281 except (IndexError, AttributeError):
283 dict['TARGETS'] = SCons.Util.PathList(map(os.path.normpath, map(str, t)))
285 dict['TARGET'] = dict['TARGETS'][0]
287 if kw.has_key('source'):
291 except AttributeError:
295 if not SCons.Util.is_List(s):
297 dict['SOURCES'] = SCons.Util.PathList(map(os.path.normpath, map(rstr, s)))
299 dict['SOURCE'] = dict['SOURCES'][0]
305 def _string_from_cmd_list(cmd_list):
306 """Takes a list of command line arguments and returns a pretty
307 representation for printing."""
310 if ' ' in arg or '\t' in arg:
311 arg = '"' + arg + '"'
313 return string.join(cl)
315 _rm = re.compile(r'\$[()]')
316 _remove = re.compile(r'\$\(([^\$]|\$[^\(])*?\$\)')
318 class EnvDictProxy(UserDict.UserDict):
319 """This is a dictionary-like class that contains the
320 Environment dictionary we pass to FunctionActions
321 and CommandGeneratorActions.
323 In addition to providing
324 normal dictionary-like access to the variables in the
325 Environment, it also exposes the functions subst()
326 and subst_list(), allowing users to easily do variable
327 interpolation when writing their FunctionActions
328 and CommandGeneratorActions."""
330 def __init__(self, env):
331 UserDict.UserDict.__init__(self, env)
333 def subst(self, string, raw=0):
338 return SCons.Util.scons_subst(string, self.data, {}, regex_remove)
340 def subst_list(self, string, raw=0):
345 return SCons.Util.scons_subst_list(string, self.data, {}, regex_remove)
347 class CommandAction(ActionBase):
348 """Class for command-execution actions."""
349 def __init__(self, cmd):
352 self.cmd_list = map(SCons.Util.to_String, cmd)
354 def execute(self, **kw):
355 dict = apply(self.subst_dict, (), kw)
357 cmd_list = SCons.Util.scons_subst_list(self.cmd_list, dict, {}, _rm)
358 for cmd_line in cmd_list:
361 self.show(_string_from_cmd_list(cmd_line))
364 ENV = kw['env']['ENV']
368 import SCons.Environment
369 default_ENV = SCons.Environment.Environment()['ENV']
371 ret = spawn(cmd_line[0], cmd_line, ENV)
376 def _sig_dict(self, kw):
377 """Supply a dictionary for use in computing signatures.
379 For signature purposes, it doesn't matter what targets or
380 sources we use, so long as we use the same ones every time
381 so the signature stays the same. We supply an array of two
382 of each to allow for distinction between TARGET and TARGETS.
384 kw['target'] = ['__t1__', '__t2__']
385 kw['source'] = ['__s1__', '__s2__']
386 return apply(self.subst_dict, (), kw)
388 def get_raw_contents(self, **kw):
389 """Return the complete contents of this action's command line.
391 return SCons.Util.scons_subst(string.join(self.cmd_list),
392 self._sig_dict(kw), {})
394 def get_contents(self, **kw):
395 """Return the signature contents of this action's command line.
397 This strips $(-$) and everything in between the string,
398 since those parts don't affect signatures.
400 return SCons.Util.scons_subst(string.join(self.cmd_list),
401 self._sig_dict(kw), {}, _remove)
403 class CommandGeneratorAction(ActionBase):
404 """Class for command-generator actions."""
405 def __init__(self, generator):
406 self.generator = generator
408 def __generate(self, kw, for_signature):
411 # Wrap the environment dictionary in an EnvDictProxy
412 # object to make variable interpolation easier for the
415 args['for_signature'] = for_signature
416 if args.has_key("env") and not isinstance(args["env"], EnvDictProxy):
417 args["env"] = EnvDictProxy(args["env"])
419 # ensure that target is a list, to make it easier to write
420 # generator functions:
421 if args.has_key("target") and not SCons.Util.is_List(args["target"]):
422 args["target"] = [args["target"]]
424 ret = apply(self.generator, (), args)
425 gen_cmd = Action(ret)
427 raise SCons.Errors.UserError("Object returned from command generator: %s cannot be used to create an Action." % repr(ret))
430 def execute(self, **kw):
431 return apply(self.__generate(kw, 0).execute, (), kw)
433 def get_contents(self, **kw):
434 """Return the signature contents of this action's command line.
436 This strips $(-$) and everything in between the string,
437 since those parts don't affect signatures.
439 return apply(self.__generate(kw, 1).get_contents, (), kw)
441 class LazyCmdGenerator:
442 """This is a simple callable class that acts as a command generator.
443 It holds on to a key into an Environment dictionary, then waits
444 until execution time to see what type it is, then tries to
445 create an Action out of it."""
446 def __init__(self, var):
447 self.var = SCons.Util.to_String(var)
449 def __call__(self, env, **kw):
450 if env.has_key(self.var):
453 # The variable reference substitutes to nothing.
456 class FunctionAction(ActionBase):
457 """Class for Python function actions."""
458 def __init__(self, function):
459 self.function = function
461 def execute(self, **kw):
463 # XXX: WHAT SHOULD WE PRINT HERE?
465 if kw.has_key('target') and not \
466 SCons.Util.is_List(kw['target']):
467 kw['target'] = [ kw['target'] ]
468 if kw.has_key('source') and not \
469 SCons.Util.is_List(kw['source']):
470 kw['source'] = [ kw['source'] ]
471 if kw.has_key("env") and not isinstance(kw["env"], EnvDictProxy):
472 kw["env"] = EnvDictProxy(kw["env"])
473 return apply(self.function, (), kw)
475 def get_contents(self, **kw):
476 """Return the signature contents of this callable action.
478 By providing direct access to the code object of the
479 function, Python makes this extremely easy. Hooray!
481 #XXX DOES NOT ACCOUNT FOR CHANGES IN ENVIRONMENT VARIABLES
482 #THE FUNCTION MAY USE
484 # "self.function" is a function.
485 code = self.function.func_code.co_code
487 # "self.function" is a callable object.
488 code = self.function.__call__.im_func.func_code.co_code
491 class ListAction(ActionBase):
492 """Class for lists of other actions."""
493 def __init__(self, list):
494 self.list = map(lambda x: Action(x), list)
496 def execute(self, **kw):
498 r = apply(l.execute, (), kw)
503 def get_contents(self, **kw):
504 """Return the signature contents of this action list.
506 Simple concatenation of the signatures of the elements.
509 return reduce(lambda x, y, kw=kw: x + str(apply(y.get_contents, (), kw)), self.list, "")