A modest string writer

gmon.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # -*- coding: utf-8 -*-
  2. import imp
  3. import os
  4. import sys
  5. class GmonPluginError(Exception):
  6. pass
  7. class XGPRenderer(object):
  8. def __init__(self, txt=None):
  9. self.txt = txt
  10. self.img = None
  11. self.tool = txt
  12. self.bar = None
  13. self.click = None
  14. self._fields = ['txt', 'img', 'tool', 'bar', 'click']
  15. def __str__(self):
  16. out = ""
  17. for field in self._fields:
  18. value = getattr(self, field, None)
  19. if value is not None:
  20. out += "<%(f)s>%(v)s</%(f)s>" % {'f': field, 'v': value}
  21. return out
  22. class BasePlugin(object):
  23. def __init__(self, data):
  24. self.data = data
  25. def render(self):
  26. method_n = "render_" + self.data.fmt
  27. def ex(__):
  28. raise GmonPluginError("method not defined: " + method_n)
  29. render_fn = getattr(self, method_n, ex)
  30. return render_fn()
  31. def render_xgp(self):
  32. return XGPRenderer(self.render_plain())
  33. class PluginData(object):
  34. def __init__(self, cmdargs):
  35. self.args = []
  36. self.fmt = "plain"
  37. self.maxlen = 40
  38. self.name = ""
  39. self._load(cmdargs)
  40. def _load(self, cmdargs):
  41. if cmdargs['--plain']:
  42. self.fmt = "plain"
  43. elif cmdargs['--xgp']:
  44. self.fmt = "xgp"
  45. self.name = cmdargs['<command>']
  46. self.args = cmdargs['<args>']
  47. class Subcommand(object):
  48. def __init__(self, args, pluginpath):
  49. self.plugindata = PluginData(args)
  50. self.name = args['<command>']
  51. self._load_plugin(pluginpath)
  52. def _load_plugin(self, pluginpath):
  53. modpath = "%s/%s.py" % (pluginpath, self.name)
  54. with open(modpath) as fh:
  55. module = imp.load_module(self.name, fh, modpath,
  56. (".py", "r", imp.PY_SOURCE))
  57. self.plugin = module.Plugin(self.plugindata)
  58. def _format_output(self, raw):
  59. suffix = "..."
  60. cooked = raw
  61. if self.plugindata.fmt == "plain":
  62. if len(raw) > self.plugindata.maxlen:
  63. newlen = self.plugindata.maxlen - len(suffix)
  64. cooked = raw[:newlen] + suffix
  65. return cooked
  66. def get_output(self):
  67. return self._format_output(self.plugin.render())
  68. class App:
  69. def __init__(self, args):
  70. self._set_pluginpath()
  71. self.subcommand = Subcommand(args, self.pluginpath)
  72. def _set_pluginpath(self):
  73. mypath = os.path.dirname(os.path.realpath(sys.argv[0]))
  74. path = mypath + "/plugins"
  75. path = os.environ.get("GMON_PLUGINS", path)
  76. self.pluginpath = path
  77. def run(self):
  78. print self.subcommand.get_output()