Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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