def getPluginMethod(self, pluginType, pluginName, pluginMethod): methods = self.getPlugin(pluginType, pluginName)["Method"] for method in methods: if pluginMethod == method["Name"]: return method Error.raiseException("Can't find {0}::{1}::{2}()".format( pluginType, pluginName, pluginMethod))
def copy(src, tgt, mkdirs=False): try: if mkdirs: Directory.make(File.getDirectory(tgt)) copyfile(src, tgt) except IOError as e: Error.handleException(e, True, True)
def promptForPassword(isNewFlag=False): if isNewFlag: p1 = Security.__showHiddenPrompt("Enter a new password") p2 = Security.__showHiddenPrompt("Enter a new password again") if p1 != p2: Error.raiseException("Mismatched passwords") return p1 return Security.__showHiddenPrompt("Enter your password")
def saveCfg(self, cfgPath=None): if cfgPath is not None: self.cfgPath = cfgPath if cfgPath is None and self.cfgPath is None: Error.raiseException("You must specify a path to save cfg file") if self.cfg is None: Error.raiseException("No cfg loaded or set") with open(self.cfgPath, "w") as fd: json.dump(self.cfg, fd)
def __getPluginMethodInstance(self, pluginInstance, pluginMethod): method = None try: method = getattr(pluginInstance, pluginMethod) except Exception as e: Error.handleException( "Something bad happened: {0}/{1}\n{2}".format( pluginInstance.__class__, pluginMethod, str(e)), True, True) return method
def load(self, verifyFlag=True): __cfgPath = self.cfgPath if not os.path.isfile(__cfgPath): Error.raiseException("Can't find cfg file: {0}".format(__cfgPath)) with open(__cfgPath) as fd: self.cfg = json.loads(fd.read()) for name, value in self.cfg.items(): self.__dict__[name] = value if verifyFlag: self.verify() self.cfgPath = __cfgPath
def deleteSafe(): try: for path in [ "./", "./Core", "./Plugin", "./Plugin/Analyzer", "./Plugin/Demo", "./Plugin/IO", "./Plugin/Test", "./Plugin/Translator" ]: Directory.delete("{0}/__pycache__".format(path)) for path in glob.glob("./Test/Tmp/*"): File.delete(File.getCanonicalPath(path)) except Exception as e: Error.handleException(e, True)
def getContent(path, asJson=False): content = None try: if asJson: with open(path, "r", encoding="utf-8") as fd: content = json.load(fd) else: with open(path, "r", encoding="utf-8") as fd: content = fd.read() except IOError as e: Error.handleException(e, True, True) return content
def deleteProtected(cfgPath): try: cfg = Cfg(cfgPath) cfg.load() for path in [ "./Database/{0}.db".format(cfg.cfg["Database"]["Name"]), "./Database/CocoscatsTest.db", "./Vault/Certificate.pem", "./Vault/Password.json", "./Vault/PrivateKey.pem", "./Vault/PublicKey.pem" ]: File.delete(path) except Exception as e: Error.handleException(e, True)
def setContent(path, content, asJson=False, asBytes=False, mkdirs=False): try: if mkdirs: Directory.make(File.getDirectory(path)) if asJson: with open(path, "w", encoding="utf-8") as fd: json.dump(content, fd) elif asBytes: with open(path, "wb") as fd: fd.write(content) else: with open(path, "w", encoding="utf-8") as fd: fd.write(content) except IOError as e: Error.handleException(e, True, True)
def LoadXml(self, filename): ''' Load a list of errors from XML .. warning:: Describe XML format here''' q = open(filename, "r") dom = xml.dom.minidom.parse(q) dom.normalize() self.errors = [] for node in dom.childNodes: if node.tagName == "errors": for error in node.childNodes: # TODO: default values currentError = {"time":0, "programmer":0, "severity":0, "item":0} for attr in error.childNodes: if attr.nodeName == "time": for k in attr.childNodes: currentError["time"] = int(k.nodeValue) elif attr.nodeName == "programmer": for k in attr.childNodes: currentError["programmer"] = k.nodeValue elif attr.nodeName == "severity": for k in attr.childNodes: currentError["severity"] = k.nodeValue elif attr.nodeName == "item": for k in attr.childNodes: currentError["item"] = k.nodeValue if currentError != {}: e = Error(time=currentError["time"], programmer=currentError["programmer"], severity=currentError["severity"], item=currentError["item"]) self.errors.append(e) q.close() self.CalculateErrorTimes()
def AddError(self, t, p, s, i): ''' Add a single new error. :param t: Time :param p: Programmer :param s: Severity :param i: Item''' e = Error(t, p, s, i) self.errors.append(e) self.CalculateErrorTimes()
if __name__ == "__main__": cfgPath = "cfg.json" parser = argparse.ArgumentParser( \ prog=os.path.basename(__file__), description="Cocoscats directory cleanup script", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-c", "--cfg", metavar="'cfg'", type=str, default=cfgPath, help="JSON configuration file") parser.add_argument( "-F", "--force", action="store_true", help= "Delete EVERYTHING including certificates, content files and content database" ) args = parser.parse_args() if args.cfg: cfgPath = args.cfg if not os.path.isfile(cfgPath): Error.handleError( "Can't find JSON configuration file: {0}".format(cfgPath), True) if args.force: deleteProtected(cfgPath) deleteSafe()
def getPlugin(self, pluginType, pluginName): for plugin in self.cfg["Plugin"]: if plugin["Type"] == pluginType and plugin["Name"] == pluginName: return plugin Error.raiseException("Plugin {0}:{1} not found.".format( pluginType, pluginName))
def raiseException(self, msg): Error.raiseException(msg)
def verify(self): for name, value in self.cfg.items(): if name == "ProjectID": if len(value) > 256 or Text.isNothing(value): Error.raiseException( "{0} can only be 256 characters or less: {1}".format( name, value)) if re.search(r'[^A-Za-z0-9_\-\\]', value): Error.raiseException( "{0} contains invalid characters: {1}".format( name, value)) if Text.isNothing(value): Error.raiseException("Missing '{0}' value in {1}".format( name, self.cfgPath)) pluginLookupMap = [] for plugin in self.cfg["Plugin"]: pluginMethods = self.getPluginMethods(plugin["Type"], plugin["Name"]) for pluginMethod in pluginMethods["Method"]: if not Framework.hasPluginClassMethod( plugin["Type"], plugin["Name"], pluginMethod["Name"]): Error.raiseException("Can't find {0}::{1}::{2}()".format( plugin["Type"], plugin["Name"], pluginMethod["Name"])) pluginLookupMap.append("{0}{1}{2}".format( plugin["Type"], plugin["Name"], pluginMethod["Name"])) if len(self.cfg["Workflow"]["Demo"]["Plugin"]) != len( self.cfg["Workflow"]["Demo"]["Method"]): Error.raiseException( "Mismatched number of demo plugins and methods") workflowPluginLookupMap = [] for workflowPluginType, workflowPluginCfg in self.cfg[ "Workflow"].items(): pluginType = self.pluginTypeAlias[workflowPluginType] if pluginType != "Demo": workflowPluginLookupMap.append("{0}{1}{2}".format( pluginType, workflowPluginCfg["Plugin"], workflowPluginCfg["Method"])) else: for i in range(0, len(workflowPluginCfg["Plugin"])): key = "{0}{1}{2}".format(pluginType, workflowPluginCfg["Plugin"][i], workflowPluginCfg["Method"][i]) if key not in pluginLookupMap: Error.raiseException( "Can't find workflow plugin {0}::{1}::{2}()". format(workflowPluginType, workflowPluginCfg["Plugin"][i], workflowPluginCfg["Method"][i]))
def checkIfCfgLoaded(self): if self.cfg is None: Error.raiseException("Missing cfg file. Did you load it?")
def handleException(msg, showStackTraceFlag=True, abortFlag=True): Error.handleException(msg, showStackTraceFlag, abortFlag)