objmethods.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. objmethods: Mixin classes for MMGen data objects
  20. """
  21. import unicodedata
  22. import mmgen.color as color_mod
  23. if 'MMGenObjectDevTools' in __builtins__: # added to builtins by devinit.init_dev()
  24. MMGenObject = __builtins__['MMGenObjectDevTools']
  25. else:
  26. class MMGenObject:
  27. 'placeholder - overridden when testing'
  28. def immutable_attr_init_check(self): pass
  29. def truncate_str(s,width): # width = screen width
  30. wide_count = 0
  31. for n,ch in enumerate(s,1):
  32. wide_count += unicodedata.east_asian_width(ch) in ('F','W')
  33. if n + wide_count > width:
  34. return s[:n-1] + ('',' ')[
  35. unicodedata.east_asian_width(ch) in ('F','W')
  36. and n + wide_count == width + 1]
  37. else:
  38. raise ValueError('string requires no truncating')
  39. class Hilite:
  40. color = 'red'
  41. width = 0
  42. trunc_ok = True
  43. # supports single-width characters only
  44. def fmt( self, width, color=False ):
  45. if len(self) > width:
  46. assert self.trunc_ok, "If 'trunc_ok' is false, 'width' must be >= width of string"
  47. return self.colorize( self[:width].ljust(width), color=color )
  48. else:
  49. return self.colorize( self.ljust(width), color=color )
  50. # class method equivalent of fmt()
  51. @classmethod
  52. def fmtc( cls, s, width, color=False ):
  53. if len(s) > width:
  54. assert cls.trunc_ok, "If 'trunc_ok' is false, 'width' must be >= width of string"
  55. return cls.colorize( s[:width].ljust(width), color=color )
  56. else:
  57. return cls.colorize( s.ljust(width), color=color )
  58. # an alternative to fmt(), with double-width char support and other features
  59. def fmt2(
  60. self,
  61. width, # screen width - must be at least 2 (one wide char)
  62. color = False,
  63. encl = '', # if set, must be exactly 2 single-width chars
  64. nullrepl = '',
  65. append_chars = '', # single-width chars only
  66. append_color = False,
  67. color_override = '' ):
  68. if self == '':
  69. return getattr( color_mod, self.color )(nullrepl.ljust(width)) if color else nullrepl.ljust(width)
  70. s_wide_count = len(['' for ch in self if unicodedata.east_asian_width(ch) in ('F','W')])
  71. a,b = encl or ('','')
  72. add_len = len(append_chars) + len(encl)
  73. if len(self) + s_wide_count + add_len > width:
  74. assert self.trunc_ok, "If 'trunc_ok' is false, 'width' must be >= screen width of string"
  75. s = a + (truncate_str(self,width-add_len) if s_wide_count else self[:width-add_len]) + b
  76. else:
  77. s = a + self + b
  78. if append_chars:
  79. return (
  80. self.colorize(s,color=color)
  81. + self.colorize2(
  82. append_chars.ljust(width-len(s)-s_wide_count),
  83. color_override = append_color ))
  84. else:
  85. return self.colorize2( s.ljust(width-s_wide_count), color=color, color_override=color_override )
  86. @classmethod
  87. def colorize(cls,s,color=True):
  88. return getattr( color_mod, cls.color )(s) if color else s
  89. @classmethod
  90. def colorize2(cls,s,color=True,color_override=''):
  91. return getattr( color_mod, color_override or cls.color )(s) if color else s
  92. def hl(self,color=True):
  93. return getattr( color_mod, self.color )(self) if color else self
  94. @classmethod
  95. def hlc(cls,s,color=True):
  96. return getattr( color_mod, cls.color )(s) if color else s
  97. # an alternative to hl(), with enclosure and color override
  98. # can be called as an unbound method with class as first argument
  99. def hl2(self,s=None,color=True,encl='',color_override=''):
  100. if encl:
  101. return self.colorize2( encl[0]+(s or self)+encl[1], color=color, color_override=color_override )
  102. else:
  103. return self.colorize2( (s or self), color=color, color_override=color_override )
  104. class InitErrors:
  105. @classmethod
  106. def init_fail(cls,e,m,e2=None,m2=None,objname=None,preformat=False):
  107. if preformat:
  108. errmsg = m
  109. else:
  110. errmsg = '{!r}: value cannot be converted to {} {}({!s})'.format(
  111. m,
  112. (objname or cls.__name__),
  113. (f'({e2!s}) ' if e2 else ''),
  114. e )
  115. if m2:
  116. errmsg = repr(m2) + '\n' + errmsg
  117. from .util import die
  118. if hasattr(cls,'passthru_excs') and type(e).__name__ in cls.passthru_excs:
  119. raise
  120. elif hasattr(cls,'exc'):
  121. die( cls.exc, errmsg )
  122. else:
  123. die( 'ObjectInitError', errmsg )
  124. @classmethod
  125. def method_not_implemented(cls):
  126. import traceback
  127. raise NotImplementedError(
  128. 'method {}() not implemented for class {!r}'.format(
  129. traceback.extract_stack()[-2].name, cls.__name__) )