Добавлен новый тип профилей xfce_xml - XML настройки для XFCE

git-svn-id: http://svn.calculate.ru/calculate2/calculate-lib/trunk@1398 c91db197-33c1-4113-bf15-f8a5c547ca64
master
asamoukin 15 years ago
parent 3162d3e8d9
commit 426026d0d6

@ -270,17 +270,35 @@ class calcHeader(_terms):
incorrectParams = set([])
# Удаление Заголовка Calculate
if comment:
reCalcHeader =\
re.compile("\s*%s\-+\s+%s.+Calculate.+\s+%s.+\s+%s\-+\s?"%(\
comment,
comment,
comment,
comment,
),
re.M|re.I)
reS = reCalcHeader.search(text)
if reS:
self.body = text[reS.end():]
# В случае текста XML
if type(comment) == types.TupleType and len(comment) == 2:
_titleList = (_("Modified"), _("File of a profile"))
reCalcHeader =\
re.compile(u"\s*%s\s+%s.+Calculate.+\s+%s.+\s+%s\s?"%(\
comment[0],
_titleList[0].decode("UTF-8"),
_titleList[1].decode("UTF-8"),
comment[1],
),
re.M|re.I|re.U)
textUnicode = text.decode("UTF-8")
reS = reCalcHeader.search(textUnicode)
if reS:
textBody = textUnicode[:reS.start()]+textUnicode[reS.end():]
if textBody:
self.body = textBody.encode("UTF-8")
else:
reCalcHeader =\
re.compile("\s*%s\-+\s+%s.+Calculate.+\s+%s.+\s+%s\-+\s?"%(\
comment,
comment,
comment,
comment,
),
re.M|re.I)
reS = reCalcHeader.search(text)
if reS:
self.body = text[reS.end():]
if fileType != False:
if fileType=="bin":
@ -2081,7 +2099,7 @@ class utfBin:
resS = reVar.search(textProfileTmp)
return textProfileTmp
class profile(_file, _terms,xmlShare):
class profile(_file, _terms, xmlShare):
"""Класс для работы с профилями
На вход 2 параметра: объект хранения переменных, имя сервиса - не
@ -2537,18 +2555,33 @@ class profile(_file, _terms,xmlShare):
def getTitle(self, comment, commentList):
"""Выдает заголовок профиля ( версия и.т.д)"""
if comment:
self._titleBody = comment + self.__titleHead + "\n"
commentFirst = comment
commentInsert = comment
commentLast = comment
flagList = False
# В случае открывающего и закрывающего комментария
if type(comment) == types.TupleType and len(comment) == 2:
commentFirst = comment[0]
commentInsert = ""
commentLast = comment[1]
flagList = True
if flagList:
self._titleBody = commentFirst + "\n"
else:
self._titleBody = commentFirst + self.__titleHead + "\n"
z = 0
lenCommentList = len(commentList) - 1
for com in self._titleList:
if lenCommentList < z:
self._titleBody += comment + " " + com + "\n"
self._titleBody += commentInsert + " " + com + "\n"
else:
self._titleBody += comment+ " " + com +\
self._titleBody += commentInsert + " " + com +\
" " + commentList[z] + "\n"
z += 1
self._titleBody += comment + self.__titleHead + "\n"
if flagList:
self._titleBody += commentLast +"\n"
else:
self._titleBody += commentLast + self.__titleHead + "\n"
return self._titleBody
else:
return ""
@ -2617,7 +2650,7 @@ class profile(_file, _terms,xmlShare):
self.numberProcessProfiles(numberProcessProfiles)
if self.getNeedProfile(fileProfile):
if self.getError():
print self.getError()
#print self.getError()
return False
oldFile = fileProfile.split(dirObj.baseDir)[1]
dirName,fileName = os.path.split(oldFile)
@ -2635,7 +2668,7 @@ class profile(_file, _terms,xmlShare):
filesApply += filesApl
else:
if self.getError():
print self.getError()
#print self.getError()
return False
self.closeFiles()
return (createdDirs, filesApply)
@ -2944,6 +2977,13 @@ class profile(_file, _terms,xmlShare):
+ objHeadNew.fileType + " : " +\
newFile)
return False
if objHeadNew.fileType == "xfce_xml":
if objProfNew.getError():
self.setError (_("False profile: " ) + newFile)
return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0]
objProfNew.setNameBodyNode(nameRootNode)
# Объект Документ
docObj = objProfNew.docObj
# Удаление комментариев из документа
@ -2967,14 +3007,24 @@ class profile(_file, _terms,xmlShare):
title = title.encode("UTF-8")
# Замена
if objHeadNew.typeAppend == "replace":
if objHeadNew.execStr:
self.oldProfile = objHeadNew.execStr+title+self.newProfile
if objHeadNew.fileType == "xfce_xml":
data = self.newProfile.split("\n")
data.insert(1,title)
self.oldProfile = "\n".join(data)
else:
self.oldProfile = title + self.newProfile
if objHeadNew.execStr:
self.oldProfile = objHeadNew.execStr+title+\
self.newProfile
else:
self.oldProfile = title + self.newProfile
self.saveOldFile()
return filesApply
# Впереди
elif objHeadNew.typeAppend == "before":
if objHeadNew.fileType == "xfce_xml":
self.setError (\
_("False option append=before in profile %s") %newFile)
return False
if objHeadOld and objHeadOld.body:
self.oldProfile = objHeadOld.body
if self.newProfile[-1] == "\n":
@ -2993,6 +3043,10 @@ class profile(_file, _terms,xmlShare):
return filesApply
# Cзади
elif objHeadNew.typeAppend == "after":
if objHeadNew.fileType == "xfce_xml":
self.setError (\
_("False option append=after in profile %s") %newFile)
return False
if objHeadOld and objHeadOld.body:
self.oldProfile = objHeadOld.body
if self.newProfile[-1] == "\n":
@ -3029,7 +3083,12 @@ class profile(_file, _terms,xmlShare):
+ objHeadNew.fileType + " : " +\
newFile)
return False
if objHeadNew.fileType == "xfce_xml":
if objProfNew.getError():
self.setError (_("False profile: " ) + newFile)
return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0]
objProfNew.setNameBodyNode(nameRootNode)
# Титл для объединения
if ListOptTitle:
title = self.getTitle(objProfNew._comment,
@ -3066,19 +3125,40 @@ class profile(_file, _terms,xmlShare):
else:
exec ("objProfOld=%s(self.oldProfile)"%\
(objHeadNew.fileType))
if objHeadNew.fileType == "xfce_xml":
if objProfOld.getError():
self.setError (_("False profile: " ) + oldFile)
return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0]
objProfOld.setNameBodyNode(nameRootNode)
#print "#%s#" %(objProfOld.docObj.body.toprettyxml())
#print "#%s#" %(objProfNew.docObj.body.toprettyxml())
objProfOld.join(objProfNew)
if objHeadNew.execStr:
self.oldProfile = objHeadNew.execStr + title +\
objProfOld.getConfig().encode("UTF-8")
elif objHeadOld.execStr:
self.oldProfile = objHeadOld.execStr + title +\
objProfOld.getConfig().encode("UTF-8")
#if objHeadNew.fileType=="xfce_xml":
#print "OLD"
#print "New"
#print objProfOld.doc.toprettyxml()
#print objProfNew.doc.toprettyxml()
if objHeadNew.fileType == "xfce_xml":
if objProfOld.getError():
self.setError (_("False profile: " ) + newFile)
return False
data = \
objProfOld.getConfig().split("\n")
#objProfOld.getConfig().encode("UTF-8").split("\n")
data.insert(1,title)
self.oldProfile = "\n".join(data)
else:
self.oldProfile = title +\
objProfOld.getConfig().encode("UTF-8")
if objHeadNew.execStr:
self.oldProfile = objHeadNew.execStr + title +\
objProfOld.getConfig().encode("UTF-8")
elif objHeadOld.execStr:
self.oldProfile = objHeadOld.execStr + title +\
objProfOld.getConfig().encode("UTF-8")
else:
self.oldProfile = title +\
objProfOld.getConfig().encode("UTF-8")
# Декодируем если кодировка не UTF-8
if flagNotUtf8New or flagNotUtf8Old:
self.newProfile = objTxtCoder.decode(self.newProfile)
@ -4966,3 +5046,239 @@ class plasma(samba):
if isinstance(kdeObj, plasma):
self.docObj.joinDoc(kdeObj.doc)
self.postXML()
class xfce_xml(_error):
"""Класс для объединения xfce-xml файлов"""
# root нода
rootNode = False
# body нода
bodyNode = False
# Документ
doc = False
# Текст профиля
text = ""
# Комментарий
_comment = ("<!--","-->")
def __init__(self, text):
self.text = text
# Создаем пустой объект
self.docObj = type("_empty_class", (object,), {})()
# Названия аттрибутов для пустого объекта
emptyMethods = ["getNodeBody","removeComment","insertBRtoBody",
"insertBeforeSepAreas"]
# Добавляем необходимые аттрибуты пустому объекту
for method in emptyMethods:
setattr(self.docObj, method, self.emptyMethod)
# Создаем XML документ
self.doc = self.textToXML()
def emptyMethod(self, *arg , **argv):
"""Пустой метод"""
return True
def setNameBodyNode(self, name):
"""Устанавливает название для корневой ноды документа"""
if not self.bodyNode:
return False
self.bodyNode.setAttribute("name", name)
return True
def textToXML(self):
"""Создание из текста XML документа
Храним xml в своем формате
"""
if not self.text.strip():
self.text = '''<?xml version="1.0" encoding="UTF-8"?>
<channel version="1.0">
</channel>'''
if hasattr(self, "objVar"):
print self.objVar.Get("cl_pass_file")
try:
self.doc = xml.dom.minidom.parseString(self.text)
except:
self.setError(_("Can not text profile is XML"))
return False
self.rootNode = self.doc.documentElement
self.bodyNode = self.rootNode
return self.doc
def join(self, xfce_xmlObj):
"""Объединяем конфигурации"""
if isinstance(xfce_xmlObj, xfce_xml):
self.joinDoc(xfce_xmlObj.doc)
def _removeDropNodesAndAttrAction(self, xmlNode):
"""Удаляет ноды с аттрибутом action='drop'
Также удаляет аттрибут action у всех нод
"""
flagError = False
childNodes = xmlNode.childNodes
if xmlNode.nodeType ==xmlNode.ELEMENT_NODE:
if xmlNode.hasAttribute("action"):
nAction = xmlNode.getAttribute("action")
if not nAction in ("join","replace","drop"):
textError = _('''In the text, XML profile, look \
for a reserved attribute 'action' with the incorrect value.\n\
Valid values attribute 'action': \
(action="join", action="replace", action="drop")''')
self.setError(textError)
return False
xmlNode.removeAttribute("action")
if nAction == "drop":
parentNode = xmlNode.parentNode
if parentNode:
parentNode.removeChild(xmlNode)
if childNodes:
for node in childNodes:
if not self._removeDropNodesAndAttrAction(node):
flagError = True
break
if flagError:
return False
return True
def postXML(self):
"""Последующая постобработка XML"""
# Удаляем теги action и удаляемые ноды
self._removeDropNodesAndAttrAction(self.bodyNode)
def _join(self, xmlNewNode, xmlOldNode, workNode=False):
"""Объединение корневой ноды профиля и корненвой ноды файла"""
xmlNode = xmlNewNode
childNodes = xmlNode.childNodes
nextOldNode = xmlOldNode
flagError = False
if xmlNode.nodeType ==xmlNode.ELEMENT_NODE:
n = xmlNode
path = u''
nName = u''
nType = u''
nValue = u''
nAction = u''
attrName = ''
attrType = ''
path = n.tagName
if n.hasAttribute("name"):
nName = n.getAttribute("name")
attrName = "attribute::name='%s'"%nName.encode("UTF-8")
if n.hasAttribute("type"):
nType = n.getAttribute("type")
attrType = "attribute::type='%s'"%nType.encode("UTF-8")
if n.hasAttribute("value"):
nValue = n.getAttribute("value")
if n.hasAttribute("action"):
nAction = n.getAttribute("action")
if not nAction in ("join","replace","drop"):
textError = _('''In the text, XML profile, look \
for a reserved attribute 'action' with the incorrect value.\n\
Valid values attribute 'action': \
(action="join", action="replace", action="drop")''')
self.setError(textError)
return False
if xmlOldNode.parentNode:
findStr = "child::%s"%path
strAttr = [attrName, attrType]
findAttr = filter(lambda x: x, strAttr)
findAttrStr = ''
if findAttr:
strAttr = ' and '.join(findAttr)
findAttrStr = "[%s]"%strAttr
findPath = "child::%s%s"%(path,findAttrStr)
# Рабочая нода
if not workNode:
workNode = xmlOldNode.parentNode
else:
workNode = xmlOldNode
oldNodes = xpath.Evaluate(findPath, workNode)
#print findPath
#print workNode
#print "----------------------------"
# Новая нода список
flagArray = False
if nType == "array":
flagArray = True
flagDrop = False
flagJoin = True
flagReplace = False
if nAction == "replace":
flagJoin = False
flagReplace = True
elif nAction == "drop":
flagJoin = False
flagDrop = True
if oldNodes:
if len(oldNodes)>1:
textError = _("The uncertainty in this profile are \
the same nodes at one level")
self.setError(textError)
return False
nextOldNode = oldNodes[0]
# Замещаем ноду в случае массива
if flagArray and not flagDrop:
replaceXmlNode = xmlNode.cloneNode(True)
if nAction:
replaceXmlNode.removeAttribute("action")
workNode.replaceChild(replaceXmlNode,
nextOldNode)
flagJoin = False
flagReplace = False
childNodes = False
# Объединение нод
if flagJoin:
if nextOldNode.hasAttribute("value"):
oValue = nextOldNode.getAttribute("value")
if nValue != oValue:
nextOldNode.setAttribute("value",nValue)
# Замещение ноды
elif flagReplace:
replaceXmlNode = xmlNode.cloneNode(True)
if not\
self._removeDropNodesAndAttrAction(replaceXmlNode):
return False
workNode.replaceChild(replaceXmlNode,
nextOldNode)
childNodes = False
# Удаление ноды
elif flagDrop:
workNode.removeChild(nextOldNode)
childNodes = False
else:
# Добавление ноды
childNodes = False
if not flagDrop:
appendXmlNode = xmlNode.cloneNode(True)
if not\
self._removeDropNodesAndAttrAction(appendXmlNode):
return False
workNode.appendChild(appendXmlNode)
if childNodes:
for node in childNodes:
if not self._join(node, nextOldNode, True):
flagError = True
break
if flagError:
return False
return True
def joinDoc(self, doc):
"""Объединение документа профиля и документа файла"""
if not self.doc:
self.setError(_("Can not text file is XML"))
return False
if not doc:
self.setError(_("Can not text profile is XML"))
return False
# Импортируем корневую ноду нового документа в текущий документ
#newImportBodyNode = self.doc.importNode(doc.documentElement, True)
# Объединение корневой ноды профиля и корненвой ноды файла
if not self._join(doc.documentElement, self.bodyNode):
return False
return True
def getConfig(self):
"""Получение текстового файла из XML документа"""
data = self.doc.toprettyxml(encoding='UTF-8').split("\n")
data = filter(lambda x: x.strip(), data)
return "\n".join(data).replace("\t"," ")

Loading…
Cancel
Save