def getPorts(self, protocol=None, user=None): """Return a list of dictionaries of .ports file entries for a user. If self.portsFileContent is None then return None. If no match then return empty list []. protocol e.g. "ssh". If None then all. user e.g. "joe". If None then all.""" if self._portsFileContent is None: # a good way to signal back to caller return None # feel the misery of not yet having better XPath from Python 2.7 and ElementTree 1.3 if protocol is not None: portElements = self._portsFileContent.findall(protocol) else: portElements = self._portsFileContent.findall("*") ports = [] for portElement in portElements: if user is not None: if user == portElement.findtext("user"): ports.append(ElementTreeUtil.simpledict(portElement)) else: ports.append(ElementTreeUtil.simpledict(portElement)) return ports
def modify(self, portsFileContentModifyingMethod): """Recommended safe wrapper to modify .ports file. Does nothing in case file doesn't exist on the host disk. Intentionally does nothing to support installation policies where .ports files are not to be stored. To make sure file exists, call create().""" # help avoid trouble if not self.exists(): # intentionally not self.create() return # read existing file with codecs.open(self._portsFilePath, "r", encoding="utf-8") as inputFile: portsFileContent = ElementTree(file=inputFile) # modify portsFileContentModifyingMethod(portsFileContent) # overwrite with codecs.open(self._portsFilePath, "w", encoding="utf-8") as outputFile: # from Python 2.7 and ElementTree 1.3 on with xml_declaration=True # portsFileContent.write(outputFile, encoding="utf-8") outputFile.write( ElementTreeUtil.tostring(portsFileContent, indent=" ", xml_declaration=True, encoding="utf-8") ) # keep up-to-date self._load()
def create(self): """Create a .ports file. As implemented creates an empty container. Does nothing in case file already exist on the host disk.""" if self.exists(): # intentionally not raise Exception("won't overwrite already existing {0}".format(self._portsFilePath)) return # just an empty container ports = Element("ports") portsFileContent = ElementTree(ports) # # write with codecs.open(self._portsFilePath, "w", encoding="utf-8") as outputFile: # from Python 2.7 and ElementTree 1.3 on with xml_declaration=True # portsFileContent.write(outputFile, encoding="utf-8") outputFile.write( ElementTreeUtil.tostring(portsFileContent, indent=" ", xml_declaration=True, encoding="utf-8") ) # keep up-to-date self._load()