# -*- coding: utf-8 -*- import imp import os import sys class GmonPluginError(Exception): pass class XGPRenderer(object): def __init__(self, txt=None): self.txt = txt self.img = None self.tool = txt self.bar = None self.click = None self._fields = ['txt', 'img', 'tool', 'bar', 'click'] def __str__(self): out = "" for field in self._fields: value = getattr(self, field, None) if value is not None: out += "<%(f)s>%(v)s" % {'f': field, 'v': value} return out class BasePlugin(object): def __init__(self, data): self.data = data def render(self): method_n = "render_" + self.data.fmt def ex(__): raise GmonPluginError("method not defined: " + method_n) render_fn = getattr(self, method_n, ex) return render_fn() def render_xgp(self): return XGPRenderer(self.render_plain()) class PluginData(object): def __init__(self, cmdargs): self.args = [] self.fmt = "plain" self.maxlen = 40 self.name = "" self._load(cmdargs) def _load(self, cmdargs): if cmdargs['--plain']: self.fmt = "plain" elif cmdargs['--xgp']: self.fmt = "xgp" self.name = cmdargs[''] self.args = cmdargs[''] class Subcommand(object): def __init__(self, args, pluginpath): self.plugindata = PluginData(args) self.name = args[''] self._load_plugin(pluginpath) def _load_plugin(self, pluginpath): modpath = "%s/%s.py" % (pluginpath, self.name) with open(modpath) as fh: module = imp.load_module(self.name, fh, modpath, (".py", "r", imp.PY_SOURCE)) self.plugin = module.Plugin(self.plugindata) def _format_output(self, raw): suffix = "..." cooked = raw if self.plugindata.fmt == "plain": if len(raw) > self.plugindata.maxlen: newlen = self.plugindata.maxlen - len(suffix) cooked = raw[:newlen] + suffix return cooked def get_output(self): return self._format_output(self.plugin.render()) class App: def __init__(self, args): self._set_pluginpath() self.subcommand = Subcommand(args, self.pluginpath) def _set_pluginpath(self): mypath = os.path.dirname(os.path.realpath(sys.argv[0])) path = mypath + "/plugins" path = os.environ.get("GMON_PLUGINS", path) self.pluginpath = path def run(self): print self.subcommand.get_output()