Added methods to work with variable both lists, also changed the algorithm of the module cl_update_config

develop
Самоукин Алексей 14 years ago
parent 62d0dca56f
commit f7dd473d5c

@ -370,7 +370,7 @@ storage of variables templates")%location)
Возвращаемые значение: Возвращаемые значение:
True запись успешна True запись успешна
False запись не удалсь False запись не удалaсь
''' '''
# получаем путь до ini файла # получаем путь до ini файла
name_calculate_ini = self.__getPathCalculateIni(location) name_calculate_ini = self.__getPathCalculateIni(location)
@ -399,7 +399,7 @@ storage of variables templates")%location)
Возвращаемые значение: Возвращаемые значение:
True удалено успешна True удалено успешна
False удаление не удалсь False удаление не удалось
''' '''
# получаем путь до ini файла # получаем путь до ini файла
name_calculate_ini = self.__getPathCalculateIni(location) name_calculate_ini = self.__getPathCalculateIni(location)
@ -422,7 +422,7 @@ storage of variables templates")%location)
else: else:
return False return False
def Write(self, vname, val, force=False, location='default',header=False): def Write(self,vname,val=None,force=False,location='default',header=False):
'''Установить и записать значение переменной в ini файл '''Установить и записать значение переменной в ini файл
Параметры: Параметры:
@ -432,11 +432,13 @@ storage of variables templates")%location)
location расположение ini файла ('default', 'local', 'remote') location расположение ini файла ('default', 'local', 'remote')
header раздел ini файла ('client', 'server', 'main') header раздел ini файла ('client', 'server', 'main')
''' '''
if self.__Set(vname, val, force)!= False: if val is None:
if not val.strip(): val = self.Get(vname)
self.__deleteVarValue(vname, location, header) else:
if self.__writeVarValue(vname, val, location, header): if self.__Set(vname, val, force) is False:
return True return False
if self.__writeVarValue(vname, val, location, header):
return True
return False return False
def Delete(self, vname, location='default', header=False): def Delete(self, vname, location='default', header=False):
@ -637,10 +639,89 @@ storage of variables templates")%location)
p_val=var[i].value p_val=var[i].value
if var[i].official: if var[i].official:
continue continue
#print ( i, mlen_name, var[i].mode.lower(), mlen_mode, p_val)
columnWrite( i, mlen_name, var[i].mode.lower(), mlen_mode, p_val) columnWrite( i, mlen_name, var[i].mode.lower(), mlen_mode, p_val)
cl_overriding.printSUCCESS(br) cl_overriding.printSUCCESS(br)
def GetList(self, nameVar, spl=","):
"""Получить значение переменной в виде списка
если значение переменной:
строка - разделяем spl (по умолчанию ',') и выводим список,
кроме строки - выводим как есть
"""
value = self.Get(nameVar)
if type(value) in (str, unicode):
return map(lambda x: x.strip(), value.split(spl))
return value
def SetList(self, nameVar, value, force=False, spl=","):
"""Записать список в переменную в виде строки, элементы разделены spl
если значение переменной:
список - объединяем через spl (по умолчанию ',')
список в строку, записываем
кроме списка - записываем
"""
if type(value) == list:
strValue = ",".join(value)
else:
strValue = value
return self.Set(nameVar, strValue, force)
def WriteList(self, vname, val=None, force=False,
location='default', header=False, spl=","):
"""Записать список в переменную в виде строки и записать в ini файл
(элементы разделены spl)
если значение переменной:
список - объединяем через spl (по умолчанию ',')
список в строку, записываем
кроме списка - записываем
"""
if val is None:
val = self.Get(vname)
if type(val) == list:
strValue = ",".join(val)
else:
strValue = val
if not strValue and type(strValue) in (str, unicode):
if self.__Set(vname, strValue, force) is False:
return False
if not self.__deleteVarValue(vname, location, header):
return False
return True
return self.Write(vname, strValue, force, location, header)
def AppendToList(self, nameVar, value, force=False, spl=",",
unique=True):
"""Добавление в переменную со строковым значением элемента
Разделитель элементов spl (по умолчанию ',')
"""
listValues = self.GetList(nameVar, spl)
if type(listValues) == list:
listValues = filter(lambda x: x, listValues)
if unique:
if not value in listValues:
listValues.append(value)
else:
listValues.append(value)
return self.SetList(nameVar, listValues, force, spl)
def RemoveToList(self, nameVar, value, force=False, spl=","):
"""Удаление из переменной со строковым значением элементов
со значением value
Разделитель элементов spl (по умолчанию ',')
"""
listValues = self.GetList(nameVar, spl)
if type(listValues) == list:
listValues = filter(lambda x: x, listValues)
listValues = filter(lambda x: x!=value, listValues)
self.SetList(nameVar, listValues, force, spl)
return True
class glob_attr: class glob_attr:
"""Глобальные аттрибуты для методов заполнения переменных""" """Глобальные аттрибуты для методов заполнения переменных"""

