Added cl_overriding.printERROR() and cl_overriding.printSUCCESS()

develop
Самоукин Алексей 14 years ago
parent b07681e60b
commit de331011c9

@ -255,8 +255,9 @@ class DataVars(object):
setattr(self, nameVar, varobj) setattr(self, nameVar, varobj)
if hasattr(self, nameVar): if hasattr(self, nameVar):
if not force and "r" in getattr(self, nameVar).mode: if not force and "r" in getattr(self, nameVar).mode:
print _("Attempt to rewrite a variable for reading") +": %s"\ cl_overriding.printERROR(\
%nameVar _("Attempt to rewrite a variable for reading") +\
": %s"%nameVar)
return False return False
getattr(self, nameVar).fillStart = False getattr(self, nameVar).fillStart = False
return getattr(self, nameVar).Set(value) return getattr(self, nameVar).Set(value)
@ -328,8 +329,9 @@ class DataVars(object):
if location in ini_dict.keys(): if location in ini_dict.keys():
name_calculate_ini = ini_dict[location] name_calculate_ini = ini_dict[location]
else: else:
print _("Unable to find the alias '%s' of the file path for \ cl_overriding.printERROR(\
storage of variables templates")%location _("Unable to find the alias '%s' of the file path for \
storage of variables templates")%location)
cl_overriding.exit(1) cl_overriding.exit(1)
return name_calculate_ini return name_calculate_ini
@ -342,8 +344,9 @@ storage of variables templates")%location
try: try:
self.Get(vname) self.Get(vname)
except self.DataVarsError, e: except self.DataVarsError, e:
print _("Not found template variable %s")%vname cl_overriding.printERROR(_("Not found template variable %s")\
print e %vname)
cl_overriding.printERROR(e)
cl_overriding.exit(1) cl_overriding.exit(1)
return getattr(self, vname).service.lower() return getattr(self, vname).service.lower()
@ -370,7 +373,7 @@ storage of variables templates")%location
# создаем его если отсутствует # создаем его если отсутствует
os.makedirs(onlydir) os.makedirs(onlydir)
except OSError (nerr,msg): except OSError (nerr,msg):
print nerr, msg cl_overriding.printERROR(str(nerr) + " " + str(msg))
return False return False
config = iniParser(name_calculate_ini) config = iniParser(name_calculate_ini)
# Получаем секцию конфигурационного файла # Получаем секцию конфигурационного файла
@ -459,7 +462,8 @@ storage of variables templates")%location
elif name_var: elif name_var:
section = "main" section = "main"
else: else:
print _("error Datavars.GetIniVar: empty section") cl_overriding.printERROR(\
_("error Datavars.GetIniVar: empty section"))
return False return False
# Значение переменной в env файлах # Значение переменной в env файлах
valueVar = "" valueVar = ""
@ -556,7 +560,7 @@ storage of variables templates")%location
try: try:
value = self.Get(vname) value = self.Get(vname)
except: except:
print _("error var %s not found")%str(vname) cl_overriding.printERROR(_("error var %s not found")%str(vname))
cl_overriding.exit(1) cl_overriding.exit(1)
if value: if value:
return True return True
@ -591,12 +595,7 @@ storage of variables templates")%location
getattr(dataVar,nameVar)['official']): getattr(dataVar,nameVar)['official']):
self.Get(nameVar) self.Get(nameVar)
if type_names: if type_names:
#type_names.sort()
varType =list(getattr(self, nameVar).type) varType =list(getattr(self, nameVar).type)
#varType.sort()
#print type_names
#print varType
#print
if not set(type_names)<=set(varType): if not set(type_names)<=set(varType):
continue continue
ret[nameVar] = getattr(self, nameVar) ret[nameVar] = getattr(self, nameVar)
@ -621,16 +620,16 @@ storage of variables templates")%location
plist.sort() plist.sort()
br = cl_utils.fillstr("-",mlen_name) + " " +\ br = cl_utils.fillstr("-",mlen_name) + " " +\
cl_utils.fillstr("-",mlen_mode) + " " + cl_utils.fillstr("-",10) cl_utils.fillstr("-",mlen_mode) + " " + cl_utils.fillstr("-",10)
print _("The list of variables:") cl_overriding.printSUCCESS(_("The list of variables:"))
print _("var name").center(mlen_name),\ cl_overriding.printSUCCESS(_("var name").center(mlen_name)+ " " +\
_("Mode"),_("Value") _("Mode") + " " +_("Value"))
print br cl_overriding.printSUCCESS(br)
for i in plist: for i in plist:
p_val=var[i].value p_val=var[i].value
if var[i].official: if var[i].official:
continue continue
columnWrite( i, mlen_name, var[i].mode.lower(), mlen_mode, p_val) columnWrite( i, mlen_name, var[i].mode.lower(), mlen_mode, p_val)
print br cl_overriding.printSUCCESS(br)
class glob_attr: class glob_attr:
"""Глобальные аттрибуты для методов заполнения переменных""" """Глобальные аттрибуты для методов заполнения переменных"""

@ -223,7 +223,8 @@ class fillVars(glob_attr):
if envData: if envData:
return map(lambda x: x[1], envData) return map(lambda x: x[1], envData)
else: else:
print _("Error:") + " " +_("Template variable cl_env_data is empty") cl_overriding.printERROR(_("Error:") + " " +\
_("Template variable cl_env_data is empty"))
cl_overriding.exit(1) cl_overriding.exit(1)
def get_cl_env_location(self): def get_cl_env_location(self):
@ -232,15 +233,18 @@ class fillVars(glob_attr):
if envData: if envData:
return map(lambda x: x[0], envData) return map(lambda x: x[0], envData)
else: else:
print _("Error:") + " " +_("Template variable cl_env_data is empty") cl_overriding.printERROR(_("Error:") + " " +\
_("Template variable cl_env_data is empty"))
cl_overriding.exit(1) cl_overriding.exit(1)
def get_os_net_domain(self): def get_os_net_domain(self):
'''Определим домен''' '''Определим домен'''
domain=self._runos("hostname -d 2>&1") domain=self._runos("hostname -d 2>&1")
if not domain: if not domain:
print _("Error:") + " " +_("Not found domain name") cl_overriding.printERROR(_("Error:") + " " +\
print _("Command 'hostname -d' returns an empty value") _("Not found domain name"))
cl_overriding.printERROR(\
_("Command 'hostname -d' returns an empty value"))
cl_overriding.exit(1) cl_overriding.exit(1)
elif re.search("^hostname: ",domain): elif re.search("^hostname: ",domain):
return "local" return "local"

