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__"
54 if ' ' in x or '\t' in x:
59 if os.name == 'posix':
61 def defaultSpawn(cmd, args, env):
66 args = ['sh', '-c', string.join(map(quote, args))]
68 os.execvpe('sh', args, env)
70 exitval = exitvalmap[e[0]]
71 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
75 pid, stat = os.waitpid(pid, 0)
81 def pathsearch(cmd, env):
82 # In order to deal with the fact that 1.5.2 doesn't have
83 # os.spawnvpe(), roll our own PATH search.
84 if os.path.isabs(cmd):
85 if not os.path.exists(cmd):
87 if not SCons.Util.is_List(exts):
88 exts = string.split(exts, os.pathsep)
97 if not SCons.Util.is_List(path):
98 path = string.split(path, os.pathsep)
100 if not SCons.Util.is_List(exts):
101 exts = string.split(exts, os.pathsep)
105 pairs.append((dir, e))
106 for dir, ext in pairs:
107 f = os.path.join(dir, cmd)
110 if os.path.exists(f):
114 # Attempt to find cmd.exe (for WinNT/2k/XP) or
115 # command.com for Win9x
118 # First see if we can look in the registry...
119 if SCons.Util.can_read_reg:
121 # Look for Windows NT system root
122 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
123 'Software\\Microsoft\\Windows NT\\CurrentVersion')
124 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
125 cmd_interp = os.path.join(val, 'System32\\cmd.exe')
126 except SCons.Util.RegError:
128 # Okay, try the Windows 9x system root
129 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
130 'Software\\Microsoft\\Windows\\CurrentVersion')
131 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
132 cmd_interp = os.path.join(val, 'command.com')
136 cmd_interp = pathsearch('cmd', os.environ)
138 cmd_interp = pathsearch('command', os.environ)
140 # The upshot of all this is that, if you are using Python 1.5.2,
141 # you had better have cmd or command.com in your PATH when you run
144 def defaultSpawn(cmd, args, env):
146 sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
150 args = [cmd_interp, '/C', quote(string.join(map(quote, args)))]
151 ret = os.spawnve(os.P_WAIT, cmd_interp, args, env)
153 ret = exitvalmap[e[0]]
154 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
157 def defaultSpawn(cmd, args, env):
158 sys.stderr.write("scons: Unknown os '%s', cannot spawn command interpreter.\n" % os.name)
159 sys.stderr.write("scons: Set your command handler with SetCommandHandler().\n")
164 def SetCommandHandler(func):
168 def GetCommandHandler():
172 class CommandGenerator:
174 Wraps a command generator function so the Action() factory
175 function can tell a generator function from a function action.
177 def __init__(self, generator):
178 self.generator = generator
180 def _do_create_action(act):
181 """This is the actual "implementation" for the
182 Action factory method, below. This handles the
183 fact that passing lists to Action() itself has
184 different semantics than passing lists as elements
187 The former will create a ListAction, the latter
188 will create a CommandAction by converting the inner
189 list elements to strings."""
191 if isinstance(act, ActionBase):
193 elif SCons.Util.is_List(act):
194 return CommandAction(act)
195 elif isinstance(act, CommandGenerator):
196 return CommandGeneratorAction(act.generator)
198 return FunctionAction(act)
199 elif SCons.Util.is_String(act):
200 var=SCons.Util.get_environment_var(act)
202 # This looks like a string that is purely an Environment
203 # variable reference, like "$FOO" or "${FOO}". We do
204 # something special here...we lazily evaluate the contents
205 # of that Environment variable, so a user could but something
206 # like a function or a CommandGenerator in that variable
207 # instead of a string.
208 return CommandGeneratorAction(LazyCmdGenerator(var))
209 listCmds = map(lambda x: CommandAction(string.split(x)),
210 string.split(act, '\n'))
211 if len(listCmds) == 1:
214 return ListAction(listCmds)
219 """A factory for action objects."""
220 if SCons.Util.is_List(act):
221 acts = filter(lambda x: not x is None,
222 map(_do_create_action, act))
226 return ListAction(acts)
228 return _do_create_action(act)
231 """Base class for actions that create output objects."""
232 def __cmp__(self, other):
233 return cmp(self.__dict__, other.__dict__)
235 def show(self, string):
238 def subst_dict(self, **kw):
239 """Create a dictionary for substitution of construction
242 This translates the following special arguments:
244 env - the construction environment itself,
245 the values of which (CC, CCFLAGS, etc.)
246 are copied straight into the dictionary
248 target - the target (object or array of objects),
249 used to generate the TARGET and TARGETS
250 construction variables
252 source - the source (object or array of objects),
253 used to generate the SOURCES and SOURCE
254 construction variables
256 Any other keyword arguments are copied into the
260 if kw.has_key('env'):
261 dict.update(kw['env'])
271 if kw.has_key('target'):
274 if not SCons.Util.is_List(t):
278 except (IndexError, AttributeError):
280 dict['TARGETS'] = SCons.Util.PathList(map(os.path.normpath, map(str, t)))
282 dict['TARGET'] = dict['TARGETS'][0]
284 if kw.has_key('source'):
288 except AttributeError:
292 if not SCons.Util.is_List(s):
294 dict['SOURCES'] = SCons.Util.PathList(map(os.path.normpath, map(rstr, s)))
296 dict['SOURCE'] = dict['SOURCES'][0]
302 def _string_from_cmd_list(cmd_list):
303 """Takes a list of command line arguments and returns a pretty
304 representation for printing."""
307 if ' ' in arg or '\t' in arg:
308 arg = '"' + arg + '"'
310 return string.join(cl)
312 _rm = re.compile(r'\$[()]')
313 _remove = re.compile(r'\$\(([^\$]|\$[^\(])*?\$\)')
315 class EnvDictProxy(UserDict.UserDict):
316 """This is a dictionary-like class that contains the
317 Environment dictionary we pass to FunctionActions
318 and CommandGeneratorActions.
320 In addition to providing
321 normal dictionary-like access to the variables in the
322 Environment, it also exposes the functions subst()
323 and subst_list(), allowing users to easily do variable
324 interpolation when writing their FunctionActions
325 and CommandGeneratorActions."""
327 def __init__(self, env):
328 UserDict.UserDict.__init__(self, env)
330 def subst(self, string, raw=0):
335 return SCons.Util.scons_subst(string, self.data, {}, regex_remove)
337 def subst_list(self, string, raw=0):
342 return SCons.Util.scons_subst_list(string, self.data, {}, regex_remove)
344 class CommandAction(ActionBase):
345 """Class for command-execution actions."""
346 def __init__(self, cmd):
349 self.cmd_list = map(SCons.Util.to_String, cmd)
351 def execute(self, **kw):
352 dict = apply(self.subst_dict, (), kw)
354 cmd_list = SCons.Util.scons_subst_list(self.cmd_list, dict, {}, _rm)
355 for cmd_line in cmd_list:
358 self.show(_string_from_cmd_list(cmd_line))
361 ENV = kw['env']['ENV']
365 import SCons.Environment
366 default_ENV = SCons.Environment.Environment()['ENV']
368 ret = spawn(cmd_line[0], cmd_line, ENV)
373 def _sig_dict(self, kw):
374 """Supply a dictionary for use in computing signatures.
376 For signature purposes, it doesn't matter what targets or
377 sources we use, so long as we use the same ones every time
378 so the signature stays the same. We supply an array of two
379 of each to allow for distinction between TARGET and TARGETS.
381 kw['target'] = ['__t1__', '__t2__']
382 kw['source'] = ['__s1__', '__s2__']
383 return apply(self.subst_dict, (), kw)
385 def get_raw_contents(self, **kw):
386 """Return the complete contents of this action's command line.
388 return SCons.Util.scons_subst(string.join(self.cmd_list),
389 self._sig_dict(kw), {})
391 def get_contents(self, **kw):
392 """Return the signature contents of this action's command line.
394 This strips $(-$) and everything in between the string,
395 since those parts don't affect signatures.
397 return SCons.Util.scons_subst(string.join(self.cmd_list),
398 self._sig_dict(kw), {}, _remove)
400 class CommandGeneratorAction(ActionBase):
401 """Class for command-generator actions."""
402 def __init__(self, generator):
403 self.generator = generator
405 def __generate(self, kw, for_signature):
408 # Wrap the environment dictionary in an EnvDictProxy
409 # object to make variable interpolation easier for the
412 args['for_signature'] = for_signature
413 if args.has_key("env") and not isinstance(args["env"], EnvDictProxy):
414 args["env"] = EnvDictProxy(args["env"])
416 # ensure that target is a list, to make it easier to write
417 # generator functions:
418 if args.has_key("target") and not SCons.Util.is_List(args["target"]):
419 args["target"] = [args["target"]]
421 ret = apply(self.generator, (), args)
422 gen_cmd = Action(ret)
424 raise SCons.Errors.UserError("Object returned from command generator: %s cannot be used to create an Action." % repr(ret))
427 def execute(self, **kw):
428 return apply(self.__generate(kw, 0).execute, (), kw)
430 def get_contents(self, **kw):
431 """Return the signature contents of this action's command line.
433 This strips $(-$) and everything in between the string,
434 since those parts don't affect signatures.
436 return apply(self.__generate(kw, 1).get_contents, (), kw)
438 class LazyCmdGenerator:
439 """This is a simple callable class that acts as a command generator.
440 It holds on to a key into an Environment dictionary, then waits
441 until execution time to see what type it is, then tries to
442 create an Action out of it."""
443 def __init__(self, var):
444 self.var = SCons.Util.to_String(var)
446 def __call__(self, env, **kw):
447 if env.has_key(self.var):
450 # The variable reference substitutes to nothing.
453 class FunctionAction(ActionBase):
454 """Class for Python function actions."""
455 def __init__(self, function):
456 self.function = function
458 def execute(self, **kw):
460 # XXX: WHAT SHOULD WE PRINT HERE?
462 if kw.has_key('target') and not \
463 SCons.Util.is_List(kw['target']):
464 kw['target'] = [ kw['target'] ]
465 if kw.has_key('source'):
469 except AttributeError:
471 if not SCons.Util.is_List(kw['source']):
472 kw['source'] = [ kw['source'] ]
473 kw['source'] = map(rfile, kw['source'])
474 if kw.has_key("env") and not isinstance(kw["env"], EnvDictProxy):
475 kw["env"] = EnvDictProxy(kw["env"])
476 return apply(self.function, (), kw)
478 def get_contents(self, **kw):
479 """Return the signature contents of this callable action.
481 By providing direct access to the code object of the
482 function, Python makes this extremely easy. Hooray!
484 #XXX DOES NOT ACCOUNT FOR CHANGES IN ENVIRONMENT VARIABLES
485 #THE FUNCTION MAY USE
487 # "self.function" is a function.
488 code = self.function.func_code.co_code
490 # "self.function" is a callable object.
491 code = self.function.__call__.im_func.func_code.co_code
494 class ListAction(ActionBase):
495 """Class for lists of other actions."""
496 def __init__(self, list):
497 self.list = map(lambda x: Action(x), list)
499 def execute(self, **kw):
501 r = apply(l.execute, (), kw)
506 def get_contents(self, **kw):
507 """Return the signature contents of this action list.
509 Simple concatenation of the signatures of the elements.
512 return reduce(lambda x, y, kw=kw: x + str(apply(y.get_contents, (), kw)), self.list, "")