diff --git a/pym/cl_apply_template.py b/pym/cl_apply_template.py new file mode 100644 index 0000000..853e6ca --- /dev/null +++ b/pym/cl_apply_template.py @@ -0,0 +1,178 @@ +#-*- coding: utf-8 -*- + +# Copyright 2010 Mir Calculate Ltd. http://www.calculate-linux.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys, os, re +import cl_install +__version__ = cl_install.__version__ +__app__ = cl_install.__app__ + +from cl_datavars import DataVars +from cl_template import template, templateClt +from cl_print import color_print + +from cl_lang import lang +tr = lang() +tr.setGlobalDomain('cl_install') +tr.setLanguage(sys.modules[__name__]) +#sys.path.insert(0, "/usr/lib/calculate-2.2/calculate-lib/pym") + +#packagePath = "/usr/lib/calculate-2.2" +#for path in os.listdir(packagePath): + #realPath = os.path.join(packagePath,path) + #if os.path.isdir(realPath): + #pymPath = os.path.join(realPath,"pym") + #if len(filter(lambda x:x.startswith("cl_vars_") and\ + #x.endswith(".py") or x.startswith("cl_fill_") and\ + #x.endswith(".py"), os.listdir(pymPath)))==2: + #sys.path.insert(0, os.path.abspath(pymPath)) + +class DataVarsObject(DataVars): + """Класс переменных для десктопа""" + def __init__(self, section): + DataVars.__init__(self) + self.section=section + + def importDataObject(self, **args): + '''Заполнить конфигурацию переменных, для десктопа''' + # Имя секции в calculate.env + #envSection = "calculate-desktop" + # заполнить переменные окружения алгоритмом по умолнанию + self.importData(self.section, ('cl_vars_%s' %self.section, + 'cl_fill_%s' %self.section)) + self.flIniFile() + +class updateConfFiles(color_print): + """Для обновления конфигурационных файлов""" + + patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*") + firstEnvFile = "/etc/calculate/calculate2.env" + + def __init__(self): + clVars = DataVarsObject("install") + clVars.importDataObject() + self.clVars = clVars + + def applyCltTemplate(self, cltTemplatePath): + """Применяем clt шаблон""" + realPath = "/usr/lib/calculate-2.2/calculate-install" + pymPath = os.path.join(realPath,"pym") + if not os.path.isdir(pymPath) or\ + not len(filter(lambda x:x.startswith("cl_vars_") and\ + x.endswith(".py") or x.startswith("cl_fill_") and\ + x.endswith(".py"), os.listdir(pymPath)))==2: + self.printERROR(_("Can not installed package %s") + %"calculate-install") + return False + dirsTemplates = self.clVars.Get("cl_template_clt_path") + flagFoundPath = False + for dirTemplates in dirsTemplates: + if cltTemplatePath.startswith(dirTemplates): + flagFoundPath = True + if not flagFoundPath: + self.printERROR(_("Incorrect path %s")%cltTemplatePath) + self.printWARNING(_("Use the following directories and their \ +subdirectories %s")%', '.join(dirsTemplates)) + return False + if not os.path.exists(cltTemplatePath): + self.printERROR(_("File '%s' does not exist")%cltTemplatePath) + return False + if not os.access(cltTemplatePath, os.R_OK): + self.printERROR(_("Permission denied: '%s'")%cltTemplatePath) + return False + if not os.path.isfile(cltTemplatePath): + self.printERROR(_("'%s' is not file")%cltTemplatePath) + return False + clTempl = templateClt(self.clVars) + if not cltTemplatePath.endswith(clTempl.extFileTemplate): + self.printERROR(_("extension of the file '%s' not '.clt'") + %cltTemplatePath) + return False + calcPkg = self.clVars.Get("cl_name")+"-" + self.clVars.Get("cl_ver") + nameFile = clTempl.applyTemplate(cltTemplatePath) + if nameFile is False: + self.printERROR(_("Error template in a package %s")\ + %calcPkg) + for errMess in clTempl.getError().splitlines(): + self.printERROR(errMess) + return False + self.printWARNING(_("Package %s has changed files")%calcPkg+":") + self.printWARNING(" "*5 + nameFile) + return True + + def printVars(self, opts): + """Печать существующих переменных""" + if opts == ["all"]: + self.clVars.printVars() + else: + self.clVars.printVars(opts) + + def applyAllTemplates(self): + """Обновление конфигурационных файлов""" + if not os.path.exists(self.firstEnvFile): + self.printERROR(_("File '%s' does not exist")%self.firstEnvFile) + return False + if not os.access(self.firstEnvFile, os.R_OK): + self.printERROR(_("Permission denied: '%s'")%self.firstEnvFile) + return False + sectionsWork = [] + for line in open(self.firstEnvFile).readlines(): + sRet = self.patternSect.search(line) + if sRet: + sectionsWork.append(sRet.group(1)) + installSect = "install" + if not installSect in sectionsWork: + sectionsWork.insert(0, installSect) + installSect = "install" + dictPakkages = {} + oldPymPath = "" + for sectName in sectionsWork: + realPath = "/usr/lib/calculate-2.2/calculate-%s"%sectName + pymPath = os.path.join(realPath,"pym") + if not os.path.isdir(pymPath): + continue + if len(filter(lambda x:x.startswith("cl_vars_") and\ + x.endswith(".py") or x.startswith("cl_fill_") and\ + x.endswith(".py"), os.listdir(pymPath)))==2: + if oldPymPath: + sys.path = filter(lambda x: x!=oldPymPath, sys.path) + sys.path.insert(0, os.path.abspath(pymPath)) + oldPymPath = os.path.abspath(pymPath) + clVars = DataVarsObject(sectName) + clVars.importDataObject() + # будут применены все шаблоны .clt (cltFilter=False) + # и обычные шаблоны + clTempl = template(clVars, cltFilter=False) + dirsFiles = clTempl.applyTemplates() + nameAndVerPkg = clVars.Get("cl_name")+"-"+\ + clVars.Get("cl_ver") + if dirsFiles is False: + self.printERROR(_("Error template in a package %s")\ + %nameAndVerPkg) + for errMess in clTempl.getError().splitlines(): + self.printERROR(errMess) + return False + if dirsFiles and dirsFiles[1]: + dictPakkages[nameAndVerPkg] =\ + sorted(list(set(dirsFiles[1]))) + if dictPakkages: + for calcPkg in dictPakkages: + self.printWARNING(_("Package %s has changed files")%calcPkg+":") + for nameF in dictPakkages[calcPkg]: + nameFile = nameF + if nameFile[:1] != "/": + nameFile = "/" + nameFile + self.printWARNING(" "*5 + nameFile) + return True \ No newline at end of file diff --git a/pym/cl_apply_template_cmd.py b/pym/cl_apply_template_cmd.py new file mode 100644 index 0000000..c0e7bcd --- /dev/null +++ b/pym/cl_apply_template_cmd.py @@ -0,0 +1,112 @@ +#-*- coding: utf-8 -*- + +# Copyright 2010 Mir Calculate Ltd. http://www.calculate-linux.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys + +from cl_apply_template import updateConfFiles, __app__, __version__ +from cl_opt import opt +from cl_share_cmd import share_cmd +from cl_lang import lang +lang().setLanguage(sys.modules[__name__]) + +USAGE = _("%prog [options]") + +COMMENT_EXAMPLES = _("Apply all of the templates for all packages") + +EXAMPLES = _("%prog --all") + +DESCRIPTION = _("The Calculate Linux utility to use templates") + +CMD_OPTIONS = [{'longOption':"clt", + 'optVal':"CLT_TEMPLATE", + 'help':_("process clt template") + }, + {'longOption':"all", + 'help':_("process all templates") + }, + {'longOption':"vars", + 'optVal':"TYPE_VAR", + 'help':_("print variables") + " (TYPE_VAR - all: " + \ + _("full variables list") +")"}] + +class apply_template_cmd(share_cmd): + def __init__(self): + # Объект опций командной строки + self.optobj = opt(\ + package=__app__, + version=__version__, + usage=USAGE, + examples=EXAMPLES, + comment_examples=COMMENT_EXAMPLES, + description=DESCRIPTION, + option_list=CMD_OPTIONS + opt.color_control, + check_values=self.checkOpts) + # Создаем объект логики + self.logicObj = updateConfFiles() + # Названия несовместимых опций + self.optionsNamesIncompatible = ["all", "clt"] + # Названия обязательных опций + self.optionsNamesRequired = self.optionsNamesIncompatible + ["vars"] + + + def getOptionsRequired(self, optObj): + """Получаем обязательные опции""" + retList = [] + for nameOpt in self.optionsNamesRequired: + retList.append(getattr(optObj, nameOpt)) + return retList + + def _getNamesAllSetOptions(self): + """Выдает словарь измененных опций""" + setOptDict = self.optobj.values.__dict__.items() + defaultOptDict = self.optobj.get_default_values().__dict__.items() + return dict(set(setOptDict) - set(defaultOptDict)).keys() + + def getStringIncompatibleOptions(self): + """Форматированная строка несовместимых опций разделенных ','""" + listOpt = list(set(self.optionsNamesIncompatible) &\ + set(self._getNamesAllSetOptions())) + return ", ".join(map(lambda x: len(x) == 1 and "'-%s'"%x or "'--%s'"%x,\ + listOpt)) + + def checkOpts(self, optObj, args): + """Проверка опций командной строки""" + optionsRequired = self.getOptionsRequired(optObj) + if len(filter(lambda x: x, optionsRequired))>1: + errMsg = _("incompatible options")+":"+" %s"\ + %self.getStringIncompatibleOptions() + self.optobj.error(errMsg) + return False + elif not filter(lambda x: x, optionsRequired): + errMsg = _("required option")+":"+" %s"\ + %" or ".join(map(lambda x:\ + len(x) == 1 and "'-%s'"%x or "'--%s'"%x,\ + self.optionsNamesRequired)) + self.optobj.error(errMsg) + return False + if len(args)>0: + errMsg = _("incorrect argument") + ":" + " %s" %" ".join(args) + self.optobj.error(errMsg) + return False + return optObj, args + + def applyCltTemplate(self, cltTemplate): + """Применяем clt шаблон""" + return self.logicObj.applyCltTemplate(cltTemplate) + + def applyAllTemplates(self): + """Применяем все шаблоны""" + return self.logicObj.applyAllTemplates() \ No newline at end of file diff --git a/scripts/cl-template b/scripts/cl-template new file mode 100644 index 0000000..834fccc --- /dev/null +++ b/scripts/cl-template @@ -0,0 +1,50 @@ +#!/usr/bin/python +#-*- coding: utf-8 -*- + +# Copyright 2010 Mir Calculate Ltd. http://www.calculate-linux.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import os +sys.path.insert(0,os.path.abspath('/usr/lib/calculate-2.2/calculate-lib/pym')) +sys.path.insert(0, + os.path.abspath('/usr/lib/calculate-2.2/calculate-install/pym')) + +from cl_apply_template_cmd import apply_template_cmd + +from cl_lang import lang +tr = lang() +tr.setGlobalDomain('cl_install') +tr.setLanguage(sys.modules[__name__]) + +if __name__ == "__main__": + obj = apply_template_cmd() + ret = obj.optobj.parse_args() + if ret is False: + sys.exit(1) + options, args = ret + # set color/nocolor for display messages + obj.setPrintNoColor(options) + # Печать переменных + obj.printVars(options) + if options.all: + # apply all templates + if not obj.applyAllTemplates(): + sys.exit(1) + elif options.clt: + # apply one clt template + if not obj.applyCltTemplate(options.clt): + sys.exit(1) + sys.exit(0) + diff --git a/setup.py b/setup.py index 41b40d0..f93a290 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # setup.py --- Setup script for calculate-install @@ -108,6 +109,7 @@ setup( package_dir = {'calculate-install': "."}, packages = ['calculate-install.pym'], data_files = data_files, - scripts=["./scripts/cl-install"], + scripts=["./scripts/cl-install", + "./scripts/cl-template"], cmdclass={'install_data': cl_install_data}, )