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__"
51 if os.name == 'posix':
53 def defaultSpawn(cmd, args, env):
58 args = [ 'sh', '-c' ] + \
59 [ string.join(map(lambda x: string.replace(str(x),
64 os.execvpe('sh', args, env)
66 exitval = exitvalmap[e[0]]
67 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
71 pid, stat = os.waitpid(pid, 0)
77 def pathsearch(cmd, env):
78 # In order to deal with the fact that 1.5.2 doesn't have
79 # os.spawnvpe(), roll our own PATH search.
80 if os.path.isabs(cmd):
81 if not os.path.exists(cmd):
83 if not SCons.Util.is_List(exts):
84 exts = string.split(exts, os.pathsep)
93 if not SCons.Util.is_List(path):
94 path = string.split(path, os.pathsep)
96 if not SCons.Util.is_List(exts):
97 exts = string.split(exts, os.pathsep)
101 pairs.append((dir, e))
102 for dir, ext in pairs:
103 f = os.path.join(dir, cmd)
106 if os.path.exists(f):
110 # Attempt to find cmd.exe (for WinNT/2k/XP) or
111 # command.com for Win9x
114 # First see if we can look in the registry...
115 if SCons.Util.can_read_reg:
117 # Look for Windows NT system root
118 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
119 'Software\\Microsoft\\Windows NT\\CurrentVersion')
120 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
121 cmd_interp = os.path.join(val, 'System32\\cmd.exe')
122 except SCons.Util.RegError:
124 # Okay, try the Windows 9x system root
125 k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
126 'Software\\Microsoft\\Windows\\CurrentVersion')
127 val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
128 cmd_interp = os.path.join(val, 'command.com')
132 cmd_interp = pathsearch('cmd', os.environ)
134 cmd_interp = pathsearch('command', os.environ)
136 # The upshot of all this is that, if you are using Python 1.5.2,
137 # you had better have cmd or command.com in your PATH when you run
140 def defaultSpawn(cmd, args, env):
142 sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
147 a = [ cmd_interp, '/C', args[0] ]
149 if ' ' in arg or '\t' in arg:
150 arg = '"' + arg + '"'
152 ret = os.spawnve(os.P_WAIT, cmd_interp, a, env)
154 ret = exitvalmap[e[0]]
155 sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
158 def defaultSpawn(cmd, args, env):
159 sys.stderr.write("scons: Unknown os '%s', cannot spawn command interpreter.\n" % os.name)
160 sys.stderr.write("scons: Set your command handler with SetCommandHandler().\n")
165 def SetCommandHandler(func):
169 def GetCommandHandler():
173 class CommandGenerator:
175 Wraps a command generator function so the Action() factory
176 function can tell a generator function from a function action.
178 def __init__(self, generator):
179 self.generator = generator
181 def _do_create_action(act):
182 """This is the actual "implementation" for the
183 Action factory method, below. This handles the
184 fact that passing lists to Action() itself has
185 different semantics than passing lists as elements
188 The former will create a ListAction, the latter
189 will create a CommandAction by converting the inner
190 list elements to strings."""
192 if isinstance(act, ActionBase):
194 elif SCons.Util.is_List(act):
195 return CommandAction(act)
196 elif isinstance(act, CommandGenerator):
197 return CommandGeneratorAction(act.generator)
199 return FunctionAction(act)
200 elif SCons.Util.is_String(act):
201 listCmds = map(lambda x: CommandAction(string.split(x)),
202 string.split(act, '\n'))
203 if len(listCmds) == 1:
206 return ListAction(listCmds)
211 """A factory for action objects."""
212 if SCons.Util.is_List(act):
213 acts = filter(lambda x: not x is None,
214 map(_do_create_action, act))
218 return ListAction(acts)
220 return _do_create_action(act)
223 """Base class for actions that create output objects."""
224 def __cmp__(self, other):
225 return cmp(self.__dict__, other.__dict__)
227 def show(self, string):
230 def subst_dict(self, **kw):
231 """Create a dictionary for substitution of construction
234 This translates the following special arguments:
236 env - the construction environment itself,
237 the values of which (CC, CCFLAGS, etc.)
238 are copied straight into the dictionary
240 target - the target (object or array of objects),
241 used to generate the TARGET and TARGETS
242 construction variables
244 source - the source (object or array of objects),
245 used to generate the SOURCES and SOURCE
246 construction variables
248 Any other keyword arguments are copied into the
252 if kw.has_key('env'):
253 dict.update(kw['env'])
263 if kw.has_key('target'):
266 if not SCons.Util.is_List(t):
270 except (IndexError, AttributeError):
272 dict['TARGETS'] = SCons.Util.PathList(map(os.path.normpath, map(str, t)))
274 dict['TARGET'] = dict['TARGETS'][0]
276 if kw.has_key('source'):
279 if not SCons.Util.is_List(s):
281 dict['SOURCES'] = SCons.Util.PathList(map(os.path.normpath, map(str, s)))
283 dict['SOURCE'] = dict['SOURCES'][0]
289 def _string_from_cmd_list(cmd_list):
290 """Takes a list of command line arguments and returns a pretty
291 representation for printing."""
294 if ' ' in arg or '\t' in arg:
295 arg = '"' + arg + '"'
297 return string.join(cl)
299 _rm = re.compile(r'\$[()]')
300 _remove = re.compile(r'\$\(([^\$]|\$[^\(])*?\$\)')
302 class EnvDictProxy(UserDict.UserDict):
303 """This is a dictionary-like class that contains the
304 Environment dictionary we pass to FunctionActions
305 and CommandGeneratorActions.
307 In addition to providing
308 normal dictionary-like access to the variables in the
309 Environment, it also exposes the functions subst()
310 and subst_list(), allowing users to easily do variable
311 interpolation when writing their FunctionActions
312 and CommandGeneratorActions."""
314 def __init__(self, env):
315 UserDict.UserDict.__init__(self, env)
317 def subst(self, string):
318 return SCons.Util.scons_subst(string, self.data, {}, _rm)
320 def subst_list(self, string):
321 return SCons.Util.scons_subst_list(string, self.data, {}, _rm)
323 class CommandAction(ActionBase):
324 """Class for command-execution actions."""
325 def __init__(self, cmd):
328 self.cmd_list = map(SCons.Util.to_String, cmd)
330 def execute(self, **kw):
331 dict = apply(self.subst_dict, (), kw)
333 cmd_list = SCons.Util.scons_subst_list(self.cmd_list, dict, {}, _rm)
334 for cmd_line in cmd_list:
337 self.show(_string_from_cmd_list(cmd_line))
340 ENV = kw['env']['ENV']
342 import SCons.Defaults
343 ENV = SCons.Defaults.ConstructionEnvironment['ENV']
344 ret = spawn(cmd_line[0], cmd_line, ENV)
349 def _sig_dict(self, kw):
350 """Supply a dictionary for use in computing signatures.
352 For signature purposes, it doesn't matter what targets or
353 sources we use, so long as we use the same ones every time
354 so the signature stays the same. We supply an array of two
355 of each to allow for distinction between TARGET and TARGETS.
357 kw['target'] = ['__t1__', '__t2__']
358 kw['source'] = ['__s1__', '__s2__']
359 return apply(self.subst_dict, (), kw)
361 def get_raw_contents(self, **kw):
362 """Return the complete contents of this action's command line.
364 return SCons.Util.scons_subst(string.join(self.cmd_list),
365 self._sig_dict(kw), {})
367 def get_contents(self, **kw):
368 """Return the signature contents of this action's command line.
370 This strips $(-$) and everything in between the string,
371 since those parts don't affect signatures.
373 return SCons.Util.scons_subst(string.join(self.cmd_list),
374 self._sig_dict(kw), {}, _remove)
376 class CommandGeneratorAction(ActionBase):
377 """Class for command-generator actions."""
378 def __init__(self, generator):
379 self.generator = generator
381 def __generate(self, kw):
384 # Wrap the environment dictionary in an EnvDictProxy
385 # object to make variable interpolation easier for the
388 if args.has_key("env") and not isinstance(args["env"], EnvDictProxy):
389 args["env"] = EnvDictProxy(args["env"])
391 # ensure that target is a list, to make it easier to write
392 # generator functions:
393 if args.has_key("target") and not SCons.Util.is_List(args["target"]):
394 args["target"] = [args["target"]]
396 ret = apply(self.generator, (), args)
397 gen_cmd = Action(ret)
399 raise SCons.Errors.UserError("Object returned from command generator: %s cannot be used to create an Action." % repr(ret))
402 def execute(self, **kw):
403 return apply(self.__generate(kw).execute, (), kw)
405 def get_contents(self, **kw):
406 """Return the signature contents of this action's command line.
408 This strips $(-$) and everything in between the string,
409 since those parts don't affect signatures.
411 return apply(self.__generate(kw).get_contents, (), kw)
413 class FunctionAction(ActionBase):
414 """Class for Python function actions."""
415 def __init__(self, function):
416 self.function = function
418 def execute(self, **kw):
420 # XXX: WHAT SHOULD WE PRINT HERE?
422 if kw.has_key('target') and not \
423 SCons.Util.is_List(kw['target']):
424 kw['target'] = [ kw['target'] ]
425 if kw.has_key('source') and not \
426 SCons.Util.is_List(kw['source']):
427 kw['source'] = [ kw['source'] ]
428 if kw.has_key("env") and not isinstance(kw["env"], EnvDictProxy):
429 kw["env"] = EnvDictProxy(kw["env"])
430 return apply(self.function, (), kw)
432 def get_contents(self, **kw):
433 """Return the signature contents of this callable action.
435 By providing direct access to the code object of the
436 function, Python makes this extremely easy. Hooray!
438 #XXX DOES NOT ACCOUNT FOR CHANGES IN ENVIRONMENT VARIABLES
439 #THE FUNCTION MAY USE
441 # "self.function" is a function.
442 code = self.function.func_code.co_code
444 # "self.function" is a callable object.
445 code = self.function.__call__.im_func.func_code.co_code
448 class ListAction(ActionBase):
449 """Class for lists of other actions."""
450 def __init__(self, list):
451 self.list = map(lambda x: Action(x), list)
453 def execute(self, **kw):
455 r = apply(l.execute, (), kw)
460 def get_contents(self, **kw):
461 """Return the signature contents of this action list.
463 Simple concatenation of the signatures of the elements.
466 return reduce(lambda x, y: x + str(y.get_contents()), self.list, "")