@ -16,6 +16,7 @@
import logging import logging
import logging.handlers import logging.handlers
import cl_overriding
class log: class log:
def __init__(self, programName, def __init__(self, programName,
@ -42,7 +43,8 @@ class log:
maxBytes=self.maxBytes, maxBytes=self.maxBytes,
backupCount=self.backupCount) backupCount=self.backupCount)
except Exception, e: except Exception, e:
print "logging - ",self.programName,"-",e cl_overriding.printERROR("logging - "+" "+self.programName+\
" - "+str(e))
return False return False
handler.setLevel(self.level) handler.setLevel(self.level)
handler.setFormatter(self.formatter) handler.setFormatter(self.formatter)

@ -55,4 +55,23 @@ def __findFileMO(domain, localedir=None, languages=None, all=0):
def exit(codeExit): def exit(codeExit):
"""Метод выхода из программы""" """Метод выхода из программы"""
sys.exit(codeExit) sys.exit(codeExit)
def printERROR(errMessage):
"""Вывод ошибки"""
if errMessage:
if type(errMessage)!=str:
errMessage = str(errMessage)
errMessage += "\n"
sys.stderr.write(errMessage)
sys.stderr.flush()
def printSUCCESS(message,printBR=True):
"""Вывод сообщения о успехе"""
if message:
if type(message)!=str:
message = str(message)
if printBR:
message += "\n"
sys.stdout.write(message)
sys.stdout.flush()

@ -19,6 +19,7 @@ import sys, struct, termios, fcntl
from cl_utils import _toUNICODE from cl_utils import _toUNICODE
class color_print(object): class color_print(object):
_printSysOut = sys.stdout
def getconsolewidth(self): def getconsolewidth(self):
"""Получить ширину текущей консоли""" """Получить ширину текущей консоли"""
@ -87,7 +88,7 @@ class color_print(object):
lst.append(fg) lst.append(fg)
if bg: if bg:
lst.append(bg) lst.append(bg)
sys.stdout.write("\033[%sm%s\033[0m" %(";".join(lst),string)) self._printSysOut.write("\033[%sm%s\033[0m" %(";".join(lst),string))
def redBrightPrint(self, string): def redBrightPrint(self, string):
"""Печатает яркое красное сообщение""" """Печатает яркое красное сообщение"""
@ -113,8 +114,8 @@ class color_print(object):
def defaultPrint(self, string): def defaultPrint(self, string):
sys.stdout.write(string) self._printSysOut.write(string)
sys.stdout.flush() self._printSysOut.flush()
def printLine(self, argL, argR, offsetL=0, printBR=True): def printLine(self, argL, argR, offsetL=0, printBR=True):
"""Печатает справа и слева консоли цветные сообщения""" """Печатает справа и слева консоли цветные сообщения"""
@ -154,10 +155,12 @@ class color_print(object):
else: else:
colorDict[''](rightString) colorDict[''](rightString)
if printBR: if printBR:
print "" self._printSysOut.write("\n")
self._printSysOut.flush()
def printNotOK(self, string, offsetL=0, printBR=True): def printNotOK(self, string, offsetL=0, printBR=True):
"""Вывод на печать в случае сбоя""" """Вывод на печать в случае сбоя"""
self._printSysOut = sys.stderr
self.printLine((('greenBr',' * '), self.printLine((('greenBr',' * '),
('',string), ('',string),
), ),
@ -168,6 +171,7 @@ class color_print(object):
def printOnlyNotOK(self, string, offsetL=0, printBR=True): def printOnlyNotOK(self, string, offsetL=0, printBR=True):
"""Вывод на печать в случае сбоя""" """Вывод на печать в случае сбоя"""
self._printSysOut = sys.stderr
self.printLine((('', string),), self.printLine((('', string),),
(('blueBr','['), (('blueBr','['),
('redBr',' !! '), ('redBr',' !! '),
@ -176,6 +180,7 @@ class color_print(object):
def printOK(self, string, offsetL=0, printBR=True): def printOK(self, string, offsetL=0, printBR=True):
"""Вывод на печать в случае успеха""" """Вывод на печать в случае успеха"""
self._printSysOut = sys.stdout
self.printLine((('greenBr',' * '), self.printLine((('greenBr',' * '),
('',string), ('',string),
), ),
@ -186,6 +191,7 @@ class color_print(object):
def printOnlyOK(self, string, offsetL=0, printBR=True): def printOnlyOK(self, string, offsetL=0, printBR=True):
"""Вывод на печать в случае успеха""" """Вывод на печать в случае успеха"""
self._printSysOut = sys.stdout
self.printLine((('',string),), self.printLine((('',string),),
(('blueBr','['), (('blueBr','['),
('greenBr',' ok '), ('greenBr',' ok '),
@ -194,6 +200,7 @@ class color_print(object):
def printWARNING(self, string, offsetL=0, printBR=True): def printWARNING(self, string, offsetL=0, printBR=True):
"""Вывод на печать предупреждения""" """Вывод на печать предупреждения"""
self._printSysOut = sys.stdout
self.printLine((('yellowBr',' * '), self.printLine((('yellowBr',' * '),
('',string), ('',string),
), ),
@ -202,6 +209,7 @@ class color_print(object):
def printERROR(self, string, offsetL=0, printBR=True): def printERROR(self, string, offsetL=0, printBR=True):
"""Вывод на печать ошибки""" """Вывод на печать ошибки"""
self._printSysOut = sys.stderr
self.printLine((('redBr',' * '), self.printLine((('redBr',' * '),
('',string), ('',string),
), ),
@ -210,6 +218,7 @@ class color_print(object):
def printSUCCESS(self, string, offsetL=0, printBR=True): def printSUCCESS(self, string, offsetL=0, printBR=True):
"""Вывод на печать в случае успеха без [ok] справа""" """Вывод на печать в случае успеха без [ok] справа"""
self._printSysOut = sys.stdout
self.printLine((('greenBr',' * '), self.printLine((('greenBr',' * '),
('',string), ('',string),
), ),

@ -16,6 +16,7 @@
from re import search, compile, S from re import search, compile, S
from cl_utils import _toUNICODE from cl_utils import _toUNICODE
import cl_overriding
def prettyColumnStr(*cols): def prettyColumnStr(*cols):
'''Функция преобразования строк в текстовые колонки. Если указанный текст '''Функция преобразования строк в текстовые колонки. Если указанный текст
@ -202,12 +203,14 @@ def columnWrite(*cols):
while q < len(cols): while q < len(cols):
# если это последний параметр, и для него не указана ширина # если это последний параметр, и для него не указана ширина
if q == len(cols)-1: if q == len(cols)-1:
# выводим его полностью не смотря на ширину окна # выводим его полностью несмотря на ширину окна
print cols[q].encode('utf8'), cl_overriding.printSUCCESS(cols[q].encode('utf8'),printBR=False)
cols[q] = '' cols[q] = ''
else: else:
# вывести часть строки не больше указанной ширины колонки # вывести часть строки не больше указанной ширины колонки
print (cols[q][:cols[q+1]].ljust(cols[q+1])).encode('utf8'), cl_overriding.printSUCCESS(\
(cols[q][:cols[q+1]].ljust(cols[q+1])).encode('utf8'),\
printBR=False)
# остальную часть строки оставить на следующую итерацию # остальную часть строки оставить на следующую итерацию
cols[q] = cols[q][cols[q+1]:] cols[q] = cols[q][cols[q+1]:]
# если от строки что то осаталось # если от строки что то осаталось

@ -197,8 +197,8 @@ class _terms(_error, _shareTermsFunction):
try: try:
valVars = self.objVar.Get(vals[0]) valVars = self.objVar.Get(vals[0])
except self.objVar.DataVarsError, e: except self.objVar.DataVarsError, e:
print textError cl_overriding.printERROR(textError)
print e cl_overriding.printERROR(e)
cl_overriding.exit(1) cl_overriding.exit(1)
# Номера версий для ini # Номера версий для ini
flagNotIniFunct = True flagNotIniFunct = True
@ -1083,12 +1083,10 @@ class xmlDoc:
if not nameField: if not nameField:
return [] return []
parentNode = xmlField.parentNode parentNode = xmlField.parentNode
#print parentNode.toprettyxml()
if parentNode: if parentNode:
fieldsVal = xpath.Evaluate(\ fieldsVal = xpath.Evaluate(\
"child::field[attribute::type='seplist'][child::name='%s'] "\ "child::field[attribute::type='seplist'][child::name='%s'] "\
%(nameField), parentNode) %(nameField), parentNode)
#print nameField
return fieldsVal return fieldsVal
else: else:
return [] return []
@ -1197,13 +1195,8 @@ class xmlDoc:
self.getActionField(node) == "drop"): self.getActionField(node) == "drop"):
self.setActionField(node,"insert") self.setActionField(node,"insert")
self.joinField(xmlOldArea, node) self.joinField(xmlOldArea, node)
#else:
#self.setActionField(node, "append")
#baseBody.appendChild(node)
for node in notSepListField: for node in notSepListField:
if self.getTypeField(node) == "seplist": if self.getTypeField(node) == "seplist":
#if removeNodesDict.has_key(self.getNameField(node)):
#print removeNodesDict[self.getNameField(node)]
self.setActionField(node, "append") self.setActionField(node, "append")
xmlOldArea.appendChild(node) xmlOldArea.appendChild(node)
else: else:
@ -2197,14 +2190,15 @@ class _shareTemplate:
gid = pwdObj.pw_gid gid = pwdObj.pw_gid
homeDir = pwdObj.pw_dir homeDir = pwdObj.pw_dir
except: except:
print _("Can not found user %s")%str(userName) cl_overriding.printERROR(_("Can not found user %s")%str(userName))
cl_overriding.exit(1) cl_overriding.exit(1)
if groupsInfo: if groupsInfo:
import grp import grp
try: try:
groupName = grp.getgrgid(gid).gr_name groupName = grp.getgrgid(gid).gr_name
except: except:
print _("Can not found group id %s")%str(gid) cl_overriding.printERROR(\
_("Can not found group id %s")%str(gid))
cl_overriding.exit(1) cl_overriding.exit(1)
groupsNames = map(lambda x: x.gr_name,\ groupsNames = map(lambda x: x.gr_name,\
filter(lambda x: userName in x.gr_mem, grp.getgrall())) filter(lambda x: userName in x.gr_mem, grp.getgrall()))
@ -2253,7 +2247,6 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
def __init__(self, objVar): def __init__(self, objVar):
# Если не определен словарь функций шаблона # Если не определен словарь функций шаблона
#print "dict", templateFunction.__dict__.items()
if not self.templateFunction: if not self.templateFunction:
# префикс функций шаблона # префикс функций шаблона
pref = "func" pref = "func"
@ -2326,26 +2319,29 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
num = int(localVars[strNum]) num = int(localVars[strNum])
except: except:
self.printErrTemplate() self.printErrTemplate()
print _("error var %s not int")%str(strNum) cl_overriding.printERROR(\
_("error var %s not int")%str(strNum))
cl_overriding.exit(1) cl_overriding.exit(1)
elif self.objVar.exists(strNum): elif self.objVar.exists(strNum):
try: try:
num = int(self.objVar.Get(strNum)) num = int(self.objVar.Get(strNum))
except: except:
self.printErrTemplate() self.printErrTemplate()
print _("error var %s not int")%str(strNum) cl_overriding.printERROR(\
_("error var %s not int")%str(strNum))
cl_overriding.exit(1) cl_overriding.exit(1)
else: else:
self.printErrTemplate() self.printErrTemplate()
print _("error local var %s not defined")\ cl_overriding.printERROR(\
%str(strNum) _("error local var %s not defined")%str(strNum))
cl_overriding.exit(1) cl_overriding.exit(1)
if minus: if minus:
num = -num num = -num
strNumers.append(num) strNumers.append(num)
return sum(strNumers) return sum(strNumers)
self.printErrTemplate() self.printErrTemplate()
print _("error template term %s, incorrect data")%str(term) cl_overriding.printERROR(_("error template term %s, incorrect data")\
%str(term))
cl_overriding.exit(1) cl_overriding.exit(1)
def multAndDiv(self, term, localVars): def multAndDiv(self, term, localVars):
@ -2432,8 +2428,8 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
if len(terms) == 2: if len(terms) == 2:
if not terms[0] in ["ver","num","char","key"]: if not terms[0] in ["ver","num","char","key"]:
self.printErrTemplate() self.printErrTemplate()
print _("first argument function is not 'ver' or 'num' or \ cl_overriding.printERROR(\
'char'") _("first argument function is not 'ver' or 'num' or 'char'"))
cl_overriding.exit(1) cl_overriding.exit(1)
if len(terms) == 1: if len(terms) == 1:
fileName = terms[0].strip() fileName = terms[0].strip()
@ -2554,13 +2550,15 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
fArgvNames = ['num','pas'] fArgvNames = ['num','pas']
if not terms[0] in fArgvNames: if not terms[0] in fArgvNames:
self.printErrTemplate() self.printErrTemplate()
print _("first argument function is not 'num' or 'pas'") cl_overriding.printERROR(\
_("first argument function is not 'num' or 'pas'"))
cl_overriding.exit(1) cl_overriding.exit(1)
try: try:
lenStr = int(terms[1]) lenStr = int(terms[1])
except: except:
self.printErrTemplate() self.printErrTemplate()
print _("two argument function is not number") cl_overriding.printERROR(\
_("two argument function is not number"))
cl_overriding.exit(1) cl_overriding.exit(1)
if terms[0] == fArgvNames[0]: if terms[0] == fArgvNames[0]:
replace=''.join([random.choice(string.digits)\ replace=''.join([random.choice(string.digits)\
@ -2593,14 +2591,15 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
fArgvNames = ['upper','lower','capitalize'] fArgvNames = ['upper','lower','capitalize']
if not terms[0] in fArgvNames: if not terms[0] in fArgvNames:
self.printErrTemplate() self.printErrTemplate()
print _("first argument function is not 'upper' or 'lower' or\ cl_overriding.printERROR(_("first argument function is not 'upper' \
'capitalize'") or 'lower' or 'capitalize'"))
cl_overriding.exit(1) cl_overriding.exit(1)
try: try:
strValue = str(self.objVar.Get(terms[1])) strValue = str(self.objVar.Get(terms[1]))
except: except:
print _("error in template %s")%self.nameTemplate cl_overriding.printERROR(_("error in template %s")\
print _("error var %s not found")%str(terms[1]) %self.nameTemplate)
cl_overriding.printERROR(_("error var %s not found")%str(terms[1]))
cl_overriding.exit(1) cl_overriding.exit(1)
replace = "" replace = ""
strValue = _toUNICODE(strValue) strValue = _toUNICODE(strValue)
@ -2640,13 +2639,15 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
self.stackGlobalVars.append(str(value)) self.stackGlobalVars.append(str(value))
else: else:
self.printErrTemplate() self.printErrTemplate()
print _("error var %s exists")%str(nameLocVar) cl_overriding.printERROR(_("error var %s exists")\
%str(nameLocVar))
cl_overriding.exit(1) cl_overriding.exit(1)
else: else:
# Если переменная не существует # Если переменная не существует
if len(terms) == 1: if len(terms) == 1:
self.printErrTemplate() self.printErrTemplate()
print _("error var %s not exists")%str(nameLocVar) cl_overriding.printERROR(_("error var %s not exists")\
%str(nameLocVar))
cl_overriding.exit(1) cl_overriding.exit(1)
elif len(terms) == 2: elif len(terms) == 2:
value = terms[1].strip() value = terms[1].strip()
@ -2674,7 +2675,8 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
localVars[nameLocVar] = self.stackGlobalVars.pop() localVars[nameLocVar] = self.stackGlobalVars.pop()
else: else:
self.printErrTemplate() self.printErrTemplate()
print _("error, gloval variables stack is empty") cl_overriding.printERROR(\
_("error, gloval variables stack is empty"))
cl_overriding.exit(1) cl_overriding.exit(1)
else: else:
self.printErrTemplate() self.printErrTemplate()
@ -2824,7 +2826,8 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
value = str(self.objVar.Get(nameVar)) value = str(self.objVar.Get(nameVar))
except: except:
self.printErrTemplate() self.printErrTemplate()
print _("not found template variable '%s'")%str(nameVar) cl_overriding.printERROR(_("not found template variable '%s'")\
%str(nameVar))
cl_overriding.exit(1) cl_overriding.exit(1)
replace = value.replace(old,new) replace = value.replace(old,new)
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\ textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
@ -2849,7 +2852,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
self.printErrTemplate() self.printErrTemplate()
errMsg = self.getError() errMsg = self.getError()
if errMsg: if errMsg:
print errMsg cl_overriding.printERROR(errMsg)
cl_overriding.exit(1) cl_overriding.exit(1)
self.valuesVarEnv[nameVar] = value self.valuesVarEnv[nameVar] = value
replace = value replace = value
@ -2938,7 +2941,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
if not funcPkg: if not funcPkg:
funcPkg = os.path.split(os.path.dirname(self.nameTemplate))[1] funcPkg = os.path.split(os.path.dirname(self.nameTemplate))[1]
if not funcPkg: if not funcPkg:
print _("incorrect template path") cl_overriding.printERROR(_("incorrect template path"))
self.printErrTemplate() self.printErrTemplate()
cl_overriding.exit(1) cl_overriding.exit(1)
pkg = self.objVar.Get("cl_belong_pkg") pkg = self.objVar.Get("cl_belong_pkg")
@ -2954,8 +2957,9 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
def printErrTemplate(self): def printErrTemplate(self):
"""Печать ошибки при обработке функций шаблона""" """Печать ошибки при обработке функций шаблона"""
print _("error in template %s")%self.nameTemplate cl_overriding.printERROR(_("error in template %s")%self.nameTemplate)
print _("error template term '%s'")%str(self.functText) cl_overriding.printERROR(_("error template term '%s'")\
%str(self.functText))
def applyFuncTemplate(self, textTemplate, nameTemplate, nameSystemFile): def applyFuncTemplate(self, textTemplate, nameTemplate, nameSystemFile):
"""Применяет функции к тексту шаблона""" """Применяет функции к тексту шаблона"""
@ -2984,8 +2988,9 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
flagIniFunc = True flagIniFunc = True
else: else:
self.printErrTemplate() self.printErrTemplate()
print _("can not found template function '%s'")\ cl_overriding.printERROR(\
%str(self.functText) _("can not found template function '%s'")\
%str(self.functText))
cl_overriding.exit(1) cl_overriding.exit(1)
if flagIniFunc: if flagIniFunc:
@ -3197,8 +3202,8 @@ re.M|re.S)
try: try:
varValue = str(self.objVar.Get(varName)) varValue = str(self.objVar.Get(varName))
except self.objVar.DataVarsError, e: except self.objVar.DataVarsError, e:
print _("error in template %s")%nameTemplate cl_overriding.printERROR(_("error in template %s")%nameTemplate)
print e cl_overriding.printERROR(e)
cl_overriding.exit(1) cl_overriding.exit(1)
textTemplateTmp = textTemplateTmp.replace(mark, varValue) textTemplateTmp = textTemplateTmp.replace(mark, varValue)
resS = self._reVar.search(textTemplateTmp) resS = self._reVar.search(textTemplateTmp)
@ -4080,7 +4085,6 @@ re.M|re.S)
self.textTemplate = self.applyTermsTemplate(self.textTemplate, self.textTemplate = self.applyTermsTemplate(self.textTemplate,
nameFileTemplate, nameFileTemplate,
nameFileConfig) nameFileConfig)
#print "|%s|" %(self.textTemplate)
# Заменяем переменные на их значения # Заменяем переменные на их значения
self.textTemplate = self.applyVarsTemplate(self.textTemplate, self.textTemplate = self.applyVarsTemplate(self.textTemplate,
nameFileTemplate) nameFileTemplate)
@ -4210,7 +4214,6 @@ re.M|re.S)
else: else:
self.textConfig = title + tmpTemplate self.textConfig = title + tmpTemplate
#print self.textConfig
self.saveConfFile() self.saveConfFile()
return filesApply return filesApply
# Cзади # Cзади
@ -4297,11 +4300,7 @@ re.M|re.S)
nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0] nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0]
objTemplOld.setNameBodyNode(nameRootNode) objTemplOld.setNameBodyNode(nameRootNode)
#print "#%s#" %(objTemplOld.docObj.body.toprettyxml())
#print "#%s#" %(objTemplNew.docObj.body.toprettyxml())
objTemplOld.join(objTemplNew) objTemplOld.join(objTemplNew)
#print objTemplOld.doc.toprettyxml()
#print objTemplNew.doc.toprettyxml()
if "xml_" in formatTemplate: if "xml_" in formatTemplate:
if objTemplOld.getError(): if objTemplOld.getError():
self.setError(_("False template") + ": " +\ self.setError(_("False template") + ": " +\

@ -255,7 +255,7 @@ def str2dict(s):
d[i] = replaceSlash(d[i]) d[i] = replaceSlash(d[i])
return d return d
else: else:
print _("wrong dict value: %s"%s) cl_overriding.printERROR(_("wrong dict value: %s"%s))
cl_overriding.exit(1) cl_overriding.exit(1)
def str2list(s): def str2list(s):
@ -281,7 +281,7 @@ def str2list(s):
replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''}) replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''})
return [replaceSlash(i) for i in reList.findall(s)] return [replaceSlash(i) for i in reList.findall(s)]
else: else:
print _("wrong list value: %s"%s) cl_overriding.printERROR(_("wrong list value: %s"%s))
cl_overriding.exit(1) cl_overriding.exit(1)
def list2str(list): def list2str(list):

@ -71,7 +71,6 @@ class apache(bind):
def join(self, apacheObj): def join(self, apacheObj):
"""Объединяем конфигурации""" """Объединяем конфигурации"""
if isinstance(apacheObj, apache): if isinstance(apacheObj, apache):
#print self.docObj.doc.toprettyxml()
self.docObj.joinDoc(apacheObj.doc) self.docObj.joinDoc(apacheObj.doc)
self.postXML() self.postXML()
@ -162,7 +161,6 @@ class apache(bind):
z = 0 z = 0
for k in txtLines: for k in txtLines:
textLine = k + endtxtLines[z] textLine = k + endtxtLines[z]
#print "#"+brBloc[z]+"#"
z += 1 z += 1
findComment = self.reComment.search(textLine) findComment = self.reComment.search(textLine)
if not textLine.strip(): if not textLine.strip():

@ -58,7 +58,6 @@ class dovecot(bind):
def join(self, dovecotObj): def join(self, dovecotObj):
"""Объединяем конфигурации""" """Объединяем конфигурации"""
if isinstance(dovecotObj, dovecot): if isinstance(dovecotObj, dovecot):
#print self.docObj.doc.toprettyxml()
self.docObj.joinDoc(dovecotObj.doc) self.docObj.joinDoc(dovecotObj.doc)
# Для добавления перевода строки перед закрывающим тегом # Для добавления перевода строки перед закрывающим тегом
# конфигурационного файла # конфигурационного файла

@ -127,7 +127,6 @@ class kde(samba):
rootNode.appendChild(fieldNode) rootNode.appendChild(fieldNode)
docObj.clearTmpFields() docObj.clearTmpFields()
z += 1 z += 1
#print docObj.doc.toprettyxml()
return docObj return docObj
def join(self, kdeObj): def join(self, kdeObj):

@ -179,6 +179,5 @@ class ldap(samba):
rootNode.appendChild(fieldNode) rootNode.appendChild(fieldNode)
docObj.clearTmpFields() docObj.clearTmpFields()
z += 1 z += 1
#print docObj.doc.toprettyxml()
return docObj return docObj

@ -217,10 +217,8 @@ class plasma(samba):
#fieldsTmp.append("\n") #fieldsTmp.append("\n")
else: else:
fieldsTmp.append(blocs[1][z]) fieldsTmp.append(blocs[1][z])
#print '"' + blocs[1][z] + '"'
z += 1 z += 1
continue continue
#print '"' + blocs[1][z] + '"'
z += 1 z += 1
slpNamesBlock = reH.split(h) slpNamesBlock = reH.split(h)
# Отступ слева для заголовка # Отступ слева для заголовка
@ -277,8 +275,6 @@ class plasma(samba):
delt = 0 delt = 0
# Добавляем тела # Добавляем тела
for body in blocs[1]: for body in blocs[1]:
#print "#" + body + "#"
#print
if not blocs[0][i]: if not blocs[0][i]:
i += 1 i += 1
delt +=1 delt +=1
@ -295,24 +291,6 @@ class plasma(samba):
#findArea.fields.pop(0) #findArea.fields.pop(0)
findArea.fields.insert(0, body) findArea.fields.insert(0, body)
i += 1 i += 1
#eee = 1
#def prAreas(ar, eee):
#for a in ar:
#if type(a) == types.StringType:
#print 'field', a
#else:
#print "--------------------"
#print "HEADER =", a.header
#print "START =", a.start
#print "FIELDS =", a.fields
#print "LEVEL", eee
#if type(a) != types.StringType:
#if a.fields:
#eee += 1
#prAreas(a.fields, eee)
#prAreas(areas, eee)
return areas return areas
def createCaptionTerm(self, header, start, end, docObj): def createCaptionTerm(self, header, start, end, docObj):
@ -487,7 +465,6 @@ class plasma(samba):
def postXML(self): def postXML(self):
"""Последующая постобработка XML""" """Последующая постобработка XML"""
# Для добавления перевода строки между областями если его нет # Для добавления перевода строки между областями если его нет
#print self.docObj.body.toprettyxml()
def getQuotesArea(xmlArea): def getQuotesArea(xmlArea):
quotes = [] quotes = []
xmlQuotes = xpath.Evaluate('child::caption/quote',xmlArea) xmlQuotes = xpath.Evaluate('child::caption/quote',xmlArea)
@ -502,15 +479,9 @@ class plasma(samba):
return quotes return quotes
xmlAreas = xpath.Evaluate("descendant::area", self.docObj.body) xmlAreas = xpath.Evaluate("descendant::area", self.docObj.body)
#print "-------------------------------------------------------"
#print xmlAreas
#if xmlAreas:
#prXmlArea = xmlAreas[0]
for xmlArea in xmlAreas: for xmlArea in xmlAreas:
# Перед пустой областью и после нее удаляем переводы строк # Перед пустой областью и после нее удаляем переводы строк
if getQuotesArea(xmlArea) == ["",""]: if getQuotesArea(xmlArea) == ["",""]:
#areaTXT = xpath.Evaluate("child::caption/name", xmlArea)[0]
#print "CL_AREA", areaTXT.firstChild
if xmlArea.previousSibling and\ if xmlArea.previousSibling and\
self.docObj.getTypeField(xmlArea.previousSibling) == "br": self.docObj.getTypeField(xmlArea.previousSibling) == "br":
parentNode = xmlArea.previousSibling.parentNode parentNode = xmlArea.previousSibling.parentNode
@ -577,8 +548,6 @@ class plasma(samba):
xmlFields[0]) xmlFields[0])
# Если последним полем BR, удаляем его # Если последним полем BR, удаляем его
if xmlFields and self.docObj.getTypeField(xmlFields[-1]) == "br": if xmlFields and self.docObj.getTypeField(xmlFields[-1]) == "br":
#print "DEL_BR", xmlFields[-1].nextSibling
#and\
if not xmlFields[-1].nextSibling: if not xmlFields[-1].nextSibling:
xmlArea.removeChild(xmlFields[-1]) xmlArea.removeChild(xmlFields[-1])

@ -81,7 +81,6 @@ class postfix(apache):
z = 0 z = 0
for k in txtLines: for k in txtLines:
textLine = k + endtxtLines[z] textLine = k + endtxtLines[z]
#print "#"+brBloc[z]+"#"
z += 1 z += 1
findComment = self.reComment.search(textLine) findComment = self.reComment.search(textLine)
if not textLine.strip(): if not textLine.strip():

@ -111,5 +111,4 @@ class procmail(objShare):
def join(self, procmailObj): def join(self, procmailObj):
"""Объединяем конфигурации""" """Объединяем конфигурации"""
if isinstance(procmailObj, procmail): if isinstance(procmailObj, procmail):
#print self.docObj.doc.toprettyxml()
self.docObj.joinDoc(procmailObj.doc) self.docObj.joinDoc(procmailObj.doc)

@ -44,7 +44,6 @@ class samba(objShare):
def postXML(self): def postXML(self):
"""Последующая постобработка XML""" """Последующая постобработка XML"""
# Для добавления перевода строки между областями если его нет # Для добавления перевода строки между областями если его нет
#print self.docObj.body.toprettyxml()
xmlAreas = xpath.Evaluate("child::area", self.docObj.body) xmlAreas = xpath.Evaluate("child::area", self.docObj.body)
for xmlArea in xmlAreas: for xmlArea in xmlAreas:
if xmlArea.previousSibling and\ if xmlArea.previousSibling and\
@ -271,6 +270,5 @@ class samba(objShare):
rootNode.appendChild(fieldNode) rootNode.appendChild(fieldNode)
docObj.clearTmpFields() docObj.clearTmpFields()
z += 1 z += 1
#print docObj.doc.toprettyxml()
return docObj return docObj

@ -82,6 +82,5 @@ class squid(procmail):
def join(self, squidObj): def join(self, squidObj):
"""Объединяем конфигурации""" """Объединяем конфигурации"""
if isinstance(squidObj, squid): if isinstance(squidObj, squid):
#print squidObj.getConfig()
self.docObj.joinDoc(squidObj.doc) self.docObj.joinDoc(squidObj.doc)

@ -171,9 +171,6 @@ Valid values attribute 'action': \
else: else:
workNode = xmlOldNode workNode = xmlOldNode
oldNodes = xpath.Evaluate(findPath, workNode) oldNodes = xpath.Evaluate(findPath, workNode)
#print findPath
#print workNode
#print "----------------------------"
# Новая нода список # Новая нода список
flagArray = False flagArray = False
if nType == "array": if nType == "array":

@ -28,6 +28,7 @@ import cl_lang
tr = cl_lang.lang() tr = cl_lang.lang()
tr.setLocalDomain('cl_lib') tr.setLocalDomain('cl_lib')
tr.setLanguage(sys.modules[__name__]) tr.setLanguage(sys.modules[__name__])
import cl_overriding
class users(color_print): class users(color_print):
"""Общие методы для серверных программ, """Общие методы для серверных программ,
@ -311,9 +312,10 @@ in a sambaDomainName',
вывод - список доверительных сетей вывод - список доверительных сетей
""" """
def printW(): def printW():
print _("Incorrect string allow networks") cl_overriding.printSUCCESS(_("Incorrect string allow networks"))
print _("Example - allow networks: 10.0.0.0/24 10.0.10.0/24") cl_overriding.printSUCCESS(\
print _("Try again\n") _("Example - allow networks: 10.0.0.0/24 10.0.10.0/24"))
cl_overriding.printSUCCESS(_("Try again\n"))
strNet = rawInput(strPrompt, strNetAllow) strNet = rawInput(strPrompt, strNetAllow)
i = 0 i = 0
while i<3 and not isCorrectStringNet(strNet): while i<3 and not isCorrectStringNet(strNet):

@ -23,6 +23,7 @@ from cl_log import log
import cl_datavars import cl_datavars
import cl_template import cl_template
from cl_print import color_print as old_color_print from cl_print import color_print as old_color_print
from cl_utils import runOsCommand
import cl_lang import cl_lang
# Перевод модуля # Перевод модуля
@ -98,8 +99,8 @@ class DataVarsObject(cl_datavars.DataVars):
'cl_fill_%s' %self.section)) 'cl_fill_%s' %self.section))
self.flIniFile() self.flIniFile()
class updateSystemConfigs(color_print, writeLog): class shareUpdateConfigs(color_print, writeLog):
"""Апдейт системных конфигурационных файлов""" """Общие методы для обновления конфигурационных файлов"""
patternBelongDir = re.compile("belong\(\)") patternBelongDir = re.compile("belong\(\)")
patternBelongName = re.compile("belong\(([^\(\)]+)\)") patternBelongName = re.compile("belong\(([^\(\)]+)\)")
patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*") patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*")
@ -108,7 +109,25 @@ class updateSystemConfigs(color_print, writeLog):
'/var/calculate/remote/templates'] '/var/calculate/remote/templates']
firstEnvFile = "/etc/calculate/calculate2.env" firstEnvFile = "/etc/calculate/calculate2.env"
def _isApplyTemplateDir(self, scanDir, nameProgram, flagDir=False): def isExistsProtectFiles(self, configPath):
"""Есть ли в защищенных директориях конфигурационные файлы"""
if not "CONFIG_PROTECT" in os.environ:
self.printERROR(_("Missing environment variable CONFIG_PROTECT"))
exit(1)
protectPaths = ["/etc"] + map(lambda x: x.strip(),
os.environ["CONFIG_PROTECT"].split(" "))
flagFoundProtect = False
for pPath in protectPaths:
fPath = os.path.join(configPath, pPath[1:])
if os.path.exists(fPath) and os.listdir(fPath):
flagFoundProtect = True
break
if not flagFoundProtect:
return False
return True
def _isApplyTemplateDir(self, scanDir, nameProgram, flagSkipDesktop=True,
flagDir=False):
"""Есть ли шаблоны в директории scanDir для пакета nameProgram """Есть ли шаблоны в директории scanDir для пакета nameProgram
выдает True, False выдает True, False
@ -117,11 +136,11 @@ class updateSystemConfigs(color_print, writeLog):
if flagDir or stat.S_ISDIR(os.stat(scanDir)[stat.ST_MODE]): if flagDir or stat.S_ISDIR(os.stat(scanDir)[stat.ST_MODE]):
for fileOrDir in sorted(os.listdir(scanDir)): for fileOrDir in sorted(os.listdir(scanDir)):
absPath = os.path.join(scanDir,fileOrDir) absPath = os.path.join(scanDir,fileOrDir)
#print absPath
statInfo = os.stat(absPath)[stat.ST_MODE] statInfo = os.stat(absPath)[stat.ST_MODE]
if stat.S_ISREG(statInfo): if stat.S_ISREG(statInfo):
textFile = open(absPath).read() textFile = open(absPath).read()
if "cl_pass_action==desktop" in textFile: if flagSkipDesktop and\
"cl_pass_action==desktop" in textFile:
break break
if self.patternBelongDir.search(textFile): if self.patternBelongDir.search(textFile):
ret = os.path.basename(os.path.dirname(absPath)) ret = os.path.basename(os.path.dirname(absPath))
@ -140,28 +159,85 @@ class updateSystemConfigs(color_print, writeLog):
else: else:
ret = False ret = False
elif stat.S_ISDIR(statInfo): elif stat.S_ISDIR(statInfo):
ret = self._isApplyTemplateDir(absPath, nameProgram, True) ret = self._isApplyTemplateDir(absPath, nameProgram, True,
flagSkipDesktop)
if ret: if ret:
break break
return ret return ret
def isExistsProtectFiles(self, configPath): class updateUserConfigs(shareUpdateConfigs):
"""Есть ли в защищенных директориях конфигурационные файлы""" """Обновление пользовательских конфигурационных файлов"""
if not "CONFIG_PROTECT" in os.environ:
self.printERROR(_("Missing environment variable CONFIG_PROTECT")) def getXUsers(self):
exit(1) """Имена пользователей в X сессии"""
protectPaths = ["/etc"] + map(lambda x: x.strip(), xSession = 0
os.environ["CONFIG_PROTECT"].split(" ")) foundTwoSession = False
flagFoundProtect = False retCode, resWho = runOsCommand("who")
for pPath in protectPaths: xUsers = []
fPath = os.path.join(configPath, pPath[1:]) if retCode==0:
if os.path.exists(fPath) and os.listdir(fPath): if resWho and type(resWho) == list:
flagFoundProtect = True xUsers = map(lambda x: x[0],
break filter(lambda x: x[1].startswith(":"),
if not flagFoundProtect: map(lambda x: filter(lambda y: y,
x.split(" "))[:2] ,resWho)))
else:
self.printERROR(_("Can not execute 'who'"))
return False
return xUsers
def updateConfig(self, nameProgram, configPath):
if not os.path.exists(configPath):
self.printERROR(_("Path '%s' does not exist")%configPath)
return False return False
if not os.path.exists(self.firstEnvFile):
self.printWARNING(_("File '%s' does not exist")%self.firstEnvFile)
return True
if not os.access(self.firstEnvFile, os.R_OK):
self.printWARNING(_("Permission denied: '%s'")%self.firstEnvFile)
return True
sectionsWork = []
for line in open(self.firstEnvFile).readlines():
sRet = self.patternSect.search(line)
if sRet:
sectionsWork.append(sRet.group(1))
sectName = "desktop"
# Если установлен calculate-desktop
if sectName in sectionsWork:
section = ""
for templatePath in self.templatePaths:
fullPath = os.path.join(templatePath,sectName)
if os.path.isdir(fullPath):
if self._isApplyTemplateDir(fullPath, nameProgram,
flagSkipDesktop=False):
section = sectName
break
dictPakkages = {}
if section:
clVars = DataVarsObject(section)
clVars.importDataObject()
clVars.Set("cl_root_path",configPath, True)
clVars.Set("cl_belong_pkg",nameProgram, True)
clTempl = cl_template.template(clVars)
dirsFiles = clTempl.applyTemplates()
if dirsFiles and dirsFiles[1]:
dictPakkages[clVars.Get("cl_name")+"-"+clVars.Get("cl_ver")] =\
sorted(list(set(dirsFiles[1])))
if dictPakkages:
self.logger.info(_("Package %s") %nameProgram)
for calcPkg in dictPakkages:
self.printWARNING(_("Package %s has changed files")%calcPkg+":")
for nameF in dictPakkages[calcPkg]:
nameFile = nameF.partition(configPath)[2]
if nameFile[:1] != "/":
nameFile = "/" + nameFile
self.printWARNING(" "*5 + nameFile)
return True return True
class updateSystemConfigs(shareUpdateConfigs):
"""Обновление системных конфигурационных файлов"""
def updateConfig(self, nameProgram, configPath): def updateConfig(self, nameProgram, configPath):
if not os.path.exists(configPath): if not os.path.exists(configPath):
self.printERROR(_("Path '%s' does not exist")%configPath) self.printERROR(_("Path '%s' does not exist")%configPath)

@ -14,8 +14,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from update_config.cl_update_config import updateSystemConfigs, color_print,\ from update_config.cl_update_config import __app__, __version__,\
__app__, __version__ updateSystemConfigs, updateUserConfigs
from cl_print import color_print as old_color_print from cl_print import color_print as old_color_print
from cl_opt import opt from cl_opt import opt
import sys import sys
@ -59,8 +59,10 @@ class update_cmd:
description=DESCRIPTION, description=DESCRIPTION,
option_list=CMD_OPTIONS + opt.color_control, option_list=CMD_OPTIONS + opt.color_control,
check_values=self.checkOpts) check_values=self.checkOpts)
# Создаем объект логики # Создаем объекты логики
self.logicObj = updateSystemConfigs() self.logicSystemObj = updateSystemConfigs()
self.logicUserObj = updateUserConfigs()
def setPrintNoColor(self, optObj): def setPrintNoColor(self, optObj):
"""Установка печати сообщений без цвета""" """Установка печати сообщений без цвета"""
@ -85,7 +87,7 @@ class update_cmd:
return False return False
if not filter(lambda x: x, [optObj.system, optObj.desktop]): if not filter(lambda x: x, [optObj.system, optObj.desktop]):
errMsg = _("no such options") + ":" + " --system " + _("or") +\ errMsg = _("no such options") + ":" + " --system " + _("or") +\
" --desktop" " --desktop"
self.optobj.error(errMsg) self.optobj.error(errMsg)
return False return False
return optObj, args return optObj, args
@ -93,11 +95,15 @@ class update_cmd:
def updateSystemConfig(self, nameProgram, configPath): def updateSystemConfig(self, nameProgram, configPath):
"""Обновление системных конфигурационных файлов""" """Обновление системных конфигурационных файлов"""
# Проверка есть ли в пакете защищенные конфигурационные файлы # Проверка есть ли в пакете защищенные конфигурационные файлы
if not self.logicObj.isExistsProtectFiles(configPath): if not self.logicSystemObj.isExistsProtectFiles(configPath):
self.logicObj.logger.info(_("Package %s") %nameProgram) self.logicSystemObj.logger.info(_("Package %s") %nameProgram)
self.logicObj.logger.warn(_("Not found protected files")) self.logicSystemObj.logger.warn(_("Not found protected files"))
return True return True
# Обновление конфигурационных файлов # Обновление конфигурационных файлов
if not self.logicObj.updateConfig(nameProgram, configPath): if not self.logicSystemObj.updateConfig(nameProgram, configPath):
return False return False
return True return True
def updateUserConfig(self):
"""Обновление конфигурационных файлов для пользователей в X сеансах"""
print self.logicUserObj.getXUsers()

@ -39,5 +39,6 @@ if __name__ == "__main__":
if not obj.updateSystemConfig(programName, opts.path): if not obj.updateSystemConfig(programName, opts.path):
sys.exit(1) sys.exit(1)
if opts.desktop: if opts.desktop:
pass if not obj.updateUserConfig():
sys.exit(1)
sys.exit(0) sys.exit(0)

Loading…
Cancel
Save