|
|
|
@ -2080,7 +2080,367 @@ class utfBin:
|
|
|
|
|
resS = reVar.search(textTemplateTmp)
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
class template(_file, _terms, xmlShare):
|
|
|
|
|
class _shareTemplate:
|
|
|
|
|
"""Общие аттрибуты для классов шаблонов"""
|
|
|
|
|
# Метка начала переменной
|
|
|
|
|
varStart = "#-"
|
|
|
|
|
# Метка конца переменной
|
|
|
|
|
varEnd = "-#"
|
|
|
|
|
_deltVarStart = len(varStart)
|
|
|
|
|
_deltVarEnd = len(varEnd)
|
|
|
|
|
|
|
|
|
|
class templateFunction(_shareTemplate):
|
|
|
|
|
"""Класс для функций шаблонов"""
|
|
|
|
|
# Список названий функций шаблона
|
|
|
|
|
namesTemplateFunction = []
|
|
|
|
|
# Словарь {название функции шаблона: функция шаблона, ...}
|
|
|
|
|
templateFunction = {}
|
|
|
|
|
# Имена установленных программ
|
|
|
|
|
installProg = []
|
|
|
|
|
# Версии установленных программ
|
|
|
|
|
installProgVersions = []
|
|
|
|
|
# кеш вызванных значений программа, номер версии
|
|
|
|
|
cacheInstallProg = {}
|
|
|
|
|
# Регулярное выражение для сложения
|
|
|
|
|
sNum = re.compile("\-[^\-\+]+|[^\-\+]+")
|
|
|
|
|
# Регулярное выражение для умножениея и деления
|
|
|
|
|
sMD = re.compile("[^\-\+\*\/]+")
|
|
|
|
|
# Имя обрабатываемого шаблона
|
|
|
|
|
nameTemplate = ""
|
|
|
|
|
|
|
|
|
|
def __init__(self, objVar):
|
|
|
|
|
# Если не определен словарь функций шаблона
|
|
|
|
|
#print "dict", templateFunction.__dict__.items()
|
|
|
|
|
if not self.templateFunction:
|
|
|
|
|
# префикс функций шаблона
|
|
|
|
|
pref = "func"
|
|
|
|
|
# cписок [(название функции, функция), ...]
|
|
|
|
|
dictFunc = filter(lambda x: x[0].startswith(pref) and\
|
|
|
|
|
hasattr(x[1],"__call__"),
|
|
|
|
|
self.__class__.__dict__.items())
|
|
|
|
|
# удаляем у названия функции префикс и переводим остаток названия
|
|
|
|
|
# в нижний регистр
|
|
|
|
|
dictFunc = map(lambda x: (x[0][len(pref):].lower(), x[1]), dictFunc)
|
|
|
|
|
# Формируем словарь функций шаблона
|
|
|
|
|
self.templateFunction.update(dictFunc)
|
|
|
|
|
# Формируем список функций шаблона
|
|
|
|
|
for nameFunction in self.templateFunction.keys():
|
|
|
|
|
self.namesTemplateFunction.append(nameFunction)
|
|
|
|
|
# Объект хранения переменных
|
|
|
|
|
self.objVar = objVar
|
|
|
|
|
self._reFunc = re.compile(("%s[a-zA-Z0-9_\-\+\(\)\, \*\/\.]+%s")\
|
|
|
|
|
%(self.varStart,self.varEnd),re.M)
|
|
|
|
|
|
|
|
|
|
def equalTerm(self, term, localVars):
|
|
|
|
|
"""Метод для вычисления выражения"""
|
|
|
|
|
terms = self.sNum.findall(term)
|
|
|
|
|
if terms:
|
|
|
|
|
strNumers = []
|
|
|
|
|
for n in terms:
|
|
|
|
|
strNum = n.strip()
|
|
|
|
|
if "*" in strNum or "/" in strNum:
|
|
|
|
|
strNum = self.multAndDiv(strNum,localVars)
|
|
|
|
|
try:
|
|
|
|
|
num = int(strNum)
|
|
|
|
|
except:
|
|
|
|
|
minus = False
|
|
|
|
|
if strNum[:1] == "-":
|
|
|
|
|
minus = True
|
|
|
|
|
strNum = strNum[1:]
|
|
|
|
|
if localVars.has_key(strNum):
|
|
|
|
|
num = localVars[strNum]
|
|
|
|
|
elif self.objVar.exists(strNum):
|
|
|
|
|
try:
|
|
|
|
|
num = int(self.objVar.Get(strNum))
|
|
|
|
|
except:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error var %s not int")%str(strNum)
|
|
|
|
|
exit(1)
|
|
|
|
|
else:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error local var %s not defined")\
|
|
|
|
|
%str(strNum)
|
|
|
|
|
exit(1)
|
|
|
|
|
if minus:
|
|
|
|
|
num =-num
|
|
|
|
|
strNumers.append(num)
|
|
|
|
|
return sum(strNumers)
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s, incorrect data")%str(term)
|
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
|
|
def multAndDiv(self, term, localVars):
|
|
|
|
|
"""Метод для умножения и деления"""
|
|
|
|
|
termTmp = term
|
|
|
|
|
varsLocal = self.sMD.findall(term)
|
|
|
|
|
for var in varsLocal:
|
|
|
|
|
flagVarTxt = True
|
|
|
|
|
try:
|
|
|
|
|
int(var)
|
|
|
|
|
except:
|
|
|
|
|
flagVarTxt = False
|
|
|
|
|
if flagVarTxt:
|
|
|
|
|
continue
|
|
|
|
|
varReplace = str(self.equalTerm(var, localVars))
|
|
|
|
|
termTmp = termTmp.replace(var,varReplace)
|
|
|
|
|
ret = eval(termTmp)
|
|
|
|
|
return ret
|
|
|
|
|
|
|
|
|
|
def funcSum(self, funTxt, resS, localVars, textTemplateTmp):
|
|
|
|
|
"""Функция шаблона, вычисляет функцию sum()"""
|
|
|
|
|
terms = funTxt.replace(" ","").split(",")
|
|
|
|
|
# Название локальной переменной
|
|
|
|
|
nameLocVar = terms[0]
|
|
|
|
|
if not localVars.has_key(nameLocVar):
|
|
|
|
|
localVars[nameLocVar] = 0
|
|
|
|
|
if len(terms) == 2:
|
|
|
|
|
if terms[1].strip():
|
|
|
|
|
localVars[nameLocVar] = self.equalTerm(terms[1], localVars)
|
|
|
|
|
replace = str(localVars[nameLocVar])
|
|
|
|
|
else:
|
|
|
|
|
replace = ""
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
elif len(terms) == 3:
|
|
|
|
|
if terms[1].strip():
|
|
|
|
|
replaceInt = self.equalTerm(terms[1], localVars)
|
|
|
|
|
replace = str(replaceInt)
|
|
|
|
|
else:
|
|
|
|
|
replace = ""
|
|
|
|
|
localVars[nameLocVar] = self.equalTerm(terms[2], localVars)
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
else:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def funcLoad(self, funTxt, resS, localVars, textTemplateTmp):
|
|
|
|
|
"""Функция шаблона load(),
|
|
|
|
|
|
|
|
|
|
если файл существует читает из файла локальную переменную
|
|
|
|
|
если один параметр - выводит значение локальной переменной
|
|
|
|
|
"""
|
|
|
|
|
terms = funTxt.replace(" ","").split(",")
|
|
|
|
|
if not terms[0].strip() or\
|
|
|
|
|
(len(terms)==2 and not terms[1].strip()) or\
|
|
|
|
|
len(terms)>2:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
if len(terms) == 2:
|
|
|
|
|
if not terms[0] in ["ver","num","char","key"]:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("first argument function is not 'ver' or 'num' or\
|
|
|
|
|
'char'")
|
|
|
|
|
exit(1)
|
|
|
|
|
if len(terms) == 1:
|
|
|
|
|
fileName = terms[0].strip()
|
|
|
|
|
if fileName[0] != "/":
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("incorrect path %s")%fileName
|
|
|
|
|
exit(1)
|
|
|
|
|
else:
|
|
|
|
|
fileName = terms[1].strip()
|
|
|
|
|
if fileName[0] != "/":
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("incorrect path %s")%fileName
|
|
|
|
|
exit(1)
|
|
|
|
|
replace = ""
|
|
|
|
|
if os.path.exists(fileName):
|
|
|
|
|
FD = open(fileName)
|
|
|
|
|
replace = FD.read().strip()
|
|
|
|
|
FD.close
|
|
|
|
|
if not replace and len(terms) == 2 and terms[0] in ["ver","num"]:
|
|
|
|
|
replace = "0"
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def getInstallPkgGentoo(self, names = [], versions = []):
|
|
|
|
|
"""Выдает два списка, инсталлированные программы и номера версий"""
|
|
|
|
|
baseDir = "/var/db/pkg"
|
|
|
|
|
pkgs = []
|
|
|
|
|
reVer = re.compile("(?<=\-)\d+\.?\d*\.?\d*")
|
|
|
|
|
def getFilesDir(pkgs, dirname, names):
|
|
|
|
|
for nameFile in names:
|
|
|
|
|
absNameFile = os.path.join(dirname,nameFile)
|
|
|
|
|
if os.path.isdir(absNameFile):
|
|
|
|
|
tail = absNameFile.split(baseDir)
|
|
|
|
|
if len(tail)==2:
|
|
|
|
|
tail = tail[1].split('/')
|
|
|
|
|
if len(tail)==3 and tail[1]!='virtual':
|
|
|
|
|
pkgs.append(tail[2])
|
|
|
|
|
return True
|
|
|
|
|
os.path.walk(baseDir,getFilesDir, pkgs)
|
|
|
|
|
pkgs.sort()
|
|
|
|
|
for pkg in pkgs:
|
|
|
|
|
findVer = reVer.search(pkg)
|
|
|
|
|
if findVer:
|
|
|
|
|
ver = findVer.group()
|
|
|
|
|
versions.append(ver)
|
|
|
|
|
names.append(pkg.split(ver)[0][:-1])
|
|
|
|
|
#return pkgs
|
|
|
|
|
return names, versions
|
|
|
|
|
|
|
|
|
|
def pkg(self, nameProg, names, versions):
|
|
|
|
|
"""Выдает установленные версии по имени программы"""
|
|
|
|
|
# Значение версии из кеша
|
|
|
|
|
if nameProg in self.cacheInstallProg:
|
|
|
|
|
return self.cacheInstallProg[nameProg]
|
|
|
|
|
i = 0
|
|
|
|
|
vers = []
|
|
|
|
|
for name in names:
|
|
|
|
|
if nameProg == name:
|
|
|
|
|
while nameProg == names[i]:
|
|
|
|
|
vers.append(versions[i])
|
|
|
|
|
i += 1
|
|
|
|
|
break
|
|
|
|
|
i += 1
|
|
|
|
|
if vers:
|
|
|
|
|
version = vers[-1]
|
|
|
|
|
# Запись значения версии в кеш
|
|
|
|
|
self.cacheInstallProg[nameProg] = version
|
|
|
|
|
return version
|
|
|
|
|
else:
|
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
|
def funcPkg(self, funTxt, resS, localVars, textTemplateTmp):
|
|
|
|
|
"""Функция шаблона pkg(), выдает номер версии программы"""
|
|
|
|
|
terms = funTxt.replace(" ","")
|
|
|
|
|
# Название программы
|
|
|
|
|
nameProg = terms
|
|
|
|
|
if not self.installProg:
|
|
|
|
|
# Получение всех названий и версий установленных программ
|
|
|
|
|
self.installProg,self.installProgVersions =\
|
|
|
|
|
self.getInstallPkgGentoo(names=self.installProg,
|
|
|
|
|
versions=self.installProgVersions)
|
|
|
|
|
replace = self.pkg(nameProg,self.installProg,self.installProgVersions)
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def funcRnd(self, funTxt, resS, localVars, textTemplateTmp):
|
|
|
|
|
"""Функция шаблона rnd(), выдает строку случайных символов
|
|
|
|
|
|
|
|
|
|
первый аргумент:
|
|
|
|
|
'num' - числа,
|
|
|
|
|
'pas' - цифры и буквы
|
|
|
|
|
второй аргумент:
|
|
|
|
|
количество символов
|
|
|
|
|
"""
|
|
|
|
|
terms = funTxt.replace(" ","").split(",")
|
|
|
|
|
if not terms[0].strip() or\
|
|
|
|
|
(len(terms)==2 and not terms[1].strip()) or\
|
|
|
|
|
len(terms)!=2:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
fArgvNames = ['num','pas']
|
|
|
|
|
if not terms[0] in fArgvNames:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("first argument function is not 'num' or 'pas'")
|
|
|
|
|
exit(1)
|
|
|
|
|
try:
|
|
|
|
|
lenStr = int(terms[1])
|
|
|
|
|
except:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("two argument function is not number")
|
|
|
|
|
exit(1)
|
|
|
|
|
if terms[0] == fArgvNames[0]:
|
|
|
|
|
replace=''.join([random.choice(string.digits)\
|
|
|
|
|
for i in xrange(lenStr)])
|
|
|
|
|
elif terms[0] == fArgvNames[1]:
|
|
|
|
|
replace=''.join([random.choice(string.ascii_letters + \
|
|
|
|
|
string.digits) for i in xrange(lenStr)])
|
|
|
|
|
else:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def funcCase(self, funTxt, resS, localVars, textTemplateTmp):
|
|
|
|
|
"""Функция шаблона case(), выдает переменную в определенном регистре
|
|
|
|
|
|
|
|
|
|
первый аргумент:
|
|
|
|
|
'upper' - верхний регистр,
|
|
|
|
|
'lower' - нижний регистр,
|
|
|
|
|
'capitalize' - первая буква в верхнем регистре
|
|
|
|
|
второй аргумент:
|
|
|
|
|
название переменной
|
|
|
|
|
"""
|
|
|
|
|
terms = funTxt.replace(" ","").split(",")
|
|
|
|
|
if not terms[0].strip() or\
|
|
|
|
|
(len(terms)==2 and not terms[1].strip()) or len(terms)!=2:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
fArgvNames = ['upper','lower','capitalize']
|
|
|
|
|
if not terms[0] in fArgvNames:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("first argument function is not 'upper' or 'lower' or\
|
|
|
|
|
'capitalize'")
|
|
|
|
|
exit(1)
|
|
|
|
|
try:
|
|
|
|
|
strValue = str(self.objVar.Get(terms[1]))
|
|
|
|
|
except:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error var %s not found")%str(terms[1])
|
|
|
|
|
exit(1)
|
|
|
|
|
replace = ""
|
|
|
|
|
strValue = _toUNICODE(strValue)
|
|
|
|
|
if terms[0] == 'upper':
|
|
|
|
|
replace = strValue.upper()
|
|
|
|
|
elif terms[0] == 'lower':
|
|
|
|
|
replace = strValue.lower()
|
|
|
|
|
elif terms[0] == 'capitalize':
|
|
|
|
|
replace = strValue.capitalize()
|
|
|
|
|
if replace:
|
|
|
|
|
replace = replace.encode("UTF-8")
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def applyFuncTemplate(self, textTemplate, nameTemplate):
|
|
|
|
|
"""Применяет функции к тексту шаблона"""
|
|
|
|
|
# Локальные переменные
|
|
|
|
|
localVars = {}
|
|
|
|
|
# Имя обрабатываемого шаблона
|
|
|
|
|
self.nameTemplate = nameTemplate
|
|
|
|
|
# Регулярное выражение для поиска функции в шаблоне
|
|
|
|
|
reFunc = self._reFunc
|
|
|
|
|
resS = reFunc.search(textTemplate)
|
|
|
|
|
textTemplateTmp = textTemplate
|
|
|
|
|
while resS:
|
|
|
|
|
mark = textTemplateTmp[resS.start():resS.end()]
|
|
|
|
|
funTxt = mark[self._deltVarStart:-self._deltVarEnd]
|
|
|
|
|
funcName, spl, funcEnd = funTxt.partition("(")
|
|
|
|
|
if funcName in self.namesTemplateFunction:
|
|
|
|
|
# аргументы функции - '(' аргументы ')'
|
|
|
|
|
funArgv = funcEnd.rpartition(")")[0]
|
|
|
|
|
# вызов функции шаблона
|
|
|
|
|
textTemplateTmp = self.templateFunction[funcName](self, funArgv,
|
|
|
|
|
resS, localVars,
|
|
|
|
|
textTemplateTmp)
|
|
|
|
|
resS = reFunc.search(textTemplateTmp)
|
|
|
|
|
else:
|
|
|
|
|
print _("error in template %s")%self.nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("can not found template function '%s'")%funTxt
|
|
|
|
|
exit(1)
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class template(_file, _terms, xmlShare, _shareTemplate):
|
|
|
|
|
"""Класс для работы с шаблонами
|
|
|
|
|
|
|
|
|
|
На вход 2 параметра: объект хранения переменных, имя сервиса - не
|
|
|
|
@ -2089,12 +2449,7 @@ class template(_file, _terms, xmlShare):
|
|
|
|
|
"""
|
|
|
|
|
# Импортированные классы поддерживаемых форматов шаблонов
|
|
|
|
|
importFormats = {}
|
|
|
|
|
# Имена установленных программ
|
|
|
|
|
installProg = []
|
|
|
|
|
# Версии установленных программ
|
|
|
|
|
installProgVersions = []
|
|
|
|
|
# кеш вызванных значений программа, номер версии
|
|
|
|
|
cacheInstallProg = {}
|
|
|
|
|
|
|
|
|
|
# Название файла шаблона директории
|
|
|
|
|
templDirNameFile = ".calculate_directory"
|
|
|
|
|
|
|
|
|
@ -2112,15 +2467,8 @@ class template(_file, _terms, xmlShare):
|
|
|
|
|
----------------------------------------"
|
|
|
|
|
self._titleBody = ""
|
|
|
|
|
self._titleList = (_("Modified"), _("File of a template"))
|
|
|
|
|
|
|
|
|
|
# Метки
|
|
|
|
|
varStart = "#-"
|
|
|
|
|
varEnd = "-#"
|
|
|
|
|
self._reVar = re.compile(("%s[a-zA-Z0-9_-]+%s")%(varStart,varEnd),re.M)
|
|
|
|
|
self._reFunc = re.compile(("%s[a-zA-Z0-9_\-\+\(\)\, \*\/\.]+%s")\
|
|
|
|
|
%(varStart,varEnd),re.M)
|
|
|
|
|
self._deltVarStart = len(varStart)
|
|
|
|
|
self._deltVarEnd = len(varEnd)
|
|
|
|
|
self._reVar = re.compile(("%s[a-zA-Z0-9_-]+%s")\
|
|
|
|
|
%(self.varStart,self.varEnd),re.M)
|
|
|
|
|
# Условия
|
|
|
|
|
self._reTermBloc = re.compile("#\?(?P<rTerm>[a-zA-Z0-9\-_]+)\
|
|
|
|
|
(?P<func>\([a-zA-Z0-9_\-\+\,\*\/\.]+\))?\
|
|
|
|
@ -2130,11 +2478,15 @@ class template(_file, _terms, xmlShare):
|
|
|
|
|
# Объект с переменными
|
|
|
|
|
self.objVar = objVar
|
|
|
|
|
# Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д
|
|
|
|
|
baseDir = self.objVar.Get("cl_root_path")
|
|
|
|
|
#self._baseDir = os.path.split(baseDir)[0]
|
|
|
|
|
self._baseDir = baseDir
|
|
|
|
|
# По умолчанию /
|
|
|
|
|
self._baseDir = self.objVar.Get("cl_root_path")
|
|
|
|
|
if self._baseDir == "/":
|
|
|
|
|
self._baseDir = ""
|
|
|
|
|
# Объект функций шаблона
|
|
|
|
|
self.functObj = templateFunction(self.objVar)
|
|
|
|
|
# Метод применения функций к шаблонам
|
|
|
|
|
self.applyFuncTemplate = self.functObj.applyFuncTemplate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def __octToInt(self, strOct):
|
|
|
|
|
"""Преобразование восьмеричного в целое (ввод строка, вывод число)"""
|
|
|
|
@ -2312,321 +2664,6 @@ class template(_file, _terms, xmlShare):
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def applyFuncTemplate(self, textTemplate, nameTemplate):
|
|
|
|
|
""" Применяет функции к тексту шаблона
|
|
|
|
|
"""
|
|
|
|
|
def equalTerm(term, sNum, sMD, localVars):
|
|
|
|
|
"""Локальная функция для вычисления выражения"""
|
|
|
|
|
terms = sNum.findall(term)
|
|
|
|
|
if terms:
|
|
|
|
|
strNumers = []
|
|
|
|
|
for n in terms:
|
|
|
|
|
strNum = n.strip()
|
|
|
|
|
if "*" in strNum or "/" in strNum:
|
|
|
|
|
strNum = multAndDiv(strNum,sNum,sMD,localVars)
|
|
|
|
|
try:
|
|
|
|
|
num = int(strNum)
|
|
|
|
|
except:
|
|
|
|
|
minus = False
|
|
|
|
|
if strNum[:1] == "-":
|
|
|
|
|
minus = True
|
|
|
|
|
strNum = strNum[1:]
|
|
|
|
|
if localVars.has_key(strNum):
|
|
|
|
|
num = localVars[strNum]
|
|
|
|
|
elif self.objVar.exists(strNum):
|
|
|
|
|
try:
|
|
|
|
|
num = int(self.objVar.Get(strNum))
|
|
|
|
|
except:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error var %s not int")%str(strNum)
|
|
|
|
|
exit(1)
|
|
|
|
|
else:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error local var %s not defined")\
|
|
|
|
|
%str(strNum)
|
|
|
|
|
exit(1)
|
|
|
|
|
if minus:
|
|
|
|
|
num =-num
|
|
|
|
|
strNumers.append(num)
|
|
|
|
|
return sum(strNumers)
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s, incorrect data")%str(term)
|
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
|
|
def multAndDiv(term,sNum,sMD,localVars):
|
|
|
|
|
"""локальная функция для умножения и деления"""
|
|
|
|
|
termTmp = term
|
|
|
|
|
varsLocal = sMD.findall(term)
|
|
|
|
|
for var in varsLocal:
|
|
|
|
|
flagVarTxt = True
|
|
|
|
|
try:
|
|
|
|
|
int(var)
|
|
|
|
|
except:
|
|
|
|
|
flagVarTxt = False
|
|
|
|
|
if flagVarTxt:
|
|
|
|
|
continue
|
|
|
|
|
varReplace = str(equalTerm(var,sNum,sMD,localVars))
|
|
|
|
|
termTmp = termTmp.replace(var,varReplace)
|
|
|
|
|
ret = eval(termTmp)
|
|
|
|
|
return ret
|
|
|
|
|
|
|
|
|
|
def funcSum(funTxt,resS,localVars,textTemplateTmp):
|
|
|
|
|
"""локальная функция вычисляет первую функцию sum() в шаблоне"""
|
|
|
|
|
terms = funTxt[4:-1].replace(" ","").split(",")
|
|
|
|
|
# Название локальной переменной
|
|
|
|
|
nameLocVar = terms[0]
|
|
|
|
|
if not localVars.has_key(nameLocVar):
|
|
|
|
|
localVars[nameLocVar] = 0
|
|
|
|
|
if len(terms) == 2:
|
|
|
|
|
if terms[1].strip():
|
|
|
|
|
localVars[nameLocVar] = equalTerm(terms[1],sNum,sMD,
|
|
|
|
|
localVars)
|
|
|
|
|
replace = str(localVars[nameLocVar])
|
|
|
|
|
else:
|
|
|
|
|
replace = ""
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
elif len(terms) == 3:
|
|
|
|
|
if terms[1].strip():
|
|
|
|
|
replaceInt = equalTerm(terms[1],sNum,sMD,localVars)
|
|
|
|
|
replace = str(replaceInt)
|
|
|
|
|
else:
|
|
|
|
|
replace = ""
|
|
|
|
|
localVars[nameLocVar] = equalTerm(terms[2],
|
|
|
|
|
sNum,sMD,localVars)
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
else:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def funcLoad(funTxt,resS,textTemplateTmp):
|
|
|
|
|
"""если файл существует читает из файла локальную переменную
|
|
|
|
|
|
|
|
|
|
если один параметр - выводит значение локальной переменной
|
|
|
|
|
"""
|
|
|
|
|
terms = funTxt[5:-1].replace(" ","").split(",")
|
|
|
|
|
if not terms[0].strip() or\
|
|
|
|
|
(len(terms)==2 and not terms[1].strip()) or\
|
|
|
|
|
len(terms)>2:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
if len(terms) == 2:
|
|
|
|
|
if not terms[0] in ["ver","num","char","key"]:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("first argument function is not 'ver' or 'num' or\
|
|
|
|
|
'char'")
|
|
|
|
|
exit(1)
|
|
|
|
|
if len(terms) == 1:
|
|
|
|
|
fileName = terms[0].strip()
|
|
|
|
|
if fileName[0] != "/":
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("incorrect path %s")%fileName
|
|
|
|
|
exit(1)
|
|
|
|
|
else:
|
|
|
|
|
fileName = terms[1].strip()
|
|
|
|
|
if fileName[0] != "/":
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("incorrect path %s")%fileName
|
|
|
|
|
exit(1)
|
|
|
|
|
replace = ""
|
|
|
|
|
if os.path.exists(fileName):
|
|
|
|
|
FD = open(fileName)
|
|
|
|
|
replace = FD.read().strip()
|
|
|
|
|
FD.close
|
|
|
|
|
if not replace and len(terms) == 2 and terms[0] in ["ver","num"]:
|
|
|
|
|
replace = "0"
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def getInstallPkgGentoo(names = [], versions = []):
|
|
|
|
|
"""Выдает два списка, инсталлированные программы и номера версий"""
|
|
|
|
|
baseDir = "/var/db/pkg"
|
|
|
|
|
pkgs = []
|
|
|
|
|
reVer = re.compile("(?<=\-)\d+\.?\d*\.?\d*")
|
|
|
|
|
def getFilesDir(pkgs, dirname, names):
|
|
|
|
|
for nameFile in names:
|
|
|
|
|
absNameFile = os.path.join(dirname,nameFile)
|
|
|
|
|
if os.path.isdir(absNameFile):
|
|
|
|
|
tail = absNameFile.split(baseDir)
|
|
|
|
|
if len(tail)==2:
|
|
|
|
|
tail = tail[1].split('/')
|
|
|
|
|
if len(tail)==3 and tail[1]!='virtual':
|
|
|
|
|
pkgs.append(tail[2])
|
|
|
|
|
return True
|
|
|
|
|
os.path.walk(baseDir,getFilesDir, pkgs)
|
|
|
|
|
pkgs.sort()
|
|
|
|
|
for pkg in pkgs:
|
|
|
|
|
findVer = reVer.search(pkg)
|
|
|
|
|
if findVer:
|
|
|
|
|
ver = findVer.group()
|
|
|
|
|
versions.append(ver)
|
|
|
|
|
names.append(pkg.split(ver)[0][:-1])
|
|
|
|
|
#return pkgs
|
|
|
|
|
return names, versions
|
|
|
|
|
|
|
|
|
|
def pkg(nameProg, names, versions):
|
|
|
|
|
"""Выдает установленные версии по имени программы"""
|
|
|
|
|
# Значение версии из кеша
|
|
|
|
|
if nameProg in self.cacheInstallProg:
|
|
|
|
|
return self.cacheInstallProg[nameProg]
|
|
|
|
|
i = 0
|
|
|
|
|
vers = []
|
|
|
|
|
for name in names:
|
|
|
|
|
if nameProg == name:
|
|
|
|
|
while nameProg == names[i]:
|
|
|
|
|
vers.append(versions[i])
|
|
|
|
|
i += 1
|
|
|
|
|
break
|
|
|
|
|
i += 1
|
|
|
|
|
if vers:
|
|
|
|
|
version = vers[-1]
|
|
|
|
|
# Запись значения версии в кеш
|
|
|
|
|
self.cacheInstallProg[nameProg] = version
|
|
|
|
|
return version
|
|
|
|
|
else:
|
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
|
def funcPkg(funTxt,resS,textTemplateTmp):
|
|
|
|
|
"""локальная функция выдает номер версии программы"""
|
|
|
|
|
terms = funTxt[4:-1].replace(" ","")
|
|
|
|
|
# Название программы
|
|
|
|
|
nameProg = terms
|
|
|
|
|
if not self.installProg:
|
|
|
|
|
# Получение всех названий и версий установленных программ
|
|
|
|
|
self.installProg,self.installProgVersions =\
|
|
|
|
|
getInstallPkgGentoo(names=self.installProg,
|
|
|
|
|
versions=self.installProgVersions)
|
|
|
|
|
replace = pkg(nameProg,self.installProg,self.installProgVersions)
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def funcRnd(funTxt,resS,textTemplateTmp):
|
|
|
|
|
"""локальная функция выдает строку случайных символов
|
|
|
|
|
|
|
|
|
|
первый аргумент:
|
|
|
|
|
'num' - числа,
|
|
|
|
|
'pas' - цифры и буквы
|
|
|
|
|
второй аргумент:
|
|
|
|
|
количество символов
|
|
|
|
|
"""
|
|
|
|
|
terms = funTxt[4:-1].replace(" ","").split(",")
|
|
|
|
|
if not terms[0].strip() or\
|
|
|
|
|
(len(terms)==2 and not terms[1].strip()) or\
|
|
|
|
|
len(terms)!=2:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
fArgvNames = ['num','pas']
|
|
|
|
|
if not terms[0] in fArgvNames:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("first argument function is not 'num' or 'pas'")
|
|
|
|
|
exit(1)
|
|
|
|
|
try:
|
|
|
|
|
lenStr = int(terms[1])
|
|
|
|
|
except:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("two argument function is not number")
|
|
|
|
|
exit(1)
|
|
|
|
|
if terms[0] == fArgvNames[0]:
|
|
|
|
|
replace=''.join([random.choice(string.digits)\
|
|
|
|
|
for i in xrange(lenStr)])
|
|
|
|
|
elif terms[0] == fArgvNames[1]:
|
|
|
|
|
replace=''.join([random.choice(string.ascii_letters + \
|
|
|
|
|
string.digits) for i in xrange(lenStr)])
|
|
|
|
|
else:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def funcCase(funTxt,resS,textTemplateTmp):
|
|
|
|
|
"""локальная функция выдает переменную в определенном регистре
|
|
|
|
|
|
|
|
|
|
первый аргумент:
|
|
|
|
|
'upper' - верхний регистр,
|
|
|
|
|
'lower' - нижний регистр,
|
|
|
|
|
'capitalize' - первая буква в верхнем регистре
|
|
|
|
|
второй аргумент:
|
|
|
|
|
название переменной
|
|
|
|
|
"""
|
|
|
|
|
terms = funTxt[5:-1].replace(" ","").split(",")
|
|
|
|
|
if not terms[0].strip() or\
|
|
|
|
|
(len(terms)==2 and not terms[1].strip()) or len(terms)!=2:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
exit(1)
|
|
|
|
|
fArgvNames = ['upper','lower','capitalize']
|
|
|
|
|
if not terms[0] in fArgvNames:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error template term %s")%str(funTxt)
|
|
|
|
|
print _("first argument function is not 'upper' or 'lower' or\
|
|
|
|
|
'capitalize'")
|
|
|
|
|
exit(1)
|
|
|
|
|
try:
|
|
|
|
|
strValue = str(self.objVar.Get(terms[1]))
|
|
|
|
|
except:
|
|
|
|
|
print _("error in template %s")%nameTemplate
|
|
|
|
|
print _("error var %s not found")%str(terms[1])
|
|
|
|
|
exit(1)
|
|
|
|
|
replace = ""
|
|
|
|
|
strValue = _toUNICODE(strValue)
|
|
|
|
|
if terms[0] == 'upper':
|
|
|
|
|
replace = strValue.upper()
|
|
|
|
|
elif terms[0] == 'lower':
|
|
|
|
|
replace = strValue.lower()
|
|
|
|
|
elif terms[0] == 'capitalize':
|
|
|
|
|
replace = strValue.capitalize()
|
|
|
|
|
if replace:
|
|
|
|
|
replace = replace.encode("UTF-8")
|
|
|
|
|
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
|
|
|
|
|
textTemplateTmp[resS.end():]
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
# Локальные переменные
|
|
|
|
|
localVars = {}
|
|
|
|
|
# Регулярное выражние для сложения
|
|
|
|
|
sNum = re.compile("\-[^\-\+]+|[^\-\+]+")
|
|
|
|
|
# Регулярное выражение для умножениея и деления
|
|
|
|
|
sMD = re.compile("[^\-\+\*\/]+")
|
|
|
|
|
resS = self._reFunc.search(textTemplate)
|
|
|
|
|
textTemplateTmp = textTemplate
|
|
|
|
|
while resS:
|
|
|
|
|
mark = textTemplateTmp[resS.start():resS.end()]
|
|
|
|
|
funTxt = mark[self._deltVarStart:-self._deltVarEnd]
|
|
|
|
|
# Функция sum
|
|
|
|
|
if funTxt[:4] == "sum(":
|
|
|
|
|
textTemplateTmp = funcSum(funTxt,resS,localVars,textTemplateTmp)
|
|
|
|
|
resS = self._reFunc.search(textTemplateTmp)
|
|
|
|
|
# Функция load
|
|
|
|
|
elif funTxt[:5] == "load(":
|
|
|
|
|
textTemplateTmp = funcLoad(funTxt,resS,textTemplateTmp)
|
|
|
|
|
resS = self._reFunc.search(textTemplateTmp)
|
|
|
|
|
elif funTxt[:4] == "pkg(":
|
|
|
|
|
textTemplateTmp = funcPkg(funTxt,resS,textTemplateTmp)
|
|
|
|
|
resS = self._reFunc.search(textTemplateTmp)
|
|
|
|
|
elif funTxt[:4] == "rnd(":
|
|
|
|
|
textTemplateTmp = funcRnd(funTxt,resS,textTemplateTmp)
|
|
|
|
|
resS = self._reFunc.search(textTemplateTmp)
|
|
|
|
|
elif funTxt[:5] == "case(":
|
|
|
|
|
textTemplateTmp = funcCase(funTxt,resS,textTemplateTmp)
|
|
|
|
|
resS = self._reFunc.search(textTemplateTmp)
|
|
|
|
|
else:
|
|
|
|
|
resS = False
|
|
|
|
|
return textTemplateTmp
|
|
|
|
|
|
|
|
|
|
def applyTermsTemplate(self,textTemplate,nameTemplate,nameSystemFile=False):
|
|
|
|
|
""" Применяет условия, к условным блокам текста
|
|
|
|
|
"""
|
|
|
|
@ -2918,6 +2955,11 @@ class template(_file, _terms, xmlShare):
|
|
|
|
|
blockDirs.append(dirTemplate)
|
|
|
|
|
continue
|
|
|
|
|
dirInfoFile = os.path.join(dirTemplate, self.templDirNameFile)
|
|
|
|
|
# Если есть базовая директория наложения шаблонов
|
|
|
|
|
# то изменяем путь к директории в системе
|
|
|
|
|
if self._baseDir:
|
|
|
|
|
pDirs["_real_path"] = os.path.join(self._baseDir,
|
|
|
|
|
pathDir[1:])
|
|
|
|
|
pathDir, propDir, crDirs = self.__getApplyHeadDir(pDirs)
|
|
|
|
|
if not propDir and self.getError():
|
|
|
|
|
self.setError(_("Error in apply template: " ) +\
|
|
|
|
@ -2943,6 +2985,14 @@ class template(_file, _terms, xmlShare):
|
|
|
|
|
titleBaseDir = os.path.split(dirObj.baseDir)[0]
|
|
|
|
|
titlePath = fileTemplate.partition(titleBaseDir)[2]
|
|
|
|
|
templTitle = '"' + titlePath[1:] + '"'
|
|
|
|
|
# Если есть базовая директория наложения шаблонов
|
|
|
|
|
# то изменяем путь к файлу в системе
|
|
|
|
|
# и директорию где этот файл находится
|
|
|
|
|
if self._baseDir:
|
|
|
|
|
pathFile = os.path.join(self._baseDir, pathFile[1:])
|
|
|
|
|
propFile["_real_path"] = pathFile
|
|
|
|
|
propFile["path"] = os.path.join(self._baseDir,
|
|
|
|
|
propFile["path"][1:])
|
|
|
|
|
# Записываем в переменную обрабатываемый файл
|
|
|
|
|
self.objVar.Set("cl_pass_file",pathFile)
|
|
|
|
|
filesApl = self.join(fileTemplate, propFile,
|
|
|
|
|