#!/usr/bin/env python #coding=utf8 ''' CloudControl Tag displaying stuff ''' from cccli.exception import * from cccli.printer import Printer, color import os import re import math import ConfigParser import time class TagDisplay(object): '''Handle tagdisplay stuff''' def __init__(self): self.option = dict() self.tagtype = dict() self.tagcolor = { "id": "lblue" } self.types = [ x[5:] for x in dir(self) if x.startswith("type_") ] def load(self, filename): '''load tagdisplay settings from file''' if os.access(filename, os.R_OK): fparser = ConfigParser.RawConfigParser() fparser.read(filename) self.__init__() if fparser.has_section("option"): self.option.update(fparser.items("option")) if fparser.has_section("type"): self.tagtype.update(fparser.items("type")) if fparser.has_section("color"): self.tagcolor.update(fparser.items("color")) def save(self, filename): '''save tagdisplay settings on file''' if os.access(filename, os.R_OK or os.W_OK): fparser = ConfigParser.RawConfigParser() fparser.read(filename) for n,d in (("type", self.tagtype), ("color", self.tagcolor), ("option", self.option)): fparser.remove_section(n) fparser.add_section(n) for k,v in d.items(): fparser.set(n, k, v) fparser.write(open(filename, "w")) def color(self, tagname): '''Return the current tag color''' if tagname in self.tagcolor and self.tagcolor[tagname] in color: return color[self.tagcolor[tagname]] return color["reset"] def resolve(self, tagname, tagvalue): '''Transform a tagvalue respecting custom display settings''' tagname = unicode(tagname) tagvalue = unicode(tagvalue) if bool(self.option.get("quotespace", False)): if re.search("\s", tagvalue) is not None: tagvalue = "'%s'"%re.sub("'", "\'", tagvalue) if tagname in self.tagtype and self.tagtype[tagname] in self.types: return getattr(self, "type_%s"%self.tagtype[tagname])(tagvalue) return tagvalue def type_lower(self, value): '''Lower case type''' return value.lower() def type_upper(self, value): '''Upper case type''' return value.upper() def type_si(self, value): '''System International type''' if value.isdecimal(): v = float(value) if v >= 1000: si = "KMGTPEZY" p = min(math.floor(math.log10(abs(v))/3.0), len(si)) d = v / pow(10, 3*p) u = si[int(p-1)] value = "%.1f%s"%(d, u) return value def type_bit(self, value): '''Bit type''' if value.isdecimal(): v = float(value) if v >= 1000: si = "KMGTPEZY" p = min(math.floor(math.log(abs(v), 2)/10.0), pow(2, len(si))) d = v / pow(2, 10*p) u = si[int(p-1)] value = "%.1f%si"%(d, u) return value def type_second(self, value): '''Second type''' if value.isdecimal(): v = long(value) if v < 60: return "%ss"%value elif v < 3600: return "%dm%ds"%(v/60, v%60) elif v < 86400: return "%dh%dm%ds"%(v/3600, v/60%60, v%60) else: return "%dd%dh%dm%ds"%(v/86400, v/3600%3600, v/60%60, v%60) return value