PageRenderTime 57ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/couchjs/scons/scons-local-2.0.1/SCons/Action.py

http://github.com/cloudant/bigcouch
Python | 1241 lines | 1190 code | 9 blank | 42 comment | 8 complexity | d39a8cf7ea8a3340a97f4d1a062fb8b3 MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Action
  2. This encapsulates information about executing any sort of action that
  3. can build one or more target Nodes (typically files) from one or more
  4. source Nodes (also typically files) given a specific Environment.
  5. The base class here is ActionBase. The base class supplies just a few
  6. OO utility methods and some generic methods for displaying information
  7. about an Action in response to the various commands that control printing.
  8. A second-level base class is _ActionAction. This extends ActionBase
  9. by providing the methods that can be used to show and perform an
  10. action. True Action objects will subclass _ActionAction; Action
  11. factory class objects will subclass ActionBase.
  12. The heavy lifting is handled by subclasses for the different types of
  13. actions we might execute:
  14. CommandAction
  15. CommandGeneratorAction
  16. FunctionAction
  17. ListAction
  18. The subclasses supply the following public interface methods used by
  19. other modules:
  20. __call__()
  21. THE public interface, "calling" an Action object executes the
  22. command or Python function. This also takes care of printing
  23. a pre-substitution command for debugging purposes.
  24. get_contents()
  25. Fetches the "contents" of an Action for signature calculation
  26. plus the varlist. This is what gets MD5 checksummed to decide
  27. if a target needs to be rebuilt because its action changed.
  28. genstring()
  29. Returns a string representation of the Action *without*
  30. command substitution, but allows a CommandGeneratorAction to
  31. generate the right action based on the specified target,
  32. source and env. This is used by the Signature subsystem
  33. (through the Executor) to obtain an (imprecise) representation
  34. of the Action operation for informative purposes.
  35. Subclasses also supply the following methods for internal use within
  36. this module:
  37. __str__()
  38. Returns a string approximation of the Action; no variable
  39. substitution is performed.
  40. execute()
  41. The internal method that really, truly, actually handles the
  42. execution of a command or Python function. This is used so
  43. that the __call__() methods can take care of displaying any
  44. pre-substitution representations, and *then* execute an action
  45. without worrying about the specific Actions involved.
  46. get_presig()
  47. Fetches the "contents" of a subclass for signature calculation.
  48. The varlist is added to this to produce the Action's contents.
  49. strfunction()
  50. Returns a substituted string representation of the Action.
  51. This is used by the _ActionAction.show() command to display the
  52. command/function that will be executed to generate the target(s).
  53. There is a related independent ActionCaller class that looks like a
  54. regular Action, and which serves as a wrapper for arbitrary functions
  55. that we want to let the user specify the arguments to now, but actually
  56. execute later (when an out-of-date check determines that it's needed to
  57. be executed, for example). Objects of this class are returned by an
  58. ActionFactory class that provides a __call__() method as a convenient
  59. way for wrapping up the functions.
  60. """
  61. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  62. #
  63. # Permission is hereby granted, free of charge, to any person obtaining
  64. # a copy of this software and associated documentation files (the
  65. # "Software"), to deal in the Software without restriction, including
  66. # without limitation the rights to use, copy, modify, merge, publish,
  67. # distribute, sublicense, and/or sell copies of the Software, and to
  68. # permit persons to whom the Software is furnished to do so, subject to
  69. # the following conditions:
  70. #
  71. # The above copyright notice and this permission notice shall be included
  72. # in all copies or substantial portions of the Software.
  73. #
  74. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  75. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  76. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  77. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  78. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  79. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  80. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  81. __revision__ = "src/engine/SCons/Action.py 5134 2010/08/16 23:02:40 bdeegan"
  82. import SCons.compat
  83. import dis
  84. import os
  85. # compat layer imports "cPickle" for us if it's available.
  86. import pickle
  87. import re
  88. import sys
  89. import subprocess
  90. from SCons.Debug import logInstanceCreation
  91. import SCons.Errors
  92. import SCons.Executor
  93. import SCons.Util
  94. import SCons.Subst
  95. # we use these a lot, so try to optimize them
  96. is_String = SCons.Util.is_String
  97. is_List = SCons.Util.is_List
  98. class _null(object):
  99. pass
  100. print_actions = 1
  101. execute_actions = 1
  102. print_actions_presub = 0
  103. def rfile(n):
  104. try:
  105. return n.rfile()
  106. except AttributeError:
  107. return n
  108. def default_exitstatfunc(s):
  109. return s
  110. try:
  111. SET_LINENO = dis.SET_LINENO
  112. HAVE_ARGUMENT = dis.HAVE_ARGUMENT
  113. except AttributeError:
  114. remove_set_lineno_codes = lambda x: x
  115. else:
  116. def remove_set_lineno_codes(code):
  117. result = []
  118. n = len(code)
  119. i = 0
  120. while i < n:
  121. c = code[i]
  122. op = ord(c)
  123. if op >= HAVE_ARGUMENT:
  124. if op != SET_LINENO:
  125. result.append(code[i:i+3])
  126. i = i+3
  127. else:
  128. result.append(c)
  129. i = i+1
  130. return ''.join(result)
  131. strip_quotes = re.compile('^[\'"](.*)[\'"]$')
  132. def _callable_contents(obj):
  133. """Return the signature contents of a callable Python object.
  134. """
  135. try:
  136. # Test if obj is a method.
  137. return _function_contents(obj.im_func)
  138. except AttributeError:
  139. try:
  140. # Test if obj is a callable object.
  141. return _function_contents(obj.__call__.im_func)
  142. except AttributeError:
  143. try:
  144. # Test if obj is a code object.
  145. return _code_contents(obj)
  146. except AttributeError:
  147. # Test if obj is a function object.
  148. return _function_contents(obj)
  149. def _object_contents(obj):
  150. """Return the signature contents of any Python object.
  151. We have to handle the case where object contains a code object
  152. since it can be pickled directly.
  153. """
  154. try:
  155. # Test if obj is a method.
  156. return _function_contents(obj.im_func)
  157. except AttributeError:
  158. try:
  159. # Test if obj is a callable object.
  160. return _function_contents(obj.__call__.im_func)
  161. except AttributeError:
  162. try:
  163. # Test if obj is a code object.
  164. return _code_contents(obj)
  165. except AttributeError:
  166. try:
  167. # Test if obj is a function object.
  168. return _function_contents(obj)
  169. except AttributeError:
  170. # Should be a pickable Python object.
  171. try:
  172. return pickle.dumps(obj)
  173. except (pickle.PicklingError, TypeError):
  174. # This is weird, but it seems that nested classes
  175. # are unpickable. The Python docs say it should
  176. # always be a PicklingError, but some Python
  177. # versions seem to return TypeError. Just do
  178. # the best we can.
  179. return str(obj)
  180. def _code_contents(code):
  181. """Return the signature contents of a code object.
  182. By providing direct access to the code object of the
  183. function, Python makes this extremely easy. Hooray!
  184. Unfortunately, older versions of Python include line
  185. number indications in the compiled byte code. Boo!
  186. So we remove the line number byte codes to prevent
  187. recompilations from moving a Python function.
  188. """
  189. contents = []
  190. # The code contents depends on the number of local variables
  191. # but not their actual names.
  192. contents.append("%s,%s" % (code.co_argcount, len(code.co_varnames)))
  193. try:
  194. contents.append(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars)))
  195. except AttributeError:
  196. # Older versions of Python do not support closures.
  197. contents.append(",0,0")
  198. # The code contents depends on any constants accessed by the
  199. # function. Note that we have to call _object_contents on each
  200. # constants because the code object of nested functions can
  201. # show-up among the constants.
  202. #
  203. # Note that we also always ignore the first entry of co_consts
  204. # which contains the function doc string. We assume that the
  205. # function does not access its doc string.
  206. contents.append(',(' + ','.join(map(_object_contents,code.co_consts[1:])) + ')')
  207. # The code contents depends on the variable names used to
  208. # accessed global variable, as changing the variable name changes
  209. # the variable actually accessed and therefore changes the
  210. # function result.
  211. contents.append(',(' + ','.join(map(_object_contents,code.co_names)) + ')')
  212. # The code contents depends on its actual code!!!
  213. contents.append(',(' + str(remove_set_lineno_codes(code.co_code)) + ')')
  214. return ''.join(contents)
  215. def _function_contents(func):
  216. """Return the signature contents of a function."""
  217. contents = [_code_contents(func.func_code)]
  218. # The function contents depends on the value of defaults arguments
  219. if func.func_defaults:
  220. contents.append(',(' + ','.join(map(_object_contents,func.func_defaults)) + ')')
  221. else:
  222. contents.append(',()')
  223. # The function contents depends on the closure captured cell values.
  224. try:
  225. closure = func.func_closure or []
  226. except AttributeError:
  227. # Older versions of Python do not support closures.
  228. closure = []
  229. #xxx = [_object_contents(x.cell_contents) for x in closure]
  230. try:
  231. xxx = [_object_contents(x.cell_contents) for x in closure]
  232. except AttributeError:
  233. xxx = []
  234. contents.append(',(' + ','.join(xxx) + ')')
  235. return ''.join(contents)
  236. def _actionAppend(act1, act2):
  237. # This function knows how to slap two actions together.
  238. # Mainly, it handles ListActions by concatenating into
  239. # a single ListAction.
  240. a1 = Action(act1)
  241. a2 = Action(act2)
  242. if a1 is None or a2 is None:
  243. raise TypeError("Cannot append %s to %s" % (type(act1), type(act2)))
  244. if isinstance(a1, ListAction):
  245. if isinstance(a2, ListAction):
  246. return ListAction(a1.list + a2.list)
  247. else:
  248. return ListAction(a1.list + [ a2 ])
  249. else:
  250. if isinstance(a2, ListAction):
  251. return ListAction([ a1 ] + a2.list)
  252. else:
  253. return ListAction([ a1, a2 ])
  254. def _do_create_keywords(args, kw):
  255. """This converts any arguments after the action argument into
  256. their equivalent keywords and adds them to the kw argument.
  257. """
  258. v = kw.get('varlist', ())
  259. # prevent varlist="FOO" from being interpreted as ['F', 'O', 'O']
  260. if is_String(v): v = (v,)
  261. kw['varlist'] = tuple(v)
  262. if args:
  263. # turn positional args into equivalent keywords
  264. cmdstrfunc = args[0]
  265. if cmdstrfunc is None or is_String(cmdstrfunc):
  266. kw['cmdstr'] = cmdstrfunc
  267. elif callable(cmdstrfunc):
  268. kw['strfunction'] = cmdstrfunc
  269. else:
  270. raise SCons.Errors.UserError(
  271. 'Invalid command display variable type. '
  272. 'You must either pass a string or a callback which '
  273. 'accepts (target, source, env) as parameters.')
  274. if len(args) > 1:
  275. kw['varlist'] = args[1:] + kw['varlist']
  276. if kw.get('strfunction', _null) is not _null \
  277. and kw.get('cmdstr', _null) is not _null:
  278. raise SCons.Errors.UserError(
  279. 'Cannot have both strfunction and cmdstr args to Action()')
  280. def _do_create_action(act, kw):
  281. """This is the actual "implementation" for the
  282. Action factory method, below. This handles the
  283. fact that passing lists to Action() itself has
  284. different semantics than passing lists as elements
  285. of lists.
  286. The former will create a ListAction, the latter
  287. will create a CommandAction by converting the inner
  288. list elements to strings."""
  289. if isinstance(act, ActionBase):
  290. return act
  291. if is_List(act):
  292. return CommandAction(act, **kw)
  293. if callable(act):
  294. try:
  295. gen = kw['generator']
  296. del kw['generator']
  297. except KeyError:
  298. gen = 0
  299. if gen:
  300. action_type = CommandGeneratorAction
  301. else:
  302. action_type = FunctionAction
  303. return action_type(act, kw)
  304. if is_String(act):
  305. var=SCons.Util.get_environment_var(act)
  306. if var:
  307. # This looks like a string that is purely an Environment
  308. # variable reference, like "$FOO" or "${FOO}". We do
  309. # something special here...we lazily evaluate the contents
  310. # of that Environment variable, so a user could put something
  311. # like a function or a CommandGenerator in that variable
  312. # instead of a string.
  313. return LazyAction(var, kw)
  314. commands = str(act).split('\n')
  315. if len(commands) == 1:
  316. return CommandAction(commands[0], **kw)
  317. # The list of string commands may include a LazyAction, so we
  318. # reprocess them via _do_create_list_action.
  319. return _do_create_list_action(commands, kw)
  320. return None
  321. def _do_create_list_action(act, kw):
  322. """A factory for list actions. Convert the input list into Actions
  323. and then wrap them in a ListAction."""
  324. acts = []
  325. for a in act:
  326. aa = _do_create_action(a, kw)
  327. if aa is not None: acts.append(aa)
  328. if not acts:
  329. return ListAction([])
  330. elif len(acts) == 1:
  331. return acts[0]
  332. else:
  333. return ListAction(acts)
  334. def Action(act, *args, **kw):
  335. """A factory for action objects."""
  336. # Really simple: the _do_create_* routines do the heavy lifting.
  337. _do_create_keywords(args, kw)
  338. if is_List(act):
  339. return _do_create_list_action(act, kw)
  340. return _do_create_action(act, kw)
  341. class ActionBase(object):
  342. """Base class for all types of action objects that can be held by
  343. other objects (Builders, Executors, etc.) This provides the
  344. common methods for manipulating and combining those actions."""
  345. def __cmp__(self, other):
  346. return cmp(self.__dict__, other)
  347. def no_batch_key(self, env, target, source):
  348. return None
  349. batch_key = no_batch_key
  350. def genstring(self, target, source, env):
  351. return str(self)
  352. def get_contents(self, target, source, env):
  353. result = [ self.get_presig(target, source, env) ]
  354. # This should never happen, as the Action() factory should wrap
  355. # the varlist, but just in case an action is created directly,
  356. # we duplicate this check here.
  357. vl = self.get_varlist(target, source, env)
  358. if is_String(vl): vl = (vl,)
  359. for v in vl:
  360. result.append(env.subst('${'+v+'}'))
  361. return ''.join(result)
  362. def __add__(self, other):
  363. return _actionAppend(self, other)
  364. def __radd__(self, other):
  365. return _actionAppend(other, self)
  366. def presub_lines(self, env):
  367. # CommandGeneratorAction needs a real environment
  368. # in order to return the proper string here, since
  369. # it may call LazyAction, which looks up a key
  370. # in that env. So we temporarily remember the env here,
  371. # and CommandGeneratorAction will use this env
  372. # when it calls its _generate method.
  373. self.presub_env = env
  374. lines = str(self).split('\n')
  375. self.presub_env = None # don't need this any more
  376. return lines
  377. def get_varlist(self, target, source, env, executor=None):
  378. return self.varlist
  379. def get_targets(self, env, executor):
  380. """
  381. Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used
  382. by this action.
  383. """
  384. return self.targets
  385. class _ActionAction(ActionBase):
  386. """Base class for actions that create output objects."""
  387. def __init__(self, cmdstr=_null, strfunction=_null, varlist=(),
  388. presub=_null, chdir=None, exitstatfunc=None,
  389. batch_key=None, targets='$TARGETS',
  390. **kw):
  391. self.cmdstr = cmdstr
  392. if strfunction is not _null:
  393. if strfunction is None:
  394. self.cmdstr = None
  395. else:
  396. self.strfunction = strfunction
  397. self.varlist = varlist
  398. self.presub = presub
  399. self.chdir = chdir
  400. if not exitstatfunc:
  401. exitstatfunc = default_exitstatfunc
  402. self.exitstatfunc = exitstatfunc
  403. self.targets = targets
  404. if batch_key:
  405. if not callable(batch_key):
  406. # They have set batch_key, but not to their own
  407. # callable. The default behavior here will batch
  408. # *all* targets+sources using this action, separated
  409. # for each construction environment.
  410. def default_batch_key(self, env, target, source):
  411. return (id(self), id(env))
  412. batch_key = default_batch_key
  413. SCons.Util.AddMethod(self, batch_key, 'batch_key')
  414. def print_cmd_line(self, s, target, source, env):
  415. sys.stdout.write(s + u"\n")
  416. def __call__(self, target, source, env,
  417. exitstatfunc=_null,
  418. presub=_null,
  419. show=_null,
  420. execute=_null,
  421. chdir=_null,
  422. executor=None):
  423. if not is_List(target):
  424. target = [target]
  425. if not is_List(source):
  426. source = [source]
  427. if presub is _null:
  428. presub = self.presub
  429. if presub is _null:
  430. presub = print_actions_presub
  431. if exitstatfunc is _null: exitstatfunc = self.exitstatfunc
  432. if show is _null: show = print_actions
  433. if execute is _null: execute = execute_actions
  434. if chdir is _null: chdir = self.chdir
  435. save_cwd = None
  436. if chdir:
  437. save_cwd = os.getcwd()
  438. try:
  439. chdir = str(chdir.abspath)
  440. except AttributeError:
  441. if not is_String(chdir):
  442. if executor:
  443. chdir = str(executor.batches[0].targets[0].dir)
  444. else:
  445. chdir = str(target[0].dir)
  446. if presub:
  447. if executor:
  448. target = executor.get_all_targets()
  449. source = executor.get_all_sources()
  450. t = ' and '.join(map(str, target))
  451. l = '\n '.join(self.presub_lines(env))
  452. out = u"Building %s with action:\n %s\n" % (t, l)
  453. sys.stdout.write(out)
  454. cmd = None
  455. if show and self.strfunction:
  456. if executor:
  457. target = executor.get_all_targets()
  458. source = executor.get_all_sources()
  459. try:
  460. cmd = self.strfunction(target, source, env, executor)
  461. except TypeError:
  462. cmd = self.strfunction(target, source, env)
  463. if cmd:
  464. if chdir:
  465. cmd = ('os.chdir(%s)\n' % repr(chdir)) + cmd
  466. try:
  467. get = env.get
  468. except AttributeError:
  469. print_func = self.print_cmd_line
  470. else:
  471. print_func = get('PRINT_CMD_LINE_FUNC')
  472. if not print_func:
  473. print_func = self.print_cmd_line
  474. print_func(cmd, target, source, env)
  475. stat = 0
  476. if execute:
  477. if chdir:
  478. os.chdir(chdir)
  479. try:
  480. stat = self.execute(target, source, env, executor=executor)
  481. if isinstance(stat, SCons.Errors.BuildError):
  482. s = exitstatfunc(stat.status)
  483. if s:
  484. stat.status = s
  485. else:
  486. stat = s
  487. else:
  488. stat = exitstatfunc(stat)
  489. finally:
  490. if save_cwd:
  491. os.chdir(save_cwd)
  492. if cmd and save_cwd:
  493. print_func('os.chdir(%s)' % repr(save_cwd), target, source, env)
  494. return stat
  495. def _string_from_cmd_list(cmd_list):
  496. """Takes a list of command line arguments and returns a pretty
  497. representation for printing."""
  498. cl = []
  499. for arg in map(str, cmd_list):
  500. if ' ' in arg or '\t' in arg:
  501. arg = '"' + arg + '"'
  502. cl.append(arg)
  503. return ' '.join(cl)
  504. # A fiddlin' little function that has an 'import SCons.Environment' which
  505. # can't be moved to the top level without creating an import loop. Since
  506. # this import creates a local variable named 'SCons', it blocks access to
  507. # the global variable, so we move it here to prevent complaints about local
  508. # variables being used uninitialized.
  509. default_ENV = None
  510. def get_default_ENV(env):
  511. global default_ENV
  512. try:
  513. return env['ENV']
  514. except KeyError:
  515. if not default_ENV:
  516. import SCons.Environment
  517. # This is a hideously expensive way to get a default shell
  518. # environment. What it really should do is run the platform
  519. # setup to get the default ENV. Fortunately, it's incredibly
  520. # rare for an Environment not to have a shell environment, so
  521. # we're not going to worry about it overmuch.
  522. default_ENV = SCons.Environment.Environment()['ENV']
  523. return default_ENV
  524. # This function is still in draft mode. We're going to need something like
  525. # it in the long run as more and more places use subprocess, but I'm sure
  526. # it'll have to be tweaked to get the full desired functionality.
  527. # one special arg (so far?), 'error', to tell what to do with exceptions.
  528. def _subproc(scons_env, cmd, error = 'ignore', **kw):
  529. """Do common setup for a subprocess.Popen() call"""
  530. # allow std{in,out,err} to be "'devnull'"
  531. io = kw.get('stdin')
  532. if is_String(io) and io == 'devnull':
  533. kw['stdin'] = open(os.devnull)
  534. io = kw.get('stdout')
  535. if is_String(io) and io == 'devnull':
  536. kw['stdout'] = open(os.devnull, 'w')
  537. io = kw.get('stderr')
  538. if is_String(io) and io == 'devnull':
  539. kw['stderr'] = open(os.devnull, 'w')
  540. # Figure out what shell environment to use
  541. ENV = kw.get('env', None)
  542. if ENV is None: ENV = get_default_ENV(scons_env)
  543. # Ensure that the ENV values are all strings:
  544. new_env = {}
  545. for key, value in ENV.items():
  546. if is_List(value):
  547. # If the value is a list, then we assume it is a path list,
  548. # because that's a pretty common list-like value to stick
  549. # in an environment variable:
  550. value = SCons.Util.flatten_sequence(value)
  551. new_env[key] = os.pathsep.join(map(str, value))
  552. else:
  553. # It's either a string or something else. If it's a string,
  554. # we still want to call str() because it might be a *Unicode*
  555. # string, which makes subprocess.Popen() gag. If it isn't a
  556. # string or a list, then we just coerce it to a string, which
  557. # is the proper way to handle Dir and File instances and will
  558. # produce something reasonable for just about everything else:
  559. new_env[key] = str(value)
  560. kw['env'] = new_env
  561. try:
  562. #FUTURE return subprocess.Popen(cmd, **kw)
  563. return subprocess.Popen(cmd, **kw)
  564. except EnvironmentError, e:
  565. if error == 'raise': raise
  566. # return a dummy Popen instance that only returns error
  567. class dummyPopen(object):
  568. def __init__(self, e): self.exception = e
  569. def communicate(self): return ('','')
  570. def wait(self): return -self.exception.errno
  571. stdin = None
  572. class f(object):
  573. def read(self): return ''
  574. def readline(self): return ''
  575. stdout = stderr = f()
  576. return dummyPopen(e)
  577. class CommandAction(_ActionAction):
  578. """Class for command-execution actions."""
  579. def __init__(self, cmd, **kw):
  580. # Cmd can actually be a list or a single item; if it's a
  581. # single item it should be the command string to execute; if a
  582. # list then it should be the words of the command string to
  583. # execute. Only a single command should be executed by this
  584. # object; lists of commands should be handled by embedding
  585. # these objects in a ListAction object (which the Action()
  586. # factory above does). cmd will be passed to
  587. # Environment.subst_list() for substituting environment
  588. # variables.
  589. if __debug__: logInstanceCreation(self, 'Action.CommandAction')
  590. _ActionAction.__init__(self, **kw)
  591. if is_List(cmd):
  592. if list(filter(is_List, cmd)):
  593. raise TypeError("CommandAction should be given only " \
  594. "a single command")
  595. self.cmd_list = cmd
  596. def __str__(self):
  597. if is_List(self.cmd_list):
  598. return ' '.join(map(str, self.cmd_list))
  599. return str(self.cmd_list)
  600. def process(self, target, source, env, executor=None):
  601. if executor:
  602. result = env.subst_list(self.cmd_list, 0, executor=executor)
  603. else:
  604. result = env.subst_list(self.cmd_list, 0, target, source)
  605. silent = None
  606. ignore = None
  607. while True:
  608. try: c = result[0][0][0]
  609. except IndexError: c = None
  610. if c == '@': silent = 1
  611. elif c == '-': ignore = 1
  612. else: break
  613. result[0][0] = result[0][0][1:]
  614. try:
  615. if not result[0][0]:
  616. result[0] = result[0][1:]
  617. except IndexError:
  618. pass
  619. return result, ignore, silent
  620. def strfunction(self, target, source, env, executor=None):
  621. if self.cmdstr is None:
  622. return None
  623. if self.cmdstr is not _null:
  624. from SCons.Subst import SUBST_RAW
  625. if executor:
  626. c = env.subst(self.cmdstr, SUBST_RAW, executor=executor)
  627. else:
  628. c = env.subst(self.cmdstr, SUBST_RAW, target, source)
  629. if c:
  630. return c
  631. cmd_list, ignore, silent = self.process(target, source, env, executor)
  632. if silent:
  633. return ''
  634. return _string_from_cmd_list(cmd_list[0])
  635. def execute(self, target, source, env, executor=None):
  636. """Execute a command action.
  637. This will handle lists of commands as well as individual commands,
  638. because construction variable substitution may turn a single
  639. "command" into a list. This means that this class can actually
  640. handle lists of commands, even though that's not how we use it
  641. externally.
  642. """
  643. escape_list = SCons.Subst.escape_list
  644. flatten_sequence = SCons.Util.flatten_sequence
  645. try:
  646. shell = env['SHELL']
  647. except KeyError:
  648. raise SCons.Errors.UserError('Missing SHELL construction variable.')
  649. try:
  650. spawn = env['SPAWN']
  651. except KeyError:
  652. raise SCons.Errors.UserError('Missing SPAWN construction variable.')
  653. else:
  654. if is_String(spawn):
  655. spawn = env.subst(spawn, raw=1, conv=lambda x: x)
  656. escape = env.get('ESCAPE', lambda x: x)
  657. ENV = get_default_ENV(env)
  658. # Ensure that the ENV values are all strings:
  659. for key, value in ENV.items():
  660. if not is_String(value):
  661. if is_List(value):
  662. # If the value is a list, then we assume it is a
  663. # path list, because that's a pretty common list-like
  664. # value to stick in an environment variable:
  665. value = flatten_sequence(value)
  666. ENV[key] = os.pathsep.join(map(str, value))
  667. else:
  668. # If it isn't a string or a list, then we just coerce
  669. # it to a string, which is the proper way to handle
  670. # Dir and File instances and will produce something
  671. # reasonable for just about everything else:
  672. ENV[key] = str(value)
  673. if executor:
  674. target = executor.get_all_targets()
  675. source = executor.get_all_sources()
  676. cmd_list, ignore, silent = self.process(target, list(map(rfile, source)), env, executor)
  677. # Use len() to filter out any "command" that's zero-length.
  678. for cmd_line in filter(len, cmd_list):
  679. # Escape the command line for the interpreter we are using.
  680. cmd_line = escape_list(cmd_line, escape)
  681. result = spawn(shell, escape, cmd_line[0], cmd_line, ENV)
  682. if not ignore and result:
  683. msg = "Error %s" % result
  684. return SCons.Errors.BuildError(errstr=msg,
  685. status=result,
  686. action=self,
  687. command=cmd_line)
  688. return 0
  689. def get_presig(self, target, source, env, executor=None):
  690. """Return the signature contents of this action's command line.
  691. This strips $(-$) and everything in between the string,
  692. since those parts don't affect signatures.
  693. """
  694. from SCons.Subst import SUBST_SIG
  695. cmd = self.cmd_list
  696. if is_List(cmd):
  697. cmd = ' '.join(map(str, cmd))
  698. else:
  699. cmd = str(cmd)
  700. if executor:
  701. return env.subst_target_source(cmd, SUBST_SIG, executor=executor)
  702. else:
  703. return env.subst_target_source(cmd, SUBST_SIG, target, source)
  704. def get_implicit_deps(self, target, source, env, executor=None):
  705. icd = env.get('IMPLICIT_COMMAND_DEPENDENCIES', True)
  706. if is_String(icd) and icd[:1] == '$':
  707. icd = env.subst(icd)
  708. if not icd or icd in ('0', 'None'):
  709. return []
  710. from SCons.Subst import SUBST_SIG
  711. if executor:
  712. cmd_list = env.subst_list(self.cmd_list, SUBST_SIG, executor=executor)
  713. else:
  714. cmd_list = env.subst_list(self.cmd_list, SUBST_SIG, target, source)
  715. res = []
  716. for cmd_line in cmd_list:
  717. if cmd_line:
  718. d = str(cmd_line[0])
  719. m = strip_quotes.match(d)
  720. if m:
  721. d = m.group(1)
  722. d = env.WhereIs(d)
  723. if d:
  724. res.append(env.fs.File(d))
  725. return res
  726. class CommandGeneratorAction(ActionBase):
  727. """Class for command-generator actions."""
  728. def __init__(self, generator, kw):
  729. if __debug__: logInstanceCreation(self, 'Action.CommandGeneratorAction')
  730. self.generator = generator
  731. self.gen_kw = kw
  732. self.varlist = kw.get('varlist', ())
  733. self.targets = kw.get('targets', '$TARGETS')
  734. def _generate(self, target, source, env, for_signature, executor=None):
  735. # ensure that target is a list, to make it easier to write
  736. # generator functions:
  737. if not is_List(target):
  738. target = [target]
  739. if executor:
  740. target = executor.get_all_targets()
  741. source = executor.get_all_sources()
  742. ret = self.generator(target=target,
  743. source=source,
  744. env=env,
  745. for_signature=for_signature)
  746. gen_cmd = Action(ret, **self.gen_kw)
  747. if not gen_cmd:
  748. raise SCons.Errors.UserError("Object returned from command generator: %s cannot be used to create an Action." % repr(ret))
  749. return gen_cmd
  750. def __str__(self):
  751. try:
  752. env = self.presub_env
  753. except AttributeError:
  754. env = None
  755. if env is None:
  756. env = SCons.Defaults.DefaultEnvironment()
  757. act = self._generate([], [], env, 1)
  758. return str(act)
  759. def batch_key(self, env, target, source):
  760. return self._generate(target, source, env, 1).batch_key(env, target, source)
  761. def genstring(self, target, source, env, executor=None):
  762. return self._generate(target, source, env, 1, executor).genstring(target, source, env)
  763. def __call__(self, target, source, env, exitstatfunc=_null, presub=_null,
  764. show=_null, execute=_null, chdir=_null, executor=None):
  765. act = self._generate(target, source, env, 0, executor)
  766. if act is None:
  767. raise UserError("While building `%s': "
  768. "Cannot deduce file extension from source files: %s"
  769. % (repr(list(map(str, target))), repr(list(map(str, source)))))
  770. return act(target, source, env, exitstatfunc, presub,
  771. show, execute, chdir, executor)
  772. def get_presig(self, target, source, env, executor=None):
  773. """Return the signature contents of this action's command line.
  774. This strips $(-$) and everything in between the string,
  775. since those parts don't affect signatures.
  776. """
  777. return self._generate(target, source, env, 1, executor).get_presig(target, source, env)
  778. def get_implicit_deps(self, target, source, env, executor=None):
  779. return self._generate(target, source, env, 1, executor).get_implicit_deps(target, source, env)
  780. def get_varlist(self, target, source, env, executor=None):
  781. return self._generate(target, source, env, 1, executor).get_varlist(target, source, env, executor)
  782. def get_targets(self, env, executor):
  783. return self._generate(None, None, env, 1, executor).get_targets(env, executor)
  784. # A LazyAction is a kind of hybrid generator and command action for
  785. # strings of the form "$VAR". These strings normally expand to other
  786. # strings (think "$CCCOM" to "$CC -c -o $TARGET $SOURCE"), but we also
  787. # want to be able to replace them with functions in the construction
  788. # environment. Consequently, we want lazy evaluation and creation of
  789. # an Action in the case of the function, but that's overkill in the more
  790. # normal case of expansion to other strings.
  791. #
  792. # So we do this with a subclass that's both a generator *and*
  793. # a command action. The overridden methods all do a quick check
  794. # of the construction variable, and if it's a string we just call
  795. # the corresponding CommandAction method to do the heavy lifting.
  796. # If not, then we call the same-named CommandGeneratorAction method.
  797. # The CommandGeneratorAction methods work by using the overridden
  798. # _generate() method, that is, our own way of handling "generation" of
  799. # an action based on what's in the construction variable.
  800. class LazyAction(CommandGeneratorAction, CommandAction):
  801. def __init__(self, var, kw):
  802. if __debug__: logInstanceCreation(self, 'Action.LazyAction')
  803. #FUTURE CommandAction.__init__(self, '${'+var+'}', **kw)
  804. CommandAction.__init__(self, '${'+var+'}', **kw)
  805. self.var = SCons.Util.to_String(var)
  806. self.gen_kw = kw
  807. def get_parent_class(self, env):
  808. c = env.get(self.var)
  809. if is_String(c) and not '\n' in c:
  810. return CommandAction
  811. return CommandGeneratorAction
  812. def _generate_cache(self, env):
  813. if env:
  814. c = env.get(self.var, '')
  815. else:
  816. c = ''
  817. gen_cmd = Action(c, **self.gen_kw)
  818. if not gen_cmd:
  819. raise SCons.Errors.UserError("$%s value %s cannot be used to create an Action." % (self.var, repr(c)))
  820. return gen_cmd
  821. def _generate(self, target, source, env, for_signature, executor=None):
  822. return self._generate_cache(env)
  823. def __call__(self, target, source, env, *args, **kw):
  824. c = self.get_parent_class(env)
  825. return c.__call__(self, target, source, env, *args, **kw)
  826. def get_presig(self, target, source, env):
  827. c = self.get_parent_class(env)
  828. return c.get_presig(self, target, source, env)
  829. def get_varlist(self, target, source, env, executor=None):
  830. c = self.get_parent_class(env)
  831. return c.get_varlist(self, target, source, env, executor)
  832. class FunctionAction(_ActionAction):
  833. """Class for Python function actions."""
  834. def __init__(self, execfunction, kw):
  835. if __debug__: logInstanceCreation(self, 'Action.FunctionAction')
  836. self.execfunction = execfunction
  837. try:
  838. self.funccontents = _callable_contents(execfunction)
  839. except AttributeError:
  840. try:
  841. # See if execfunction will do the heavy lifting for us.
  842. self.gc = execfunction.get_contents
  843. except AttributeError:
  844. # This is weird, just do the best we can.
  845. self.funccontents = _object_contents(execfunction)
  846. _ActionAction.__init__(self, **kw)
  847. def function_name(self):
  848. try:
  849. return self.execfunction.__name__
  850. except AttributeError:
  851. try:
  852. return self.execfunction.__class__.__name__
  853. except AttributeError:
  854. return "unknown_python_function"
  855. def strfunction(self, target, source, env, executor=None):
  856. if self.cmdstr is None:
  857. return None
  858. if self.cmdstr is not _null:
  859. from SCons.Subst import SUBST_RAW
  860. if executor:
  861. c = env.subst(self.cmdstr, SUBST_RAW, executor=executor)
  862. else:
  863. c = env.subst(self.cmdstr, SUBST_RAW, target, source)
  864. if c:
  865. return c
  866. def array(a):
  867. def quote(s):
  868. try:
  869. str_for_display = s.str_for_display
  870. except AttributeError:
  871. s = repr(s)
  872. else:
  873. s = str_for_display()
  874. return s
  875. return '[' + ", ".join(map(quote, a)) + ']'
  876. try:
  877. strfunc = self.execfunction.strfunction
  878. except AttributeError:
  879. pass
  880. else:
  881. if strfunc is None:
  882. return None
  883. if callable(strfunc):
  884. return strfunc(target, source, env)
  885. name = self.function_name()
  886. tstr = array(target)
  887. sstr = array(source)
  888. return "%s(%s, %s)" % (name, tstr, sstr)
  889. def __str__(self):
  890. name = self.function_name()
  891. if name == 'ActionCaller':
  892. return str(self.execfunction)
  893. return "%s(target, source, env)" % name
  894. def execute(self, target, source, env, executor=None):
  895. exc_info = (None,None,None)
  896. try:
  897. if executor:
  898. target = executor.get_all_targets()
  899. source = executor.get_all_sources()
  900. rsources = list(map(rfile, source))
  901. try:
  902. result = self.execfunction(target=target, source=rsources, env=env)
  903. except KeyboardInterrupt, e:
  904. raise
  905. except SystemExit, e:
  906. raise
  907. except Exception, e:
  908. result = e
  909. exc_info = sys.exc_info()
  910. if result:
  911. result = SCons.Errors.convert_to_BuildError(result, exc_info)
  912. result.node=target
  913. result.action=self
  914. try:
  915. result.command=self.strfunction(target, source, env, executor)
  916. except TypeError:
  917. result.command=self.strfunction(target, source, env)
  918. # FIXME: This maintains backward compatibility with respect to
  919. # which type of exceptions were returned by raising an
  920. # exception and which ones were returned by value. It would
  921. # probably be best to always return them by value here, but
  922. # some codes do not check the return value of Actions and I do
  923. # not have the time to modify them at this point.
  924. if (exc_info[1] and
  925. not isinstance(exc_info[1],EnvironmentError)):
  926. raise result
  927. return result
  928. finally:
  929. # Break the cycle between the traceback object and this
  930. # function stack frame. See the sys.exc_info() doc info for
  931. # more information about this issue.
  932. del exc_info
  933. def get_presig(self, target, source, env):
  934. """Return the signature contents of this callable action."""
  935. try:
  936. return self.gc(target, source, env)
  937. except AttributeError:
  938. return self.funccontents
  939. def get_implicit_deps(self, target, source, env):
  940. return []
  941. class ListAction(ActionBase):
  942. """Class for lists of other actions."""
  943. def __init__(self, actionlist):
  944. if __debug__: logInstanceCreation(self, 'Action.ListAction')
  945. def list_of_actions(x):
  946. if isinstance(x, ActionBase):
  947. return x
  948. return Action(x)
  949. self.list = list(map(list_of_actions, actionlist))
  950. # our children will have had any varlist
  951. # applied; we don't need to do it again
  952. self.varlist = ()
  953. self.targets = '$TARGETS'
  954. def genstring(self, target, source, env):
  955. return '\n'.join([a.genstring(target, source, env) for a in self.list])
  956. def __str__(self):
  957. return '\n'.join(map(str, self.list))
  958. def presub_lines(self, env):
  959. return SCons.Util.flatten_sequence(
  960. [a.presub_lines(env) for a in self.list])
  961. def get_presig(self, target, source, env):
  962. """Return the signature contents of this action list.
  963. Simple concatenation of the signatures of the elements.
  964. """
  965. return "".join([x.get_contents(target, source, env) for x in self.list])
  966. def __call__(self, target, source, env, exitstatfunc=_null, presub=_null,
  967. show=_null, execute=_null, chdir=_null, executor=None):
  968. if executor:
  969. target = executor.get_all_targets()
  970. source = executor.get_all_sources()
  971. for act in self.list:
  972. stat = act(target, source, env, exitstatfunc, presub,
  973. show, execute, chdir, executor)
  974. if stat:
  975. return stat
  976. return 0
  977. def get_implicit_deps(self, target, source, env):
  978. result = []
  979. for act in self.list:
  980. result.extend(act.get_implicit_deps(target, source, env))
  981. return result
  982. def get_varlist(self, target, source, env, executor=None):
  983. result = SCons.Util.OrderedDict()
  984. for act in self.list:
  985. for var in act.get_varlist(target, source, env, executor):
  986. result[var] = True
  987. return list(result.keys())
  988. class ActionCaller(object):
  989. """A class for delaying calling an Action function with specific
  990. (positional and keyword) arguments until the Action is actually
  991. executed.
  992. This class looks to the rest of the world like a normal Action object,
  993. but what it's really doing is hanging on to the arguments until we
  994. have a target, source and env to use for the expansion.
  995. """
  996. def __init__(self, parent, args, kw):
  997. self.parent = parent
  998. self.args = args
  999. self.kw = kw
  1000. def get_contents(self, target, source, env):
  1001. actfunc = self.parent.actfunc
  1002. try:
  1003. # "self.actfunc" is a function.
  1004. contents = str(actfunc.func_code.co_code)
  1005. except AttributeError:
  1006. # "self.actfunc" is a callable object.
  1007. try:
  1008. contents = str(actfunc.__call__.im_func.func_code.co_code)
  1009. except AttributeError:
  1010. # No __call__() method, so it might be a builtin
  1011. # or something like that. Do the best we can.
  1012. contents = str(actfunc)
  1013. contents = remove_set_lineno_codes(contents)
  1014. return contents
  1015. def subst(self, s, target, source, env):
  1016. # If s is a list, recursively apply subst()
  1017. # to every element in the list
  1018. if is_List(s):
  1019. result = []
  1020. for elem in s:
  1021. result.append(self.subst(elem, target, source, env))
  1022. return self.parent.convert(result)
  1023. # Special-case hack: Let a custom function wrapped in an
  1024. # ActionCaller get at the environment through which the action
  1025. # was called by using this hard-coded value as a special return.
  1026. if s == '$__env__':
  1027. return env
  1028. elif is_String(s):
  1029. return env.subst(s, 1, target, source)
  1030. return self.parent.convert(s)
  1031. def subst_args(self, target, source, env):
  1032. return [self.subst(x, target, source, env) for x in self.args]
  1033. def subst_kw(self, target, source, env):
  1034. kw = {}
  1035. for key in self.kw.keys():
  1036. kw[key] = self.subst(self.kw[key], target, source, env)
  1037. return kw
  1038. def __call__(self, target, source, env, executor=None):
  1039. args = self.subst_args(target, source, env)
  1040. kw = self.subst_kw(target, source, env)
  1041. return self.parent.actfunc(*args, **kw)
  1042. def strfunction(self, target, source, env):
  1043. args = self.subst_args(target, source, env)
  1044. kw = self.subst_kw(target, source, env)
  1045. return self.parent.strfunc(*args, **kw)
  1046. def __str__(self):
  1047. return self.parent.strfunc(*self.args, **self.kw)
  1048. class ActionFactory(object):
  1049. """A factory class that will wrap up an arbitrary function
  1050. as an SCons-executable Action object.
  1051. The real heavy lifting here is done by the ActionCaller class.
  1052. We just collect the (positional and keyword) arguments that we're
  1053. called with and give them to the ActionCaller object we create,
  1054. so it can hang onto them until it needs them.
  1055. """
  1056. def __init__(self, actfunc, strfunc, convert=lambda x: x):
  1057. self.actfunc = actfunc
  1058. self.strfunc = strfunc
  1059. self.convert = convert
  1060. def __call__(self, *args, **kw):
  1061. ac = ActionCaller(self, args, kw)
  1062. action = Action(ac, strfunction=ac.strfunction)
  1063. return action
  1064. # Local Variables:
  1065. # tab-width:4
  1066. # indent-tabs-mode:nil
  1067. # End:
  1068. # vim: set expandtab tabstop=4 shiftwidth=4: