From de331011c99d0351446431c61fda8c6718aea5f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B0=D0=BC=D0=BE=D1=83=D0=BA=D0=B8=D0=BD=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Thu, 17 Jun 2010 15:16:42 +0400 Subject: [PATCH] Added cl_overriding.printERROR() and cl_overriding.printSUCCESS() --- pym/cl_datavars.py | 37 ++++--- pym/cl_fill.py | 12 ++- pym/cl_log.py | 4 +- pym/cl_overriding.py | 21 +++- pym/cl_print.py | 17 +++- pym/cl_string.py | 9 +- pym/cl_template.py | 85 ++++++++-------- pym/cl_utils.py | 4 +- pym/format/apache.py | 2 - pym/format/dovecot.py | 1 - pym/format/kde.py | 1 - pym/format/ldap.py | 1 - pym/format/plasma.py | 31 ------ pym/format/postfix.py | 1 - pym/format/procmail.py | 1 - pym/format/samba.py | 2 - pym/format/squid.py | 1 - pym/format/xml_xfce.py | 3 - pym/server/users.py | 8 +- pym/update_config/cl_update_config.py | 116 ++++++++++++++++++---- pym/update_config/cl_update_config_cmd.py | 24 +++-- scripts/cl-update-config | 3 +- 22 files changed, 230 insertions(+), 154 deletions(-) diff --git a/pym/cl_datavars.py b/pym/cl_datavars.py index 346b502..27a35b2 100644 --- a/pym/cl_datavars.py +++ b/pym/cl_datavars.py @@ -255,8 +255,9 @@ class DataVars(object): setattr(self, nameVar, varobj) if hasattr(self, nameVar): if not force and "r" in getattr(self, nameVar).mode: - print _("Attempt to rewrite a variable for reading") +": %s"\ - %nameVar + cl_overriding.printERROR(\ + _("Attempt to rewrite a variable for reading") +\ + ": %s"%nameVar) return False getattr(self, nameVar).fillStart = False return getattr(self, nameVar).Set(value) @@ -328,8 +329,9 @@ class DataVars(object): if location in ini_dict.keys(): name_calculate_ini = ini_dict[location] else: - print _("Unable to find the alias '%s' of the file path for \ -storage of variables templates")%location + cl_overriding.printERROR(\ + _("Unable to find the alias '%s' of the file path for \ +storage of variables templates")%location) cl_overriding.exit(1) return name_calculate_ini @@ -342,8 +344,9 @@ storage of variables templates")%location try: self.Get(vname) except self.DataVarsError, e: - print _("Not found template variable %s")%vname - print e + cl_overriding.printERROR(_("Not found template variable %s")\ + %vname) + cl_overriding.printERROR(e) cl_overriding.exit(1) return getattr(self, vname).service.lower() @@ -370,7 +373,7 @@ storage of variables templates")%location # создаем его если отсутствует os.makedirs(onlydir) except OSError (nerr,msg): - print nerr, msg + cl_overriding.printERROR(str(nerr) + " " + str(msg)) return False config = iniParser(name_calculate_ini) # Получаем секцию конфигурационного файла @@ -459,7 +462,8 @@ storage of variables templates")%location elif name_var: section = "main" else: - print _("error Datavars.GetIniVar: empty section") + cl_overriding.printERROR(\ + _("error Datavars.GetIniVar: empty section")) return False # Значение переменной в env файлах valueVar = "" @@ -556,7 +560,7 @@ storage of variables templates")%location try: value = self.Get(vname) except: - print _("error var %s not found")%str(vname) + cl_overriding.printERROR(_("error var %s not found")%str(vname)) cl_overriding.exit(1) if value: return True @@ -591,12 +595,7 @@ storage of variables templates")%location getattr(dataVar,nameVar)['official']): self.Get(nameVar) if type_names: - #type_names.sort() varType =list(getattr(self, nameVar).type) - #varType.sort() - #print type_names - #print varType - #print if not set(type_names)<=set(varType): continue ret[nameVar] = getattr(self, nameVar) @@ -621,16 +620,16 @@ storage of variables templates")%location plist.sort() br = cl_utils.fillstr("-",mlen_name) + " " +\ cl_utils.fillstr("-",mlen_mode) + " " + cl_utils.fillstr("-",10) - print _("The list of variables:") - print _("var name").center(mlen_name),\ - _("Mode"),_("Value") - print br + cl_overriding.printSUCCESS(_("The list of variables:")) + cl_overriding.printSUCCESS(_("var name").center(mlen_name)+ " " +\ + _("Mode") + " " +_("Value")) + cl_overriding.printSUCCESS(br) for i in plist: p_val=var[i].value if var[i].official: continue columnWrite( i, mlen_name, var[i].mode.lower(), mlen_mode, p_val) - print br + cl_overriding.printSUCCESS(br) class glob_attr: """Глобальные аттрибуты для методов заполнения переменных""" diff --git a/pym/cl_fill.py b/pym/cl_fill.py index 9317c32..d884039 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -223,7 +223,8 @@ class fillVars(glob_attr): if envData: return map(lambda x: x[1], envData) 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) def get_cl_env_location(self): @@ -232,15 +233,18 @@ class fillVars(glob_attr): if envData: return map(lambda x: x[0], envData) 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) def get_os_net_domain(self): '''Определим домен''' domain=self._runos("hostname -d 2>&1") if not domain: - print _("Error:") + " " +_("Not found domain name") - print _("Command 'hostname -d' returns an empty value") + cl_overriding.printERROR(_("Error:") + " " +\ + _("Not found domain name")) + cl_overriding.printERROR(\ + _("Command 'hostname -d' returns an empty value")) cl_overriding.exit(1) elif re.search("^hostname: ",domain): return "local" diff --git a/pym/cl_log.py b/pym/cl_log.py index d931ac8..92c3cf7 100644 --- a/pym/cl_log.py +++ b/pym/cl_log.py @@ -16,6 +16,7 @@ import logging import logging.handlers +import cl_overriding class log: def __init__(self, programName, @@ -42,7 +43,8 @@ class log: maxBytes=self.maxBytes, backupCount=self.backupCount) except Exception, e: - print "logging - ",self.programName,"-",e + cl_overriding.printERROR("logging - "+" "+self.programName+\ + " - "+str(e)) return False handler.setLevel(self.level) handler.setFormatter(self.formatter) diff --git a/pym/cl_overriding.py b/pym/cl_overriding.py index 3400dbe..0ace480 100644 --- a/pym/cl_overriding.py +++ b/pym/cl_overriding.py @@ -55,4 +55,23 @@ def __findFileMO(domain, localedir=None, languages=None, all=0): def exit(codeExit): """Метод выхода из программы""" - sys.exit(codeExit) \ No newline at end of file + 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() \ No newline at end of file diff --git a/pym/cl_print.py b/pym/cl_print.py index e3578b9..2d9ace0 100644 --- a/pym/cl_print.py +++ b/pym/cl_print.py @@ -19,6 +19,7 @@ import sys, struct, termios, fcntl from cl_utils import _toUNICODE class color_print(object): + _printSysOut = sys.stdout def getconsolewidth(self): """Получить ширину текущей консоли""" @@ -87,7 +88,7 @@ class color_print(object): lst.append(fg) if 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): """Печатает яркое красное сообщение""" @@ -113,8 +114,8 @@ class color_print(object): def defaultPrint(self, string): - sys.stdout.write(string) - sys.stdout.flush() + self._printSysOut.write(string) + self._printSysOut.flush() def printLine(self, argL, argR, offsetL=0, printBR=True): """Печатает справа и слева консоли цветные сообщения""" @@ -154,10 +155,12 @@ class color_print(object): else: colorDict[''](rightString) if printBR: - print "" + self._printSysOut.write("\n") + self._printSysOut.flush() def printNotOK(self, string, offsetL=0, printBR=True): """Вывод на печать в случае сбоя""" + self._printSysOut = sys.stderr self.printLine((('greenBr',' * '), ('',string), ), @@ -168,6 +171,7 @@ class color_print(object): def printOnlyNotOK(self, string, offsetL=0, printBR=True): """Вывод на печать в случае сбоя""" + self._printSysOut = sys.stderr self.printLine((('', string),), (('blueBr','['), ('redBr',' !! '), @@ -176,6 +180,7 @@ class color_print(object): def printOK(self, string, offsetL=0, printBR=True): """Вывод на печать в случае успеха""" + self._printSysOut = sys.stdout self.printLine((('greenBr',' * '), ('',string), ), @@ -186,6 +191,7 @@ class color_print(object): def printOnlyOK(self, string, offsetL=0, printBR=True): """Вывод на печать в случае успеха""" + self._printSysOut = sys.stdout self.printLine((('',string),), (('blueBr','['), ('greenBr',' ok '), @@ -194,6 +200,7 @@ class color_print(object): def printWARNING(self, string, offsetL=0, printBR=True): """Вывод на печать предупреждения""" + self._printSysOut = sys.stdout self.printLine((('yellowBr',' * '), ('',string), ), @@ -202,6 +209,7 @@ class color_print(object): def printERROR(self, string, offsetL=0, printBR=True): """Вывод на печать ошибки""" + self._printSysOut = sys.stderr self.printLine((('redBr',' * '), ('',string), ), @@ -210,6 +218,7 @@ class color_print(object): def printSUCCESS(self, string, offsetL=0, printBR=True): """Вывод на печать в случае успеха без [ok] справа""" + self._printSysOut = sys.stdout self.printLine((('greenBr',' * '), ('',string), ), diff --git a/pym/cl_string.py b/pym/cl_string.py index 757cbfb..ba6488a 100644 --- a/pym/cl_string.py +++ b/pym/cl_string.py @@ -16,6 +16,7 @@ from re import search, compile, S from cl_utils import _toUNICODE +import cl_overriding def prettyColumnStr(*cols): '''Функция преобразования строк в текстовые колонки. Если указанный текст @@ -202,12 +203,14 @@ def columnWrite(*cols): while q < len(cols): # если это последний параметр, и для него не указана ширина if q == len(cols)-1: - # выводим его полностью не смотря на ширину окна - print cols[q].encode('utf8'), + # выводим его полностью несмотря на ширину окна + cl_overriding.printSUCCESS(cols[q].encode('utf8'),printBR=False) cols[q] = '' 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]:] # если от строки что то осаталось diff --git a/pym/cl_template.py b/pym/cl_template.py index 34cef5e..66dde02 100644 --- a/pym/cl_template.py +++ b/pym/cl_template.py @@ -197,8 +197,8 @@ class _terms(_error, _shareTermsFunction): try: valVars = self.objVar.Get(vals[0]) except self.objVar.DataVarsError, e: - print textError - print e + cl_overriding.printERROR(textError) + cl_overriding.printERROR(e) cl_overriding.exit(1) # Номера версий для ini flagNotIniFunct = True @@ -1083,12 +1083,10 @@ class xmlDoc: if not nameField: return [] parentNode = xmlField.parentNode - #print parentNode.toprettyxml() if parentNode: fieldsVal = xpath.Evaluate(\ "child::field[attribute::type='seplist'][child::name='%s'] "\ %(nameField), parentNode) - #print nameField return fieldsVal else: return [] @@ -1197,13 +1195,8 @@ class xmlDoc: self.getActionField(node) == "drop"): self.setActionField(node,"insert") self.joinField(xmlOldArea, node) - #else: - #self.setActionField(node, "append") - #baseBody.appendChild(node) for node in notSepListField: if self.getTypeField(node) == "seplist": - #if removeNodesDict.has_key(self.getNameField(node)): - #print removeNodesDict[self.getNameField(node)] self.setActionField(node, "append") xmlOldArea.appendChild(node) else: @@ -2197,14 +2190,15 @@ class _shareTemplate: gid = pwdObj.pw_gid homeDir = pwdObj.pw_dir except: - print _("Can not found user %s")%str(userName) + cl_overriding.printERROR(_("Can not found user %s")%str(userName)) cl_overriding.exit(1) if groupsInfo: import grp try: groupName = grp.getgrgid(gid).gr_name 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) groupsNames = map(lambda x: x.gr_name,\ filter(lambda x: userName in x.gr_mem, grp.getgrall())) @@ -2253,7 +2247,6 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): def __init__(self, objVar): # Если не определен словарь функций шаблона - #print "dict", templateFunction.__dict__.items() if not self.templateFunction: # префикс функций шаблона pref = "func" @@ -2326,26 +2319,29 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): num = int(localVars[strNum]) except: self.printErrTemplate() - print _("error var %s not int")%str(strNum) + cl_overriding.printERROR(\ + _("error var %s not int")%str(strNum)) cl_overriding.exit(1) elif self.objVar.exists(strNum): try: num = int(self.objVar.Get(strNum)) except: self.printErrTemplate() - print _("error var %s not int")%str(strNum) + cl_overriding.printERROR(\ + _("error var %s not int")%str(strNum)) cl_overriding.exit(1) else: self.printErrTemplate() - print _("error local var %s not defined")\ - %str(strNum) + cl_overriding.printERROR(\ + _("error local var %s not defined")%str(strNum)) cl_overriding.exit(1) if minus: num = -num strNumers.append(num) return sum(strNumers) 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) def multAndDiv(self, term, localVars): @@ -2432,8 +2428,8 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): if len(terms) == 2: if not terms[0] in ["ver","num","char","key"]: self.printErrTemplate() - print _("first argument function is not 'ver' or 'num' or \ -'char'") + cl_overriding.printERROR(\ + _("first argument function is not 'ver' or 'num' or 'char'")) cl_overriding.exit(1) if len(terms) == 1: fileName = terms[0].strip() @@ -2554,13 +2550,15 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): fArgvNames = ['num','pas'] if not terms[0] in fArgvNames: 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) try: lenStr = int(terms[1]) except: self.printErrTemplate() - print _("two argument function is not number") + cl_overriding.printERROR(\ + _("two argument function is not number")) cl_overriding.exit(1) if terms[0] == fArgvNames[0]: replace=''.join([random.choice(string.digits)\ @@ -2593,14 +2591,15 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): fArgvNames = ['upper','lower','capitalize'] if not terms[0] in fArgvNames: self.printErrTemplate() - print _("first argument function is not 'upper' or 'lower' or\ -'capitalize'") + cl_overriding.printERROR(_("first argument function is not 'upper' \ +or 'lower' or 'capitalize'")) cl_overriding.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]) + cl_overriding.printERROR(_("error in template %s")\ + %self.nameTemplate) + cl_overriding.printERROR(_("error var %s not found")%str(terms[1])) cl_overriding.exit(1) replace = "" strValue = _toUNICODE(strValue) @@ -2640,13 +2639,15 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): self.stackGlobalVars.append(str(value)) else: self.printErrTemplate() - print _("error var %s exists")%str(nameLocVar) + cl_overriding.printERROR(_("error var %s exists")\ + %str(nameLocVar)) cl_overriding.exit(1) else: # Если переменная не существует if len(terms) == 1: self.printErrTemplate() - print _("error var %s not exists")%str(nameLocVar) + cl_overriding.printERROR(_("error var %s not exists")\ + %str(nameLocVar)) cl_overriding.exit(1) elif len(terms) == 2: value = terms[1].strip() @@ -2674,7 +2675,8 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): localVars[nameLocVar] = self.stackGlobalVars.pop() else: self.printErrTemplate() - print _("error, gloval variables stack is empty") + cl_overriding.printERROR(\ + _("error, gloval variables stack is empty")) cl_overriding.exit(1) else: self.printErrTemplate() @@ -2824,7 +2826,8 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): value = str(self.objVar.Get(nameVar)) except: self.printErrTemplate() - print _("not found template variable '%s'")%str(nameVar) + cl_overriding.printERROR(_("not found template variable '%s'")\ + %str(nameVar)) cl_overriding.exit(1) replace = value.replace(old,new) textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\ @@ -2849,7 +2852,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): self.printErrTemplate() errMsg = self.getError() if errMsg: - print errMsg + cl_overriding.printERROR(errMsg) cl_overriding.exit(1) self.valuesVarEnv[nameVar] = value replace = value @@ -2938,7 +2941,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): if not funcPkg: funcPkg = os.path.split(os.path.dirname(self.nameTemplate))[1] if not funcPkg: - print _("incorrect template path") + cl_overriding.printERROR(_("incorrect template path")) self.printErrTemplate() cl_overriding.exit(1) pkg = self.objVar.Get("cl_belong_pkg") @@ -2954,8 +2957,9 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): def printErrTemplate(self): """Печать ошибки при обработке функций шаблона""" - print _("error in template %s")%self.nameTemplate - print _("error template term '%s'")%str(self.functText) + cl_overriding.printERROR(_("error in template %s")%self.nameTemplate) + cl_overriding.printERROR(_("error template term '%s'")\ + %str(self.functText)) def applyFuncTemplate(self, textTemplate, nameTemplate, nameSystemFile): """Применяет функции к тексту шаблона""" @@ -2984,8 +2988,9 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction): flagIniFunc = True else: self.printErrTemplate() - print _("can not found template function '%s'")\ - %str(self.functText) + cl_overriding.printERROR(\ + _("can not found template function '%s'")\ + %str(self.functText)) cl_overriding.exit(1) if flagIniFunc: @@ -3197,8 +3202,8 @@ re.M|re.S) try: varValue = str(self.objVar.Get(varName)) except self.objVar.DataVarsError, e: - print _("error in template %s")%nameTemplate - print e + cl_overriding.printERROR(_("error in template %s")%nameTemplate) + cl_overriding.printERROR(e) cl_overriding.exit(1) textTemplateTmp = textTemplateTmp.replace(mark, varValue) resS = self._reVar.search(textTemplateTmp) @@ -4080,7 +4085,6 @@ re.M|re.S) self.textTemplate = self.applyTermsTemplate(self.textTemplate, nameFileTemplate, nameFileConfig) - #print "|%s|" %(self.textTemplate) # Заменяем переменные на их значения self.textTemplate = self.applyVarsTemplate(self.textTemplate, nameFileTemplate) @@ -4210,7 +4214,6 @@ re.M|re.S) else: self.textConfig = title + tmpTemplate - #print self.textConfig self.saveConfFile() return filesApply # Cзади @@ -4297,11 +4300,7 @@ re.M|re.S) nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0] objTemplOld.setNameBodyNode(nameRootNode) - #print "#%s#" %(objTemplOld.docObj.body.toprettyxml()) - #print "#%s#" %(objTemplNew.docObj.body.toprettyxml()) objTemplOld.join(objTemplNew) - #print objTemplOld.doc.toprettyxml() - #print objTemplNew.doc.toprettyxml() if "xml_" in formatTemplate: if objTemplOld.getError(): self.setError(_("False template") + ": " +\ diff --git a/pym/cl_utils.py b/pym/cl_utils.py index f00ffb1..ef7ebac 100644 --- a/pym/cl_utils.py +++ b/pym/cl_utils.py @@ -255,7 +255,7 @@ def str2dict(s): d[i] = replaceSlash(d[i]) return d else: - print _("wrong dict value: %s"%s) + cl_overriding.printERROR(_("wrong dict value: %s"%s)) cl_overriding.exit(1) def str2list(s): @@ -281,7 +281,7 @@ def str2list(s): replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''}) return [replaceSlash(i) for i in reList.findall(s)] else: - print _("wrong list value: %s"%s) + cl_overriding.printERROR(_("wrong list value: %s"%s)) cl_overriding.exit(1) def list2str(list): diff --git a/pym/format/apache.py b/pym/format/apache.py index 5d96fef..5da3fad 100644 --- a/pym/format/apache.py +++ b/pym/format/apache.py @@ -71,7 +71,6 @@ class apache(bind): def join(self, apacheObj): """Объединяем конфигурации""" if isinstance(apacheObj, apache): - #print self.docObj.doc.toprettyxml() self.docObj.joinDoc(apacheObj.doc) self.postXML() @@ -162,7 +161,6 @@ class apache(bind): z = 0 for k in txtLines: textLine = k + endtxtLines[z] - #print "#"+brBloc[z]+"#" z += 1 findComment = self.reComment.search(textLine) if not textLine.strip(): diff --git a/pym/format/dovecot.py b/pym/format/dovecot.py index c6832cb..5958482 100644 --- a/pym/format/dovecot.py +++ b/pym/format/dovecot.py @@ -58,7 +58,6 @@ class dovecot(bind): def join(self, dovecotObj): """Объединяем конфигурации""" if isinstance(dovecotObj, dovecot): - #print self.docObj.doc.toprettyxml() self.docObj.joinDoc(dovecotObj.doc) # Для добавления перевода строки перед закрывающим тегом # конфигурационного файла diff --git a/pym/format/kde.py b/pym/format/kde.py index 3e3b0c6..a979d08 100644 --- a/pym/format/kde.py +++ b/pym/format/kde.py @@ -127,7 +127,6 @@ class kde(samba): rootNode.appendChild(fieldNode) docObj.clearTmpFields() z += 1 - #print docObj.doc.toprettyxml() return docObj def join(self, kdeObj): diff --git a/pym/format/ldap.py b/pym/format/ldap.py index 1f9efc6..750ed08 100644 --- a/pym/format/ldap.py +++ b/pym/format/ldap.py @@ -179,6 +179,5 @@ class ldap(samba): rootNode.appendChild(fieldNode) docObj.clearTmpFields() z += 1 - #print docObj.doc.toprettyxml() return docObj diff --git a/pym/format/plasma.py b/pym/format/plasma.py index 2522f42..927efda 100644 --- a/pym/format/plasma.py +++ b/pym/format/plasma.py @@ -217,10 +217,8 @@ class plasma(samba): #fieldsTmp.append("\n") else: fieldsTmp.append(blocs[1][z]) - #print '"' + blocs[1][z] + '"' z += 1 continue - #print '"' + blocs[1][z] + '"' z += 1 slpNamesBlock = reH.split(h) # Отступ слева для заголовка @@ -277,8 +275,6 @@ class plasma(samba): delt = 0 # Добавляем тела for body in blocs[1]: - #print "#" + body + "#" - #print if not blocs[0][i]: i += 1 delt +=1 @@ -295,24 +291,6 @@ class plasma(samba): #findArea.fields.pop(0) findArea.fields.insert(0, body) 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 def createCaptionTerm(self, header, start, end, docObj): @@ -487,7 +465,6 @@ class plasma(samba): def postXML(self): """Последующая постобработка XML""" # Для добавления перевода строки между областями если его нет - #print self.docObj.body.toprettyxml() def getQuotesArea(xmlArea): quotes = [] xmlQuotes = xpath.Evaluate('child::caption/quote',xmlArea) @@ -502,15 +479,9 @@ class plasma(samba): return quotes xmlAreas = xpath.Evaluate("descendant::area", self.docObj.body) - #print "-------------------------------------------------------" - #print xmlAreas - #if xmlAreas: - #prXmlArea = xmlAreas[0] for xmlArea in xmlAreas: # Перед пустой областью и после нее удаляем переводы строк if getQuotesArea(xmlArea) == ["",""]: - #areaTXT = xpath.Evaluate("child::caption/name", xmlArea)[0] - #print "CL_AREA", areaTXT.firstChild if xmlArea.previousSibling and\ self.docObj.getTypeField(xmlArea.previousSibling) == "br": parentNode = xmlArea.previousSibling.parentNode @@ -577,8 +548,6 @@ class plasma(samba): xmlFields[0]) # Если последним полем BR, удаляем его if xmlFields and self.docObj.getTypeField(xmlFields[-1]) == "br": - #print "DEL_BR", xmlFields[-1].nextSibling - #and\ if not xmlFields[-1].nextSibling: xmlArea.removeChild(xmlFields[-1]) diff --git a/pym/format/postfix.py b/pym/format/postfix.py index c4a9c75..670d98a 100644 --- a/pym/format/postfix.py +++ b/pym/format/postfix.py @@ -81,7 +81,6 @@ class postfix(apache): z = 0 for k in txtLines: textLine = k + endtxtLines[z] - #print "#"+brBloc[z]+"#" z += 1 findComment = self.reComment.search(textLine) if not textLine.strip(): diff --git a/pym/format/procmail.py b/pym/format/procmail.py index 50fa05f..303c5fe 100644 --- a/pym/format/procmail.py +++ b/pym/format/procmail.py @@ -111,5 +111,4 @@ class procmail(objShare): def join(self, procmailObj): """Объединяем конфигурации""" if isinstance(procmailObj, procmail): - #print self.docObj.doc.toprettyxml() self.docObj.joinDoc(procmailObj.doc) diff --git a/pym/format/samba.py b/pym/format/samba.py index f2d963a..88ea04a 100644 --- a/pym/format/samba.py +++ b/pym/format/samba.py @@ -44,7 +44,6 @@ class samba(objShare): def postXML(self): """Последующая постобработка XML""" # Для добавления перевода строки между областями если его нет - #print self.docObj.body.toprettyxml() xmlAreas = xpath.Evaluate("child::area", self.docObj.body) for xmlArea in xmlAreas: if xmlArea.previousSibling and\ @@ -271,6 +270,5 @@ class samba(objShare): rootNode.appendChild(fieldNode) docObj.clearTmpFields() z += 1 - #print docObj.doc.toprettyxml() return docObj diff --git a/pym/format/squid.py b/pym/format/squid.py index 06d91f9..1461046 100644 --- a/pym/format/squid.py +++ b/pym/format/squid.py @@ -82,6 +82,5 @@ class squid(procmail): def join(self, squidObj): """Объединяем конфигурации""" if isinstance(squidObj, squid): - #print squidObj.getConfig() self.docObj.joinDoc(squidObj.doc) diff --git a/pym/format/xml_xfce.py b/pym/format/xml_xfce.py index 5e39d59..9817f0a 100644 --- a/pym/format/xml_xfce.py +++ b/pym/format/xml_xfce.py @@ -171,9 +171,6 @@ Valid values attribute 'action': \ else: workNode = xmlOldNode oldNodes = xpath.Evaluate(findPath, workNode) - #print findPath - #print workNode - #print "----------------------------" # Новая нода список flagArray = False if nType == "array": diff --git a/pym/server/users.py b/pym/server/users.py index a7178f7..bc4487c 100644 --- a/pym/server/users.py +++ b/pym/server/users.py @@ -28,6 +28,7 @@ import cl_lang tr = cl_lang.lang() tr.setLocalDomain('cl_lib') tr.setLanguage(sys.modules[__name__]) +import cl_overriding class users(color_print): """Общие методы для серверных программ, @@ -311,9 +312,10 @@ in a sambaDomainName', вывод - список доверительных сетей """ def printW(): - print _("Incorrect string allow networks") - print _("Example - allow networks: 10.0.0.0/24 10.0.10.0/24") - print _("Try again\n") + cl_overriding.printSUCCESS(_("Incorrect string allow networks")) + cl_overriding.printSUCCESS(\ + _("Example - allow networks: 10.0.0.0/24 10.0.10.0/24")) + cl_overriding.printSUCCESS(_("Try again\n")) strNet = rawInput(strPrompt, strNetAllow) i = 0 while i<3 and not isCorrectStringNet(strNet): diff --git a/pym/update_config/cl_update_config.py b/pym/update_config/cl_update_config.py index b2b1bca..edabfd9 100644 --- a/pym/update_config/cl_update_config.py +++ b/pym/update_config/cl_update_config.py @@ -23,6 +23,7 @@ from cl_log import log import cl_datavars import cl_template from cl_print import color_print as old_color_print +from cl_utils import runOsCommand import cl_lang # Перевод модуля @@ -98,8 +99,8 @@ class DataVarsObject(cl_datavars.DataVars): 'cl_fill_%s' %self.section)) self.flIniFile() -class updateSystemConfigs(color_print, writeLog): - """Апдейт системных конфигурационных файлов""" +class shareUpdateConfigs(color_print, writeLog): + """Общие методы для обновления конфигурационных файлов""" patternBelongDir = re.compile("belong\(\)") patternBelongName = re.compile("belong\(([^\(\)]+)\)") patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*") @@ -108,7 +109,25 @@ class updateSystemConfigs(color_print, writeLog): '/var/calculate/remote/templates'] 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 выдает True, False @@ -117,11 +136,11 @@ class updateSystemConfigs(color_print, writeLog): if flagDir or stat.S_ISDIR(os.stat(scanDir)[stat.ST_MODE]): for fileOrDir in sorted(os.listdir(scanDir)): absPath = os.path.join(scanDir,fileOrDir) - #print absPath statInfo = os.stat(absPath)[stat.ST_MODE] if stat.S_ISREG(statInfo): textFile = open(absPath).read() - if "cl_pass_action==desktop" in textFile: + if flagSkipDesktop and\ + "cl_pass_action==desktop" in textFile: break if self.patternBelongDir.search(textFile): ret = os.path.basename(os.path.dirname(absPath)) @@ -140,28 +159,85 @@ class updateSystemConfigs(color_print, writeLog): else: ret = False elif stat.S_ISDIR(statInfo): - ret = self._isApplyTemplateDir(absPath, nameProgram, True) + ret = self._isApplyTemplateDir(absPath, nameProgram, True, + flagSkipDesktop) if ret: break return ret - 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: +class updateUserConfigs(shareUpdateConfigs): + """Обновление пользовательских конфигурационных файлов""" + + def getXUsers(self): + """Имена пользователей в X сессии""" + xSession = 0 + foundTwoSession = False + retCode, resWho = runOsCommand("who") + xUsers = [] + if retCode==0: + if resWho and type(resWho) == list: + xUsers = map(lambda x: x[0], + filter(lambda x: x[1].startswith(":"), + 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 + 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 + + +class updateSystemConfigs(shareUpdateConfigs): + """Обновление системных конфигурационных файлов""" + def updateConfig(self, nameProgram, configPath): if not os.path.exists(configPath): self.printERROR(_("Path '%s' does not exist")%configPath) diff --git a/pym/update_config/cl_update_config_cmd.py b/pym/update_config/cl_update_config_cmd.py index da53d43..b74eb3e 100644 --- a/pym/update_config/cl_update_config_cmd.py +++ b/pym/update_config/cl_update_config_cmd.py @@ -14,8 +14,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from update_config.cl_update_config import updateSystemConfigs, color_print,\ - __app__, __version__ +from update_config.cl_update_config import __app__, __version__,\ + updateSystemConfigs, updateUserConfigs from cl_print import color_print as old_color_print from cl_opt import opt import sys @@ -59,8 +59,10 @@ class update_cmd: description=DESCRIPTION, option_list=CMD_OPTIONS + opt.color_control, check_values=self.checkOpts) - # Создаем объект логики - self.logicObj = updateSystemConfigs() + # Создаем объекты логики + self.logicSystemObj = updateSystemConfigs() + self.logicUserObj = updateUserConfigs() + def setPrintNoColor(self, optObj): """Установка печати сообщений без цвета""" @@ -85,7 +87,7 @@ class update_cmd: return False if not filter(lambda x: x, [optObj.system, optObj.desktop]): errMsg = _("no such options") + ":" + " --system " + _("or") +\ - " --desktop" + " --desktop" self.optobj.error(errMsg) return False return optObj, args @@ -93,11 +95,15 @@ class update_cmd: def updateSystemConfig(self, nameProgram, configPath): """Обновление системных конфигурационных файлов""" # Проверка есть ли в пакете защищенные конфигурационные файлы - if not self.logicObj.isExistsProtectFiles(configPath): - self.logicObj.logger.info(_("Package %s") %nameProgram) - self.logicObj.logger.warn(_("Not found protected files")) + if not self.logicSystemObj.isExistsProtectFiles(configPath): + self.logicSystemObj.logger.info(_("Package %s") %nameProgram) + self.logicSystemObj.logger.warn(_("Not found protected files")) return True # Обновление конфигурационных файлов - if not self.logicObj.updateConfig(nameProgram, configPath): + if not self.logicSystemObj.updateConfig(nameProgram, configPath): return False return True + + def updateUserConfig(self): + """Обновление конфигурационных файлов для пользователей в X сеансах""" + print self.logicUserObj.getXUsers() \ No newline at end of file diff --git a/scripts/cl-update-config b/scripts/cl-update-config index a377c3b..d253512 100644 --- a/scripts/cl-update-config +++ b/scripts/cl-update-config @@ -39,5 +39,6 @@ if __name__ == "__main__": if not obj.updateSystemConfig(programName, opts.path): sys.exit(1) if opts.desktop: - pass + if not obj.updateUserConfig(): + sys.exit(1) sys.exit(0)