PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/cloudant/bigcouch
Python | 480 lines | 398 code | 36 blank | 46 comment | 49 complexity | ce597f78f171fe1d3f118dce7ec5414e MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Defaults
  2. Builders and other things for the local site. Here's where we'll
  3. duplicate the functionality of autoconf until we move it into the
  4. installation procedure or use something like qmconf.
  5. The code that reads the registry to find MSVC components was borrowed
  6. from distutils.msvccompiler.
  7. """
  8. #
  9. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  10. #
  11. # Permission is hereby granted, free of charge, to any person obtaining
  12. # a copy of this software and associated documentation files (the
  13. # "Software"), to deal in the Software without restriction, including
  14. # without limitation the rights to use, copy, modify, merge, publish,
  15. # distribute, sublicense, and/or sell copies of the Software, and to
  16. # permit persons to whom the Software is furnished to do so, subject to
  17. # the following conditions:
  18. #
  19. # The above copyright notice and this permission notice shall be included
  20. # in all copies or substantial portions of the Software.
  21. #
  22. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  23. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  24. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. #
  30. from __future__ import division
  31. __revision__ = "src/engine/SCons/Defaults.py 5134 2010/08/16 23:02:40 bdeegan"
  32. import os
  33. import errno
  34. import shutil
  35. import stat
  36. import time
  37. import sys
  38. import SCons.Action
  39. import SCons.Builder
  40. import SCons.CacheDir
  41. import SCons.Environment
  42. import SCons.PathList
  43. import SCons.Subst
  44. import SCons.Tool
  45. # A placeholder for a default Environment (for fetching source files
  46. # from source code management systems and the like). This must be
  47. # initialized later, after the top-level directory is set by the calling
  48. # interface.
  49. _default_env = None
  50. # Lazily instantiate the default environment so the overhead of creating
  51. # it doesn't apply when it's not needed.
  52. def _fetch_DefaultEnvironment(*args, **kw):
  53. """
  54. Returns the already-created default construction environment.
  55. """
  56. global _default_env
  57. return _default_env
  58. def DefaultEnvironment(*args, **kw):
  59. """
  60. Initial public entry point for creating the default construction
  61. Environment.
  62. After creating the environment, we overwrite our name
  63. (DefaultEnvironment) with the _fetch_DefaultEnvironment() function,
  64. which more efficiently returns the initialized default construction
  65. environment without checking for its existence.
  66. (This function still exists with its _default_check because someone
  67. else (*cough* Script/__init__.py *cough*) may keep a reference
  68. to this function. So we can't use the fully functional idiom of
  69. having the name originally be a something that *only* creates the
  70. construction environment and then overwrites the name.)
  71. """
  72. global _default_env
  73. if not _default_env:
  74. import SCons.Util
  75. _default_env = SCons.Environment.Environment(*args, **kw)
  76. if SCons.Util.md5:
  77. _default_env.Decider('MD5')
  78. else:
  79. _default_env.Decider('timestamp-match')
  80. global DefaultEnvironment
  81. DefaultEnvironment = _fetch_DefaultEnvironment
  82. _default_env._CacheDir_path = None
  83. return _default_env
  84. # Emitters for setting the shared attribute on object files,
  85. # and an action for checking that all of the source files
  86. # going into a shared library are, in fact, shared.
  87. def StaticObjectEmitter(target, source, env):
  88. for tgt in target:
  89. tgt.attributes.shared = None
  90. return (target, source)
  91. def SharedObjectEmitter(target, source, env):
  92. for tgt in target:
  93. tgt.attributes.shared = 1
  94. return (target, source)
  95. def SharedFlagChecker(source, target, env):
  96. same = env.subst('$STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME')
  97. if same == '0' or same == '' or same == 'False':
  98. for src in source:
  99. try:
  100. shared = src.attributes.shared
  101. except AttributeError:
  102. shared = None
  103. if not shared:
  104. raise SCons.Errors.UserError("Source file: %s is static and is not compatible with shared target: %s" % (src, target[0]))
  105. SharedCheck = SCons.Action.Action(SharedFlagChecker, None)
  106. # Some people were using these variable name before we made
  107. # SourceFileScanner part of the public interface. Don't break their
  108. # SConscript files until we've given them some fair warning and a
  109. # transition period.
  110. CScan = SCons.Tool.CScanner
  111. DScan = SCons.Tool.DScanner
  112. LaTeXScan = SCons.Tool.LaTeXScanner
  113. ObjSourceScan = SCons.Tool.SourceFileScanner
  114. ProgScan = SCons.Tool.ProgramScanner
  115. # These aren't really tool scanners, so they don't quite belong with
  116. # the rest of those in Tool/__init__.py, but I'm not sure where else
  117. # they should go. Leave them here for now.
  118. import SCons.Scanner.Dir
  119. DirScanner = SCons.Scanner.Dir.DirScanner()
  120. DirEntryScanner = SCons.Scanner.Dir.DirEntryScanner()
  121. # Actions for common languages.
  122. CAction = SCons.Action.Action("$CCCOM", "$CCCOMSTR")
  123. ShCAction = SCons.Action.Action("$SHCCCOM", "$SHCCCOMSTR")
  124. CXXAction = SCons.Action.Action("$CXXCOM", "$CXXCOMSTR")
  125. ShCXXAction = SCons.Action.Action("$SHCXXCOM", "$SHCXXCOMSTR")
  126. ASAction = SCons.Action.Action("$ASCOM", "$ASCOMSTR")
  127. ASPPAction = SCons.Action.Action("$ASPPCOM", "$ASPPCOMSTR")
  128. LinkAction = SCons.Action.Action("$LINKCOM", "$LINKCOMSTR")
  129. ShLinkAction = SCons.Action.Action("$SHLINKCOM", "$SHLINKCOMSTR")
  130. LdModuleLinkAction = SCons.Action.Action("$LDMODULECOM", "$LDMODULECOMSTR")
  131. # Common tasks that we allow users to perform in platform-independent
  132. # ways by creating ActionFactory instances.
  133. ActionFactory = SCons.Action.ActionFactory
  134. def get_paths_str(dest):
  135. # If dest is a list, we need to manually call str() on each element
  136. if SCons.Util.is_List(dest):
  137. elem_strs = []
  138. for element in dest:
  139. elem_strs.append('"' + str(element) + '"')
  140. return '[' + ', '.join(elem_strs) + ']'
  141. else:
  142. return '"' + str(dest) + '"'
  143. def chmod_func(dest, mode):
  144. SCons.Node.FS.invalidate_node_memos(dest)
  145. if not SCons.Util.is_List(dest):
  146. dest = [dest]
  147. for element in dest:
  148. os.chmod(str(element), mode)
  149. def chmod_strfunc(dest, mode):
  150. return 'Chmod(%s, 0%o)' % (get_paths_str(dest), mode)
  151. Chmod = ActionFactory(chmod_func, chmod_strfunc)
  152. def copy_func(dest, src):
  153. SCons.Node.FS.invalidate_node_memos(dest)
  154. if SCons.Util.is_List(src) and os.path.isdir(dest):
  155. for file in src:
  156. shutil.copy2(file, dest)
  157. return 0
  158. elif os.path.isfile(src):
  159. return shutil.copy2(src, dest)
  160. else:
  161. return shutil.copytree(src, dest, 1)
  162. Copy = ActionFactory(copy_func,
  163. lambda dest, src: 'Copy("%s", "%s")' % (dest, src),
  164. convert=str)
  165. def delete_func(dest, must_exist=0):
  166. SCons.Node.FS.invalidate_node_memos(dest)
  167. if not SCons.Util.is_List(dest):
  168. dest = [dest]
  169. for entry in dest:
  170. entry = str(entry)
  171. if not must_exist and not os.path.exists(entry):
  172. continue
  173. if not os.path.exists(entry) or os.path.isfile(entry):
  174. os.unlink(entry)
  175. continue
  176. else:
  177. shutil.rmtree(entry, 1)
  178. continue
  179. def delete_strfunc(dest, must_exist=0):
  180. return 'Delete(%s)' % get_paths_str(dest)
  181. Delete = ActionFactory(delete_func, delete_strfunc)
  182. def mkdir_func(dest):
  183. SCons.Node.FS.invalidate_node_memos(dest)
  184. if not SCons.Util.is_List(dest):
  185. dest = [dest]
  186. for entry in dest:
  187. try:
  188. os.makedirs(str(entry))
  189. except os.error, e:
  190. p = str(entry)
  191. if (e.args[0] == errno.EEXIST or
  192. (sys.platform=='win32' and e.args[0]==183)) \
  193. and os.path.isdir(str(entry)):
  194. pass # not an error if already exists
  195. else:
  196. raise
  197. Mkdir = ActionFactory(mkdir_func,
  198. lambda dir: 'Mkdir(%s)' % get_paths_str(dir))
  199. def move_func(dest, src):
  200. SCons.Node.FS.invalidate_node_memos(dest)
  201. SCons.Node.FS.invalidate_node_memos(src)
  202. shutil.move(src, dest)
  203. Move = ActionFactory(move_func,
  204. lambda dest, src: 'Move("%s", "%s")' % (dest, src),
  205. convert=str)
  206. def touch_func(dest):
  207. SCons.Node.FS.invalidate_node_memos(dest)
  208. if not SCons.Util.is_List(dest):
  209. dest = [dest]
  210. for file in dest:
  211. file = str(file)
  212. mtime = int(time.time())
  213. if os.path.exists(file):
  214. atime = os.path.getatime(file)
  215. else:
  216. open(file, 'w')
  217. atime = mtime
  218. os.utime(file, (atime, mtime))
  219. Touch = ActionFactory(touch_func,
  220. lambda file: 'Touch(%s)' % get_paths_str(file))
  221. # Internal utility functions
  222. def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None):
  223. """
  224. Creates a new list from 'list' by first interpolating each element
  225. in the list using the 'env' dictionary and then calling f on the
  226. list, and finally calling _concat_ixes to concatenate 'prefix' and
  227. 'suffix' onto each element of the list.
  228. """
  229. if not list:
  230. return list
  231. l = f(SCons.PathList.PathList(list).subst_path(env, target, source))
  232. if l is not None:
  233. list = l
  234. return _concat_ixes(prefix, list, suffix, env)
  235. def _concat_ixes(prefix, list, suffix, env):
  236. """
  237. Creates a new list from 'list' by concatenating the 'prefix' and
  238. 'suffix' arguments onto each element of the list. A trailing space
  239. on 'prefix' or leading space on 'suffix' will cause them to be put
  240. into separate list elements rather than being concatenated.
  241. """
  242. result = []
  243. # ensure that prefix and suffix are strings
  244. prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW))
  245. suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW))
  246. for x in list:
  247. if isinstance(x, SCons.Node.FS.File):
  248. result.append(x)
  249. continue
  250. x = str(x)
  251. if x:
  252. if prefix:
  253. if prefix[-1] == ' ':
  254. result.append(prefix[:-1])
  255. elif x[:len(prefix)] != prefix:
  256. x = prefix + x
  257. result.append(x)
  258. if suffix:
  259. if suffix[0] == ' ':
  260. result.append(suffix[1:])
  261. elif x[-len(suffix):] != suffix:
  262. result[-1] = result[-1]+suffix
  263. return result
  264. def _stripixes(prefix, itms, suffix, stripprefixes, stripsuffixes, env, c=None):
  265. """
  266. This is a wrapper around _concat()/_concat_ixes() that checks for
  267. the existence of prefixes or suffixes on list items and strips them
  268. where it finds them. This is used by tools (like the GNU linker)
  269. that need to turn something like 'libfoo.a' into '-lfoo'.
  270. """
  271. if not itms:
  272. return itms
  273. if not callable(c):
  274. env_c = env['_concat']
  275. if env_c != _concat and callable(env_c):
  276. # There's a custom _concat() method in the construction
  277. # environment, and we've allowed people to set that in
  278. # the past (see test/custom-concat.py), so preserve the
  279. # backwards compatibility.
  280. c = env_c
  281. else:
  282. c = _concat_ixes
  283. stripprefixes = list(map(env.subst, SCons.Util.flatten(stripprefixes)))
  284. stripsuffixes = list(map(env.subst, SCons.Util.flatten(stripsuffixes)))
  285. stripped = []
  286. for l in SCons.PathList.PathList(itms).subst_path(env, None, None):
  287. if isinstance(l, SCons.Node.FS.File):
  288. stripped.append(l)
  289. continue
  290. if not SCons.Util.is_String(l):
  291. l = str(l)
  292. for stripprefix in stripprefixes:
  293. lsp = len(stripprefix)
  294. if l[:lsp] == stripprefix:
  295. l = l[lsp:]
  296. # Do not strip more than one prefix
  297. break
  298. for stripsuffix in stripsuffixes:
  299. lss = len(stripsuffix)
  300. if l[-lss:] == stripsuffix:
  301. l = l[:-lss]
  302. # Do not strip more than one suffix
  303. break
  304. stripped.append(l)
  305. return c(prefix, stripped, suffix, env)
  306. def processDefines(defs):
  307. """process defines, resolving strings, lists, dictionaries, into a list of
  308. strings
  309. """
  310. if SCons.Util.is_List(defs):
  311. l = []
  312. for d in defs:
  313. if SCons.Util.is_List(d) or isinstance(d, tuple):
  314. l.append(str(d[0]) + '=' + str(d[1]))
  315. else:
  316. l.append(str(d))
  317. elif SCons.Util.is_Dict(defs):
  318. # The items in a dictionary are stored in random order, but
  319. # if the order of the command-line options changes from
  320. # invocation to invocation, then the signature of the command
  321. # line will change and we'll get random unnecessary rebuilds.
  322. # Consequently, we have to sort the keys to ensure a
  323. # consistent order...
  324. l = []
  325. for k,v in sorted(defs.items()):
  326. if v is None:
  327. l.append(str(k))
  328. else:
  329. l.append(str(k) + '=' + str(v))
  330. else:
  331. l = [str(defs)]
  332. return l
  333. def _defines(prefix, defs, suffix, env, c=_concat_ixes):
  334. """A wrapper around _concat_ixes that turns a list or string
  335. into a list of C preprocessor command-line definitions.
  336. """
  337. return c(prefix, env.subst_path(processDefines(defs)), suffix, env)
  338. class NullCmdGenerator(object):
  339. """This is a callable class that can be used in place of other
  340. command generators if you don't want them to do anything.
  341. The __call__ method for this class simply returns the thing
  342. you instantiated it with.
  343. Example usage:
  344. env["DO_NOTHING"] = NullCmdGenerator
  345. env["LINKCOM"] = "${DO_NOTHING('$LINK $SOURCES $TARGET')}"
  346. """
  347. def __init__(self, cmd):
  348. self.cmd = cmd
  349. def __call__(self, target, source, env, for_signature=None):
  350. return self.cmd
  351. class Variable_Method_Caller(object):
  352. """A class for finding a construction variable on the stack and
  353. calling one of its methods.
  354. We use this to support "construction variables" in our string
  355. eval()s that actually stand in for methods--specifically, use
  356. of "RDirs" in call to _concat that should actually execute the
  357. "TARGET.RDirs" method. (We used to support this by creating a little
  358. "build dictionary" that mapped RDirs to the method, but this got in
  359. the way of Memoizing construction environments, because we had to
  360. create new environment objects to hold the variables.)
  361. """
  362. def __init__(self, variable, method):
  363. self.variable = variable
  364. self.method = method
  365. def __call__(self, *args, **kw):
  366. try: 1//0
  367. except ZeroDivisionError:
  368. # Don't start iterating with the current stack-frame to
  369. # prevent creating reference cycles (f_back is safe).
  370. frame = sys.exc_info()[2].tb_frame.f_back
  371. variable = self.variable
  372. while frame:
  373. if variable in frame.f_locals:
  374. v = frame.f_locals[variable]
  375. if v:
  376. method = getattr(v, self.method)
  377. return method(*args, **kw)
  378. frame = frame.f_back
  379. return None
  380. ConstructionEnvironment = {
  381. 'BUILDERS' : {},
  382. 'SCANNERS' : [],
  383. 'CONFIGUREDIR' : '#/.sconf_temp',
  384. 'CONFIGURELOG' : '#/config.log',
  385. 'CPPSUFFIXES' : SCons.Tool.CSuffixes,
  386. 'DSUFFIXES' : SCons.Tool.DSuffixes,
  387. 'ENV' : {},
  388. 'IDLSUFFIXES' : SCons.Tool.IDLSuffixes,
  389. # 'LATEXSUFFIXES' : SCons.Tool.LaTeXSuffixes, # moved to the TeX tools generate functions
  390. '_concat' : _concat,
  391. '_defines' : _defines,
  392. '_stripixes' : _stripixes,
  393. '_LIBFLAGS' : '${_concat(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, __env__)}',
  394. '_LIBDIRFLAGS' : '$( ${_concat(LIBDIRPREFIX, LIBPATH, LIBDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)',
  395. '_CPPINCFLAGS' : '$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)',
  396. '_CPPDEFFLAGS' : '${_defines(CPPDEFPREFIX, CPPDEFINES, CPPDEFSUFFIX, __env__)}',
  397. 'TEMPFILE' : NullCmdGenerator,
  398. 'Dir' : Variable_Method_Caller('TARGET', 'Dir'),
  399. 'Dirs' : Variable_Method_Caller('TARGET', 'Dirs'),
  400. 'File' : Variable_Method_Caller('TARGET', 'File'),
  401. 'RDirs' : Variable_Method_Caller('TARGET', 'RDirs'),
  402. }
  403. # Local Variables:
  404. # tab-width:4
  405. # indent-tabs-mode:nil
  406. # End:
  407. # vim: set expandtab tabstop=4 shiftwidth=4: