diff --git a/pym/cl_template.py b/pym/cl_template.py index d2d83ed..361c44e 100644 --- a/pym/cl_template.py +++ b/pym/cl_template.py @@ -31,7 +31,7 @@ from cl_ldap import ldapFun # Переопределение exit import cl_overriding -from cl_utils import _error, _toUNICODE, getModeFile, removeDir +from cl_utils import _error, _toUNICODE, getModeFile, removeDir, typeFile import cl_lang tr = cl_lang.lang() @@ -115,7 +115,7 @@ class _terms(_error): break if not flagLog: self.setError("'%s'"%term + " " + _("incorrect")) - self.setError (textError) + self.setError(textError) return False else: # если and @@ -164,17 +164,17 @@ class _terms(_error): self.setError("'%s'"%term + " " + _("incorrect")) self.setError(textError) return False - if "load" == searchFunct.group(1): - if re.search("\(\s*num\s*,",vals[0]): - if valVars: - try: - valVars = int(valVars) - except: - self.setError("'%s'"%term + " " + \ - _("incorrect")) - self.setError (textError) - return False - flagIntTypeVar = True + if "load" == searchFunct.group(1) and\ + re.search("\(\s*num\s*,",vals[0]): + if valVars: + try: + valVars = int(valVars) + except: + self.setError("'%s'"%term + " " + \ + _("incorrect")) + self.setError(textError) + return False + flagIntTypeVar = True else: flagIntTypeVar = False else: @@ -218,12 +218,12 @@ class _terms(_error): # Проверка значения на версию if self._re_not_Version.search(vals[1]): self.setError("'%s'"%term + " " + _("incorrect")) - self.setError (_("Value is not version")) + self.setError(_("Value is not version")) return False # Проверка значения функции на версию if self._re_not_Version.search(valVars): self.setError("'%s'"%term + " " + _("incorrect")) - self.setError (_("Value function is not version")) + self.setError(_("Value function is not version")) return False verFile, verVar = self._convertVers(vals[1],valVars) exec("res=("+"'"+verVar+"'"+sepF+"'"+verFile+"'"+")") @@ -233,7 +233,7 @@ class _terms(_error): listEqual.append(False) flagNotIniFunct = False else: - if flagIntTypeVar == None: + if flagIntTypeVar is None: flagIntTypeVar = True try: valVars = int(valVars) @@ -246,7 +246,7 @@ class _terms(_error): valFile = int(vals[1]) except: self.setError("'%s'"%term +" " +_("incorrect")) - self.setError (textError) + self.setError(textError) return False valVar = valVars exec("res=(%d%s%d)"%(valVar,sepF,valFile)) @@ -273,7 +273,7 @@ class _terms(_error): else: self.setError("'%s'"%term + " "\ + _("incorrect")) - self.setError (textError) + self.setError(textError) return False if listEqual == [] or False in listEqual: return False @@ -1896,44 +1896,6 @@ class _file(_error): # Дескриптор файла конфигурационного файла self.F_CONF = False - - def getFileType(self): - """выдать тип шаблона (text, bin) - """ - nameFile = self.nameFileTemplate - if not nameFile: - print _("ERROR:") - print _("The name of template is not specified, \ -it is impossible to execute the command") + " 'file name_of_template'" - cl_overriding.exit(1) - execStr = "file '%s'"%nameFile - sp = subprocess.Popen(execStr, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - close_fds=True, shell=True) - fout, fin, ferr = (sp.stdout, sp.stdin, sp.stderr) - fin.close() - textLine = fout.readline() - fout.readlines() - fout.close() - retText = "" - # Ошибка - if "`" in textLine: - print _("Can not execute:") + ": %s"%execStr - print textLine - cl_overriding.exit(1) - if textLine: - listTextLine = textLine.split(":") - if len(listTextLine) == 2: - textFormats = ["text", "XML"] - retText = "bin" - fileTypeString = listTextLine[1] - for textFormat in textFormats: - if textFormat in fileTypeString: - retText = "text" - break - ferr.close() - return retText - def saveConfFile(self): """Записать конфигурацию""" if self.F_CONF: @@ -1944,7 +1906,7 @@ it is impossible to execute the command") + " 'file name_of_template'" try: self.F_CONF.write(self.textConfig) except: - self.setError (_("not open file:" ) + self.nameFileConfig) + self.setError(_("not open file:" ) + self.nameFileConfig) return False self.F_CONF.flush() return True @@ -1955,7 +1917,7 @@ it is impossible to execute the command") + " 'file name_of_template'" try: F_TEMPL = open(nameFileTemplate, "r") except: - self.setError (_("not open file:" ) + nameFileTemplate) + self.setError(_("not open file:" ) + nameFileTemplate) return False return F_TEMPL @@ -1983,7 +1945,7 @@ it is impossible to execute the command") + " 'file name_of_template'" os.close(fd) F_CONF = open(nameFileConfig, "r+") except: - self.setError (_("not open file:" ) + nameFileConfig) + self.setError(_("not open file:" ) + nameFileConfig) return False return F_CONF @@ -2751,9 +2713,6 @@ class templateFunction(_error, _shareTemplate): Используеться совместно c funcIni """ localVarsIni = {} - # Выходим если есть предыдущие ошибки - if self.getError(): - return False # получить объект ini файла config = iniParser(iniFileName) # получаем все секции из конфигурационного файла @@ -2992,6 +2951,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.functObj = templateFunction(self.objVar) # Метод применения функций к шаблонам self.applyFuncTemplate = self.functObj.applyFuncTemplate + # Объект для определения типа файла шаблона + self.typeFileObj = typeFile() # Преобразование восьмеричного в целое (ввод строка, вывод число) @@ -3000,14 +2961,26 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): try: exec("res =" + "0" + strOct) except: - self.setError (_("Not valid oct value: ") + str(strOct)) + self.setError(_("Not valid oct value: ") + str(strOct)) return False return res else: - self.setError (_("Empty oct value")) + self.setError(_("Empty oct value")) return False - + def getTemplateType(self): + """выдать тип шаблона (text, bin)""" + isBin = self.typeFileObj.isBinary(self.nameFileTemplate) + typeTemplate = "bin" + if isBin is True: + typeTemplate = "bin" + elif isBin is False: + typeTemplate = "text" + else: + self.setError(_("ERROR") + ": getTemplateType()") + self.setError(isBin) + return False + return typeTemplate def createDir(self, dirName, mode=False, uid=False, gid=False): """Создает директорию""" @@ -3023,7 +2996,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): try: tmpMode,dUid,dGid = getModeFile(prevDir) except OSError: - self.setError (_("Not access dir: " ) + prevDir) + self.setError(_("Not access dir: " ) + prevDir) return False if not mode is False: dMode = mode @@ -3040,7 +3013,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): os.mkdir(nameDir) os.chown(nameDir, dUid, dGid) except: - self.setError (_("Can not create dir: " ) + nameDir) + self.setError(_("Can not create dir: " ) + nameDir) return False try: if dMode: @@ -3050,7 +3023,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): os.chown(dirName, dUid, dGid) createDirs.append(dirName) except: - self.setError (_("Can not create dir: " ) + dirName) + self.setError(_("Can not create dir: " ) + dirName) return False return createDirs @@ -3132,7 +3105,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): else: return True else: - self.setError (_("name template not valid: ")+ str(fileTemplate)) + self.setError(_("name template not valid: ")+ str(fileTemplate)) return False def getTitle(self, comment, commentList): @@ -3211,7 +3184,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): return dictTemplates if not self.objVar.defined("cl_template_path"): - self.setError (_("not defined Var: ") + "cl_template_path") + self.setError(_("not defined Var: ") + "cl_template_path") return False dirsTemplates = self.objVar.Get("cl_template_path") dirsTemplates.sort() @@ -3321,29 +3294,31 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): # Пропуск шаблонов директорий if self.templDirNameFile == os.path.split(path)[1]: return True - if self.getNeedTemplate(path): - if self.getError(): - return False - oldFile = path.partition(prefix)[2] - # файл в системе без условий - oldFile = "/".join(map(lambda x:x.split("?")[0],\ - oldFile.split("/"))) - listTemplTitle = prefix.split("/")[-2:] - templTitle = '"' + "/".join(listTemplTitle) + '"' - # Записываем в переменную обрабатываемый файл - self.objVar.Set("cl_pass_file",oldFile) - # Пишем время модификации *.env файлов - if oldFile.endswith(".env"): - self.timeConfigsIni[oldFile] = float(time.time()) - filesApl = self.join(path, oldFile,(self.programVersion,templTitle), - optFile) - if filesApl: - self.filesApply += filesApl - else: + # Проверка на переменные в названии файла + if not self.getNeedTemplate(path): if self.getError(): - #print self.getError() return False - pathTemplate, nameTemplate = os.path.split(oldFile) + return True + if self.getError(): + return False + nameFileConfig = path.partition(prefix)[2] + # файл в системе без условий + nameFileConfig = "/".join(map(lambda x:x.split("?")[0],\ + nameFileConfig.split("/"))) + listTemplTitle = prefix.split("/")[-2:] + templTitle = '"' + "/".join(listTemplTitle) + '"' + # Записываем в переменную обрабатываемый файл + self.objVar.Set("cl_pass_file",nameFileConfig) + # Пишем время модификации *.env файлов + if nameFileConfig.endswith(".env"): + self.timeConfigsIni[nameFileConfig] = float(time.time()) + filesApl = self.join(path, nameFileConfig,(self.programVersion, + templTitle), optFile) + if self.getError(): + return False + if filesApl: + self.filesApply += filesApl + pathTemplate, nameTemplate = os.path.split(nameFileConfig) return {"path":pathTemplate, "name":nameTemplate} def processingDirectory(self, path, prefix, opt): @@ -3355,25 +3330,12 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): # Применяем шаблон pathDir, objHeadDir = self.__getApplyHeadDir(newDir, dirInfoFile, opt) if objHeadDir: - if isinstance(objHeadDir, dirHeader): - if not objHeadDir.headerCorrect: - self.setError(_("Incorrect template: " ) +\ - dirInfoFile) - self.setError(objHeadDir.errorMessage) - return False - if not objHeadDir.headerTerm: - if objHeadDir.getError(): - self.setError(_("Incorrect template: " ) +\ - dirInfoFile) - return False crDirs = self.createDir(pathDir) if crDirs is False: return False self.createdDirs += crDirs else: if self.getError(): - self.setError(_("Incorrect template: " ) +\ - dirInfoFile) return False # Добавление количества файлов в пропущенной директории if path in self.dictTemplates.keys(): @@ -3420,11 +3382,12 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): templateDirFile) self.setError(objHead.errorMessage) return (applyDir, False) + # Директория с профилями не будет применена if not objHead.headerTerm: if objHead.getError(): self.setError(_("Incorrect template: " ) +\ templateDirFile) - return (applyDir, False) + return (applyDir, False) flagNoSkipDir = True if objHead.typeAppend == "skip": @@ -3434,7 +3397,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if "path" in objHead.params: path = objHead.params['path'] if not path or path and path[0] != "/": - self.setError (_("False value 'path' in template: " ) +\ + self.setError(_("False value 'path' in template: " ) +\ templateDirFile) return (applyDir, False) path = os.path.join(self._baseDir, path[1:]) @@ -3443,7 +3406,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if "name" in objHead.params: nameDir = objHead.params['name'] if "/" in nameDir or nameDir == ".." or nameDir == ".": - self.setError (_("False value 'name' in template: " ) +\ + self.setError(_("False value 'name' in template: " ) +\ templateDirFile) return (applyDir, False) # Новый путь к директории @@ -3477,7 +3440,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): else: os.chmod(applyDir, mode) else: - self.setError (_("False value 'chmod' in template: " ) +\ + self.setError(_("False value 'chmod' in template: " ) +\ templateDirFile) return (applyDir, False) @@ -3491,16 +3454,16 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): try: uid = pwd.getpwnam(strUid)[2] except: - self.setError (_("Not user in this system: ") + strUid) - self.setError (_("False value 'chown' in template: " )+\ + self.setError(_("Not user in this system: ") + strUid) + self.setError(_("False value 'chown' in template: " )+\ templateDirFile) return (applyDir, False) try: import grp gid = grp.getgrnam(strGid)[2] except: - self.setError (_("Not group in this system: ")+strGid) - self.setError (_("False value 'chown' in template: " )+\ + self.setError(_("Not group in this system: ")+strGid) + self.setError(_("False value 'chown' in template: " )+\ templateDirFile) return (applyDir, False) @@ -3510,43 +3473,46 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): else: os.chown(applyDir, uid, gid) else: - self.setError (_("False value 'chown' in template: " ) +\ + self.setError(_("False value 'chown' in template: " ) +\ templateDirFile) return (applyDir, False) else: - self.setError (_("False value 'chown' in template: " ) +\ + self.setError(_("False value 'chown' in template: " ) +\ templateDirFile) return (applyDir, False) return (applyDir, objHead) - def __getApplyHeadTemplate(self, newFile, oldFile, copyFile, optFile): + def __getApplyHeadTemplate(self, nameFileTemplate, nameFileConfig, + templateFileType, optFile): """Применяет заголовок к шаблону (права, владелец, и.т. д)""" def function(text): """Функция обработки функций в заголовке""" - return self.applyFuncTemplate(text, newFile, oldFile) + return self.applyFuncTemplate(text,nameFileTemplate,nameFileConfig) self.closeFiles() # Файлы в системе к которым были применены шаблоны - applyFiles = [oldFile] - if copyFile: - self.nameFileTemplate = os.path.abspath(newFile) + applyFiles = [nameFileConfig] + # В случае бинарного типа файла читаем шаблон + if templateFileType == "bin": + self.nameFileTemplate = os.path.abspath(nameFileTemplate) self.F_TEMPL = self.openTemplFile(self.nameFileTemplate) self.textTemplate = self.F_TEMPL.read() self.closeTemplFile() objHeadNew = fileHeader(self.textTemplate, False, - self.getFileType(),objVar=self.objVar, + templateFileType ,objVar=self.objVar, function=function) if not objHeadNew.headerCorrect: self.setError(_("Incorrect template: " ) +\ - newFile) + nameFileTemplate) self.setError(objHeadNew.errorMessage) return (applyFiles, False) + # файл шаблона не будет применен if not objHeadNew.headerTerm: - if objHeadNew.getError(): - self.setError(_("Incorrect template: " ) +\ - newFile) - return (applyFiles, False) + if objHeadNew.getError(): + self.setError(_("Incorrect template: " ) +\ + nameFileTemplate) + return (applyFiles, False) pathProg = "" # Родительская директория @@ -3556,7 +3522,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if "path" in objHeadNew.params: path = objHeadNew.params['path'] if not path or path and path[0] != "/": - self.setError (_("False value 'path' in template: " ) +\ + self.setError(_("False value 'path' in template: " ) +\ templateDirFile) return (applyDir, False) path = os.path.join(self._baseDir, path[1:]) @@ -3566,12 +3532,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if objHeadNew.params.has_key("name"): nameFile = objHeadNew.params['name'] if "/" in nameFile or nameFile == ".." or nameFile == ".": - self.setError (_("False value 'name' in template: " ) + newFile) + self.setError(_("False value 'name' in template: " ) +\ + nameFileTemplate) return (applyFiles, False) # Новый путь к оригинальному файлу pathOldFile = os.path.join(path,nameFile) else: - pathOldFile = os.path.join(path,os.path.split(oldFile)[1]) + pathOldFile = os.path.join(path,os.path.split(nameFileConfig)[1]) applyFiles = [pathOldFile] # Фильтрация шаблонов по названию файла @@ -3650,11 +3617,16 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if foundTemplateFile: fd = os.open(pathOldFile, os.O_CREAT) os.close(fd) - os.chmod(pathOldFile, fMode) - os.chown(pathOldFile, fUid, fGid) - F_CONFN = open(pathOldFile, "r+") - F_CONFN.write(buff) - F_CONFN.close() + oMode, oUid, oGid = getModeFile(pathOldFile) + # Если права не совпадают, меняем права + if fMode != oMode: + os.chmod(pathOldFile, fMode) + # Если владелец не совпадает, меняем владельца + if (fUid, fGid) != (oUid, oGid): + os.chown(pathOldFile, fUid, fGid) + FD = open(pathOldFile, "r+") + FD.write(buff) + FD.close() # Если символическая ссылка if objHeadNew.params.has_key("symbolic"): @@ -3675,8 +3647,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): os.close(fd) os.chmod(pathOldFile, mode) else: - self.setError (_("False value 'chmod' in template: " ) +\ - newFile) + self.setError(_("False value 'chmod' in template: " ) +\ + nameFileTemplate) return (applyFiles, False) # chown - изменяем владельца и группу if objHeadNew.params.has_key("chown"): @@ -3688,17 +3660,17 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): try: uid = pwd.getpwnam(strUid)[2] except: - self.setError (_("Not user in this system: ") + strUid) - self.setError (_("False value 'chown' in template: " )+\ - newFile) + self.setError(_("Not user in this system: ") + strUid) + self.setError(_("False value 'chown' in template: " )+\ + nameFileTemplate) return (applyFiles, False) try: import grp gid = grp.getgrnam(strGid)[2] except: - self.setError (_("Not group in this system: ")+strGid) - self.setError (_("False value 'chown' in template: " )+\ - newFile) + self.setError(_("Not group in this system: ")+strGid) + self.setError(_("False value 'chown' in template: " )+\ + nameFileTemplate) return (applyFiles, False) if not os.path.exists(pathOldFile): @@ -3706,15 +3678,14 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): os.close(fd) os.chown(pathOldFile, uid, gid) else: - self.setError (_("False value 'chown' in template: " ) +\ - newFile) + self.setError(_("False value 'chown' in template: " ) +\ + nameFileTemplate) return (applyFiles, False) else: - self.setError (_("False value 'chown' in template: " ) +\ - newFile) + self.setError(_("False value 'chown' in template: " ) +\ + nameFileTemplate) return (applyFiles, False) - - self.openFiles(newFile, pathOldFile) + self.openFiles(nameFileTemplate, pathOldFile) if flagSymlink: if os.path.exists(prevOldFile) or os.path.islink(prevOldFile): if os.path.islink(prevOldFile): @@ -3778,34 +3749,41 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): return False return True - def join(self, newFile, oldFile, ListOptTitle, optFile): + def join(self, nameFileTemplate, nameFileConfig, ListOptTitle, optFile): """Объединения шаблона и конф. файла - join(newFile, oldFile, ListOptTitle) - Объединение шаблона newFile и конф. файла oldFile, + join(nameFileTemplate, nameFileConfig, ListOptTitle) + Объединение шаблона nameFileTemplate и конф. файла nameFileConfig, ListOptTitle - список строк которые добавятся в заголовок optFile = опции для шаблона """ # Выполняем условия для блока текста а так-же заменяем переменные - self.nameFileTemplate = os.path.abspath(newFile) + self.nameFileTemplate = os.path.abspath(nameFileTemplate) self.F_TEMPL = self.openTemplFile(self.nameFileTemplate) self.textTemplate = self.F_TEMPL.read() self.closeTemplFile() - copyFile = True - if self.getFileType() != "bin": + # Флаг копирования шаблона в конфигурационный файл + flagCopyTemplate = True + # Тип шаблона бинарный или текстовый + templateFileType = self.getTemplateType() + if templateFileType != "bin": # Вычисляем условные блоки self.textTemplate = self.applyTermsTemplate(self.textTemplate, - newFile, oldFile) + nameFileTemplate, + nameFileConfig) #print "|%s|" %(self.textTemplate) # Заменяем переменные на их значения self.textTemplate = self.applyVarsTemplate(self.textTemplate, - newFile) + nameFileTemplate) # Вычисляем функции self.textTemplate = self.applyFuncTemplate(self.textTemplate, - newFile, oldFile) - copyFile = False - filesApply, objHeadNew = self.__getApplyHeadTemplate(newFile, oldFile, - copyFile, optFile) + nameFileTemplate, + nameFileConfig) + flagCopyTemplate = False + filesApply, objHeadNew = self.__getApplyHeadTemplate(nameFileTemplate, + nameFileConfig, + templateFileType, + optFile) if not objHeadNew: return filesApply # Флаг - кодировка с бинарными примесями у файла шаблона включаем при @@ -3813,19 +3791,19 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): flagNotUtf8New = False # Флаг - кодировка с бинарными примесями у оригинального файла flagNotUtf8Old = False - if not copyFile: + if not flagCopyTemplate: # проверяем кодировку шаблона - if not self.fileIsUtf(newFile): + if not self.fileIsUtf(nameFileTemplate): flagNotUtf8New = True if not (objHeadNew.params.has_key("link") and\ objHeadNew.params.has_key("symbolic")): # проверяем кодировку оригинального файла - if not self.fileIsUtf(oldFile): + if not self.fileIsUtf(nameFileConfig): flagNotUtf8Old = True self.textTemplate = objHeadNew.body #if objHeadNew.fileType != "bin": #self.textTemplate = self.applyTermsTemplate(self.textTemplate, - #newFile) + #nameFileTemplate) #self.textTemplate = self.applyVarsTemplate(self.textTemplate) # Титл конфигурационного файла @@ -3856,15 +3834,15 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): objTemplNew = self.getFormatObj(objHeadNew.fileType, self.textTemplate) if not objTemplNew: - self.setError (\ + self.setError(\ _("Incorrect header parmeter format=%s in template")\ - %formatTemplate + " " + newFile) + %formatTemplate + " " + nameFileTemplate) return False if "xml_" in objHeadNew.fileType: if objTemplNew.getError(): - self.setError (_("False template: " ) + newFile) + self.setError(_("False template: " ) + nameFileTemplate) return False - nameRootNode = oldFile.rpartition("/")[2].split(".")[0] + nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0] objTemplNew.setNameBodyNode(nameRootNode) # Объект Документ docObj = objTemplNew.docObj @@ -3904,8 +3882,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): # Впереди elif objHeadNew.typeAppend == "before": if "xml_" in objHeadNew.fileType: - self.setError (\ - _("False option append=before in template %s") %newFile) + self.setError(\ + _("False option append=before in template %s")\ + %nameFileTemplate) return False if objHeadOld and objHeadOld.body: self.textConfig = objHeadOld.body @@ -3926,8 +3905,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): # Cзади elif objHeadNew.typeAppend == "after": if "xml_" in objHeadNew.fileType: - self.setError (\ - _("False option append=after in template %s") %newFile) + self.setError(\ + _("False option append=after in template %s")\ + %nameFileTemplate) return False if objHeadOld and objHeadOld.body: self.textConfig = objHeadOld.body @@ -3952,15 +3932,15 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): objTemplNew = self.getFormatObj(objHeadNew.fileType, self.textTemplate) if not objTemplNew: - self.setError (\ + self.setError(\ _("Incorrect header parmeter format=%s in template")\ - %formatTemplate + " " + newFile) + %formatTemplate + " " + nameFileTemplate) return False if "xml_" in objHeadNew.fileType: if objTemplNew.getError(): - self.setError (_("False template: " ) + newFile) + self.setError(_("False template: " ) + nameFileTemplate) return False - nameRootNode = oldFile.rpartition("/")[2].split(".")[0] + nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0] objTemplNew.setNameBodyNode(nameRootNode) # Титл для объединения if ListOptTitle: @@ -3994,13 +3974,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): objTemplOld = self.getFormatObj(objHeadNew.fileType, self.textConfig) if not objTemplOld: - self.setError (_("Error in template %s") %oldFile) + self.setError(_("Error in template %s") %nameFileConfig) return False if "xml_" in objHeadNew.fileType: if objTemplOld.getError(): - self.setError (_("False template: " ) + oldFile) + self.setError(_("False template: " ) + nameFileConfig) return False - nameRootNode = oldFile.rpartition("/")[2].split(".")[0] + nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0] objTemplOld.setNameBodyNode(nameRootNode) #print "#%s#" %(objTemplOld.docObj.body.toprettyxml()) @@ -4010,7 +3990,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): #print objTemplNew.doc.toprettyxml() if "xml_" in objHeadNew.fileType: if objTemplOld.getError(): - self.setError (_("False template: " ) + newFile) + self.setError(_("False template: " ) + nameFileTemplate) return False data = \ objTemplOld.getConfig().encode("UTF-8").split("\n") @@ -4033,11 +4013,11 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.saveConfFile() return filesApply else: - self.setError (_("False (type append) template: " ) +\ + self.setError(_("False (type append) template: " ) +\ objHeadNew.typeAppend) return False else: - self.setError (_("Type template not found: ") + newFile) + self.setError(_("Type template not found: ") + nameFileTemplate) return False return filesApply @@ -4126,7 +4106,7 @@ class iniParser(_error, templateFormat): def checkIniFile(self, textIni): """Проверка на правильность формата файла""" - if self.checkIni == None: + if self.checkIni is None: # Ошибка if textIni == False: self.checkIni = False diff --git a/pym/cl_utils.py b/pym/cl_utils.py index 2ead420..1a7156c 100644 --- a/pym/cl_utils.py +++ b/pym/cl_utils.py @@ -22,6 +22,7 @@ import types import subprocess import stat from shutil import copytree, rmtree +import ctypes class _error: # Здесь ошибки, если они есть @@ -40,6 +41,46 @@ class _error: self.error.append(error) return True +class typeFile: + """Получение типа файла""" + __mgc = None + __cookie = None + + def __init__(self): + # Загружаем libmagic.so + self.__mgc = ctypes.cdll.LoadLibrary("libmagic.so") + # Создаем новый cookie (требуется для + # работы с magic-последовательностями) + # 0x10 | 0x400 = MAGIC_MIME (константа + # декларируется в magic.h) + self.__cookie = self.__mgc.magic_open(0x10 | 0x400) + # Загружаем в __cookie + # /etc/file/magic.mime (т.к. указано None) + self.__mgc.magic_load(self.__cookie, None) + + def __del__(self): + """Закрываем __cookie""" + self.__mgc.magic_close(self.__cookie) + + def getMType(self,filename): + """информация о типе файла""" + result = self.__mgc.magic_file(self.__cookie,filename) + # magic_file возвращает указатель const char*, + # mimetype.value - это строка по указателю + mimetype = ctypes.c_char_p(result) + rez = mimetype.value + return rez + + def isBinary(self,filename): + """является ли файл бинарным""" + mime = self.getMType(filename) + if mime.count("`"): + return mime + elif mime.count("binary"): + return True + return False + + def runOsCommand(cmd, inStr=None, ret_first=None, env_dict=None): """Выполняет внешнюю программу diff --git a/pym/format/xml_gconf.py b/pym/format/xml_gconf.py index 59f5994..6e7abf2 100644 --- a/pym/format/xml_gconf.py +++ b/pym/format/xml_gconf.py @@ -16,6 +16,7 @@ import sys import time +import re from xml import xpath import xml.dom.minidom from format.xml_xfce import xml_xfce