PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/cloudant/bigcouch
Python | 1492 lines | 1448 code | 10 blank | 34 comment | 17 complexity | 38d3781ce1c9cf8b32531ae64eea69c0 MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Util
  2. Various utility functions go here.
  3. """
  4. #
  5. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included
  16. # in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  19. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  20. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. __revision__ = "src/engine/SCons/Util.py 5134 2010/08/16 23:02:40 bdeegan"
  26. import os
  27. import sys
  28. import copy
  29. import re
  30. import types
  31. from collections import UserDict, UserList, UserString
  32. # Don't "from types import ..." these because we need to get at the
  33. # types module later to look for UnicodeType.
  34. InstanceType = types.InstanceType
  35. MethodType = types.MethodType
  36. FunctionType = types.FunctionType
  37. try: unicode
  38. except NameError: UnicodeType = None
  39. else: UnicodeType = unicode
  40. def dictify(keys, values, result={}):
  41. for k, v in zip(keys, values):
  42. result[k] = v
  43. return result
  44. _altsep = os.altsep
  45. if _altsep is None and sys.platform == 'win32':
  46. # My ActivePython 2.0.1 doesn't set os.altsep! What gives?
  47. _altsep = '/'
  48. if _altsep:
  49. def rightmost_separator(path, sep):
  50. return max(path.rfind(sep), path.rfind(_altsep))
  51. else:
  52. def rightmost_separator(path, sep):
  53. return path.rfind(sep)
  54. # First two from the Python Cookbook, just for completeness.
  55. # (Yeah, yeah, YAGNI...)
  56. def containsAny(str, set):
  57. """Check whether sequence str contains ANY of the items in set."""
  58. for c in set:
  59. if c in str: return 1
  60. return 0
  61. def containsAll(str, set):
  62. """Check whether sequence str contains ALL of the items in set."""
  63. for c in set:
  64. if c not in str: return 0
  65. return 1
  66. def containsOnly(str, set):
  67. """Check whether sequence str contains ONLY items in set."""
  68. for c in str:
  69. if c not in set: return 0
  70. return 1
  71. def splitext(path):
  72. "Same as os.path.splitext() but faster."
  73. sep = rightmost_separator(path, os.sep)
  74. dot = path.rfind('.')
  75. # An ext is only real if it has at least one non-digit char
  76. if dot > sep and not containsOnly(path[dot:], "0123456789."):
  77. return path[:dot],path[dot:]
  78. else:
  79. return path,""
  80. def updrive(path):
  81. """
  82. Make the drive letter (if any) upper case.
  83. This is useful because Windows is inconsitent on the case
  84. of the drive letter, which can cause inconsistencies when
  85. calculating command signatures.
  86. """
  87. drive, rest = os.path.splitdrive(path)
  88. if drive:
  89. path = drive.upper() + rest
  90. return path
  91. class NodeList(UserList):
  92. """This class is almost exactly like a regular list of Nodes
  93. (actually it can hold any object), with one important difference.
  94. If you try to get an attribute from this list, it will return that
  95. attribute from every item in the list. For example:
  96. >>> someList = NodeList([ ' foo ', ' bar ' ])
  97. >>> someList.strip()
  98. [ 'foo', 'bar' ]
  99. """
  100. def __nonzero__(self):
  101. return len(self.data) != 0
  102. def __str__(self):
  103. return ' '.join(map(str, self.data))
  104. def __iter__(self):
  105. return iter(self.data)
  106. def __call__(self, *args, **kwargs):
  107. result = [x(*args, **kwargs) for x in self.data]
  108. return self.__class__(result)
  109. def __getattr__(self, name):
  110. result = [getattr(x, name) for x in self.data]
  111. return self.__class__(result)
  112. _get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')
  113. def get_environment_var(varstr):
  114. """Given a string, first determine if it looks like a reference
  115. to a single environment variable, like "$FOO" or "${FOO}".
  116. If so, return that variable with no decorations ("FOO").
  117. If not, return None."""
  118. mo=_get_env_var.match(to_String(varstr))
  119. if mo:
  120. var = mo.group(1)
  121. if var[0] == '{':
  122. return var[1:-1]
  123. else:
  124. return var
  125. else:
  126. return None
  127. class DisplayEngine(object):
  128. print_it = True
  129. def __call__(self, text, append_newline=1):
  130. if not self.print_it:
  131. return
  132. if append_newline: text = text + '\n'
  133. try:
  134. sys.stdout.write(unicode(text))
  135. except IOError:
  136. # Stdout might be connected to a pipe that has been closed
  137. # by now. The most likely reason for the pipe being closed
  138. # is that the user has press ctrl-c. It this is the case,
  139. # then SCons is currently shutdown. We therefore ignore
  140. # IOError's here so that SCons can continue and shutdown
  141. # properly so that the .sconsign is correctly written
  142. # before SCons exits.
  143. pass
  144. def set_mode(self, mode):
  145. self.print_it = mode
  146. def render_tree(root, child_func, prune=0, margin=[0], visited={}):
  147. """
  148. Render a tree of nodes into an ASCII tree view.
  149. root - the root node of the tree
  150. child_func - the function called to get the children of a node
  151. prune - don't visit the same node twice
  152. margin - the format of the left margin to use for children of root.
  153. 1 results in a pipe, and 0 results in no pipe.
  154. visited - a dictionary of visited nodes in the current branch if not prune,
  155. or in the whole tree if prune.
  156. """
  157. rname = str(root)
  158. children = child_func(root)
  159. retval = ""
  160. for pipe in margin[:-1]:
  161. if pipe:
  162. retval = retval + "| "
  163. else:
  164. retval = retval + " "
  165. if rname in visited:
  166. return retval + "+-[" + rname + "]\n"
  167. retval = retval + "+-" + rname + "\n"
  168. if not prune:
  169. visited = copy.copy(visited)
  170. visited[rname] = 1
  171. for i in range(len(children)):
  172. margin.append(i<len(children)-1)
  173. retval = retval + render_tree(children[i], child_func, prune, margin, visited
  174. )
  175. margin.pop()
  176. return retval
  177. IDX = lambda N: N and 1 or 0
  178. def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}):
  179. """
  180. Print a tree of nodes. This is like render_tree, except it prints
  181. lines directly instead of creating a string representation in memory,
  182. so that huge trees can be printed.
  183. root - the root node of the tree
  184. child_func - the function called to get the children of a node
  185. prune - don't visit the same node twice
  186. showtags - print status information to the left of each node line
  187. margin - the format of the left margin to use for children of root.
  188. 1 results in a pipe, and 0 results in no pipe.
  189. visited - a dictionary of visited nodes in the current branch if not prune,
  190. or in the whole tree if prune.
  191. """
  192. rname = str(root)
  193. if showtags:
  194. if showtags == 2:
  195. legend = (' E = exists\n' +
  196. ' R = exists in repository only\n' +
  197. ' b = implicit builder\n' +
  198. ' B = explicit builder\n' +
  199. ' S = side effect\n' +
  200. ' P = precious\n' +
  201. ' A = always build\n' +
  202. ' C = current\n' +
  203. ' N = no clean\n' +
  204. ' H = no cache\n' +
  205. '\n')
  206. sys.stdout.write(unicode(legend))
  207. tags = ['[']
  208. tags.append(' E'[IDX(root.exists())])
  209. tags.append(' R'[IDX(root.rexists() and not root.exists())])
  210. tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] +
  211. [0,2][IDX(root.has_builder())]])
  212. tags.append(' S'[IDX(root.side_effect)])
  213. tags.append(' P'[IDX(root.precious)])
  214. tags.append(' A'[IDX(root.always_build)])
  215. tags.append(' C'[IDX(root.is_up_to_date())])
  216. tags.append(' N'[IDX(root.noclean)])
  217. tags.append(' H'[IDX(root.nocache)])
  218. tags.append(']')
  219. else:
  220. tags = []
  221. def MMM(m):
  222. return [" ","| "][m]
  223. margins = list(map(MMM, margin[:-1]))
  224. children = child_func(root)
  225. if prune and rname in visited and children:
  226. sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + u'\n')
  227. return
  228. sys.stdout.write(''.join(tags + margins + ['+-', rname]) + u'\n')
  229. visited[rname] = 1
  230. if children:
  231. margin.append(1)
  232. idx = IDX(showtags)
  233. for C in children[:-1]:
  234. print_tree(C, child_func, prune, idx, margin, visited)
  235. margin[-1] = 0
  236. print_tree(children[-1], child_func, prune, idx, margin, visited)
  237. margin.pop()
  238. # Functions for deciding if things are like various types, mainly to
  239. # handle UserDict, UserList and UserString like their underlying types.
  240. #
  241. # Yes, all of this manual testing breaks polymorphism, and the real
  242. # Pythonic way to do all of this would be to just try it and handle the
  243. # exception, but handling the exception when it's not the right type is
  244. # often too slow.
  245. # We are using the following trick to speed up these
  246. # functions. Default arguments are used to take a snapshot of the
  247. # the global functions and constants used by these functions. This
  248. # transforms accesses to global variable into local variables
  249. # accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL).
  250. DictTypes = (dict, UserDict)
  251. ListTypes = (list, UserList)
  252. SequenceTypes = (list, tuple, UserList)
  253. # Note that profiling data shows a speed-up when comparing
  254. # explicitely with str and unicode instead of simply comparing
  255. # with basestring. (at least on Python 2.5.1)
  256. StringTypes = (str, unicode, UserString)
  257. # Empirically, it is faster to check explicitely for str and
  258. # unicode than for basestring.
  259. BaseStringTypes = (str, unicode)
  260. def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
  261. return isinstance(obj, DictTypes)
  262. def is_List(obj, isinstance=isinstance, ListTypes=ListTypes):
  263. return isinstance(obj, ListTypes)
  264. def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes):
  265. return isinstance(obj, SequenceTypes)
  266. def is_Tuple(obj, isinstance=isinstance, tuple=tuple):
  267. return isinstance(obj, tuple)
  268. def is_String(obj, isinstance=isinstance, StringTypes=StringTypes):
  269. return isinstance(obj, StringTypes)
  270. def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes):
  271. # Profiling shows that there is an impressive speed-up of 2x
  272. # when explicitely checking for strings instead of just not
  273. # sequence when the argument (i.e. obj) is already a string.
  274. # But, if obj is a not string then it is twice as fast to
  275. # check only for 'not sequence'. The following code therefore
  276. # assumes that the obj argument is a string must of the time.
  277. return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes)
  278. def do_flatten(sequence, result, isinstance=isinstance,
  279. StringTypes=StringTypes, SequenceTypes=SequenceTypes):
  280. for item in sequence:
  281. if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
  282. result.append(item)
  283. else:
  284. do_flatten(item, result)
  285. def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
  286. SequenceTypes=SequenceTypes, do_flatten=do_flatten):
  287. """Flatten a sequence to a non-nested list.
  288. Flatten() converts either a single scalar or a nested sequence
  289. to a non-nested list. Note that flatten() considers strings
  290. to be scalars instead of sequences like Python would.
  291. """
  292. if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
  293. return [obj]
  294. result = []
  295. for item in obj:
  296. if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
  297. result.append(item)
  298. else:
  299. do_flatten(item, result)
  300. return result
  301. def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
  302. SequenceTypes=SequenceTypes, do_flatten=do_flatten):
  303. """Flatten a sequence to a non-nested list.
  304. Same as flatten(), but it does not handle the single scalar
  305. case. This is slightly more efficient when one knows that
  306. the sequence to flatten can not be a scalar.
  307. """
  308. result = []
  309. for item in sequence:
  310. if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
  311. result.append(item)
  312. else:
  313. do_flatten(item, result)
  314. return result
  315. # Generic convert-to-string functions that abstract away whether or
  316. # not the Python we're executing has Unicode support. The wrapper
  317. # to_String_for_signature() will use a for_signature() method if the
  318. # specified object has one.
  319. #
  320. def to_String(s,
  321. isinstance=isinstance, str=str,
  322. UserString=UserString, BaseStringTypes=BaseStringTypes):
  323. if isinstance(s,BaseStringTypes):
  324. # Early out when already a string!
  325. return s
  326. elif isinstance(s, UserString):
  327. # s.data can only be either a unicode or a regular
  328. # string. Please see the UserString initializer.
  329. return s.data
  330. else:
  331. return str(s)
  332. def to_String_for_subst(s,
  333. isinstance=isinstance, str=str, to_String=to_String,
  334. BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes,
  335. UserString=UserString):
  336. # Note that the test cases are sorted by order of probability.
  337. if isinstance(s, BaseStringTypes):
  338. return s
  339. elif isinstance(s, SequenceTypes):
  340. l = []
  341. for e in s:
  342. l.append(to_String_for_subst(e))
  343. return ' '.join( s )
  344. elif isinstance(s, UserString):
  345. # s.data can only be either a unicode or a regular
  346. # string. Please see the UserString initializer.
  347. return s.data
  348. else:
  349. return str(s)
  350. def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
  351. AttributeError=AttributeError):
  352. try:
  353. f = obj.for_signature
  354. except AttributeError:
  355. return to_String_for_subst(obj)
  356. else:
  357. return f()
  358. # The SCons "semi-deep" copy.
  359. #
  360. # This makes separate copies of lists (including UserList objects)
  361. # dictionaries (including UserDict objects) and tuples, but just copies
  362. # references to anything else it finds.
  363. #
  364. # A special case is any object that has a __semi_deepcopy__() method,
  365. # which we invoke to create the copy, which is used by the BuilderDict
  366. # class because of its extra initialization argument.
  367. #
  368. # The dispatch table approach used here is a direct rip-off from the
  369. # normal Python copy module.
  370. _semi_deepcopy_dispatch = d = {}
  371. def _semi_deepcopy_dict(x):
  372. copy = {}
  373. for key, val in x.items():
  374. # The regular Python copy.deepcopy() also deepcopies the key,
  375. # as follows:
  376. #
  377. # copy[semi_deepcopy(key)] = semi_deepcopy(val)
  378. #
  379. # Doesn't seem like we need to, but we'll comment it just in case.
  380. copy[key] = semi_deepcopy(val)
  381. return copy
  382. d[dict] = _semi_deepcopy_dict
  383. def _semi_deepcopy_list(x):
  384. return list(map(semi_deepcopy, x))
  385. d[list] = _semi_deepcopy_list
  386. def _semi_deepcopy_tuple(x):
  387. return tuple(map(semi_deepcopy, x))
  388. d[tuple] = _semi_deepcopy_tuple
  389. def semi_deepcopy(x):
  390. copier = _semi_deepcopy_dispatch.get(type(x))
  391. if copier:
  392. return copier(x)
  393. else:
  394. if hasattr(x, '__semi_deepcopy__'):
  395. return x.__semi_deepcopy__()
  396. elif isinstance(x, UserDict):
  397. return x.__class__(_semi_deepcopy_dict(x))
  398. elif isinstance(x, UserList):
  399. return x.__class__(_semi_deepcopy_list(x))
  400. return x
  401. class Proxy(object):
  402. """A simple generic Proxy class, forwarding all calls to
  403. subject. So, for the benefit of the python newbie, what does
  404. this really mean? Well, it means that you can take an object, let's
  405. call it 'objA', and wrap it in this Proxy class, with a statement
  406. like this
  407. proxyObj = Proxy(objA),
  408. Then, if in the future, you do something like this
  409. x = proxyObj.var1,
  410. since Proxy does not have a 'var1' attribute (but presumably objA does),
  411. the request actually is equivalent to saying
  412. x = objA.var1
  413. Inherit from this class to create a Proxy.
  414. Note that, with new-style classes, this does *not* work transparently
  415. for Proxy subclasses that use special .__*__() method names, because
  416. those names are now bound to the class, not the individual instances.
  417. You now need to know in advance which .__*__() method names you want
  418. to pass on to the underlying Proxy object, and specifically delegate
  419. their calls like this:
  420. class Foo(Proxy):
  421. __str__ = Delegate('__str__')
  422. """
  423. def __init__(self, subject):
  424. """Wrap an object as a Proxy object"""
  425. self._subject = subject
  426. def __getattr__(self, name):
  427. """Retrieve an attribute from the wrapped object. If the named
  428. attribute doesn't exist, AttributeError is raised"""
  429. return getattr(self._subject, name)
  430. def get(self):
  431. """Retrieve the entire wrapped object"""
  432. return self._subject
  433. def __cmp__(self, other):
  434. if issubclass(other.__class__, self._subject.__class__):
  435. return cmp(self._subject, other)
  436. return cmp(self.__dict__, other.__dict__)
  437. class Delegate(object):
  438. """A Python Descriptor class that delegates attribute fetches
  439. to an underlying wrapped subject of a Proxy. Typical use:
  440. class Foo(Proxy):
  441. __str__ = Delegate('__str__')
  442. """
  443. def __init__(self, attribute):
  444. self.attribute = attribute
  445. def __get__(self, obj, cls):
  446. if isinstance(obj, cls):
  447. return getattr(obj._subject, self.attribute)
  448. else:
  449. return self
  450. # attempt to load the windows registry module:
  451. can_read_reg = 0
  452. try:
  453. import winreg
  454. can_read_reg = 1
  455. hkey_mod = winreg
  456. RegOpenKeyEx = winreg.OpenKeyEx
  457. RegEnumKey = winreg.EnumKey
  458. RegEnumValue = winreg.EnumValue
  459. RegQueryValueEx = winreg.QueryValueEx
  460. RegError = winreg.error
  461. except ImportError:
  462. try:
  463. import win32api
  464. import win32con
  465. can_read_reg = 1
  466. hkey_mod = win32con
  467. RegOpenKeyEx = win32api.RegOpenKeyEx
  468. RegEnumKey = win32api.RegEnumKey
  469. RegEnumValue = win32api.RegEnumValue
  470. RegQueryValueEx = win32api.RegQueryValueEx
  471. RegError = win32api.error
  472. except ImportError:
  473. class _NoError(Exception):
  474. pass
  475. RegError = _NoError
  476. if can_read_reg:
  477. HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
  478. HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
  479. HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
  480. HKEY_USERS = hkey_mod.HKEY_USERS
  481. def RegGetValue(root, key):
  482. """This utility function returns a value in the registry
  483. without having to open the key first. Only available on
  484. Windows platforms with a version of Python that can read the
  485. registry. Returns the same thing as
  486. SCons.Util.RegQueryValueEx, except you just specify the entire
  487. path to the value, and don't have to bother opening the key
  488. first. So:
  489. Instead of:
  490. k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
  491. r'SOFTWARE\Microsoft\Windows\CurrentVersion')
  492. out = SCons.Util.RegQueryValueEx(k,
  493. 'ProgramFilesDir')
  494. You can write:
  495. out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
  496. r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
  497. """
  498. # I would use os.path.split here, but it's not a filesystem
  499. # path...
  500. p = key.rfind('\\') + 1
  501. keyp = key[:p-1] # -1 to omit trailing slash
  502. val = key[p:]
  503. k = RegOpenKeyEx(root, keyp)
  504. return RegQueryValueEx(k,val)
  505. else:
  506. try:
  507. e = WindowsError
  508. except NameError:
  509. # Make sure we have a definition of WindowsError so we can
  510. # run platform-independent tests of Windows functionality on
  511. # platforms other than Windows. (WindowsError is, in fact, an
  512. # OSError subclass on Windows.)
  513. class WindowsError(OSError):
  514. pass
  515. import builtins
  516. builtins.WindowsError = WindowsError
  517. else:
  518. del e
  519. HKEY_CLASSES_ROOT = None
  520. HKEY_LOCAL_MACHINE = None
  521. HKEY_CURRENT_USER = None
  522. HKEY_USERS = None
  523. def RegGetValue(root, key):
  524. raise WindowsError
  525. def RegOpenKeyEx(root, key):
  526. raise WindowsError
  527. if sys.platform == 'win32':
  528. def WhereIs(file, path=None, pathext=None, reject=[]):
  529. if path is None:
  530. try:
  531. path = os.environ['PATH']
  532. except KeyError:
  533. return None
  534. if is_String(path):
  535. path = path.split(os.pathsep)
  536. if pathext is None:
  537. try:
  538. pathext = os.environ['PATHEXT']
  539. except KeyError:
  540. pathext = '.COM;.EXE;.BAT;.CMD'
  541. if is_String(pathext):
  542. pathext = pathext.split(os.pathsep)
  543. for ext in pathext:
  544. if ext.lower() == file[-len(ext):].lower():
  545. pathext = ['']
  546. break
  547. if not is_List(reject) and not is_Tuple(reject):
  548. reject = [reject]
  549. for dir in path:
  550. f = os.path.join(dir, file)
  551. for ext in pathext:
  552. fext = f + ext
  553. if os.path.isfile(fext):
  554. try:
  555. reject.index(fext)
  556. except ValueError:
  557. return os.path.normpath(fext)
  558. continue
  559. return None
  560. elif os.name == 'os2':
  561. def WhereIs(file, path=None, pathext=None, reject=[]):
  562. if path is None:
  563. try:
  564. path = os.environ['PATH']
  565. except KeyError:
  566. return None
  567. if is_String(path):
  568. path = path.split(os.pathsep)
  569. if pathext is None:
  570. pathext = ['.exe', '.cmd']
  571. for ext in pathext:
  572. if ext.lower() == file[-len(ext):].lower():
  573. pathext = ['']
  574. break
  575. if not is_List(reject) and not is_Tuple(reject):
  576. reject = [reject]
  577. for dir in path:
  578. f = os.path.join(dir, file)
  579. for ext in pathext:
  580. fext = f + ext
  581. if os.path.isfile(fext):
  582. try:
  583. reject.index(fext)
  584. except ValueError:
  585. return os.path.normpath(fext)
  586. continue
  587. return None
  588. else:
  589. def WhereIs(file, path=None, pathext=None, reject=[]):
  590. import stat
  591. if path is None:
  592. try:
  593. path = os.environ['PATH']
  594. except KeyError:
  595. return None
  596. if is_String(path):
  597. path = path.split(os.pathsep)
  598. if not is_List(reject) and not is_Tuple(reject):
  599. reject = [reject]
  600. for d in path:
  601. f = os.path.join(d, file)
  602. if os.path.isfile(f):
  603. try:
  604. st = os.stat(f)
  605. except OSError:
  606. # os.stat() raises OSError, not IOError if the file
  607. # doesn't exist, so in this case we let IOError get
  608. # raised so as to not mask possibly serious disk or
  609. # network issues.
  610. continue
  611. if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
  612. try:
  613. reject.index(f)
  614. except ValueError:
  615. return os.path.normpath(f)
  616. continue
  617. return None
  618. def PrependPath(oldpath, newpath, sep = os.pathsep,
  619. delete_existing=1, canonicalize=None):
  620. """This prepends newpath elements to the given oldpath. Will only
  621. add any particular path once (leaving the first one it encounters
  622. and ignoring the rest, to preserve path order), and will
  623. os.path.normpath and os.path.normcase all paths to help assure
  624. this. This can also handle the case where the given old path
  625. variable is a list instead of a string, in which case a list will
  626. be returned instead of a string.
  627. Example:
  628. Old Path: "/foo/bar:/foo"
  629. New Path: "/biz/boom:/foo"
  630. Result: "/biz/boom:/foo:/foo/bar"
  631. If delete_existing is 0, then adding a path that exists will
  632. not move it to the beginning; it will stay where it is in the
  633. list.
  634. If canonicalize is not None, it is applied to each element of
  635. newpath before use.
  636. """
  637. orig = oldpath
  638. is_list = 1
  639. paths = orig
  640. if not is_List(orig) and not is_Tuple(orig):
  641. paths = paths.split(sep)
  642. is_list = 0
  643. if is_String(newpath):
  644. newpaths = newpath.split(sep)
  645. elif not is_List(newpath) and not is_Tuple(newpath):
  646. newpaths = [ newpath ] # might be a Dir
  647. else:
  648. newpaths = newpath
  649. if canonicalize:
  650. newpaths=list(map(canonicalize, newpaths))
  651. if not delete_existing:
  652. # First uniquify the old paths, making sure to
  653. # preserve the first instance (in Unix/Linux,
  654. # the first one wins), and remembering them in normpaths.
  655. # Then insert the new paths at the head of the list
  656. # if they're not already in the normpaths list.
  657. result = []
  658. normpaths = []
  659. for path in paths:
  660. if not path:
  661. continue
  662. normpath = os.path.normpath(os.path.normcase(path))
  663. if normpath not in normpaths:
  664. result.append(path)
  665. normpaths.append(normpath)
  666. newpaths.reverse() # since we're inserting at the head
  667. for path in newpaths:
  668. if not path:
  669. continue
  670. normpath = os.path.normpath(os.path.normcase(path))
  671. if normpath not in normpaths:
  672. result.insert(0, path)
  673. normpaths.append(normpath)
  674. paths = result
  675. else:
  676. newpaths = newpaths + paths # prepend new paths
  677. normpaths = []
  678. paths = []
  679. # now we add them only if they are unique
  680. for path in newpaths:
  681. normpath = os.path.normpath(os.path.normcase(path))
  682. if path and not normpath in normpaths:
  683. paths.append(path)
  684. normpaths.append(normpath)
  685. if is_list:
  686. return paths
  687. else:
  688. return sep.join(paths)
  689. def AppendPath(oldpath, newpath, sep = os.pathsep,
  690. delete_existing=1, canonicalize=None):
  691. """This appends new path elements to the given old path. Will
  692. only add any particular path once (leaving the last one it
  693. encounters and ignoring the rest, to preserve path order), and
  694. will os.path.normpath and os.path.normcase all paths to help
  695. assure this. This can also handle the case where the given old
  696. path variable is a list instead of a string, in which case a list
  697. will be returned instead of a string.
  698. Example:
  699. Old Path: "/foo/bar:/foo"
  700. New Path: "/biz/boom:/foo"
  701. Result: "/foo/bar:/biz/boom:/foo"
  702. If delete_existing is 0, then adding a path that exists
  703. will not move it to the end; it will stay where it is in the list.
  704. If canonicalize is not None, it is applied to each element of
  705. newpath before use.
  706. """
  707. orig = oldpath
  708. is_list = 1
  709. paths = orig
  710. if not is_List(orig) and not is_Tuple(orig):
  711. paths = paths.split(sep)
  712. is_list = 0
  713. if is_String(newpath):
  714. newpaths = newpath.split(sep)
  715. elif not is_List(newpath) and not is_Tuple(newpath):
  716. newpaths = [ newpath ] # might be a Dir
  717. else:
  718. newpaths = newpath
  719. if canonicalize:
  720. newpaths=list(map(canonicalize, newpaths))
  721. if not delete_existing:
  722. # add old paths to result, then
  723. # add new paths if not already present
  724. # (I thought about using a dict for normpaths for speed,
  725. # but it's not clear hashing the strings would be faster
  726. # than linear searching these typically short lists.)
  727. result = []
  728. normpaths = []
  729. for path in paths:
  730. if not path:
  731. continue
  732. result.append(path)
  733. normpaths.append(os.path.normpath(os.path.normcase(path)))
  734. for path in newpaths:
  735. if not path:
  736. continue
  737. normpath = os.path.normpath(os.path.normcase(path))
  738. if normpath not in normpaths:
  739. result.append(path)
  740. normpaths.append(normpath)
  741. paths = result
  742. else:
  743. # start w/ new paths, add old ones if not present,
  744. # then reverse.
  745. newpaths = paths + newpaths # append new paths
  746. newpaths.reverse()
  747. normpaths = []
  748. paths = []
  749. # now we add them only if they are unique
  750. for path in newpaths:
  751. normpath = os.path.normpath(os.path.normcase(path))
  752. if path and not normpath in normpaths:
  753. paths.append(path)
  754. normpaths.append(normpath)
  755. paths.reverse()
  756. if is_list:
  757. return paths
  758. else:
  759. return sep.join(paths)
  760. if sys.platform == 'cygwin':
  761. def get_native_path(path):
  762. """Transforms an absolute path into a native path for the system. In
  763. Cygwin, this converts from a Cygwin path to a Windows one."""
  764. return os.popen('cygpath -w ' + path).read().replace('\n', '')
  765. else:
  766. def get_native_path(path):
  767. """Transforms an absolute path into a native path for the system.
  768. Non-Cygwin version, just leave the path alone."""
  769. return path
  770. display = DisplayEngine()
  771. def Split(arg):
  772. if is_List(arg) or is_Tuple(arg):
  773. return arg
  774. elif is_String(arg):
  775. return arg.split()
  776. else:
  777. return [arg]
  778. class CLVar(UserList):
  779. """A class for command-line construction variables.
  780. This is a list that uses Split() to split an initial string along
  781. white-space arguments, and similarly to split any strings that get
  782. added. This allows us to Do the Right Thing with Append() and
  783. Prepend() (as well as straight Python foo = env['VAR'] + 'arg1
  784. arg2') regardless of whether a user adds a list or a string to a
  785. command-line construction variable.
  786. """
  787. def __init__(self, seq = []):
  788. UserList.__init__(self, Split(seq))
  789. def __add__(self, other):
  790. return UserList.__add__(self, CLVar(other))
  791. def __radd__(self, other):
  792. return UserList.__radd__(self, CLVar(other))
  793. def __coerce__(self, other):
  794. return (self, CLVar(other))
  795. def __str__(self):
  796. return ' '.join(self.data)
  797. # A dictionary that preserves the order in which items are added.
  798. # Submitted by David Benjamin to ActiveState's Python Cookbook web site:
  799. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
  800. # Including fixes/enhancements from the follow-on discussions.
  801. class OrderedDict(UserDict):
  802. def __init__(self, dict = None):
  803. self._keys = []
  804. UserDict.__init__(self, dict)
  805. def __delitem__(self, key):
  806. UserDict.__delitem__(self, key)
  807. self._keys.remove(key)
  808. def __setitem__(self, key, item):
  809. UserDict.__setitem__(self, key, item)
  810. if key not in self._keys: self._keys.append(key)
  811. def clear(self):
  812. UserDict.clear(self)
  813. self._keys = []
  814. def copy(self):
  815. dict = OrderedDict()
  816. dict.update(self)
  817. return dict
  818. def items(self):
  819. return list(zip(self._keys, list(self.values())))
  820. def keys(self):
  821. return self._keys[:]
  822. def popitem(self):
  823. try:
  824. key = self._keys[-1]
  825. except IndexError:
  826. raise KeyError('dictionary is empty')
  827. val = self[key]
  828. del self[key]
  829. return (key, val)
  830. def setdefault(self, key, failobj = None):
  831. UserDict.setdefault(self, key, failobj)
  832. if key not in self._keys: self._keys.append(key)
  833. def update(self, dict):
  834. for (key, val) in dict.items():
  835. self.__setitem__(key, val)
  836. def values(self):
  837. return list(map(self.get, self._keys))
  838. class Selector(OrderedDict):
  839. """A callable ordered dictionary that maps file suffixes to
  840. dictionary values. We preserve the order in which items are added
  841. so that get_suffix() calls always return the first suffix added."""
  842. def __call__(self, env, source, ext=None):
  843. if ext is None:
  844. try:
  845. ext = source[0].suffix
  846. except IndexError:
  847. ext = ""
  848. try:
  849. return self[ext]
  850. except KeyError:
  851. # Try to perform Environment substitution on the keys of
  852. # the dictionary before giving up.
  853. s_dict = {}
  854. for (k,v) in self.items():
  855. if k is not None:
  856. s_k = env.subst(k)
  857. if s_k in s_dict:
  858. # We only raise an error when variables point
  859. # to the same suffix. If one suffix is literal
  860. # and a variable suffix contains this literal,
  861. # the literal wins and we don't raise an error.
  862. raise KeyError(s_dict[s_k][0], k, s_k)
  863. s_dict[s_k] = (k,v)
  864. try:
  865. return s_dict[ext][1]
  866. except KeyError:
  867. try:
  868. return self[None]
  869. except KeyError:
  870. return None
  871. if sys.platform == 'cygwin':
  872. # On Cygwin, os.path.normcase() lies, so just report back the
  873. # fact that the underlying Windows OS is case-insensitive.
  874. def case_sensitive_suffixes(s1, s2):
  875. return 0
  876. else:
  877. def case_sensitive_suffixes(s1, s2):
  878. return (os.path.normcase(s1) != os.path.normcase(s2))
  879. def adjustixes(fname, pre, suf, ensure_suffix=False):
  880. if pre:
  881. path, fn = os.path.split(os.path.normpath(fname))
  882. if fn[:len(pre)] != pre:
  883. fname = os.path.join(path, pre + fn)
  884. # Only append a suffix if the suffix we're going to add isn't already
  885. # there, and if either we've been asked to ensure the specific suffix
  886. # is present or there's no suffix on it at all.
  887. if suf and fname[-len(suf):] != suf and \
  888. (ensure_suffix or not splitext(fname)[1]):
  889. fname = fname + suf
  890. return fname
  891. # From Tim Peters,
  892. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
  893. # ASPN: Python Cookbook: Remove duplicates from a sequence
  894. # (Also in the printed Python Cookbook.)
  895. def unique(s):
  896. """Return a list of the elements in s, but without duplicates.
  897. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
  898. unique("abcabc") some permutation of ["a", "b", "c"], and
  899. unique(([1, 2], [2, 3], [1, 2])) some permutation of
  900. [[2, 3], [1, 2]].
  901. For best speed, all sequence elements should be hashable. Then
  902. unique() will usually work in linear time.
  903. If not possible, the sequence elements should enjoy a total
  904. ordering, and if list(s).sort() doesn't raise TypeError it's
  905. assumed that they do enjoy a total ordering. Then unique() will
  906. usually work in O(N*log2(N)) time.
  907. If that's not possible either, the sequence elements must support
  908. equality-testing. Then unique() will usually work in quadratic
  909. time.
  910. """
  911. n = len(s)
  912. if n == 0:
  913. return []
  914. # Try using a dict first, as that's the fastest and will usually
  915. # work. If it doesn't work, it will usually fail quickly, so it
  916. # usually doesn't cost much to *try* it. It requires that all the
  917. # sequence elements be hashable, and support equality comparison.
  918. u = {}
  919. try:
  920. for x in s:
  921. u[x] = 1
  922. except TypeError:
  923. pass # move on to the next method
  924. else:
  925. return list(u.keys())
  926. del u
  927. # We can't hash all the elements. Second fastest is to sort,
  928. # which brings the equal elements together; then duplicates are
  929. # easy to weed out in a single pass.
  930. # NOTE: Python's list.sort() was designed to be efficient in the
  931. # presence of many duplicate elements. This isn't true of all
  932. # sort functions in all languages or libraries, so this approach
  933. # is more effective in Python than it may be elsewhere.
  934. try:
  935. t = sorted(s)
  936. except TypeError:
  937. pass # move on to the next method
  938. else:
  939. assert n > 0
  940. last = t[0]
  941. lasti = i = 1
  942. while i < n:
  943. if t[i] != last:
  944. t[lasti] = last = t[i]
  945. lasti = lasti + 1
  946. i = i + 1
  947. return t[:lasti]
  948. del t
  949. # Brute force is all that's left.
  950. u = []
  951. for x in s:
  952. if x not in u:
  953. u.append(x)
  954. return u
  955. # From Alex Martelli,
  956. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
  957. # ASPN: Python Cookbook: Remove duplicates from a sequence
  958. # First comment, dated 2001/10/13.
  959. # (Also in the printed Python Cookbook.)
  960. def uniquer(seq, idfun=None):
  961. if idfun is None:
  962. def idfun(x): return x
  963. seen = {}
  964. result = []
  965. for item in seq:
  966. marker = idfun(item)
  967. # in old Python versions:
  968. # if seen.has_key(marker)
  969. # but in new ones:
  970. if marker in seen: continue
  971. seen[marker] = 1
  972. result.append(item)
  973. return result
  974. # A more efficient implementation of Alex's uniquer(), this avoids the
  975. # idfun() argument and function-call overhead by assuming that all
  976. # items in the sequence are hashable.
  977. def uniquer_hashables(seq):
  978. seen = {}
  979. result = []
  980. for item in seq:
  981. #if not item in seen:
  982. if item not in seen:
  983. seen[item] = 1
  984. result.append(item)
  985. return result
  986. # Much of the logic here was originally based on recipe 4.9 from the
  987. # Python CookBook, but we had to dumb it way down for Python 1.5.2.
  988. class LogicalLines(object):
  989. def __init__(self, fileobj):
  990. self.fileobj = fileobj
  991. def readline(self):
  992. result = []
  993. while True:
  994. line = self.fileobj.readline()
  995. if not line:
  996. break
  997. if line[-2:] == '\\\n':
  998. result.append(line[:-2])
  999. else:
  1000. result.append(line)
  1001. break
  1002. return ''.join(result)
  1003. def readlines(self):
  1004. result = []
  1005. while True:
  1006. line = self.readline()
  1007. if not line:
  1008. break
  1009. result.append(line)
  1010. return result
  1011. class UniqueList(UserList):
  1012. def __init__(self, seq = []):
  1013. UserList.__init__(self, seq)
  1014. self.unique = True
  1015. def __make_unique(self):
  1016. if not self.unique:
  1017. self.data = uniquer_hashables(self.data)
  1018. self.unique = True
  1019. def __lt__(self, other):
  1020. self.__make_unique()
  1021. return UserList.__lt__(self, other)
  1022. def __le__(self, other):
  1023. self.__make_unique()
  1024. return UserList.__le__(self, other)
  1025. def __eq__(self, other):
  1026. self.__make_unique()
  1027. return UserList.__eq__(self, other)
  1028. def __ne__(self, other):
  1029. self.__make_unique()
  1030. return UserList.__ne__(self, other)
  1031. def __gt__(self, other):
  1032. self.__make_unique()
  1033. return UserList.__gt__(self, other)
  1034. def __ge__(self, other):
  1035. self.__make_unique()
  1036. return UserList.__ge__(self, other)
  1037. def __cmp__(self, other):
  1038. self.__make_unique()
  1039. return UserList.__cmp__(self, other)
  1040. def __len__(self):
  1041. self.__make_unique()
  1042. return UserList.__len__(self)
  1043. def __getitem__(self, i):
  1044. self.__make_unique()
  1045. return UserList.__getitem__(self, i)
  1046. def __setitem__(self, i, item):
  1047. UserList.__setitem__(self, i, item)
  1048. self.unique = False
  1049. def __getslice__(self, i, j):
  1050. self.__make_unique()
  1051. return UserList.__getslice__(self, i, j)
  1052. def __setslice__(self, i, j, other):
  1053. UserList.__setslice__(self, i, j, other)
  1054. self.unique = False
  1055. def __add__(self, other):
  1056. result = UserList.__add__(self, other)
  1057. result.unique = False
  1058. return result
  1059. def __radd__(self, other):
  1060. result = UserList.__radd__(self, other)
  1061. result.unique = False
  1062. return result
  1063. def __iadd__(self, other):
  1064. result = UserList.__iadd__(self, other)
  1065. result.unique = False
  1066. return result
  1067. def __mul__(self, other):
  1068. result = UserList.__mul__(self, other)
  1069. result.unique = False
  1070. return result
  1071. def __rmul__(self, other):
  1072. result = UserList.__rmul__(self, other)
  1073. result.unique = False
  1074. return result
  1075. def __imul__(self, other):
  1076. result = UserList.__imul__(self, other)
  1077. result.unique = False
  1078. return result
  1079. def append(self, item):
  1080. UserList.append(self, item)
  1081. self.unique = False
  1082. def insert(self, i):
  1083. UserList.insert(self, i)
  1084. self.unique = False
  1085. def count(self, item):
  1086. self.__make_unique()
  1087. return UserList.count(self, item)
  1088. def index(self, item):
  1089. self.__make_unique()
  1090. return UserList.index(self, item)
  1091. def reverse(self):
  1092. self.__make_unique()
  1093. UserList.reverse(self)
  1094. def sort(self, *args, **kwds):
  1095. self.__make_unique()
  1096. return UserList.sort(self, *args, **kwds)
  1097. def extend(self, other):
  1098. UserList.extend(self, other)
  1099. self.unique = False
  1100. class Unbuffered(object):
  1101. """
  1102. A proxy class that wraps a file object, flushing after every write,
  1103. and delegating everything else to the wrapped object.
  1104. """
  1105. def __init__(self, file):
  1106. self.file = file
  1107. self.softspace = 0 ## backward compatibility; not supported in Py3k
  1108. def write(self, arg):
  1109. try:
  1110. self.file.write(arg)
  1111. self.file.flush()
  1112. except IOError:
  1113. # Stdout might be connected to a pipe that has been closed
  1114. # by now. The most likely reason for the pipe being closed
  1115. # is that the user has press ctrl-c. It this is the case,
  1116. # then SCons is currently shutdown. We therefore ignore
  1117. # IOError's here so that SCons can continue and shutdown
  1118. # properly so that the .sconsign is correctly written
  1119. # before SCons exits.
  1120. pass
  1121. def __getattr__(self, attr):
  1122. return getattr(self.file, attr)
  1123. def make_path_relative(path):
  1124. """ makes an absolute path name to a relative pathname.
  1125. """
  1126. if os.path.isabs(path):
  1127. drive_s,path = os.path.splitdrive(path)
  1128. import re
  1129. if not drive_s:
  1130. path=re.compile("/*(.*)").findall(path)[0]
  1131. else:
  1132. path=path[1:]
  1133. assert( not os.path.isabs( path ) ), path
  1134. return path
  1135. # The original idea for AddMethod() and RenameFunction() come from the
  1136. # following post to the ActiveState Python Cookbook:
  1137. #
  1138. # ASPN: Python Cookbook : Install bound methods in an instance
  1139. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613
  1140. #
  1141. # That code was a little fragile, though, so the following changes
  1142. # have been wrung on it:
  1143. #
  1144. # * Switched the installmethod() "object" and "function" arguments,
  1145. # so the order reflects that the left-hand side is the thing being
  1146. # "assigned to" and the right-hand side is the value being assigned.
  1147. #
  1148. # * Changed explicit type-checking to the "try: klass = object.__class__"
  1149. # block in installmethod() below so that it still works with the
  1150. # old-style classes that SCons uses.
  1151. #
  1152. # * Replaced the by-hand creation of methods and functions with use of
  1153. # the "new" module, as alluded to in Alex Martelli's response to the
  1154. # following Cookbook post:
  1155. #
  1156. # ASPN: Python Cookbook : Dynamically added methods to a class
  1157. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732
  1158. def AddMethod(obj, function, name=None):
  1159. """
  1160. Adds either a bound method to an instance or an unbound method to
  1161. a class. If name is ommited the name of the specified function
  1162. is used by default.
  1163. Example:
  1164. a = A()
  1165. def f(self, x, y):
  1166. self.z = x + y
  1167. AddMethod(f, A, "add")
  1168. a.add(2, 4)
  1169. print a.z
  1170. AddMethod(lambda self, i: self.l[i], a, "listIndex")
  1171. print a.listIndex(5)
  1172. """
  1173. if name is None:
  1174. name = function.func_name
  1175. else:
  1176. function = RenameFunction(function, name)
  1177. if hasattr(obj, '__class__') and obj.__class__ is not type:
  1178. # "obj" is an instance, so it gets a bound method.
  1179. setattr(obj, name, MethodType(function, obj, obj.__class__))
  1180. else:
  1181. # "obj" is a class, so it gets an unbound method.
  1182. setattr(obj, name, MethodType(function, None, obj))
  1183. def RenameFunction(function, name):
  1184. """
  1185. Returns a function identical to the specified function, but with
  1186. the specified name.
  1187. """
  1188. return FunctionType(function.func_code,
  1189. function.func_globals,
  1190. name,
  1191. function.func_defaults)
  1192. md5 = False
  1193. def MD5signature(s):
  1194. return str(s)
  1195. def MD5filesignature(fname, chunksize=65536):
  1196. f = open(fname, "rb")
  1197. result = f.read()
  1198. f.close()
  1199. return result
  1200. try:
  1201. import hashlib
  1202. except ImportError:
  1203. pass
  1204. else:
  1205. if hasattr(hashlib, 'md5'):
  1206. md5 = True
  1207. def MD5signature(s):
  1208. m = hashlib.md5()
  1209. m.update(str(s))
  1210. return m.hexdigest()
  1211. def MD5filesignature(fname, chunksize=65536):
  1212. m = hashlib.md5()
  1213. f = open(fname, "rb")
  1214. while True:
  1215. blck = f.read(chunksize)
  1216. if not blck:
  1217. break
  1218. m.update(str(blck))
  1219. f.close()
  1220. return m.hexdigest()
  1221. def MD5collect(signatures):
  1222. """
  1223. Collects a list of signatures into an aggregate signature.
  1224. signatures - a list of signatures
  1225. returns - the aggregate signature
  1226. """
  1227. if len(signatures) == 1:
  1228. return signatures[0]
  1229. else:
  1230. return MD5signature(', '.join(signatures))
  1231. def silent_intern(x):
  1232. """
  1233. Perform sys.intern() on the passed argument and return the result.
  1234. If the input is ineligible (e.g. a unicode string) the original argument is
  1235. returned and no exception is thrown.
  1236. """
  1237. try:
  1238. return sys.intern(x)
  1239. except TypeError:
  1240. return x
  1241. # From Dinu C. Gherman,
  1242. # Python Cookbook, second edition, recipe 6.17, p. 277.
  1243. # Also:
  1244. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205
  1245. # ASPN: Python Cookbook: Null Object Design Pattern
  1246. #TODO??? class Null(object):
  1247. class Null(object):
  1248. """ Null objects always and reliably "do nothing." """
  1249. def __new__(cls, *args, **kwargs):
  1250. if not '_instance' in vars(cls):
  1251. cls._instance = super(Null, cls).__new__(cls, *args, **kwargs)
  1252. return cls._instance
  1253. def __init__(self, *args, **kwargs):
  1254. pass
  1255. def __call__(self, *args, **kwargs):
  1256. return self
  1257. def __repr__(self):
  1258. return "Null(0x%08X)" % id(self)
  1259. def __nonzero__(self):
  1260. return False
  1261. def __getattr__(self, name):
  1262. return self
  1263. def __setattr__(self, name, value):
  1264. return self
  1265. def __delattr__(self, name):
  1266. return self
  1267. class NullSeq(Null):
  1268. def __len__(self):
  1269. return 0
  1270. def __iter__(self):
  1271. return iter(())
  1272. def __getitem__(self, i):
  1273. return self
  1274. def __delitem__(self, i):
  1275. return self
  1276. def __setitem__(self, i, v):
  1277. return self
  1278. del __revision__
  1279. # Local Variables:
  1280. # tab-width:4
  1281. # indent-tabs-mode:nil
  1282. # End:
  1283. # vim: set expandtab tabstop=4 shiftwidth=4: