strings.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  11. # implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import re
  15. STR_MASK = '*' * 8
  16. COLORS = {'nocolor': "\033[0m", 'red': "\033[0;31m",
  17. 'green': "\033[32m", 'blue': "\033[34m",
  18. 'yellow': "\033[33m"}
  19. def color_text(text, color):
  20. """
  21. Returns given text string with appropriate color tag. Allowed values
  22. for color parameter are 'red', 'blue', 'green' and 'yellow'.
  23. """
  24. return '%s%s%s' % (COLORS[color], text, COLORS['nocolor'])
  25. def mask_string(unmasked, mask_list=None, replace_list=None):
  26. """
  27. Replaces words from mask_list with MASK in unmasked string.
  28. If words are needed to be transformed before masking, transformation
  29. could be describe in replace list. For example [("'","'\\''")]
  30. replaces all ' characters with '\\''.
  31. """
  32. mask_list = mask_list or []
  33. replace_list = replace_list or []
  34. masked = unmasked
  35. for word in sorted(mask_list, lambda x, y: len(y) - len(x)):
  36. if not word:
  37. continue
  38. for before, after in replace_list:
  39. word = word.replace(before, after)
  40. masked = masked.replace(word, STR_MASK)
  41. return masked
  42. def state_format(msg, state, color):
  43. """
  44. Formats state with offset according to given message.
  45. """
  46. _msg = '%s' % msg.strip()
  47. for clr in COLORS.values():
  48. _msg = re.sub(re.escape(clr), '', msg)
  49. space = 70 - len(_msg)
  50. state = '[ %s ]' % color_text(state, color)
  51. return state.rjust(space)
  52. def state_message(msg, state, color):
  53. """
  54. Formats given message with colored state information.
  55. """
  56. return '%s%s' % (msg, state_format(msg, state, color))