Merge branch 'master' of git.calculate.ru:/calculate-lib

Conflicts:
	pym/cl_datavars.py
	pym/cl_template.py
develop
Самоукин Алексей 14 years ago
commit abb72d0c59

@ -17,6 +17,7 @@
import os
import sys
import cl_utils
import re
from cl_lang import lang
from cl_template import iniParser
from cl_string import columnWrite
@ -36,7 +37,7 @@ class var:
# Для какой программы переменная
service = None
# значение переменной
value = ""
value = None
# режим записи (атрибут mode)
mode = "r"
# переменная для внутреннего использования (official)
@ -101,10 +102,9 @@ class var:
return self.value
def Fill(self):
"""Заполнение переменной в далнейшем заменяем методом заполнения"""
"""Заполнение переменной в дальнейшем заменяем методом заполнения"""
return self.value
class DataVars(object):
"""Класс хранения переменных шаблонов"""
@ -339,7 +339,8 @@ class DataVars(object):
_("Unable to find the alias '%s' of the file path for \
storage of variables templates")%location)
cl_overriding.exit(1)
return name_calculate_ini
name_calculate_ini = name_calculate_ini.strip('/')
return os.path.join(self.Get('cl_chroot_path'),name_calculate_ini)
def __getSection(self, vname):
"""секция для записи в ini файл переменной
@ -652,3 +653,75 @@ class glob_attr:
if not retCode:
return programOut
return False
def get_composite_from_xorgconf(self,chroot="/"):
xorgConfig = os.path.join(chroot,
"etc/X11/xorg.conf")
try:
confLines = open(xorgConfig,"r").readlines()
except:
return None
flagStartExtensions = False
lineCompositeTmp = ""
lineComposite = ""
for line in confLines:
if flagStartExtensions:
if 'EndSection' in line:
lineComposite = lineCompositeTmp
break
elif 'Section' in line:
break
if 'Option' in line and '"Composite"' in line:
lineCompositeTmp = line
else:
if '"Extensions"' in line and 'Section' in line:
flagStartExtensions = True
if lineComposite:
listOpt = filter(lambda x: x.strip(), lineComposite.split('"'))
if len(listOpt) == 3:
ret = listOpt[2].lower()
if ret in ("on","true","yes","1"):
return "on"
elif ret in ("off","false","no","0"):
return "off"
return None
def getValueFromCmdLine(self,option,num):
"""Get value of parameter from boot params
Parameters:
option param name
num number part of value parameter (, split)
"""
cmdLine = "/proc/cmdline"
calculateParam = "calculate"
# try get timezone from kernel calculate param
try:
for param in open(cmdLine,"r").read().split(" "):
parname,op,value = param.partition("=")
if parname == calculateParam and op == "=":
values = value.split(",")
if len(values) > num and values[num].strip():
return values[num].strip()
except IOError,e:
return ""
def getValueFromConfig(self,config,name):
"""Get value of parameter from bash type file
Parameters:
config config file name
name param name
"""
reMatch = re.compile("^%s\s*=\s*\"?(.*)\"?$"%name, re.I)
try:
if os.path.exists(config):
for line in open(config,"r").readlines():
match = reMatch.match(line)
if match:
return group().strip()
except:
pass
return False

@ -23,6 +23,7 @@ import cl_overriding
from cl_ldap import ldapUser
from cl_datavars import glob_attr
from os.path import exists as pathexists
class clLocale:
lang = {
@ -35,6 +36,15 @@ class clLocale:
'xkblayout':'us,by',
'language':'ru',
},
#Bulgarian
'bg_BG' : {
'locale':'bg_BG.UTF-8',
'keymap':'bg_bds-utf8',
'dumpkeys_charset': '',
'consolefont':'ter-m14n',
'xkblayout':'us,bg',
'language':'bg',
},
#Belgian
'fr_BE' : {
'locale':'fr_BE.UTF-8',
@ -265,8 +275,24 @@ class fillVars(glob_attr):
else:
return domain
dictLinuxName = {"CLD":"Calculate Linux Desktop",
"CLDX":"Calculate Linux Desktop",
"CLDG":"Calculate Linux Desktop",
"CDS":"Calculate Directory Server",
"CLS":"Calculate Linx Scratch",
"CSS":"Calculate Scratch Server",
"Gentoo":"Gentoo"}
def get_os_linux_shortname(self):
'''Получить переменную короткого названия системы'''
makeprofile = '/etc/make.profile'
if os.path.exists(makeprofile):
link = os.readlink(makeprofile)
reMakeProfileLink = re.compile('calculate/(desktop|server)/(%s)'%
"|".join(self.dictLinuxName.keys()),re.S)
shortnameSearch = reMakeProfileLink.search(link)
if shortnameSearch:
return shortnameSearch.groups()[1]
path = '/etc/calculate/calculate.ini'
if os.path.exists(path):
FD = open(path)
@ -289,15 +315,8 @@ class fillVars(glob_attr):
"""полное название системы"""
linuxShortName = self.Get("os_linux_shortname")
if linuxShortName:
dictLinuxName = {"CLD":"Calculate Linux Desktop",
"CLDX":"Calculate Linux Desktop",
"CLDG":"Calculate Linux Desktop",
"CDS":"Calculate Directory Server",
"CLS":"Calculate Linx Scratch",
"CSS":"Calculate Scratch Server",
"Gentoo":"Gentoo"}
if linuxShortName in dictLinuxName.keys():
return dictLinuxName[linuxShortName]
if linuxShortName in self.dictLinuxName.keys():
return self.dictLinuxName[linuxShortName]
else:
return "Linux"
else:
@ -316,7 +335,21 @@ class fillVars(glob_attr):
return ""
def get_os_linux_ver(self):
'''Получить версию системы'''
'''Get system version'''
def get_from_metapackage():
"""Get version from meta package"""
shortname = self.Get('os_linux_shortname')
metaPkgs = filter(lambda x:"%s-meta"%shortname.lower() in x,
os.listdir('/var/db/pkg/app-misc/'))
if metaPkgs:
reFindVer = re.compile("(?<=\-)\d+\.?\d*\.?\d*")
findVer = reFindVer.search(metaPkgs[0])
if findVer:
return findVer.group()
return None
def get_from_calculate_ini():
"""Get version from calculate ini"""
path = '/etc/calculate/calculate.ini'
if os.path.exists(path):
FD = open(path)
@ -329,19 +362,24 @@ class fillVars(glob_attr):
x.split("=")[1].strip(), data))
if shortNameList:
return shortNameList[0]
def get_from_gentoo_files():
"""Get version from gentoo files"""
gentooFile = "/etc/gentoo-release"
systemVersion = ""
flagGentoo = False
if os.path.exists(gentooFile):
gentooLink = "/etc/make.profile"
if os.path.islink(gentooLink):
systemVersion = os.readlink(gentooLink).rpartition("/")[2]
flagGentoo = True
if not flagGentoo:
return os.readlink(gentooLink).rpartition("/")[2]
def get_from_uname():
"""Get version from uname"""
kernelVersion=self._runos("uname -r")
if kernelVersion:
systemVersion = kernelVersion.partition("-")[0]
return systemVersion
return kernelVersion.partition("-")[0]
return get_from_metapackage() or get_from_calculate_ini() or \
get_from_gentoo_files() or get_from_uname() or "0"
def get_os_net_hostname(self):
'''Считать имя компьютера net_host'''
@ -418,13 +456,6 @@ class fillVars(glob_attr):
return ""
return ",".join(networks)
def get_os_locale_xkbname(self):
"""названия используемых раскладок клавиатуры для X"""
localeXkb = self.Get("os_locale_xkb")
if localeXkb:
return localeXkb.split("(")[0]
return ""
def get_os_arch_machine(self):
"""архитектура процессора"""
march = self._runos("uname -m")
@ -503,44 +534,6 @@ class fillVars(glob_attr):
break
return virtName
def getValueFromConfig(self,config,name):
"""Get value of parameter from bash type file
Parameters:
config config file name
name param name
"""
reMatch = re.compile("^%s\s*=\s*\"?(.*)\"?$"%name, re.I)
try:
if os.path.exists(config):
for line in open(config,"r").readlines():
match = reMatch.match(line)
if match:
return group().strip()
except:
pass
return False
def getValueFromCmdLine(self,option,num):
"""Get value of parameter from boot params
Parameters:
option param name
num number part of value parameter (, split)
"""
cmdLine = "/proc/cmdline"
calculateParam = "calculate"
# try get timezone from kernel calculate param
try:
for param in open(cmdLine,"r").read().split(" "):
parname,op,value = param.partition("=")
if parname == calculateParam and op == "=":
values = value.split(",")
if len(values) > num and values[num].strip():
return values[num].strip()
except IOError,e:
return ""
def get_hr_board_model(self):
"""motherboard model"""
modelFile = "/sys/class/dmi/id/board_name"
@ -591,65 +584,15 @@ class fillVars(glob_attr):
def get_os_locale_xkb(self):
"""xkb layouts (example: en,ru)"""
locale = clLocale()
# is specified keymap support by locale hash
if self.Get('os_locale_keymap') in locale.getFields('keymap'):
return locale.getFieldByKeymap("xkblayout",
self.Get('os_locale_keymap'))
else:
return locale.getFieldByLang("xkblayout",
self.Get('os_locale_lang'))
def get_os_locale_keymap(self):
"""keymap of locale (used for /etc/conf.d/keymaps)"""
locale = clLocale()
# get keymap from boot calculate param (keymap specified
# by lang)
keymapConfd = '/etc/conf.d/keymaps'
keymap = self.getValueFromCmdLine("calculate",1)
if locale.isLangExists(keymap):
return locale.getFieldByLang('keymap',keymap)
# get keymap by os_locale_lang
keymap = self.getValueFromConfig(keymapConfd,'KEYMAP')
if keymap:
return keymap
return locale.getFieldByLang("keymap",self.Get("os_locale_lang"))
def get_os_locale_dumpkeys(self):
"""dumpkeys charset for keymap"""
locale = clLocale()
# is specified keymap support by locale hash
if self.Get('os_locale_keymap') in locale.getFields('keymap'):
return locale.getFieldByKeymap("dumpkeys_charset",
self.Get('os_locale_keymap'))
else:
return locale.getFieldByLang("dumpkeys_charset",
self.Get('os_locale_lang'))
def get_os_clock_timezone(self):
"""timezone for clock"""
zoneinfodir = "/usr/share/zoneinfo/"
localtimefile = "/etc/localtime"
# try get timezone from kernel calculate param
timezone = self.getValueFromCmdLine("calculate",2)
if timezone and \
os.path.exists(os.path.join(zoneinfodir,timezone)):
return timezone
# get timezone from localtime symlink
if os.path.lexists(localtimefile):
return os.readlink(localtimefile).replace(zoneinfodir,"")
return "UTC"
def get_os_clock_type(self):
"""type of clock (UTC or local)"""
clockTypeFile = ['/etc/conf.d/clock','/etc/conf.d/hwclock']
for f in clockTypeFile:
clock = self.getValueFromConfig(f,"clock")
if clock:
if clock.upper() == 'UTC':
return clock.upper()
elif clock.lower() == 'local':
return clock.lower()
return "local"
def get_os_locale_xkbname(self):
"""названия используемых раскладок клавиатуры для X"""
localeXkb = self.Get("os_locale_xkb")
if localeXkb:
return localeXkb.split("(")[0]
return ""
def get_ur_login(self):
"""Имя пользователя"""
@ -745,16 +688,22 @@ class fillVars(glob_attr):
else:
return ""
def get_hr_x11_video_drv(self):
def get_os_x11_video_drv(self):
"""Get video driver used by xorg"""
xorg_modules_dir = '/usr/lib/xorg/modules/drivers'
xorg_conf = '/etc/X11/xorg.conf'
# Try analize Xorg.{DISPLAY}.log
display = os.environ.get('DISPLAY')
if display and os.path.exists(xorg_modules_dir):
list_avialable_drivers = os.listdir(xorg_modules_dir)
if list_avialable_drivers:
reDriver = re.compile('|'.join(list_avialable_drivers))
if pathexists(xorg_modules_dir):
list_avialable_drivers = \
map(lambda x: x[:-7],
filter(lambda x: x.endswith('_drv.so'),
os.listdir(xorg_modules_dir)))
else:
list_avialable_drivers = []
if display and list_avialable_drivers:
reDriver = re.compile('|'.join(map(lambda x: "%s_drv.so"%x,
list_avialable_drivers)))
display_number = re.search(r':(\d+)\..*', display)
if display_number:
xorg_log_file = '/var/log/Xorg.%s.log' % \
@ -777,8 +726,130 @@ class fillVars(glob_attr):
matchSect.group(0),re.S)
if resDriver:
return resDriver.group(1)
defaultDriver = {
'vesa':'vesa',
'nvidia':'nvidia' if "nvidia" in list_avialable_drivers else "nv",
'ati':'fglrx' if "fglrx" in list_avialable_drivers else "radeon",
'intel':'intel',
'via':'via',
'vmware':'vmware'}
hr_video = self.Get('hr_video')
if hr_video in defaultDriver and \
defaultDriver[hr_video] in list_avialable_drivers:
return defaultDriver[hr_video]
else:
return "vesa"
def getX11Resolution(self):
"""возвращает текущее разрешение экрана (ширина, высота), X запущен"""
lines=self._runos("xdpyinfo")
if not lines:
return ""
reRes = re.compile("dimensions:\s+(\d+)x(\d+)\s+pixels")
searchRes=False
for line in lines:
searchRes = reRes.search(line)
if searchRes:
break
if searchRes:
return (searchRes.group(1), searchRes.group(2))
else:
return ""
def get_os_x11_height(self):
"""Получить высоту экрана в пикселах"""
resolution = self.getX11Resolution()
if resolution:
self.Set('os_x11_width',resolution[0])
return resolution[1]
return "768"
def get_os_x11_width(self):
"""Получить ширину экрана в пикселах"""
resolution = self.getX11Resolution()
if resolution:
self.Set('os_x11_height',resolution[1])
return resolution[0]
return "1024"
def get_os_x11_standart(self):
"""Get the nearest standard size of image relative current
screen resolution"""
#Стандартные разрешения
widthVal = self.Get('os_x11_width')
heightVal = self.Get('os_x11_height')
if not widthVal or not heightVal:
return ""
width = int(widthVal)
height = int(heightVal)
res = [(1024,768),
(1280,1024),
(1280,800),
(1440,900),
(1600,1200),
(1680,1050),
(1920,1200)]
resolution = []
formats = []
for w, h in res:
formats.append(float(w)/float(h))
listFr = list(set(formats))
listFormats = {}
for fr in listFr:
listFormats[fr] = []
for w, h in res:
for fr in listFormats.keys():
if fr == float(w)/float(h):
listFormats[fr].append((w,h))
break
format = float(width)/float(height)
deltaFr = {}
for fr in listFormats.keys():
deltaFr[abs(format - fr)] = fr
resolution = listFormats[deltaFr[min(deltaFr.keys())]]
flagFound = False
stResol = []
stHeights = []
stWidths = []
stWidth = False
stHeight = False
for w, h in resolution:
if w >= width and h >= height:
stResol.append((w,h))
stHeights.append(h)
if stHeights:
stHeight = min(stHeights)
for w, h in stResol:
if stHeight == h:
stWidths.append(w)
if stWidths:
stWidth = min(stWidths)
if (not stWidth) or (not stHeight):
return "%sx%s"%(resolution[-1][0],resolution[-1][1])
else:
return "%sx%s"%(stWidth,stHeight)
def get_os_x11_composite(self):
"""Включен ли композитный режим видеокарты on/off"""
state = self.get_composite_from_xorgconf()
return state or "off"
def get_hr_laptop(self):
"""Если компьютер ноутбук, то его производитель"""
formfactor = self._runos("hal-get-property --udi \
/org/freedesktop/Hal/devices/computer --key system.formfactor")
if not formfactor:
return ""
if formfactor == 'laptop':
vendor = self._runos("hal-get-property --udi \
/org/freedesktop/Hal/devices/computer --key system.hardware.vendor")
if vendor:
vendor = vendor.split(" ")[0]
else:
vendor = "unknown"
return vendor.lower()
return ""
def get_hr_video(self):
"""Производитель видеокарты"""
lines=self._runos("lspci")

@ -68,7 +68,7 @@ class lang:
#self.nameDomain = ''
""" Название файла перевода (Домен) если используется 1 файл перевода
"""
self.__catalog = os.path.abspath('/usr/share/calculate-2.2/i18n')
self.__catalog = os.path.abspath('/usr/share/calculate/i18n')
""" Путь к каталогу переводов (в этом каталоге
ru_RU/LC_MESSAGES в котором файл перевода)
"""

@ -217,10 +217,9 @@ class opt(optparse.OptionParser):
'action':'append',
'help':_("set value for variable (comma - delimeter)")
},
{'longOption':"vars",
'optVal':"TYPE_VAR",
'help':_("print variables") + " (TYPE_VAR - all: " + \
_("full variables list") +")"
{'shortOption':"v",
'longOption':"vars",
'help':_("print variables")
}]
color_control = \
@ -292,7 +291,9 @@ class opt(optparse.OptionParser):
should either exit or raise an exception.
"""
self.print_usage(sys.stderr)
self.exit(2, "%s: %s: %s\n" % (self.get_prog_name(), _("error"), msg))
self.exit(2, "%s: %s: %s\n%s\n" % (self.get_prog_name(), _("error"), msg,
_("Try `%s' for more information")%
("%s --help"%self.get_prog_name())))
def checkVarSyntax(self,values):
"""Check value of parameter set, was used for change vars"""

