messaging.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from .compat import py27, binary_type, string_types
  2. import sys
  3. from sqlalchemy.engine import url
  4. import warnings
  5. import textwrap
  6. import collections
  7. import logging
  8. log = logging.getLogger(__name__)
  9. if py27:
  10. # disable "no handler found" errors
  11. logging.getLogger('alembic').addHandler(logging.NullHandler())
  12. try:
  13. import fcntl
  14. import termios
  15. import struct
  16. ioctl = fcntl.ioctl(0, termios.TIOCGWINSZ,
  17. struct.pack('HHHH', 0, 0, 0, 0))
  18. _h, TERMWIDTH, _hp, _wp = struct.unpack('HHHH', ioctl)
  19. if TERMWIDTH <= 0: # can occur if running in emacs pseudo-tty
  20. TERMWIDTH = None
  21. except (ImportError, IOError):
  22. TERMWIDTH = None
  23. def write_outstream(stream, *text):
  24. encoding = getattr(stream, 'encoding', 'ascii') or 'ascii'
  25. for t in text:
  26. if not isinstance(t, binary_type):
  27. t = t.encode(encoding, 'replace')
  28. t = t.decode(encoding)
  29. try:
  30. stream.write(t)
  31. except IOError:
  32. # suppress "broken pipe" errors.
  33. # no known way to handle this on Python 3 however
  34. # as the exception is "ignored" (noisily) in TextIOWrapper.
  35. break
  36. def status(_statmsg, fn, *arg, **kw):
  37. msg(_statmsg + " ...", False)
  38. try:
  39. ret = fn(*arg, **kw)
  40. write_outstream(sys.stdout, " done\n")
  41. return ret
  42. except:
  43. write_outstream(sys.stdout, " FAILED\n")
  44. raise
  45. def err(message):
  46. log.error(message)
  47. msg("FAILED: %s" % message)
  48. sys.exit(-1)
  49. def obfuscate_url_pw(u):
  50. u = url.make_url(u)
  51. if u.password:
  52. u.password = 'XXXXX'
  53. return str(u)
  54. def warn(msg):
  55. warnings.warn(msg)
  56. def msg(msg, newline=True):
  57. if TERMWIDTH is None:
  58. write_outstream(sys.stdout, msg)
  59. if newline:
  60. write_outstream(sys.stdout, "\n")
  61. else:
  62. # left indent output lines
  63. lines = textwrap.wrap(msg, TERMWIDTH)
  64. if len(lines) > 1:
  65. for line in lines[0:-1]:
  66. write_outstream(sys.stdout, " ", line, "\n")
  67. write_outstream(sys.stdout, " ", lines[-1], ("\n" if newline else ""))
  68. def format_as_comma(value):
  69. if value is None:
  70. return ""
  71. elif isinstance(value, string_types):
  72. return value
  73. elif isinstance(value, collections.Iterable):
  74. return ", ".join(value)
  75. else:
  76. raise ValueError("Don't know how to comma-format %r" % value)