@ -4446,7 +4446,7 @@ re.M|re.S)
tmpTemplate = self.textTemplate + "\n" + self.textConfig tmpTemplate = self.textTemplate + "\n" + self.textConfig
if objHeadNew.execStr: if objHeadNew.execStr:
self.textConfig = objHeadNew.execStr + title + tmpTemplate self.textConfig = objHeadNew.execStr + title + tmpTemplate
elif objHeadOld.execStr: elif objHeadOld and objHeadOld.execStr:
self.textConfig = objHeadOld.execStr + title + tmpTemplate self.textConfig = objHeadOld.execStr + title + tmpTemplate
else: else:
self.textConfig = title + tmpTemplate self.textConfig = title + tmpTemplate
@ -4468,7 +4468,7 @@ re.M|re.S)
tmpTemplate = self.textConfig + "\n" + self.textTemplate tmpTemplate = self.textConfig + "\n" + self.textTemplate
if objHeadNew.execStr: if objHeadNew.execStr:
self.textConfig = objHeadNew.execStr + title + tmpTemplate self.textConfig = objHeadNew.execStr + title + tmpTemplate
elif objHeadOld.execStr: elif objHeadOld and objHeadOld.execStr:
self.textConfig = objHeadOld.execStr + title + tmpTemplate self.textConfig = objHeadOld.execStr + title + tmpTemplate
else: else:
self.textConfig = title + tmpTemplate self.textConfig = title + tmpTemplate

@ -475,3 +475,23 @@ def getTupleVersion(ver):
vers = toTuple(vers) vers = toTuple(vers)
revision = toTuple(revision or "r0") revision = toTuple(revision or "r0")
return [vers,revision] return [vers,revision]
def appendProgramToEnvFile(nameProg, objVar):
"""Append name program to variable cl-merges and
save /etc/calculate/calculate.env """
if not objVar.AppendToList("cl_merges", nameProg, force=True):
return False
if not objVar.WriteList("cl_merges", force=True):
return False
return True
def removeProgramToEnvFile(nameProg, objVar):
"""Remove name program from variable cl-merges and save
/etc/calculate/calculate.env"""
if not objVar.RemoveToList("cl_merges", nameProg, force=True):
return False
if not objVar.WriteList("cl_merges", force=True):
return False
return True

@ -134,9 +134,8 @@ class Data:
cl_chroot_path = {'mode':"r", 'value':"/"} cl_chroot_path = {'mode':"r", 'value':"/"}
# program action # program action
# user - user profile generation # install, uninstall, merge, domain, undomain, system, desktop
# install / uninstall - install or uninstall program cl_action = {}
cl_pass_action = {}
# program state # program state
# specifies addition to cl_pass_action for needing # specifies addition to cl_pass_action for needing
@ -158,13 +157,13 @@ class Data:
# hasn't belong function # hasn't belong function
# (package_name == value of cl_belong_pkg) # (package_name == value of cl_belong_pkg)
cl_belong_pkg = {'mode':'r', 'official':True} cl_belong_pkg = {'mode':'r', 'official':True}
# vertical resolution for X server # vertical resolution for X server
os_x11_height = {'mode':"w"} os_x11_height = {'mode':"w"}
# horizontal resolution for X server # horizontal resolution for X server
os_x11_width = {'mode':"w"} os_x11_width = {'mode':"w"}
# the nearest standard size of image to current screen resolution # the nearest standard size of image to current screen resolution
os_x11_standart = {} os_x11_standart = {}
@ -180,5 +179,5 @@ class Data:
# on/off composite mode # on/off composite mode
os_x11_composite = {} os_x11_composite = {}
# on/off apply templates # programs have templates setup
cl_templates_set = {'mode':"w", 'value':"off"} cl_merges = {}

