fields.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. # Copyright (C) 2020 Red Hat, Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  13. # implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import textwrap
  17. from stevedore.example import base
  18. class FieldList(base.FormatterBase):
  19. """Format values as a reStructuredText field list.
  20. For example::
  21. : name1 : value
  22. : name2 : value
  23. : name3 : a long value
  24. will be wrapped with
  25. a hanging indent
  26. """
  27. def format(self, data):
  28. """Format the data and return unicode text.
  29. :param data: A dictionary with string keys and simple types as
  30. values.
  31. :type data: dict(str:?)
  32. """
  33. for name, value in sorted(data.items()):
  34. full_text = ': {name} : {value}'.format(
  35. name=name,
  36. value=value,
  37. )
  38. wrapped_text = textwrap.fill(
  39. full_text,
  40. initial_indent='',
  41. subsequent_indent=' ',
  42. width=self.max_width,
  43. )
  44. yield wrapped_text + '\n'