util.py 27 KB

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