util.py 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. # -*- test-case-name: twisted.python.test.test_util -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. from __future__ import division, absolute_import, print_function
  5. import os, sys, errno, warnings
  6. try:
  7. import pwd, grp
  8. except ImportError:
  9. pwd = grp = None
  10. try:
  11. from os import setgroups, getgroups
  12. except ImportError:
  13. setgroups = getgroups = None
  14. from twisted.python.compat import _PY3, unicode
  15. from incremental import Version
  16. from twisted.python.deprecate import deprecatedModuleAttribute
  17. from twisted.python._oldstyle import _oldStyle, _replaceIf
  18. # For backwards compatibility, some things import this, so just link it
  19. from collections import OrderedDict
  20. deprecatedModuleAttribute(
  21. Version("Twisted", 15, 5, 0),
  22. "Use collections.OrderedDict instead.",
  23. "twisted.python.util",
  24. "OrderedDict")
  25. @_oldStyle
  26. class InsensitiveDict:
  27. """
  28. Dictionary, that has case-insensitive keys.
  29. Normally keys are retained in their original form when queried with
  30. .keys() or .items(). If initialized with preserveCase=0, keys are both
  31. looked up in lowercase and returned in lowercase by .keys() and .items().
  32. """
  33. """
  34. Modified recipe at
  35. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315 originally
  36. contributed by Sami Hangaslammi.
  37. """
  38. def __init__(self, dict=None, preserve=1):
  39. """
  40. Create an empty dictionary, or update from 'dict'.
  41. """
  42. self.data = {}
  43. self.preserve=preserve
  44. if dict:
  45. self.update(dict)
  46. def __delitem__(self, key):
  47. k=self._lowerOrReturn(key)
  48. del self.data[k]
  49. def _lowerOrReturn(self, key):
  50. if isinstance(key, bytes) or isinstance(key, unicode):
  51. return key.lower()
  52. else:
  53. return key
  54. def __getitem__(self, key):
  55. """
  56. Retrieve the value associated with 'key' (in any case).
  57. """
  58. k = self._lowerOrReturn(key)
  59. return self.data[k][1]
  60. def __setitem__(self, key, value):
  61. """
  62. Associate 'value' with 'key'. If 'key' already exists, but
  63. in different case, it will be replaced.
  64. """
  65. k = self._lowerOrReturn(key)
  66. self.data[k] = (key, value)
  67. def has_key(self, key):
  68. """
  69. Case insensitive test whether 'key' exists.
  70. """
  71. k = self._lowerOrReturn(key)
  72. return k in self.data
  73. __contains__ = has_key
  74. def _doPreserve(self, key):
  75. if not self.preserve and (isinstance(key, bytes)
  76. or isinstance(key, unicode)):
  77. return key.lower()
  78. else:
  79. return key
  80. def keys(self):
  81. """
  82. List of keys in their original case.
  83. """
  84. return list(self.iterkeys())
  85. def values(self):
  86. """
  87. List of values.
  88. """
  89. return list(self.itervalues())
  90. def items(self):
  91. """
  92. List of (key,value) pairs.
  93. """
  94. return list(self.iteritems())
  95. def get(self, key, default=None):
  96. """
  97. Retrieve value associated with 'key' or return default value
  98. if 'key' doesn't exist.
  99. """
  100. try:
  101. return self[key]
  102. except KeyError:
  103. return default
  104. def setdefault(self, key, default):
  105. """
  106. If 'key' doesn't exist, associate it with the 'default' value.
  107. Return value associated with 'key'.
  108. """
  109. if not self.has_key(key):
  110. self[key] = default
  111. return self[key]
  112. def update(self, dict):
  113. """
  114. Copy (key,value) pairs from 'dict'.
  115. """
  116. for k,v in dict.items():
  117. self[k] = v
  118. def __repr__(self):
  119. """
  120. String representation of the dictionary.
  121. """
  122. items = ", ".join([("%r: %r" % (k,v)) for k,v in self.items()])
  123. return "InsensitiveDict({%s})" % items
  124. def iterkeys(self):
  125. for v in self.data.values():
  126. yield self._doPreserve(v[0])
  127. def itervalues(self):
  128. for v in self.data.values():
  129. yield v[1]
  130. def iteritems(self):
  131. for (k, v) in self.data.values():
  132. yield self._doPreserve(k), v
  133. def popitem(self):
  134. i=self.items()[0]
  135. del self[i[0]]
  136. return i
  137. def clear(self):
  138. for k in self.keys():
  139. del self[k]
  140. def copy(self):
  141. return InsensitiveDict(self, self.preserve)
  142. def __len__(self):
  143. return len(self.data)
  144. def __eq__(self, other):
  145. for k,v in self.items():
  146. if not (k in other) or not (other[k]==v):
  147. return 0
  148. return len(self)==len(other)
  149. def uniquify(lst):
  150. """
  151. Make the elements of a list unique by inserting them into a dictionary.
  152. This must not change the order of the input lst.
  153. """
  154. dct = {}
  155. result = []
  156. for k in lst:
  157. if k not in dct:
  158. result.append(k)
  159. dct[k] = 1
  160. return result
  161. def padTo(n, seq, default=None):
  162. """
  163. Pads a sequence out to n elements,
  164. filling in with a default value if it is not long enough.
  165. If the input sequence is longer than n, raises ValueError.
  166. Details, details:
  167. This returns a new list; it does not extend the original sequence.
  168. The new list contains the values of the original sequence, not copies.
  169. """
  170. if len(seq) > n:
  171. raise ValueError("%d elements is more than %d." % (len(seq), n))
  172. blank = [default] * n
  173. blank[:len(seq)] = list(seq)
  174. return blank
  175. def getPluginDirs():
  176. warnings.warn(
  177. "twisted.python.util.getPluginDirs is deprecated since Twisted 12.2.",
  178. DeprecationWarning, stacklevel=2)
  179. import twisted
  180. systemPlugins = os.path.join(os.path.dirname(os.path.dirname(
  181. os.path.abspath(twisted.__file__))), 'plugins')
  182. userPlugins = os.path.expanduser("~/TwistedPlugins")
  183. confPlugins = os.path.expanduser("~/.twisted")
  184. allPlugins = filter(os.path.isdir, [systemPlugins, userPlugins, confPlugins])
  185. return allPlugins
  186. def addPluginDir():
  187. warnings.warn(
  188. "twisted.python.util.addPluginDir is deprecated since Twisted 12.2.",
  189. DeprecationWarning, stacklevel=2)
  190. sys.path.extend(getPluginDirs())
  191. def sibpath(path, sibling):
  192. """
  193. Return the path to a sibling of a file in the filesystem.
  194. This is useful in conjunction with the special C{__file__} attribute
  195. that Python provides for modules, so modules can load associated
  196. resource files.
  197. """
  198. return os.path.join(os.path.dirname(os.path.abspath(path)), sibling)
  199. def _getpass(prompt):
  200. """
  201. Helper to turn IOErrors into KeyboardInterrupts.
  202. """
  203. import getpass
  204. try:
  205. return getpass.getpass(prompt)
  206. except IOError as e:
  207. if e.errno == errno.EINTR:
  208. raise KeyboardInterrupt
  209. raise
  210. except EOFError:
  211. raise KeyboardInterrupt
  212. def getPassword(prompt = 'Password: ', confirm = 0, forceTTY = 0,
  213. confirmPrompt = 'Confirm password: ',
  214. mismatchMessage = "Passwords don't match."):
  215. """
  216. Obtain a password by prompting or from stdin.
  217. If stdin is a terminal, prompt for a new password, and confirm (if
  218. C{confirm} is true) by asking again to make sure the user typed the same
  219. thing, as keystrokes will not be echoed.
  220. If stdin is not a terminal, and C{forceTTY} is not true, read in a line
  221. and use it as the password, less the trailing newline, if any. If
  222. C{forceTTY} is true, attempt to open a tty and prompt for the password
  223. using it. Raise a RuntimeError if this is not possible.
  224. @returns: C{str}
  225. """
  226. isaTTY = hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()
  227. old = None
  228. try:
  229. if not isaTTY:
  230. if forceTTY:
  231. try:
  232. old = sys.stdin, sys.stdout
  233. sys.stdin = sys.stdout = open('/dev/tty', 'r+')
  234. except:
  235. raise RuntimeError("Cannot obtain a TTY")
  236. else:
  237. password = sys.stdin.readline()
  238. if password[-1] == '\n':
  239. password = password[:-1]
  240. return password
  241. while 1:
  242. try1 = _getpass(prompt)
  243. if not confirm:
  244. return try1
  245. try2 = _getpass(confirmPrompt)
  246. if try1 == try2:
  247. return try1
  248. else:
  249. sys.stderr.write(mismatchMessage + "\n")
  250. finally:
  251. if old:
  252. sys.stdin.close()
  253. sys.stdin, sys.stdout = old
  254. def println(*a):
  255. sys.stdout.write(' '.join(map(str, a))+'\n')
  256. # XXX
  257. # This does not belong here
  258. # But where does it belong?
  259. def str_xor(s, b):
  260. return ''.join([chr(ord(c) ^ b) for c in s])
  261. def makeStatBar(width, maxPosition, doneChar = '=', undoneChar = '-', currentChar = '>'):
  262. """
  263. Creates a function that will return a string representing a progress bar.
  264. """
  265. aValue = width / float(maxPosition)
  266. def statBar(position, force = 0, last = ['']):
  267. assert len(last) == 1, "Don't mess with the last parameter."
  268. done = int(aValue * position)
  269. toDo = width - done - 2
  270. result = "[%s%s%s]" % (doneChar * done, currentChar, undoneChar * toDo)
  271. if force:
  272. last[0] = result
  273. return result
  274. if result == last[0]:
  275. return ''
  276. last[0] = result
  277. return result
  278. statBar.__doc__ = """statBar(position, force = 0) -> '[%s%s%s]'-style progress bar
  279. returned string is %d characters long, and the range goes from 0..%d.
  280. The 'position' argument is where the '%s' will be drawn. If force is false,
  281. '' will be returned instead if the resulting progress bar is identical to the
  282. previously returned progress bar.
  283. """ % (doneChar * 3, currentChar, undoneChar * 3, width, maxPosition, currentChar)
  284. return statBar
  285. def spewer(frame, s, ignored):
  286. """
  287. A trace function for sys.settrace that prints every function or method call.
  288. """
  289. from twisted.python import reflect
  290. if 'self' in frame.f_locals:
  291. se = frame.f_locals['self']
  292. if hasattr(se, '__class__'):
  293. k = reflect.qual(se.__class__)
  294. else:
  295. k = reflect.qual(type(se))
  296. print('method %s of %s at %s' % (
  297. frame.f_code.co_name, k, id(se)))
  298. else:
  299. print('function %s in %s, line %s' % (
  300. frame.f_code.co_name,
  301. frame.f_code.co_filename,
  302. frame.f_lineno))
  303. def searchupwards(start, files=[], dirs=[]):
  304. """
  305. Walk upwards from start, looking for a directory containing
  306. all files and directories given as arguments::
  307. >>> searchupwards('.', ['foo.txt'], ['bar', 'bam'])
  308. If not found, return None
  309. """
  310. start=os.path.abspath(start)
  311. parents=start.split(os.sep)
  312. exists=os.path.exists; join=os.sep.join; isdir=os.path.isdir
  313. while len(parents):
  314. candidate=join(parents)+os.sep
  315. allpresent=1
  316. for f in files:
  317. if not exists("%s%s" % (candidate, f)):
  318. allpresent=0
  319. break
  320. if allpresent:
  321. for d in dirs:
  322. if not isdir("%s%s" % (candidate, d)):
  323. allpresent=0
  324. break
  325. if allpresent: return candidate
  326. parents.pop(-1)
  327. return None
  328. @_oldStyle
  329. class LineLog:
  330. """
  331. A limited-size line-based log, useful for logging line-based
  332. protocols such as SMTP.
  333. When the log fills up, old entries drop off the end.
  334. """
  335. def __init__(self, size=10):
  336. """
  337. Create a new log, with size lines of storage (default 10).
  338. A log size of 0 (or less) means an infinite log.
  339. """
  340. if size < 0:
  341. size = 0
  342. self.log = [None] * size
  343. self.size = size
  344. def append(self,line):
  345. if self.size:
  346. self.log[:-1] = self.log[1:]
  347. self.log[-1] = line
  348. else:
  349. self.log.append(line)
  350. def str(self):
  351. return bytes(self)
  352. if not _PY3:
  353. def __str__(self):
  354. return self.__bytes__()
  355. def __bytes__(self):
  356. return b'\n'.join(filter(None, self.log))
  357. def __getitem__(self, item):
  358. return filter(None, self.log)[item]
  359. def clear(self):
  360. """
  361. Empty the log.
  362. """
  363. self.log = [None] * self.size
  364. def raises(exception, f, *args, **kwargs):
  365. """
  366. Determine whether the given call raises the given exception.
  367. """
  368. try:
  369. f(*args, **kwargs)
  370. except exception:
  371. return 1
  372. return 0
  373. class IntervalDifferential(object):
  374. """
  375. Given a list of intervals, generate the amount of time to sleep between
  376. "instants".
  377. For example, given 7, 11 and 13, the three (infinite) sequences::
  378. 7 14 21 28 35 ...
  379. 11 22 33 44 ...
  380. 13 26 39 52 ...
  381. will be generated, merged, and used to produce::
  382. (7, 0) (4, 1) (2, 2) (1, 0) (7, 0) (1, 1) (4, 2) (2, 0) (5, 1) (2, 0)
  383. New intervals may be added or removed as iteration proceeds using the
  384. proper methods.
  385. """
  386. def __init__(self, intervals, default=60):
  387. """
  388. @type intervals: C{list} of C{int}, C{long}, or C{float} param
  389. @param intervals: The intervals between instants.
  390. @type default: C{int}, C{long}, or C{float}
  391. @param default: The duration to generate if the intervals list
  392. becomes empty.
  393. """
  394. self.intervals = intervals[:]
  395. self.default = default
  396. def __iter__(self):
  397. return _IntervalDifferentialIterator(self.intervals, self.default)
  398. class _IntervalDifferentialIterator(object):
  399. def __init__(self, i, d):
  400. self.intervals = [[e, e, n] for (e, n) in zip(i, range(len(i)))]
  401. self.default = d
  402. self.last = 0
  403. def __next__(self):
  404. if not self.intervals:
  405. return (self.default, None)
  406. last, index = self.intervals[0][0], self.intervals[0][2]
  407. self.intervals[0][0] += self.intervals[0][1]
  408. self.intervals.sort()
  409. result = last - self.last
  410. self.last = last
  411. return result, index
  412. # Iterators on Python 2 use next(), not __next__()
  413. next = __next__
  414. def addInterval(self, i):
  415. if self.intervals:
  416. delay = self.intervals[0][0] - self.intervals[0][1]
  417. self.intervals.append([delay + i, i, len(self.intervals)])
  418. self.intervals.sort()
  419. else:
  420. self.intervals.append([i, i, 0])
  421. def removeInterval(self, interval):
  422. for i in range(len(self.intervals)):
  423. if self.intervals[i][1] == interval:
  424. index = self.intervals[i][2]
  425. del self.intervals[i]
  426. for i in self.intervals:
  427. if i[2] > index:
  428. i[2] -= 1
  429. return
  430. raise ValueError("Specified interval not in IntervalDifferential")
  431. @_oldStyle
  432. class FancyStrMixin:
  433. """
  434. Mixin providing a flexible implementation of C{__str__}.
  435. C{__str__} output will begin with the name of the class, or the contents
  436. of the attribute C{fancybasename} if it is set.
  437. The body of C{__str__} can be controlled by overriding C{showAttributes} in
  438. a subclass. Set C{showAttributes} to a sequence of strings naming
  439. attributes, or sequences of C{(attributeName, callable)}, or sequences of
  440. C{(attributeName, displayName, formatCharacter)}. In the second case, the
  441. callable is passed the value of the attribute and its return value used in
  442. the output of C{__str__}. In the final case, the attribute is looked up
  443. using C{attributeName}, but the output uses C{displayName} instead, and
  444. renders the value of the attribute using C{formatCharacter}, e.g. C{"%.3f"}
  445. might be used for a float.
  446. """
  447. # Override in subclasses:
  448. showAttributes = ()
  449. def __str__(self):
  450. r = ['<', (hasattr(self, 'fancybasename') and self.fancybasename)
  451. or self.__class__.__name__]
  452. for attr in self.showAttributes:
  453. if isinstance(attr, str):
  454. r.append(' %s=%r' % (attr, getattr(self, attr)))
  455. elif len(attr) == 2:
  456. r.append((' %s=' % (attr[0],)) + attr[1](getattr(self, attr[0])))
  457. else:
  458. r.append((' %s=' + attr[2]) % (attr[1], getattr(self, attr[0])))
  459. r.append('>')
  460. return ''.join(r)
  461. __repr__ = __str__
  462. @_oldStyle
  463. class FancyEqMixin:
  464. """
  465. Mixin that implements C{__eq__} and C{__ne__}.
  466. Comparison is done using the list of attributes defined in
  467. C{compareAttributes}.
  468. """
  469. compareAttributes = ()
  470. def __eq__(self, other):
  471. if not self.compareAttributes:
  472. return self is other
  473. if isinstance(self, other.__class__):
  474. return (
  475. [getattr(self, name) for name in self.compareAttributes] ==
  476. [getattr(other, name) for name in self.compareAttributes])
  477. return NotImplemented
  478. def __ne__(self, other):
  479. result = self.__eq__(other)
  480. if result is NotImplemented:
  481. return result
  482. return not result
  483. try:
  484. # initgroups is available in Python 2.7+ on UNIX-likes
  485. from os import initgroups as _initgroups
  486. except ImportError:
  487. _initgroups = None
  488. if _initgroups is None:
  489. def initgroups(uid, primaryGid):
  490. """
  491. Do nothing.
  492. Underlying platform support require to manipulate groups is missing.
  493. """
  494. else:
  495. def initgroups(uid, primaryGid):
  496. """
  497. Initializes the group access list.
  498. This uses the stdlib support which calls initgroups(3) under the hood.
  499. If the given user is a member of more than C{NGROUPS}, arbitrary
  500. groups will be silently discarded to bring the number below that
  501. limit.
  502. @type uid: C{int}
  503. @param uid: The UID for which to look up group information.
  504. @type primaryGid: C{int} or L{None}
  505. @param primaryGid: If provided, an additional GID to include when
  506. setting the groups.
  507. """
  508. return _initgroups(pwd.getpwuid(uid)[0], primaryGid)
  509. def switchUID(uid, gid, euid=False):
  510. """
  511. Attempts to switch the uid/euid and gid/egid for the current process.
  512. If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
  513. this function will issue a L{UserWarning} and not raise an exception.
  514. @type uid: C{int} or L{None}
  515. @param uid: the UID (or EUID) to switch the current process to. This
  516. parameter will be ignored if the value is L{None}.
  517. @type gid: C{int} or L{None}
  518. @param gid: the GID (or EGID) to switch the current process to. This
  519. parameter will be ignored if the value is L{None}.
  520. @type euid: C{bool}
  521. @param euid: if True, set only effective user-id rather than real user-id.
  522. (This option has no effect unless the process is running
  523. as root, in which case it means not to shed all
  524. privileges, retaining the option to regain privileges
  525. in cases such as spawning processes. Use with caution.)
  526. """
  527. if euid:
  528. setuid = os.seteuid
  529. setgid = os.setegid
  530. getuid = os.geteuid
  531. else:
  532. setuid = os.setuid
  533. setgid = os.setgid
  534. getuid = os.getuid
  535. if gid is not None:
  536. setgid(gid)
  537. if uid is not None:
  538. if uid == getuid():
  539. uidText = (euid and "euid" or "uid")
  540. actionText = "tried to drop privileges and set%s %s" % (uidText, uid)
  541. problemText = "%s is already %s" % (uidText, getuid())
  542. warnings.warn("%s but %s; should we be root? Continuing."
  543. % (actionText, problemText))
  544. else:
  545. initgroups(uid, gid)
  546. setuid(uid)
  547. class SubclassableCStringIO(object):
  548. """
  549. A wrapper around cStringIO to allow for subclassing.
  550. """
  551. __csio = None
  552. def __init__(self, *a, **kw):
  553. from cStringIO import StringIO
  554. self.__csio = StringIO(*a, **kw)
  555. def __iter__(self):
  556. return self.__csio.__iter__()
  557. def next(self):
  558. return self.__csio.next()
  559. def close(self):
  560. return self.__csio.close()
  561. def isatty(self):
  562. return self.__csio.isatty()
  563. def seek(self, pos, mode=0):
  564. return self.__csio.seek(pos, mode)
  565. def tell(self):
  566. return self.__csio.tell()
  567. def read(self, n=-1):
  568. return self.__csio.read(n)
  569. def readline(self, length=None):
  570. return self.__csio.readline(length)
  571. def readlines(self, sizehint=0):
  572. return self.__csio.readlines(sizehint)
  573. def truncate(self, size=None):
  574. return self.__csio.truncate(size)
  575. def write(self, s):
  576. return self.__csio.write(s)
  577. def writelines(self, list):
  578. return self.__csio.writelines(list)
  579. def flush(self):
  580. return self.__csio.flush()
  581. def getvalue(self):
  582. return self.__csio.getvalue()
  583. def untilConcludes(f, *a, **kw):
  584. """
  585. Call C{f} with the given arguments, handling C{EINTR} by retrying.
  586. @param f: A function to call.
  587. @param *a: Positional arguments to pass to C{f}.
  588. @param **kw: Keyword arguments to pass to C{f}.
  589. @return: Whatever C{f} returns.
  590. @raise: Whatever C{f} raises, except for C{IOError} or C{OSError} with
  591. C{errno} set to C{EINTR}.
  592. """
  593. while True:
  594. try:
  595. return f(*a, **kw)
  596. except (IOError, OSError) as e:
  597. if e.args[0] == errno.EINTR:
  598. continue
  599. raise
  600. def mergeFunctionMetadata(f, g):
  601. """
  602. Overwrite C{g}'s name and docstring with values from C{f}. Update
  603. C{g}'s instance dictionary with C{f}'s.
  604. @return: A function that has C{g}'s behavior and metadata merged from
  605. C{f}.
  606. """
  607. try:
  608. g.__name__ = f.__name__
  609. except TypeError:
  610. pass
  611. try:
  612. g.__doc__ = f.__doc__
  613. except (TypeError, AttributeError):
  614. pass
  615. try:
  616. g.__dict__.update(f.__dict__)
  617. except (TypeError, AttributeError):
  618. pass
  619. try:
  620. g.__module__ = f.__module__
  621. except TypeError:
  622. pass
  623. return g
  624. def nameToLabel(mname):
  625. """
  626. Convert a string like a variable name into a slightly more human-friendly
  627. string with spaces and capitalized letters.
  628. @type mname: C{str}
  629. @param mname: The name to convert to a label. This must be a string
  630. which could be used as a Python identifier. Strings which do not take
  631. this form will result in unpredictable behavior.
  632. @rtype: C{str}
  633. """
  634. labelList = []
  635. word = ''
  636. lastWasUpper = False
  637. for letter in mname:
  638. if letter.isupper() == lastWasUpper:
  639. # Continuing a word.
  640. word += letter
  641. else:
  642. # breaking a word OR beginning a word
  643. if lastWasUpper:
  644. # could be either
  645. if len(word) == 1:
  646. # keep going
  647. word += letter
  648. else:
  649. # acronym
  650. # we're processing the lowercase letter after the acronym-then-capital
  651. lastWord = word[:-1]
  652. firstLetter = word[-1]
  653. labelList.append(lastWord)
  654. word = firstLetter + letter
  655. else:
  656. # definitely breaking: lower to upper
  657. labelList.append(word)
  658. word = letter
  659. lastWasUpper = letter.isupper()
  660. if labelList:
  661. labelList[0] = labelList[0].capitalize()
  662. else:
  663. return mname.capitalize()
  664. labelList.append(word)
  665. return ' '.join(labelList)
  666. def uidFromString(uidString):
  667. """
  668. Convert a user identifier, as a string, into an integer UID.
  669. @type uid: C{str}
  670. @param uid: A string giving the base-ten representation of a UID or the
  671. name of a user which can be converted to a UID via L{pwd.getpwnam}.
  672. @rtype: C{int}
  673. @return: The integer UID corresponding to the given string.
  674. @raise ValueError: If the user name is supplied and L{pwd} is not
  675. available.
  676. """
  677. try:
  678. return int(uidString)
  679. except ValueError:
  680. if pwd is None:
  681. raise
  682. return pwd.getpwnam(uidString)[2]
  683. def gidFromString(gidString):
  684. """
  685. Convert a group identifier, as a string, into an integer GID.
  686. @type uid: C{str}
  687. @param uid: A string giving the base-ten representation of a GID or the
  688. name of a group which can be converted to a GID via L{grp.getgrnam}.
  689. @rtype: C{int}
  690. @return: The integer GID corresponding to the given string.
  691. @raise ValueError: If the group name is supplied and L{grp} is not
  692. available.
  693. """
  694. try:
  695. return int(gidString)
  696. except ValueError:
  697. if grp is None:
  698. raise
  699. return grp.getgrnam(gidString)[2]
  700. def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
  701. """
  702. Run the given function wrapped with seteuid/setegid calls.
  703. This will try to minimize the number of seteuid/setegid calls, comparing
  704. current and wanted permissions
  705. @param euid: effective UID used to call the function.
  706. @type euid: C{int}
  707. @type egid: effective GID used to call the function.
  708. @param egid: C{int}
  709. @param function: the function run with the specific permission.
  710. @type function: any callable
  711. @param *args: arguments passed to C{function}
  712. @param **kwargs: keyword arguments passed to C{function}
  713. """
  714. uid, gid = os.geteuid(), os.getegid()
  715. if uid == euid and gid == egid:
  716. return function(*args, **kwargs)
  717. else:
  718. if uid != 0 and (uid != euid or gid != egid):
  719. os.seteuid(0)
  720. if gid != egid:
  721. os.setegid(egid)
  722. if euid != 0 and (euid != uid or gid != egid):
  723. os.seteuid(euid)
  724. try:
  725. return function(*args, **kwargs)
  726. finally:
  727. if euid != 0 and (uid != euid or gid != egid):
  728. os.seteuid(0)
  729. if gid != egid:
  730. os.setegid(gid)
  731. if uid != 0 and (uid != euid or gid != egid):
  732. os.seteuid(uid)
  733. def runWithWarningsSuppressed(suppressedWarnings, f, *args, **kwargs):
  734. """
  735. Run C{f(*args, **kwargs)}, but with some warnings suppressed.
  736. Unlike L{twisted.internet.utils.runWithWarningsSuppressed}, it has no
  737. special support for L{twisted.internet.defer.Deferred}.
  738. @param suppressedWarnings: A list of arguments to pass to filterwarnings.
  739. Must be a sequence of 2-tuples (args, kwargs).
  740. @param f: A callable.
  741. @param args: Arguments for C{f}.
  742. @param kwargs: Keyword arguments for C{f}
  743. @return: The result of C{f(*args, **kwargs)}.
  744. """
  745. with warnings.catch_warnings():
  746. for a, kw in suppressedWarnings:
  747. warnings.filterwarnings(*a, **kw)
  748. return f(*args, **kwargs)
  749. __all__ = [
  750. "uniquify", "padTo", "getPluginDirs", "addPluginDir", "sibpath",
  751. "getPassword", "println", "makeStatBar", "OrderedDict",
  752. "InsensitiveDict", "spewer", "searchupwards", "LineLog",
  753. "raises", "IntervalDifferential", "FancyStrMixin", "FancyEqMixin",
  754. "switchUID", "SubclassableCStringIO", "mergeFunctionMetadata",
  755. "nameToLabel", "uidFromString", "gidFromString", "runAsEffectiveUser",
  756. "untilConcludes", "runWithWarningsSuppressed", "_replaceIf",
  757. ]
  758. if _PY3:
  759. __notported__ = ["SubclassableCStringIO", "makeStatBar"]
  760. for name in __all__[:]:
  761. if name in __notported__:
  762. __all__.remove(name)
  763. del globals()[name]
  764. del name, __notported__