@ -317,7 +317,7 @@ class tableReport:
strList.append(self.columnsWidth[i])
return strList
def printReport(self):
def printReport(self,printRows=True):
"""Напечатать данные в табличном виде"""
cl_overriding.printSUCCESS(self.title)
listStrSep = []
@ -342,6 +342,7 @@ class tableReport:
char ="-+-"
convLines.append(self._insertStrChar(lines[i], lenCols, char))
cl_overriding.printSUCCESS("\n".join(convLines))
if printRows:
cl_overriding.printSUCCESS("(%s %s)"%(len(self.dataList), _("rows")))
def _insertStrChar(self, line, lenCols, char):

@ -3120,10 +3120,10 @@ os_disk_install not found mount point '\' and '\%s'")%mountPoint)
reGrubEntry = re.compile("title.*?(?=title|$)", re.S | re.I )
grubconf = reRemoveComments.sub("",open(pathGrubConf,'r').read())
roothd = filter(lambda x: x[1] == '/',
zip(self.objVar.Get('os_disk_grub'),
zip(self.objVar.Get('os_disk_dev'),
self.objVar.Get('os_install_disk_mount')))
if roothd:
roothd = "root (hd%s)" % roothd[0][0]
roothd = "root=%s" % roothd[0][0]
replace = ("".join(filter(lambda x: not roothd in x,
reGrubEntry.findall(grubconf)))).strip()
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
@ -4231,6 +4231,8 @@ re.M|re.S)
"%s -> %s"%(prevOldFile, pathOldFile))
return ([], False)
if not objHeadNew.body.strip():
if pathProg:
os.chdir(pathProg)
return ([], False)
else:
applyFiles = [pathOldFile]

