Added format template 'patch'

develop
Самоукин Алексей 14 years ago
parent 47987c8c7e
commit 20af70828c

@ -301,7 +301,8 @@ class fileHeader(_terms):
# Тип вставки шаблона
typeAppend = ""
# Возможные типы вставки шаблонов
_fileAppend = "join", "before", "after", "replace", "remove", "skip"
_fileAppend = "join", "before", "after", "replace", "remove", "skip",\
"patch"
# Интерпретатор (#!/bin/bash) (#!/usr/bin/python)
execStr = ""
# Символ комментария
@ -419,7 +420,7 @@ class fileHeader(_terms):
def _getType(self):
"""Выдать тип файла"""
if self.params.has_key("format"):
if "format" in self.params:
return self.params["format"]
else:
return "raw"
@ -432,6 +433,9 @@ class fileHeader(_terms):
else:
if self.fileType != "raw" and self.fileType != "bin" and\
self.fileType != "":
if "format" in self.params and self.params["format"] == "patch":
self.params["append"] = "patch"
return "patch"
self.params["append"] = "join"
return "join"
self.params["append"] = "replace"
@ -4336,6 +4340,34 @@ re.M|re.S)
if objHeadNew.fileType:
formatTemplate = objHeadNew.fileType
typeAppendTemplate = objHeadNew.typeAppend
if formatTemplate == "patch":
if typeAppendTemplate != "patch":
self.setError(\
_("False option append=%(type)s in template %(file)s")\
%{"type":typeAppendTemplate,"file":nameFileTemplate})
return False
# создаем объект формата шаблона
objTempl = self.getFormatObj(formatTemplate, self.textTemplate)
if not objTempl:
self.setError(\
_("Incorrect header parmeter format=%s in template")\
%formatTemplate + " " + nameFileTemplate)
return False
if objHeadOld and objHeadOld.body:
self.textConfig = objHeadOld.body
# обработка конфигурационного файла
self.textTemplate = objTempl.processingFile(self.textConfig)
if objTempl.getError():
self.setError(_("False template") + ": " +\
nameFileTemplate)
return False
if objHeadNew.execStr:
self.textConfig = objHeadNew.execStr+title+\
self.textTemplate
else:
self.textConfig = title + self.textTemplate
self.saveConfFile()
return filesApply
# Создаем объект в случае параметра format в заголовке
if (typeAppendTemplate == "replace" or\
typeAppendTemplate == "before" or\

@ -0,0 +1,106 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys, re
import xml.dom.minidom
from cl_utils import _error
# Перевод cообщений модуля
from cl_lang import lang
tr = lang()
tr.setLocalDomain('cl_lib')
tr.setLanguage(sys.modules[__name__])
class patch(_error):
"""Класс для замены, добавления, удаления, строк в файле"""
# root нода
rootNode = False
# Документ
doc = False
# Текст шаблона
text = ""
def __init__(self, text):
self.text = text
# Создаем XML документ
self.doc = self.textToXML()
if self.doc:
self.rootNode = self.doc.documentElement
def textToXML(self):
"""Создание из текста XML документа
Храним xml в своем формате
"""
if not self.text.strip():
self.text = ''
text = '<?xml version="1.0" encoding="UTF-8"?>\n<patch>%s</patch>'\
%self.text
try:
self.doc = xml.dom.minidom.parseString(text)
except:
return False
return self.doc
def processingFile(self, textConfigFile):
"""Обработка конфигурационного файла"""
if not self.doc:
self.setError(_("Can not convert text template in XML"))
return False
retTextConfigFile = textConfigFile
tags = ["reg", "text"]
dataList = []
tagsIndex = 0
for node in self.rootNode.childNodes:
if node.nodeType==node.ELEMENT_NODE:
if not node.tagName == tags[tagsIndex]:
self.setError(_("Incorrect text template"))
return False
if tagsIndex == 1:
tagsIndex = 0
else:
tagsIndex += 1
# регулярное выражение
if node.tagName == "reg":
if node.firstChild:
reText = node.firstChild.nodeValue
else:
self.setError(\
_("Incorrect text template '<reg></reg>'"))
return False
if not reText.strip():
self.setError(\
_("Incorrect text template '<reg>%s</reg>'")\
%reText)
return False
try:
regex = re.compile(reText)
except:
self.setError(\
_("Incorrect text template '<reg>%s</reg>'")\
%reText)
return False
elif node.tagName == "text" and regex:
if node.firstChild:
text = node.firstChild.nodeValue
else:
text = ""
dataList.append((regex, text))
regex = False
for regex, text in dataList:
# Замены в тексте конфигурационного файла
retTextConfigFile = regex.sub(text, retTextConfigFile)
return retTextConfigFile
Loading…
Cancel
Save