123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- # -*- 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)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['COMMAND']
- self.args = cmdargs['ARGS']
- if cmdargs['--chars']:
- self.maxlen = int(cmdargs['--chars'])
-
-
- class Subcommand(object):
-
- def __init__(self, cmdargs, pluginpath):
- self.plugindata = PluginData(cmdargs)
- self.name = cmdargs['COMMAND']
- self._load_plugin(pluginpath)
-
- def _load_plugin(self, pluginpath):
- modpath = "%s/%s.py" % (pluginpath, self.name)
- try:
- with open(modpath) as fh:
- module = imp.load_module(self.name, fh, modpath,
- (".py", "r", imp.PY_SOURCE))
- except IOError:
- raise GmonPluginError(self.name)
- 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, cmdargs):
- self._set_pluginpath()
- try:
- self.subcommand = Subcommand(cmdargs, self.pluginpath)
- except GmonPluginError as e:
- self.die("no such plugin: %s" % e)
-
- 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 die(self, msg, rv=9):
- sys.stderr.write(msg + "\n")
- self.exit(rv)
-
- def exit(self, rv=0):
- sys.exit(rv)
-
- def run(self):
- print self.subcommand.get_output()
|