text.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.utils.text
  4. ~~~~~~~~~~~~~~~~~
  5. Text formatting utilities
  6. """
  7. from __future__ import absolute_import
  8. from itertools import ifilter, imap
  9. from textwrap import fill
  10. from pprint import pformat
  11. from kombu.utils.encoding import safe_repr
  12. def dedent_initial(s, n=4):
  13. return s[n:] if s[:n] == ' ' * n else s
  14. def dedent(s, n=4):
  15. return '\n'.join(imap(dedent_initial, s.splitlines()))
  16. def fill_paragraphs(s, width):
  17. return '\n'.join(fill(p, width) for p in s.split('\n'))
  18. def join(l):
  19. return '\n'.join(ifilter(None, l))
  20. def ensure_2lines(s):
  21. if len(s.splitlines()) <= 2:
  22. return s + '\n'
  23. return s
  24. def abbr(S, max, ellipsis='...'):
  25. if S is None:
  26. return '???'
  27. if len(S) > max:
  28. return ellipsis and (S[:max - len(ellipsis)] + ellipsis) or S[:max]
  29. return S
  30. def abbrtask(S, max):
  31. if S is None:
  32. return '???'
  33. if len(S) > max:
  34. module, _, cls = S.rpartition('.')
  35. module = abbr(module, max - len(cls) - 3, False)
  36. return module + '[.]' + cls
  37. return S
  38. def indent(t, indent=0):
  39. """Indent text."""
  40. return '\n'.join(' ' * indent + p for p in t.split('\n'))
  41. def truncate(text, maxlen=128, suffix='...'):
  42. """Truncates text to a maximum number of characters."""
  43. if len(text) >= maxlen:
  44. return text[:maxlen].rsplit(' ', 1)[0] + suffix
  45. return text
  46. def pluralize(n, text, suffix='s'):
  47. if n > 1:
  48. return text + suffix
  49. return text
  50. def pretty(value, width=80, nl_width=80, **kw):
  51. if isinstance(value, dict):
  52. return '{{\n {0}'.format(pformat(value, 4, nl_width)[1:])
  53. elif isinstance(value, tuple):
  54. return '\n{0}{1}'.format(' ' * 4, pformat(value, width=nl_width, **kw))
  55. else:
  56. return pformat(value, width=width, **kw)
  57. def dump_body(m, body):
  58. return '{0} ({1}b)'.format(truncate(safe_repr(body), 1024),
  59. len(m.body))