format.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # vim: set fileencoding=utf-8 :
  2. #
  3. # (C) 2014 Guido Guenther <agx@sigxcpu.org>
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, please see
  16. # <http://www.gnu.org/licenses/>
  17. """Format a message"""
  18. from gbp.errors import GbpError
  19. def format_str(msg, args):
  20. """
  21. Format a string with the given dict. Be a bit more verbose than
  22. default python about the error cause.
  23. >>> format_str("%(foo)", {})
  24. Traceback (most recent call last):
  25. ...
  26. GbpError: Failed to format %(foo): Missing value 'foo' in {}
  27. >>> format_str("%(foo)", {'foo': 'bar'})
  28. Traceback (most recent call last):
  29. ...
  30. GbpError: Failed to format %(foo) with {'foo': 'bar'}: incomplete format
  31. >>> format_str("A %(foo)s is a %(bar)s", {'foo': 'dog', 'bar': 'mamal'})
  32. 'A dog is a mamal'
  33. """
  34. try:
  35. return msg % args
  36. except ValueError as e:
  37. raise GbpError("Failed to format %s with %s: %s" % (msg, args, e))
  38. except KeyError as e:
  39. raise GbpError("Failed to format %s: Missing value %s in %s" %
  40. (msg, e, args))