@ -27,6 +27,7 @@ import cl_overriding
import re
import sys
import getpass
from types import StringType
import cl_lang
tr = cl_lang.lang()
@ -447,3 +448,30 @@ incorrect option 'flag=%s'")%flag)
return False
userPwd = pwdA
return userPwd
def cmpVersion(v1,v2):
"""Compare versions specified by tuple or string"""
if isinstance(v1,StringType):
v1 = getTupleVersion(v1)
if isinstance(v2,StringType):
v2 = getTupleVersion(v2)
return cmp((v1[0]+[0,]*(len(v2[0])-len(v1[0])),v1[1]),
(v2[0]+[0,]*(len(v1[0])-len(v2[0])),v2[1]))
def getTupleVersion(ver):
"""Get version specified by string as list:
Example:
2.6.30 [(2,6,30),('r',0)]
2.6.31-r1 [(2,6,31),('r',1)]
"""
suffix_value = {"pre": -2, "p": 0, "alpha": -4, "beta": -3,
"rc": -1}
def toTuple(v):
return map(lambda x: suffix_value[x] if x in suffix_value else x,
map(lambda x: int(x) if x.isdigit() else x,
re.findall("r\d+$|\d+|[a-zA-Z+]+",
v.replace('-SNAPSHOT',''))))
vers, revision = re.search("(^.*?)(-r\d+)?$",ver,re.S).groups()
vers = toTuple(vers)
revision = toTuple(revision or "r0")
return [vers,revision]