@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
__version__ = "2.2.0.0" __version__ = "2.2.0.0"
__app__ = "calculate-lib" __app__ = "calculate-lib"
@ -35,16 +34,6 @@ tr.setLanguage(sys.modules[__name__])
cl_overriding.printERROR = lambda x:filter(lambda y:color_print().printERROR(y), cl_overriding.printERROR = lambda x:filter(lambda y:color_print().printERROR(y),
str(x).splitlines()) str(x).splitlines())
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 writeLog: class writeLog:
"""Класс логгирования""" """Класс логгирования"""
logger = log("apply-templates", logger = log("apply-templates",
@ -88,69 +77,41 @@ class color_print(old_color_print, writeLog):
class DataVarsObject(cl_datavars.DataVars): class DataVarsObject(cl_datavars.DataVars):
"""Класс переменных для десктопа""" """Класс переменных для десктопа"""
def __init__(self, section): packagePath = "/usr/lib/calculate-2.2"
def __init__(self, nameProgram):
cl_datavars.DataVars.__init__(self) cl_datavars.DataVars.__init__(self)
self.section=section self.nameProgram = nameProgram
def findPathVars(self):
pymPath = os.path.join(self.packagePath, self.nameProgram, "pym")
if os.path.isdir(pymPath) and\
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:
importPath = os.path.abspath(pymPath)
if not importPath in sys.path:
sys.path.insert(0, importPath)
return True
return False
def importDataObject(self, **args): def importDataObject(self, **args):
'''Заполнить конфигурацию переменных, для десктопа''' '''Заполнить конфигурацию переменных, для десктопа'''
# Имя секции в calculate.env
#envSection = "calculate-desktop"
# заполнить переменные окружения алгоритмом по умолнанию # заполнить переменные окружения алгоритмом по умолнанию
self.importData(self.section, ('cl_vars_%s' %self.section, sectName = self.nameProgram.rpartition("-")[2]
'cl_fill_%s' %self.section)) self.importData(sectName, ('cl_vars_%s' %sectName,
'cl_fill_%s' %sectName))
self.flIniFile() self.flIniFile()
class shareUpdateConfigs(color_print, writeLog): class shareUpdateConfigs(color_print, writeLog):
"""Общие методы для обновления конфигурационных файлов""" """Общие методы для обновления конфигурационных файлов"""
patternBelongDir = re.compile("belong\(\)")
patternBelongName = re.compile("belong\(([^\(\)]+)\)")
patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*")
templatePaths = ['/usr/share/calculate/templates',
'/var/calculate/templates',
'/var/calculate/remote/templates']
firstEnvFile = "/etc/calculate/calculate2.env"
reCleanVer = re.compile("\d+\.?\d*\.?\d*") reCleanVer = re.compile("\d+\.?\d*\.?\d*")
def _isApplyTemplateDir(self, scanDir, nameProgram, flagSkipDesktop=True, def getPrograms(self):
flagDir=False): """Получаем установленные программы работающие с шаблонами"""
"""Есть ли шаблоны в директории scanDir для пакета nameProgram clVars = cl_datavars.DataVars()
clVars.flIniFile()
выдает True, False return clVars.GetList("cl_merges")
"""
ret = False
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)
statInfo = os.stat(absPath)[stat.ST_MODE]
if stat.S_ISREG(statInfo):
textFile = open(absPath).read()
if flagSkipDesktop and\
"cl_pass_action==desktop" in textFile:
break
if self.patternBelongDir.search(textFile):
ret = os.path.basename(os.path.dirname(absPath))
if ret == nameProgram:
ret = True
break
else:
ret = False
else:
searchObj = self.patternBelongName.search(textFile)
if searchObj:
ret = searchObj.group(1)
if ret == nameProgram:
ret = True
break
else:
ret = False
elif stat.S_ISDIR(statInfo):
ret = self._isApplyTemplateDir(absPath, nameProgram, True,
flagSkipDesktop)
if ret:
break
return ret
class updateUserConfigs(shareUpdateConfigs): class updateUserConfigs(shareUpdateConfigs):
"""Обновление пользовательских конфигурационных файлов""" """Обновление пользовательских конфигурационных файлов"""
@ -172,25 +133,6 @@ class updateUserConfigs(shareUpdateConfigs):
return False return False
return xUsers return xUsers
def _getUserTemplateDirs(self, scanDir, userTemplDirs=[], flagDir=False):
"""Находит в директории scanDir директории шаблонов для пользователя
выдает найденные директории.
"""
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)
statInfo = os.stat(absPath)[stat.ST_MODE]
if stat.S_ISREG(statInfo):
textFile = open(absPath).read()
if "cl_pass_action==desktop" in textFile:
userTemplDirs.append(scanDir)
break
elif stat.S_ISDIR(statInfo):
self._getUserTemplateDirs(absPath, userTemplDirs, True)
return userTemplDirs
def updateConfig(self, nameProgram, category, version, xUsers): def updateConfig(self, nameProgram, category, version, xUsers):
"""Обновление конфигурационных файлов у пользователей""" """Обновление конфигурационных файлов у пользователей"""
cleanVer = self.reCleanVer.search(version) cleanVer = self.reCleanVer.search(version)
@ -198,57 +140,43 @@ class updateUserConfigs(shareUpdateConfigs):
version = cleanVer.group() version = cleanVer.group()
self.logger.info(_("Package %s") %nameProgram) self.logger.info(_("Package %s") %nameProgram)
self.logger.info(_("Update desktop configuration files")) self.logger.info(_("Update desktop configuration files"))
if not os.path.exists(self.firstEnvFile): # Программы используемые для наложения шаблонов
self.printWARNING(_("File '%s' does not exist")%self.firstEnvFile) mergePrograms = self.getPrograms()
return True if "calculate-desktop" in mergePrograms:
if not os.access(self.firstEnvFile, os.R_OK): mergePrograms = ["calculate-desktop"]
self.printWARNING(_("Permission denied: '%s'")%self.firstEnvFile) else:
return True mergePrograms = []
sectionsWork = []
for line in open(self.firstEnvFile).readlines():
sRet = self.patternSect.search(line)
if sRet:
sectionsWork.append(sRet.group(1))
sectName = "desktop"
dictPakkages = {} dictPakkages = {}
# Если установлен calculate-desktop # Добавление условия, что программа category/nameProgram
if sectName in sectionsWork: # установлена
section = "" cl_template.templateFunction.installProg.update(\
for templatePath in self.templatePaths:
fullPath = os.path.join(templatePath,sectName)
if os.path.isdir(fullPath):
for foundUserPath in self._getUserTemplateDirs(fullPath):
if self._isApplyTemplateDir(foundUserPath, nameProgram,
flagSkipDesktop=False):
section = sectName
break
if section:
# Добавление условия, что программа category/nameProgram
# установлена
cl_template.templateFunction.installProg.update(\
{"%s/%s"%(category,nameProgram):[version], {"%s/%s"%(category,nameProgram):[version],
"%s"%(nameProgram):[version]}) "%s"%(nameProgram):[version]})
for userName in xUsers: for mergeProgram in mergePrograms:
clVars = DataVarsObject(section) for userName in xUsers:
clVars.importDataObject() clVars = DataVarsObject(mergeProgram)
clVars.Set("ur_login", userName, True) if not clVars.findPathVars():
clVars.Set("cl_pass_action", section, True) continue
clVars.Set("cl_belong_pkg", nameProgram, True) clVars.importDataObject()
clTempl = cl_template.template(clVars) clVars.Set("ur_login", userName, True)
dirsFiles = clTempl.applyTemplates() clVars.Set("cl_action", "desktop", True)
if dirsFiles is False: clVars.Set("cl_belong_pkg", nameProgram, True)
self.printERROR(\ clTempl = cl_template.template(clVars)
_("Error using templates for the user %s")%userName) dirsFiles = clTempl.applyTemplates()
for errMess in clTempl.getError().splitlines(): if dirsFiles is False:
self.printERROR(errMess) self.printERROR(\
return False _("Error using templates for the user %s")\
if dirsFiles and dirsFiles[1]: %userName)
nameAndVerPkg = clVars.Get("cl_name")+"-"+\ for errMess in clTempl.getError().splitlines():
clVars.Get("cl_ver") self.printERROR(errMess)
if not nameAndVerPkg in dictPakkages: return False
dictPakkages[nameAndVerPkg] = [] if dirsFiles and dirsFiles[1]:
dictPakkages[nameAndVerPkg].append((userName, nameAndVerPkg = clVars.Get("cl_name")+"-"+\
sorted(list(set(dirsFiles[1]))))) clVars.Get("cl_ver")
if not nameAndVerPkg in dictPakkages:
dictPakkages[nameAndVerPkg] = []
dictPakkages[nameAndVerPkg].append((userName,
sorted(list(set(dirsFiles[1])))))
if dictPakkages: if dictPakkages:
for calcPkg in dictPakkages: for calcPkg in dictPakkages:
self.printWARNING(_("Package %s has changed files")\ self.printWARNING(_("Package %s has changed files")\
@ -292,37 +220,21 @@ class updateSystemConfigs(shareUpdateConfigs):
if not os.path.exists(configPath): if not os.path.exists(configPath):
self.printERROR(_("Path '%s' does not exist")%configPath) self.printERROR(_("Path '%s' does not exist")%configPath)
return False return False
if not os.path.exists(self.firstEnvFile): # Программы используемые для наложения шаблонов
self.printWARNING(_("File '%s' does not exist")%self.firstEnvFile) mergePrograms = self.getPrograms()
return True
if not os.access(self.firstEnvFile, os.R_OK):
self.printWARNING(_("Permission denied: '%s'")%self.firstEnvFile)
return True
sections = []
sectionsWork = []
for line in open(self.firstEnvFile).readlines():
sRet = self.patternSect.search(line)
if sRet:
sectionsWork.append(sRet.group(1))
#sectionsWork = os.listdir(self.templatePaths[0])
for sectName in sectionsWork:
for templatePath in self.templatePaths:
fullPath = os.path.join(templatePath,sectName)
if not sectName in sections and os.path.isdir(fullPath):
if self._isApplyTemplateDir(fullPath, nameProgram):
sections.append(sectName)
dictPakkages = {} dictPakkages = {}
if sections: # Добавление условия, что программа category/nameProgram установлена
# Добавление условия, что программа category/nameProgram установлена cl_template.templateFunction.installProg.update(\
cl_template.templateFunction.installProg.update(\ {"%s/%s"%(category,nameProgram):[version],
{"%s/%s"%(category,nameProgram):[version], "%s"%(nameProgram):[version]})
"%s"%(nameProgram):[version]}) for mergeProgram in mergePrograms:
for sectName in sections: clVars = DataVarsObject(mergeProgram)
clVars = DataVarsObject(sectName) if not clVars.findPathVars():
continue
clVars.importDataObject() clVars.importDataObject()
clVars.Set("cl_root_path",configPath, True) clVars.Set("cl_root_path", configPath, True)
clVars.Set("cl_belong_pkg",nameProgram, True) clVars.Set("cl_belong_pkg", nameProgram, True)
clVars.Set("cl_action", 'merge', True)
clTempl = cl_template.template(clVars) clTempl = cl_template.template(clVars)
dirsFiles = clTempl.applyTemplates() dirsFiles = clTempl.applyTemplates()
nameAndVerPkg = clVars.Get("cl_name")+"-"+clVars.Get("cl_ver") nameAndVerPkg = clVars.Get("cl_name")+"-"+clVars.Get("cl_ver")

Loading…
Cancel
Save