diff --git a/pym/cl_template.py b/pym/cl_template.py index 859f4b5..507816a 100644 --- a/pym/cl_template.py +++ b/pym/cl_template.py @@ -30,8 +30,8 @@ import time # Переопределение exit import cl_overriding -from cl_utils import _error, _toUNICODE, getModeFile, removeDir, typeFile,\ -scanDirectory, convertStrListDict, pathJoin +from cl_utils import _error, _warning, _toUNICODE, getModeFile, removeDir,\ + typeFile, scanDirectory, convertStrListDict, pathJoin import cl_lang tr = cl_lang.lang() @@ -3207,7 +3207,7 @@ os_disk_install not found mount point '\' and '\%s'")%mountPoint) os.chown(self.fileConfigIni, self.uid, self.gid) return textTemplateTmp -class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): +class template(_file,_terms,_warning,xmlShare,templateFormat,_shareTemplate): """Класс для работы с шаблонами На вход 2 параметра: объект хранения переменных, имя сервиса - не @@ -3218,7 +3218,11 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate): templDirNameFile = ".calculate_directory" def __init__(self, objVar, servDir=False, dirsFilter=[], filesFilter=[], - cltObj=True, cltFilter=True): + cltObj=True, cltFilter=True, printWarning=True): + # Предупреждения + self.warning = [] + # Печатать ли предупреждения о корневых шаблонах без cl_name==pkg + self.printWarning = printWarning # Необрабатываемые директории self.dirsFilter = dirsFilter # Необрабатываемые файлы @@ -3499,6 +3503,91 @@ re.M|re.S) """ return True + def getHeaderText(self, text): + textLines = text.splitlines() + paramLine = "" + if textLines: + textLine = textLines[0] + rePar = re.compile(\ + "\s*#\s*calculate\s+\\\\?|\s*#\s*calculate\\\\?$",re.I) + reP = rePar.search(textLine) + if reP: + reL = False + reLns = re.compile(r"\A([^\\\n]*\\\n)+[^\n]*\n*",re.M) + reLs = reLns.search(text) + if reLs: + reL = reLs + paramLine = text[reP.end():reLs.end()] + paramLine = paramLine.replace("\\"," ") + else: + reLn = re.compile("\n") + reL = reLn.search(text) + paramLine = textLine[reP.end():] + return paramLine + + def getTemplateDirs(self, dirsTemplates): + """Check template variable cl_name in first directories and files""" + notAppendTemplateAndDirs = [] + for dirsTemplate in dirsTemplates: + filesAndDirs = map(lambda x: os.path.join(dirsTemplate,x), + os.listdir(dirsTemplate)) + skipDirs = [] + skipTemplates = [] + for dirFile in filesAndDirs: + if os.path.isdir(dirFile): + flagDir = True + templatePath = os.path.join(dirFile,self.templDirNameFile) + if not os.path.isfile(templatePath): + skipDirs.append(dirFile) + continue + else: + flagDir = False + templatePath = dirFile + if os.path.isfile(templatePath) and\ + self.getFileType(templatePath) != "bin": + textTemplate = open(templatePath).read() + if textTemplate: + headerLine = self.getHeaderText(textTemplate) + if headerLine: + if not "cl_name==" in headerLine: + if flagDir: + skipDirs.append(dirFile) + else: + skipTemplates.append(dirFile) + else: + if flagDir: + skipDirs.append(dirFile) + else: + skipTemplates.append(dirFile) + if skipDirs or skipTemplates: + # print warning + from cl_print import color_print + printObj = color_print() + setWARNING = lambda x: self.setWarning(x) and\ + self.printWarning and\ + printObj.printWARNING(x) + setWARNING(_("No conditions of checking a value of the \ +variable 'cl-name'")) + skipDirTemplates = [] + for skipDir in skipDirs: + skipTempl = os.path.join(skipDir,self.templDirNameFile) + if os.path.isfile(skipTempl): + skipDirTemplates.append(skipTempl) + if skipTemplates or skipDirTemplates: + setWARNING(_("Skip templates:")) + for skipTemplate in skipTemplates + skipDirTemplates: + setWARNING(" "*6 + skipTemplate) + if skipDirs: + setWARNING(_("Skip directories:")) + for skipDir in skipDirs: + setWARNING(" "*6 + skipDir) + setWARNING("") + setWARNING(_("Headers directory and template files first level \ +should include a check of the variable 'cl-name'.")) + setWARNING(_("Example:")) + setWARNING("# Calculate cl_name==calculate-install") + return skipDirs + skipTemplates + def applyTemplates(self): """Применяет шаблоны к конфигурационным файлам""" @@ -3544,7 +3633,6 @@ re.M|re.S) self.functObj.currDictIni = {} # Словарь времен модификации env файлов для ini() self.functObj.timeConfigsIni = {} - if self._servDir: tmpDirsTemplates = [] for dirP in dirsTemplates: @@ -3562,6 +3650,8 @@ re.M|re.S) self.setError(_("No such template directories") +\ ": %s"%", ".join(map(lambda x: "'%s'"%x ,dirsTemplates))) return (self.createdDirs, self.filesApply) + # check cl_name in first template dirs and files + skipTemplates = self.getTemplateDirs(dirsTemplatesExists) for dirTemplate in dirsTemplatesExists: scanObj.scanningDirectory(dirTemplate) # Считаем количество шаблонов clt @@ -3580,7 +3670,8 @@ re.M|re.S) self.numberAllTemplates(self.allTemplates) # Обрабатываем шаблоны for dirTemplate in dirsTemplatesExists: - if self.scanningTemplates(dirTemplate) is False: + if self.scanningTemplates(dirTemplate, + skipTemplates=skipTemplates) is False: return False if self.cltObj: # Созданные директории @@ -3606,7 +3697,8 @@ re.M|re.S) return (self.createdDirs, self.filesApply) - def scanningTemplates(self, scanDir, prefix=None, flagDir=False, optDir={}): + def scanningTemplates(self, scanDir, prefix=None, flagDir=False, + optDir={}, skipTemplates=[]): """Сканирование и обработка шаблонов в директории scanDir""" ret = True if not prefix: @@ -3626,6 +3718,8 @@ re.M|re.S) 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) + if skipTemplates and absPath in skipTemplates: + continue stInfo = os.lstat(absPath) statInfo = stInfo[stat.ST_MODE] if stat.S_ISREG(statInfo): @@ -4656,7 +4750,7 @@ class templateClt(scanDirectoryClt, template): """Обработка в случае шаблона файла""" self.numberProcessTempl += 1 self.numberProcessTemplates(self.numberProcessTempl) - # Пропуск шаблонов директорий + # Пропуск шаблонов директорийscanningTemplates if self.templDirNameFile == os.path.split(path)[1]: return True # Проверка на переменные в названии файла diff --git a/pym/cl_utils.py b/pym/cl_utils.py index 983c79f..d8964ae 100644 --- a/pym/cl_utils.py +++ b/pym/cl_utils.py @@ -52,6 +52,23 @@ class _error: self.error.append(error) return True +class _warning: + # Здесь предупреждения + warning = [] + def getWarning(self): + """Выдать ошибки""" + if not self.warning: + return False + warning = "" + for w in self.warning: + warning += w + "\n" + return warning + + def setWarning(self, warning): + """Установка ошибки""" + self.warning.append(warning) + return True + class typeFile: """Получение типа файла""" diff --git a/pym/update_config/cl_update_config.py b/pym/update_config/cl_update_config.py index e5754e0..2395184 100644 --- a/pym/update_config/cl_update_config.py +++ b/pym/update_config/cl_update_config.py @@ -175,7 +175,7 @@ class updateUserConfigs(shareUpdateConfigs): clVars.Set("ur_login", userName, True) clVars.Set("cl_action", "desktop", True) clVars.Set("cl_belong_pkg", nameProgram, True) - clTempl = cl_template.template(clVars) + clTempl = cl_template.template(clVars, printWarning=False) dirsFiles = clTempl.applyTemplates() if dirsFiles is False: self.printERROR(\ @@ -264,6 +264,7 @@ class updateSystemConfigs(shareUpdateConfigs): cl_template.templateFunction.installProg.update(\ {"%s/%s"%(category,nameProgram):[version], "%s"%(nameProgram):[version]}) + clTempl = False for mergeProgram in mergePrograms: clVars = DataVarsObject(mergeProgram) if not clVars.findPathVars(): @@ -281,7 +282,8 @@ class updateSystemConfigs(shareUpdateConfigs): cltObject.filterApplyTemplates = configFiles else: cltObject.filterApplyTemplates = [] - clTempl = cl_template.template(clVars, cltObj=cltObject) + clTempl = cl_template.template(clVars, cltObj=cltObject, + printWarning=False) dirsFiles = clTempl.applyTemplates() nameAndVerPkg = nameProg + "-"+clVars.Get("cl_ver") if dirsFiles is False: @@ -305,4 +307,9 @@ class updateSystemConfigs(shareUpdateConfigs): self.printWARNING(" "*5 + nameFile) else: self.logger.warn(_("Not found templates")) + if clTempl and clTempl.getWarning(): + cl_overriding.printSUCCESS("") + for warn in clTempl.getWarning().split("\n"): + self.printWARNING(warn) + cl_overriding.printSUCCESS("") return True