@ -14,99 +14,86 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#Допустимые ключи значений
# mode - режим переменной r-не переназначается из командной строки,
# w-переназначается из командной строки
# type - тип переменной состоит из двух элементов(что это и для чего
# это)
# value - значение переменной
# official - флаг того, что данная переменная служебная и не отображается
# при печати списка значений переменных
#Allowed keys
# mode - variable mode: 'w' - you can change value from command line,
# 'r' you cann't change value from command line
# type - depricated
# value - value
# official - show or not variable for display values
class Data:
# имя компьютера
# computer hostname
os_net_hostname = {'mode':"w"}
# разрешенные сети
# allowed networks
os_net_allow ={}
# ip на всех интерфейсах
# ip for all network interfaces (comma delimeter)
os_net_ip ={}
# Существующие сетевые интерфейсы
# network interfaces
os_net_interfaces={'official':True}
#короткое название системы (CLD)
os_linux_shortname={}
#домен
# computer domain
os_net_domain = {'mode':"w"}
# Алиасы и пути к ini файлам
# short system name (CLD)
os_linux_shortname={}
# aliases and path to ini files
cl_env_data = {'official':True,
'value':[('default', '/etc/calculate/calculate2.env'),
('local', '/var/calculate/calculate2.env'),
('remote', '/var/calculate/remote/calculate2.env')]}
# Алиасы путей к ini файлам (из cl_env_data)
# path aliases to ini files (from cl_env_data)
cl_env_location = {'official':True}
# Пути к ini файлам (из cl_env_data)
# path to ini files (from cl_env_data)
cl_env_path = {}
# Путь к информационному файлу сервера
# path to information file on server
cl_env_server_path = {'official':True,
'value':'/var/calculate/remote/server.env'}
# Пути к файлам шаблонов
cl_template_path = {'value':["/usr/share/calculate-2.2/templates",
# paths to template files
cl_template_path = {'value':["/usr/share/calculate/templates",
"/var/calculate/templates",
"/var/calculate/remote/templates"]}
# Пути к файлам шаблонов clt
cl_template_clt_path = {'value':""}
# локаль (прим: ru_RU.UTF-8)
# paths to clt-template files
cl_template_clt_path = {}
# locale (at example: ru_RU.UTF-8)
os_locale_locale = {}
# язык (прим: ru_RU)
# full language (at example: ru_RU)
os_locale_lang = {}
# язык (прим: ru)
# short language (at example ru)
os_locale_language = {}
# раскладка клавиатуры для X
# keyboard layout for X server
os_locale_xkb = {}
# названия используемых раскладок клавиатуры для X
# keyboard layout name for X server
os_locale_xkbname = {}
# keymap of locale (used for /etc/conf.d/keymaps)
os_locale_keymap = {}
# dumpkeys_charset for keymap
os_locale_dumpkeys = {}
# timezone for clock
os_clock_timezone = {}
# type of clock (UTC or local)
os_clock_type = {}
# архитектура компьютера (i686,x86_64)
# computer architecture (i686,x86_64)
os_arch_machine = {}
#проход при наложении профилей 1,2,3,4,5 и.т д
# pass for templates join 1,2,3,4,5 and etc
cl_pass_step = {}
# обрабатываемый файл профиля
# template file performed at now
cl_pass_file = {'mode':"w"}
# корневой раздел файловой системы
# root partition of filesystem
os_root_dev = {}
# тип носителя (ram, hdd, usb-hdd, livecd)
# root type (ram, hdd, usb-hdd, livecd)
os_root_type = {}
# полное название системы
# full system name
os_linux_name = {}
# постфикс к названию системы
# postfix to system name (KDE GNOME and etc)
os_linux_subname = {}
# system (desktop or server)
@ -121,60 +108,74 @@ class Data:
# processors count
hr_cpu_num = {}
# название виртуальной машины (virtualbox, vmware, qemu)
# virtual machine name (virtualbox, vmware, qemu)
hr_virtual = {}
# версия системы
# system version
os_linux_ver = {}
# Логин пользователя
# user login
ur_login = {}
# Название группы пользователя
# user group name
ur_group = {'official':True}
#Полное имя пользователя
# user fullname
ur_fullname = {'official':True}
# Домашняя директория пользователя
# user home directory
ur_home_path = {'official':True}
# Путь к директории относительно которой происходит наложение профилей на
#файлы системы (песочница)
# path to directory relative which perform joining templates to system files
# (sandbox)
cl_root_path = {'mode':"w", 'value':"/"}
# Путь к директории другой системы
cl_chroot_path = {'mode':"w", 'value':"/"}
# path to directory which contain other system
cl_chroot_path = {'mode':"r", 'value':"/"}
# Действие программы
# user - генерация профиля пользователя
# install / uninstall - установка и удаление программы
# program action
# user - user profile generation
# install / uninstall - install or uninstall program
cl_pass_action = {}
# Состояние программы
# Указываем дополнительно к cl_pass_action в случае необходимости
# program state
# specifies addition to cl_pass_action for needing
cl_pass_state = {}
# Jabber ID пользователя
# User Jabber ID
ur_jid = {'official':True}
# Почтовый адрес пользователя
# user email
ur_mail = {'official':True}
# Переменные пакета calculate-client для calculate-desktop
# ip или имя домена (под управлением calculate-server)
# variable for calculate-client and calculate-desktop packages
# ip or domain name of CDS
cl_remote_host = {'mode':'r', 'official':True}
# Переменная работающая совместно с функцией шаблонов belong(имя_пакета)
# Если переменная будет определена то будут использованы шаблоны
# у которых параметр имя пакета функции шаблонов belong(имя_пакета)
# совпадает с значением этой переменной
# (имя_пакета == значение cl_belong_pkg)
# this variable work with template function belong(package_name)
# if the variable is defined then will use only template, which
# has package_name in belong equal value of this variable or
# hasn't belong function
# (package_name == value of cl_belong_pkg)
cl_belong_pkg = {'mode':'r', 'official':True}
# Название производителя видеокарты
hr_video = {'official':True}
# vertical resolution for X server
os_x11_height = {'mode':"w"}
# horizontal resolution for X server
os_x11_width = {'mode':"w"}
# the nearest standard size of image to current screen resolution
os_x11_standart = {}
# if computer is noteboot, the this variable containt its vendor
hr_laptop = {}
# video verdor name
hr_video = {}
# Video driver used by xorg
hr_x11_video_drv = {'official':True}
os_x11_video_drv = {}
# on/off composite mode
os_x11_composite = {}

@ -106,11 +106,12 @@ class shareUpdateConfigs(color_print, writeLog):
patternBelongDir = re.compile("belong\(\)")
patternBelongName = re.compile("belong\(([^\(\)]+)\)")
patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*")
templatePaths = ['/usr/share/calculate-2.2/templates',
templatePaths = ['/usr/share/calculate/templates',
'/var/calculate/templates',
'/var/calculate/remote/templates']
firstEnvFile = "/etc/calculate/calculate2.env"
reCleanVer = re.compile("\d+\.?\d*\.?\d*")
def _isApplyTemplateDir(self, scanDir, nameProgram, flagSkipDesktop=True,
flagDir=False):
@ -192,6 +193,9 @@ class updateUserConfigs(shareUpdateConfigs):
def updateConfig(self, nameProgram, category, version, xUsers):
"""Обновление конфигурационных файлов у пользователей"""
cleanVer = self.reCleanVer.search(version)
if cleanVer:
version = cleanVer.group()
self.logger.info(_("Package %s") %nameProgram)
self.logger.info(_("Update desktop configuration files"))
if not os.path.exists(self.firstEnvFile):
@ -280,6 +284,9 @@ class updateSystemConfigs(shareUpdateConfigs):
def updateConfig(self, nameProgram, category, version, configPath):
"""Обновление системных конфигурационных файлов"""
cleanVer = self.reCleanVer.search(version)
if cleanVer:
version = cleanVer.group()
self.logger.info(_("Package %s") %nameProgram)
self.logger.info(_("Update system cofiguration files"))
if not os.path.exists(configPath):

@ -69,7 +69,7 @@ setup(
'calculate-lib.pym.server',
'calculate-lib.pym.client',
'calculate-lib.pym.update_config'],
data_files = [("/usr/share/calculate-2.2/i18n",['i18n/cl_lib_ru.mo']),
data_files = [("/usr/share/calculate/i18n",['i18n/cl_lib_ru.mo']),
("/var/calculate/remote",[])],
scripts=["./scripts/cl-update-config"],
cmdclass={'build_scripts':cl_build_scripts,

Loading…
Cancel
Save