From 9471e1a85967100fbee6b0799fc22e13c374a5d1 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, 29 Apr 2010 18:03:13 +0400 Subject: [PATCH] Reorganization --- README | 1 + pym/cl_template.py | 338 ++++++++++++++++++++------------------------- pym/cl_utils.py | 77 +++++++++-- 3 files changed, 218 insertions(+), 198 deletions(-) diff --git a/README b/README index c65a3de..ea663fb 100644 --- a/README +++ b/README @@ -8,6 +8,7 @@ calculate-lib needs the following library version installed, in order to run: python-ldap >= 2.0.0 pyxml >= 0.8 py-smbpasswd >= 1.0 + file >= 4.26 To install calculate-lib , just execute the install script 'setup.py'. Example: diff --git a/pym/cl_template.py b/pym/cl_template.py index 361c44e..78c2398 100644 --- a/pym/cl_template.py +++ b/pym/cl_template.py @@ -31,7 +31,8 @@ from cl_ldap import ldapFun # Переопределение exit import cl_overriding -from cl_utils import _error, _toUNICODE, getModeFile, removeDir, typeFile +from cl_utils import _error, _toUNICODE, getModeFile, removeDir, typeFile,\ +scanDirectory import cl_lang tr = cl_lang.lang() @@ -289,8 +290,6 @@ class fileHeader(_terms): allowParam = ["format", "format_conf", "comment", "append", "force", "link", "mirror", "symbolic", "chmod", "chown", "name", "path"] - # Корректность заголовка - headerCorrect = True # Тип шаблона fileType = "" @@ -310,11 +309,9 @@ class fileHeader(_terms): listParNotVal = ("symbolic", "force", "mirror") # Результат вычисления условия в заголовке headerTerm = True - # Сообщение о ошибке - errorMessage = "" - def __init__(self, text, comment=False, fileType=False, objVar=False, - function=False): + def __init__(self, templateName, text, comment=False, fileType=False, + objVar=False, function=False): self.body = text # Объект с переменными self.objVar=objVar @@ -388,14 +385,17 @@ class fileHeader(_terms): for term in self.terms: if term in i: foundTerm = True + errorMsg = _("Incorrect template") +\ + ": "+ templateName +"\n"+\ + _("header template not valid")+\ + ": "+ i if function: - rezTerm = self._equalTerm(i,\ - _("header template not valid: ") + \ - i,function) + rezTerm = self._equalTerm(i, + errorMsg, + function) else: - rezTerm = self._equalTerm(i,\ - _("header template not valid: ") + \ - i) + rezTerm = self._equalTerm(i, + errorMsg) if not rezTerm: self.headerTerm = False break @@ -421,9 +421,8 @@ class fileHeader(_terms): incorrectParams = set(self.params.keys()) - set(self.allowParam) if incorrectParams: self.headerTerm = False - self.headerCorrect = False - self.errorMessage = _("incorrect header parameters - '%s'")\ - % " ".join(list(incorrectParams)) + self.setError(_("incorrect header parameters - '%s'")\ + %" ".join(list(incorrectParams))) def _getType(self): """Выдать тип файла""" @@ -459,23 +458,23 @@ class dirHeader(_terms): """ # Допустимые параметры заголовка allowParam = ["append", "chmod", "chown", "name", "path"] - # Корректность заголовка - headerCorrect = True # Тип вставки шаблона typeAppend = "" + # Возможные типы вставки шаблонов _fileAppend = "join", "remove", "skip" + # условные операторы terms = ('>', '<', '==', '!=', '>=', '<=') + # параметры без значения listParNotVal = ("symbolic", "force") + # Результат вычисления условия в заголовке headerTerm = True - # Сообщение о ошибке - errorMessage = "" - def __init__(self, text, objVar=False, function=False): + def __init__(self, templateName, text, objVar=False, function=False): self.body = text # Объект с переменными self.objVar=objVar @@ -508,9 +507,8 @@ class dirHeader(_terms): self.body = "" if self.body.strip(): self.headerTerm = False - self.headerCorrect = False - self.errorMessage = _("incorrect text in template: '%s'")\ - %self.body + self.setError(_("incorrect text in template: '%s'")\ + %self.body) flagErrorBody = True if not flagErrorBody: paramList = re.split("\s+",paramLine) @@ -520,14 +518,14 @@ class dirHeader(_terms): for term in self.terms: if term in i: foundTerm = True + errorMsg = _("Incorrect template") +\ + ": "+ templateName +"\n"+\ + _("header template not valid")+ ": "+ i if function: - rezTerm = self._equalTerm(i,\ - _("header template not valid: ") + \ - i,function) + rezTerm = self._equalTerm(i, errorMsg, + function) else: - rezTerm = self._equalTerm(i,\ - _("header template not valid: ") + \ - i) + rezTerm = self._equalTerm(i, errorMsg) if not rezTerm: self.headerTerm = False break @@ -547,9 +545,8 @@ class dirHeader(_terms): incorrectParams = set(self.params.keys()) - set(self.allowParam) if incorrectParams: self.headerTerm = False - self.headerCorrect = False - self.errorMessage = _("incorrect header parameters - '%s'")\ - % " ".join(list(incorrectParams)) + self.setError(_("incorrect header parameters - '%s'")\ + %" ".join(list(incorrectParams))) def _getAppend(self): """Выдать тип добавления директории""" @@ -1885,11 +1882,11 @@ class _file(_error): def __init__(self): # Имя файла конфигурационного файла self.nameFileConfig = "" - # Старый шаблон + # Содержимое конфигурационного файла self.textConfig = "" # Имя файла шаблона self.nameFileTemplate = "" - # Новый шаблон + # Содержимое шаблона self.textTemplate = "" # Дескриптор файла шаблона self.F_TEMPL = False @@ -1932,7 +1929,7 @@ class _file(_error): self.F_CONF = False def __openConfFile(self, nameFileConfig): - """Октрыть конфигурационный файл""" + """Отктрыть конфигурационный файл""" F_CONF = False try: if os.path.islink(nameFileConfig): @@ -1941,9 +1938,7 @@ class _file(_error): F_CONF = open (nameFileConfig, "r+") except: try: - fd = os.open(nameFileConfig, os.O_CREAT) - os.close(fd) - F_CONF = open(nameFileConfig, "r+") + F_CONF = open(nameFileConfig, "w+") except: self.setError(_("not open file:" ) + nameFileConfig) return False @@ -2131,59 +2126,6 @@ class utfBin: resS = reVar.search(textTemplateTmp) return textTemplateTmp -class scanDirectory: - """Класс для cканирования директории""" - - def processingFile(self, path, prefix): - """Обработка в случае файла""" - return True - - def processingDirectory(self, path, prefix): - """Обработка в случае директории если возвращаем None то пропуск дир.""" - return True - - def scanningDirectory(self, scanDir, skipFile=[], skipDir=[], - prefix=None, flagDir=False): - """Сканирование и обработка шаблонов в директории scanDir""" - ret = True - if not prefix: - prefix = os.path.join(scanDir,"")[:-1] - if not flagDir: - # проверка корневой директории - retDir = self.processingDirectory(scanDir, scanDir) - if retDir is None: - return None - elif retDir is False: - return False - if flagDir or stat.S_ISDIR(os.lstat(scanDir)[stat.ST_MODE]): - for fileOrDir in sorted(os.listdir(scanDir)): - absPath = os.path.join(scanDir,fileOrDir) - relPath = absPath.split(prefix)[1] - stInfo = os.lstat(absPath) - statInfo = stInfo[stat.ST_MODE] - if stat.S_ISREG(statInfo): - # Обработка файла - if relPath in skipFile: - continue - if not self.processingFile(absPath, prefix): - ret = False - break - elif stat.S_ISDIR(statInfo): - # Обработка директории - if relPath in skipDir: - continue - retDir = self.processingDirectory(absPath, prefix) - if retDir is None: - continue - elif retDir is False: - ret = False - break - ret = self.scanningDirectory(absPath, skipFile, - skipDir, prefix, True) - if ret is False: - break - return ret - class templateFormat: """Методы получения классов и объектов форматов шаблонов""" # Импортированные классы поддерживаемых форматов шаблонов @@ -2238,6 +2180,22 @@ class _shareTemplate: _deltVarStart = len(varStart) _deltVarEnd = len(varEnd) + def getDataUser(self): + """Получить информацию о пользователе""" + userName = self.objVar.Get("ur_login") + if not userName: + userName = "root" + import pwd + try: + pwdObj = pwd.getpwnam(userName) + uid = pwdObj.pw_uid + gid = pwdObj.pw_gid + homeDir = pwdObj.pw_dir + except: + print _("Can not found user %s")%str(userName) + cl_overriding.exit(1) + return uid, gid, homeDir + class templateFunction(_error, _shareTemplate): """Класс для функций шаблонов""" # Словарь установленных программ {"имя программы":[версии]} @@ -2296,6 +2254,8 @@ class templateFunction(_error, _shareTemplate): self.namesTemplateFunction.append(nameFunction) # Объект хранения переменных self.objVar = objVar + # Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д + self._baseDir = self.objVar.Get("cl_root_path") self._reFunc = re.compile(("%s[a-zA-Z0-9_\-\+\(\)\, \*\/\.\'\"~]+%s")\ %(self.varStart,self.varEnd),re.M) # Аттрибуты для функции шаблона ini() @@ -2306,28 +2266,14 @@ class templateFunction(_error, _shareTemplate): # Время модификации конфигурационного файла для ini() self.timeIni = -1 self.uid, self.gid, self.homeDir = self.getDataUser() - # Путь к конфигурационному файлу для ini() + # Домашняя директория, плюс базовая директория + self.homeDir = os.path.join(self._baseDir, self.homeDir[1:]) + # Путь к конфигурационному файлу для ini() self.pathConfigIni = os.path.join(self.homeDir, ".calculate") self.fileConfigIni = os.path.join(self.pathConfigIni,"ini.env") # Словарь времен модификации env файлов self.timeConfigsIni = {} - def getDataUser(self): - """Получить информацию о пользователе""" - userName = self.objVar.Get("ur_login") - if not userName: - userName = "root" - import pwd - try: - pwdObj = pwd.getpwnam(userName) - uid = pwdObj.pw_uid - gid = pwdObj.pw_gid - homeDir = pwdObj.pw_dir - except: - print _("Can not found user %s")%str(userName) - cl_overriding.exit(1) - return uid, gid, homeDir - def equalTerm(self, term, localVars): """Метод для вычисления выражения""" terms = self.sNum.findall(term) @@ -2745,7 +2691,7 @@ class templateFunction(_error, _shareTemplate): # Создаем директорию if not os.path.exists(self.pathConfigIni): os.makedirs(self.pathConfigIni) - os.chown(self.pathConfigIni, int(self.uid), int(self.gid)) + os.chown(self.pathConfigIni, self.uid, self.gid) termsRaw = funArgv.split(",") flagFirst = True terms = [] @@ -2876,13 +2822,9 @@ class templateFunction(_error, _shareTemplate): self.timeIni = self.getTimeFile(self.fileConfigIni) # Меняем владельца в случае необходимости if os.path.exists(self.fileConfigIni): - fd = os.open(self.fileConfigIni, os.O_RDONLY) - fst = os.fstat(fd) - uid = fst.st_uid - gid = fst.st_gid - os.close(fd) + uid, gid = getModeFile(self.fileConfigIni, "owner") if self.uid!=uid or self.gid!=gid: - os.chown(self.fileConfigIni, int(self.uid), int(self.gid)) + os.chown(self.fileConfigIni, self.uid, self.gid) return textTemplateTmp class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): @@ -2919,10 +2861,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): # Объект с переменными self.objVar = objVar # Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д - #self._baseDir = os.path.split(baseDir)[0] self._baseDir = self.objVar.Get("cl_root_path") - #if self._baseDir == "/": - #self._baseDir = "" # Последняя часть директории шаблона (имя сервиса: samba, mail) self._servDir = servDir if self._servDir: @@ -2953,6 +2892,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.applyFuncTemplate = self.functObj.applyFuncTemplate # Объект для определения типа файла шаблона self.typeFileObj = typeFile() + self.uid, self.gid, self.homeDir = self.getDataUser() + # Домашняя директория, плюс базовая директория + self.homeDir = os.path.join(self._baseDir, self.homeDir[1:]) # Преобразование восьмеричного в целое (ввод строка, вывод число) @@ -2994,7 +2936,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): createDirs.append(prevDir) prevDir = os.path.split(prevDir)[0] try: - tmpMode,dUid,dGid = getModeFile(prevDir) + dUid,dGid = getModeFile(prevDir,"owner") except OSError: self.setError(_("Not access dir: " ) + prevDir) return False @@ -3330,10 +3272,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): # Применяем шаблон pathDir, objHeadDir = self.__getApplyHeadDir(newDir, dirInfoFile, opt) if objHeadDir: - crDirs = self.createDir(pathDir) - if crDirs is False: - return False - self.createdDirs += crDirs + self.createdDirs += [pathDir] else: if self.getError(): return False @@ -3376,16 +3315,11 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): # Заменяем переменные на их значения textTemplate = self.applyVarsTemplate(textTemplate, templateDirFile) # Обработка заголовка - objHead = dirHeader(textTemplate, self.objVar,function) - if not objHead.headerCorrect: - self.setError(_("Incorrect template: " ) +\ - templateDirFile) - self.setError(objHead.errorMessage) - return (applyDir, False) + objHead = dirHeader(templateDirFile,textTemplate,self.objVar,function) # Директория с профилями не будет применена if not objHead.headerTerm: if objHead.getError(): - self.setError(_("Incorrect template: " ) +\ + self.setError(_("Incorrect template") + ": " +\ templateDirFile) return (applyDir, False) @@ -3480,6 +3414,16 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.setError(_("False value 'chown' in template: " ) +\ templateDirFile) return (applyDir, False) + else: + # Устанавливаем владельцем директории, пользователя по умолчанию + # (переменная шаблона ur_login) + if os.path.exists(applyDir): + tUid, tGid = getModeFile(applyDir, mode="owner") + if (self.uid, self.gid) != (tUid, tGid): + os.chown(applyDir, self.uid, self.gid) + else: + if not self.createDir(applyDir, False, self.uid, self.gid): + return False return (applyDir, objHead) def __getApplyHeadTemplate(self, nameFileTemplate, nameFileConfig, @@ -3499,18 +3443,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.F_TEMPL = self.openTemplFile(self.nameFileTemplate) self.textTemplate = self.F_TEMPL.read() self.closeTemplFile() - objHeadNew = fileHeader(self.textTemplate, False, + objHeadNew = fileHeader(nameFileTemplate, self.textTemplate, False, templateFileType ,objVar=self.objVar, function=function) - if not objHeadNew.headerCorrect: - self.setError(_("Incorrect template: " ) +\ - nameFileTemplate) - self.setError(objHeadNew.errorMessage) - return (applyFiles, False) # файл шаблона не будет применен if not objHeadNew.headerTerm: if objHeadNew.getError(): - self.setError(_("Incorrect template: " ) +\ + self.setError(_("Incorrect template") + ": " +\ nameFileTemplate) return (applyFiles, False) @@ -3545,9 +3484,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): realPath = os.path.join("/",pathOldFile.partition(self._baseDir)[2]) if realPath in self.filesFilter: return (applyFiles, False) - + typeAppendTemplate = objHeadNew.typeAppend # Удаляем оригинальный файл - if objHeadNew.typeAppend == "remove": + if typeAppendTemplate == "remove": if os.path.islink(pathOldFile): # удаляем ссылку try: @@ -3564,7 +3503,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): pathOldFile) return (applyFiles, False) # Пропускаем обработку шаблона - elif objHeadNew.typeAppend == "skip": + elif typeAppendTemplate == "skip": return (applyFiles, False) # Создаем директорию для файла если ее нет @@ -3615,18 +3554,30 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if os.path.exists(pathOldFile): os.remove(pathOldFile) if foundTemplateFile: - fd = os.open(pathOldFile, os.O_CREAT) - os.close(fd) + try: + FD = open(pathOldFile, "w+") + FD.write(buff) + FD.close() + except: + self.setError(_("Error in template: " ) +\ + nameFileTemplate) + self.setError(_("Can not create file") + " '%s'"\ + %pathOldFile) + return (applyFiles, False) 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() + try: + os.chown(pathOldFile, fUid, fGid) + except: + self.setError(_("Error in template: " ) +\ + nameFileTemplate) + self.setError(_("Can not change owner to file") + \ + " '%s'" %pathOldFile) + return (applyFiles, False) # Если символическая ссылка if objHeadNew.params.has_key("symbolic"): @@ -3643,8 +3594,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): mode = self.__octToInt(objHeadNew.params['chmod']) if mode: if not os.path.exists(pathOldFile): - fd = os.open(pathOldFile, os.O_CREAT) - os.close(fd) + # Создание файла + FD = open(pathOldFile, "w") + FD.close() os.chmod(pathOldFile, mode) else: self.setError(_("False value 'chmod' in template: " ) +\ @@ -3674,8 +3626,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): return (applyFiles, False) if not os.path.exists(pathOldFile): - fd = os.open(pathOldFile, os.O_CREAT) - os.close(fd) + # Создание файла + FD = open(pathOldFile, "w") + FD.close() os.chown(pathOldFile, uid, gid) else: self.setError(_("False value 'chown' in template: " ) +\ @@ -3685,7 +3638,14 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.setError(_("False value 'chown' in template: " ) +\ nameFileTemplate) return (applyFiles, False) + self.openFiles(nameFileTemplate, pathOldFile) + if not objHeadNew.params.has_key("chown"): + # Устанавливаем владельцем конфигурационного файла, + # пользователя по умолчанию (переменная шаблона ur_login) + tUid, tGid = getModeFile(pathOldFile, mode="owner") + if (self.uid, self.gid) != (tUid, tGid): + os.chown(pathOldFile, self.uid, self.gid) if flagSymlink: if os.path.exists(prevOldFile) or os.path.islink(prevOldFile): if os.path.islink(prevOldFile): @@ -3707,7 +3667,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if pathProg: os.chdir(pathProg) # Если файлы заменяются не нужно их обрабатывать дальше - if objHeadNew.typeAppend == "replace" and\ + if typeAppendTemplate == "replace" and\ not objHeadNew.params.has_key("symbolic") and\ objHeadNew.params.has_key("link"): return (applyFiles, False) @@ -3786,6 +3746,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): optFile) if not objHeadNew: return filesApply + # Настоящее имя конфигурационного файла + nameFileConfig = filesApply[0] # Флаг - кодировка с бинарными примесями у файла шаблона включаем при # условии текстового файла и кодировки отличной от UTF-8 flagNotUtf8New = False @@ -3801,10 +3763,6 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): if not self.fileIsUtf(nameFileConfig): flagNotUtf8Old = True self.textTemplate = objHeadNew.body - #if objHeadNew.fileType != "bin": - #self.textTemplate = self.applyTermsTemplate(self.textTemplate, - #nameFileTemplate) - #self.textTemplate = self.applyVarsTemplate(self.textTemplate) # Титл конфигурационного файла title = "" @@ -3815,33 +3773,34 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): objHeadOld = False if objHeadNew.comment: - objHeadOld = fileHeader(self.textConfig, objHeadNew.comment) - # Тестирование - #print self.nameFileConfig - #print objHeadNew.typeAppend + objHeadOld = fileHeader(nameFileConfig, self.textConfig, + objHeadNew.comment) if objHeadNew.fileType: + formatTemplate = objHeadNew.fileType + typeAppendTemplate = objHeadNew.typeAppend # Создаем объект в случае параметра format в заголовке - if (objHeadNew.typeAppend == "replace" or\ - objHeadNew.typeAppend == "before" or\ - objHeadNew.typeAppend == "after") and\ - not (objHeadNew.fileType == "bin" or\ - objHeadNew.fileType == "raw"): + if (typeAppendTemplate == "replace" or\ + typeAppendTemplate == "before" or\ + typeAppendTemplate == "after") and\ + not (formatTemplate == "bin" or\ + formatTemplate == "raw"): # Преобразовываем бинарные файлы if flagNotUtf8New: objTxtCoder = utfBin() self.textTemplate = objTxtCoder.encode(self.textTemplate) # создаем объект формата шаблона - objTemplNew = self.getFormatObj(objHeadNew.fileType, + objTemplNew = self.getFormatObj(formatTemplate, self.textTemplate) if not objTemplNew: self.setError(\ _("Incorrect header parmeter format=%s in template")\ %formatTemplate + " " + nameFileTemplate) return False - if "xml_" in objHeadNew.fileType: + if "xml_" in formatTemplate: if objTemplNew.getError(): self.setError(_("False template: " ) + nameFileTemplate) return False + # Имя файла внутри xml xfce конфигурационных файлов nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0] objTemplNew.setNameBodyNode(nameRootNode) # Объект Документ @@ -3866,8 +3825,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): ListOptTitle) title = title.encode("UTF-8") # Замена - if objHeadNew.typeAppend == "replace": - if "xml_" in objHeadNew.fileType: + if typeAppendTemplate == "replace": + if "xml_" in formatTemplate: data = self.textTemplate.split("\n") data.insert(1,title) self.textConfig = "\n".join(data) @@ -3880,8 +3839,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.saveConfFile() return filesApply # Впереди - elif objHeadNew.typeAppend == "before": - if "xml_" in objHeadNew.fileType: + elif typeAppendTemplate == "before": + if "xml_" in formatTemplate: self.setError(\ _("False option append=before in template %s")\ %nameFileTemplate) @@ -3903,8 +3862,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.saveConfFile() return filesApply # Cзади - elif objHeadNew.typeAppend == "after": - if "xml_" in objHeadNew.fileType: + elif typeAppendTemplate == "after": + if "xml_" in formatTemplate: self.setError(\ _("False option append=after in template %s")\ %nameFileTemplate) @@ -3924,19 +3883,19 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): self.saveConfFile() return filesApply # Объединение - elif objHeadNew.typeAppend == "join": + elif typeAppendTemplate == "join": if flagNotUtf8New: objTxtCoder = utfBin() self.textTemplate = objTxtCoder.encode(self.textTemplate) # создаем объект формата шаблона - objTemplNew = self.getFormatObj(objHeadNew.fileType, + objTemplNew = self.getFormatObj(formatTemplate, self.textTemplate) if not objTemplNew: self.setError(\ _("Incorrect header parmeter format=%s in template")\ %formatTemplate + " " + nameFileTemplate) return False - if "xml_" in objHeadNew.fileType: + if "xml_" in formatTemplate: if objTemplNew.getError(): self.setError(_("False template: " ) + nameFileTemplate) return False @@ -3962,7 +3921,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): #self.saveConfFile() #return True - objHeadOld = fileHeader(self.textConfig, objTemplNew._comment) + objHeadOld = fileHeader(nameFileConfig, self.textConfig, + objTemplNew._comment) if objHeadOld.body: self.textConfig = objHeadOld.body else: @@ -3971,12 +3931,12 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): objTxtCoder = utfBin() self.textConfig = objTxtCoder.encode(self.textConfig) # создаем объект формата шаблона для конфигурационного файла - objTemplOld = self.getFormatObj(objHeadNew.fileType, + objTemplOld = self.getFormatObj(formatTemplate, self.textConfig) if not objTemplOld: self.setError(_("Error in template %s") %nameFileConfig) return False - if "xml_" in objHeadNew.fileType: + if "xml_" in formatTemplate: if objTemplOld.getError(): self.setError(_("False template: " ) + nameFileConfig) return False @@ -3988,7 +3948,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): objTemplOld.join(objTemplNew) #print objTemplOld.doc.toprettyxml() #print objTemplNew.doc.toprettyxml() - if "xml_" in objHeadNew.fileType: + if "xml_" in formatTemplate: if objTemplOld.getError(): self.setError(_("False template: " ) + nameFileTemplate) return False @@ -4014,7 +3974,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): return filesApply else: self.setError(_("False (type append) template: " ) +\ - objHeadNew.typeAppend) + typeAppendTemplate) return False else: self.setError(_("Type template not found: ") + nameFileTemplate) @@ -4047,13 +4007,15 @@ class iniParser(_error, templateFormat): def writeIniFile(self, txtConfig): if not os.path.exists(self.iniFile): - fd = os.open(self.iniFile, os.O_CREAT) - os.close(fd) - os.chmod(self.iniFile, self.mode) - if not os.path.exists(self.iniFile): - self.setError(_("Unable to create file") + ": " + self.iniFile) - return False - FD = open(self.iniFile, "r+") + try: + # Создание файла + FD = open(self.iniFile, "w+") + os.chmod(self.iniFile, self.mode) + except: + self.setError(_("Unable to create file") + ": " + self.iniFile) + return False + else: + FD = open(self.iniFile, "r+") FD.truncate(0) FD.seek(0) FD.write(txtConfig) diff --git a/pym/cl_utils.py b/pym/cl_utils.py index 1a7156c..83fd78d 100644 --- a/pym/cl_utils.py +++ b/pym/cl_utils.py @@ -74,12 +74,65 @@ class typeFile: def isBinary(self,filename): """является ли файл бинарным""" mime = self.getMType(filename) + # В случае ошибки if mime.count("`"): return mime elif mime.count("binary"): return True return False +class scanDirectory: + """Класс для cканирования директории""" + + def processingFile(self, path, prefix): + """Обработка в случае файла""" + return True + + def processingDirectory(self, path, prefix): + """Обработка в случае директории если возвращаем None то пропуск дир.""" + return True + + def scanningDirectory(self, scanDir, skipFile=[], skipDir=[], + prefix=None, flagDir=False): + """Сканирование и обработка шаблонов в директории scanDir""" + ret = True + if not prefix: + prefix = os.path.join(scanDir,"")[:-1] + if not flagDir: + # проверка корневой директории + retDir = self.processingDirectory(scanDir, scanDir) + if retDir is None: + return None + elif retDir is False: + return False + if flagDir or stat.S_ISDIR(os.lstat(scanDir)[stat.ST_MODE]): + for fileOrDir in sorted(os.listdir(scanDir)): + absPath = os.path.join(scanDir,fileOrDir) + relPath = absPath.split(prefix)[1] + stInfo = os.lstat(absPath) + statInfo = stInfo[stat.ST_MODE] + if stat.S_ISREG(statInfo): + # Обработка файла + if relPath in skipFile: + continue + if not self.processingFile(absPath, prefix): + ret = False + break + elif stat.S_ISDIR(statInfo): + # Обработка директории + if relPath in skipDir: + continue + retDir = self.processingDirectory(absPath, prefix) + if retDir is None: + continue + elif retDir is False: + ret = False + break + ret = self.scanningDirectory(absPath, skipFile, + skipDir, prefix, True) + if ret is False: + break + return ret def runOsCommand(cmd, inStr=None, ret_first=None, env_dict=None): """Выполняет внешнюю программу @@ -197,18 +250,22 @@ def _toUNICODE(val): return str(val).decode('UTF-8') -def getModeFile(nameFile): +def getModeFile(nameFile, mode="all"): """Выдает информацию о файле - - права файла, владелец, группа файла (777,test, group) + mode=="all" + права файла, владелец, группа файла + mode=="mode" + права файла + mode=="owner" + владелец, группа файла """ - fd = os.open(nameFile, os.O_RDONLY) - fst = os.fstat(fd) - uid = fst.st_uid - gid = fst.st_gid - mode = stat.S_IMODE(fst.st_mode) - os.close(fd) - return (mode,uid,gid) + fst = os.lstat(nameFile) + if mode == "all": + return (stat.S_IMODE(fst.st_mode), fst.st_uid, fst.st_gid) + if mode == "mode": + return stat.S_IMODE(fst.st_mode) + if mode == "owner": + return fst.st_uid, fst.st_gid def chownR(directory, uid, gid):