objmethods.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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):
  29. pass
  30. def truncate_str(s,width): # width = screen width
  31. wide_count = 0
  32. for n,ch in enumerate(s,1):
  33. wide_count += unicodedata.east_asian_width(ch) in ('F','W')
  34. if n + wide_count > width:
  35. return s[:n-1] + ('',' ')[
  36. unicodedata.east_asian_width(ch) in ('F','W')
  37. and n + wide_count == width + 1]
  38. else:
  39. raise ValueError('string requires no truncating')
  40. class Hilite:
  41. color = 'red'
  42. width = 0
  43. trunc_ok = True
  44. # supports single-width characters only
  45. def fmt( self, width, color=False ):
  46. if len(self) > width:
  47. assert self.trunc_ok, "If 'trunc_ok' is false, 'width' must be >= width of string"
  48. return self.colorize( self[:width].ljust(width), color=color )
  49. else:
  50. return self.colorize( self.ljust(width), color=color )
  51. # class method equivalent of fmt()
  52. @classmethod
  53. def fmtc( cls, s, width, color=False ):
  54. if len(s) > width:
  55. assert cls.trunc_ok, "If 'trunc_ok' is false, 'width' must be >= width of string"
  56. return cls.colorize( s[:width].ljust(width), color=color )
  57. else:
  58. return cls.colorize( s.ljust(width), color=color )
  59. # an alternative to fmt(), with double-width char support and other features
  60. def fmt2(
  61. self,
  62. width, # screen width - must be at least 2 (one wide char)
  63. color = False,
  64. encl = '', # if set, must be exactly 2 single-width chars
  65. nullrepl = '',
  66. append_chars = '', # single-width chars only
  67. append_color = False,
  68. color_override = '' ):
  69. if self == '':
  70. return getattr( color_mod, self.color )(nullrepl.ljust(width)) if color else nullrepl.ljust(width)
  71. s_wide_count = len(['' for ch in self if unicodedata.east_asian_width(ch) in ('F','W')])
  72. a,b = encl or ('','')
  73. add_len = len(append_chars) + len(encl)
  74. if len(self) + s_wide_count + add_len > width:
  75. assert self.trunc_ok, "If 'trunc_ok' is false, 'width' must be >= screen width of string"
  76. s = a + (truncate_str(self,width-add_len) if s_wide_count else self[:width-add_len]) + b
  77. else:
  78. s = a + self + b
  79. if append_chars:
  80. return (
  81. self.colorize(s,color=color)
  82. + self.colorize2(
  83. append_chars.ljust(width-len(s)-s_wide_count),
  84. color_override = append_color ))
  85. else:
  86. return self.colorize2( s.ljust(width-s_wide_count), color=color, color_override=color_override )
  87. @classmethod
  88. def colorize(cls,s,color=True):
  89. return getattr( color_mod, cls.color )(s) if color else s
  90. @classmethod
  91. def colorize2(cls,s,color=True,color_override=''):
  92. return getattr( color_mod, color_override or cls.color )(s) if color else s
  93. def hl(self,color=True):
  94. return getattr( color_mod, self.color )(self) if color else self
  95. @classmethod
  96. def hlc(cls,s,color=True):
  97. return getattr( color_mod, cls.color )(s) if color else s
  98. # an alternative to hl(), with enclosure and color override
  99. # can be called as an unbound method with class as first argument
  100. def hl2(self,s=None,color=True,encl='',color_override=''):
  101. if encl:
  102. return self.colorize2( encl[0]+(s or self)+encl[1], color=color, color_override=color_override )
  103. else:
  104. return self.colorize2( (s or self), color=color, color_override=color_override )
  105. class InitErrors:
  106. @classmethod
  107. def init_fail(cls,e,m,e2=None,m2=None,objname=None,preformat=False):
  108. if preformat:
  109. errmsg = m
  110. else:
  111. errmsg = '{!r}: value cannot be converted to {} {}({!s})'.format(
  112. m,
  113. (objname or cls.__name__),
  114. (f'({e2!s}) ' if e2 else ''),
  115. e )
  116. if m2:
  117. errmsg = repr(m2) + '\n' + errmsg
  118. from .util import die
  119. if hasattr(cls,'passthru_excs') and type(e).__name__ in cls.passthru_excs:
  120. raise
  121. elif hasattr(cls,'exc'):
  122. die( cls.exc, errmsg )
  123. else:
  124. die( 'ObjectInitError', errmsg )
  125. @classmethod
  126. def method_not_implemented(cls):
  127. import traceback
  128. raise NotImplementedError(
  129. 'method {}() not implemented for class {!r}'.format(
  130. traceback.extract_stack()[-2].name, cls.__name__) )