text.py 1.7 KB

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