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 os
import sys import sys
import cl_utils import cl_utils
import re
from cl_lang import lang from cl_lang import lang
from cl_template import iniParser from cl_template import iniParser
from cl_string import columnWrite from cl_string import columnWrite
@ -36,7 +37,7 @@ class var:
# Для какой программы переменная # Для какой программы переменная
service = None service = None
# значение переменной # значение переменной
value = "" value = None
# режим записи (атрибут mode) # режим записи (атрибут mode)
mode = "r" mode = "r"
# переменная для внутреннего использования (official) # переменная для внутреннего использования (official)
@ -86,7 +87,7 @@ class var:
if self.isCallFill: if self.isCallFill:
self.isSet = True self.isSet = True
return self.value return self.value
self.isCallFill = True self.isCallFill = True
self.value = self.Fill() self.value = self.Fill()
if self.dependValues and self.is_update(): if self.dependValues and self.is_update():
self.isCallFill = True self.isCallFill = True
@ -101,10 +102,9 @@ class var:
return self.value return self.value
def Fill(self): def Fill(self):
"""Заполнение переменной в далнейшем заменяем методом заполнения""" """Заполнение переменной в дальнейшем заменяем методом заполнения"""
return self.value return self.value
class DataVars(object): class DataVars(object):
"""Класс хранения переменных шаблонов""" """Класс хранения переменных шаблонов"""
@ -339,7 +339,8 @@ class DataVars(object):
_("Unable to find the alias '%s' of the file path for \ _("Unable to find the alias '%s' of the file path for \
storage of variables templates")%location) storage of variables templates")%location)
cl_overriding.exit(1) 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): def __getSection(self, vname):
"""секция для записи в ini файл переменной """секция для записи в ini файл переменной
@ -652,3 +653,75 @@ class glob_attr:
if not retCode: if not retCode:
return programOut return programOut
return False 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_ldap import ldapUser
from cl_datavars import glob_attr from cl_datavars import glob_attr
from os.path import exists as pathexists
class clLocale: class clLocale:
lang = { lang = {
@ -35,6 +36,15 @@ class clLocale:
'xkblayout':'us,by', 'xkblayout':'us,by',
'language':'ru', '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 #Belgian
'fr_BE' : { 'fr_BE' : {
'locale':'fr_BE.UTF-8', 'locale':'fr_BE.UTF-8',
@ -265,8 +275,24 @@ class fillVars(glob_attr):
else: else:
return domain 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): 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' path = '/etc/calculate/calculate.ini'
if os.path.exists(path): if os.path.exists(path):
FD = open(path) FD = open(path)
@ -289,15 +315,8 @@ class fillVars(glob_attr):
"""полное название системы""" """полное название системы"""
linuxShortName = self.Get("os_linux_shortname") linuxShortName = self.Get("os_linux_shortname")
if linuxShortName: if linuxShortName:
dictLinuxName = {"CLD":"Calculate Linux Desktop", if linuxShortName in self.dictLinuxName.keys():
"CLDX":"Calculate Linux Desktop", return self.dictLinuxName[linuxShortName]
"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]
else: else:
return "Linux" return "Linux"
else: else:
@ -316,32 +335,51 @@ class fillVars(glob_attr):
return "" return ""
def get_os_linux_ver(self): def get_os_linux_ver(self):
'''Получить версию системы''' '''Get system version'''
path = '/etc/calculate/calculate.ini' def get_from_metapackage():
if os.path.exists(path): """Get version from meta package"""
FD = open(path) shortname = self.Get('os_linux_shortname')
data = FD.readlines() metaPkgs = filter(lambda x:"%s-meta"%shortname.lower() in x,
FD.close() os.listdir('/var/db/pkg/app-misc/'))
shortNameList = filter(lambda y:y, if metaPkgs:
map(lambda x:\ reFindVer = re.compile("(?<=\-)\d+\.?\d*\.?\d*")
len(x.split("="))==2 and\ findVer = reFindVer.search(metaPkgs[0])
x.split("=")[0]=="linuxver" and\ if findVer:
x.split("=")[1].strip(), data)) return findVer.group()
if shortNameList: return None
return shortNameList[0]
gentooFile = "/etc/gentoo-release" def get_from_calculate_ini():
systemVersion = "" """Get version from calculate ini"""
flagGentoo = False path = '/etc/calculate/calculate.ini'
if os.path.exists(gentooFile): if os.path.exists(path):
gentooLink = "/etc/make.profile" FD = open(path)
if os.path.islink(gentooLink): data = FD.readlines()
systemVersion = os.readlink(gentooLink).rpartition("/")[2] FD.close()
flagGentoo = True shortNameList = filter(lambda y:y,
if not flagGentoo: map(lambda x:\
len(x.split("="))==2 and\
x.split("=")[0]=="linuxver" and\
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):
return os.readlink(gentooLink).rpartition("/")[2]
def get_from_uname():
"""Get version from uname"""
kernelVersion=self._runos("uname -r") kernelVersion=self._runos("uname -r")
if kernelVersion: if kernelVersion:
systemVersion = kernelVersion.partition("-")[0] return kernelVersion.partition("-")[0]
return systemVersion 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): def get_os_net_hostname(self):
'''Считать имя компьютера net_host''' '''Считать имя компьютера net_host'''
@ -418,13 +456,6 @@ class fillVars(glob_attr):
return "" return ""
return ",".join(networks) 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): def get_os_arch_machine(self):
"""архитектура процессора""" """архитектура процессора"""
march = self._runos("uname -m") march = self._runos("uname -m")
@ -503,44 +534,6 @@ class fillVars(glob_attr):
break break
return virtName 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): def get_hr_board_model(self):
"""motherboard model""" """motherboard model"""
modelFile = "/sys/class/dmi/id/board_name" modelFile = "/sys/class/dmi/id/board_name"
@ -591,65 +584,15 @@ class fillVars(glob_attr):
def get_os_locale_xkb(self): def get_os_locale_xkb(self):
"""xkb layouts (example: en,ru)""" """xkb layouts (example: en,ru)"""
locale = clLocale() locale = clLocale()
# is specified keymap support by locale hash return locale.getFieldByLang("xkblayout",
if self.Get('os_locale_keymap') in locale.getFields('keymap'): self.Get('os_locale_lang'))
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): def get_os_locale_xkbname(self):
"""keymap of locale (used for /etc/conf.d/keymaps)""" """названия используемых раскладок клавиатуры для X"""
locale = clLocale() localeXkb = self.Get("os_locale_xkb")
# get keymap from boot calculate param (keymap specified if localeXkb:
# by lang) return localeXkb.split("(")[0]
keymapConfd = '/etc/conf.d/keymaps' return ""
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_ur_login(self): def get_ur_login(self):
"""Имя пользователя""" """Имя пользователя"""
@ -745,28 +688,34 @@ class fillVars(glob_attr):
else: else:
return "" return ""
def get_hr_x11_video_drv(self): def get_os_x11_video_drv(self):
"""Get video driver used by xorg""" """Get video driver used by xorg"""
xorg_modules_dir = '/usr/lib/xorg/modules/drivers' xorg_modules_dir = '/usr/lib/xorg/modules/drivers'
xorg_conf = '/etc/X11/xorg.conf' xorg_conf = '/etc/X11/xorg.conf'
# Try analize Xorg.{DISPLAY}.log # Try analize Xorg.{DISPLAY}.log
display = os.environ.get('DISPLAY') display = os.environ.get('DISPLAY')
if display and os.path.exists(xorg_modules_dir): if pathexists(xorg_modules_dir):
list_avialable_drivers = os.listdir(xorg_modules_dir) list_avialable_drivers = \
if list_avialable_drivers: map(lambda x: x[:-7],
reDriver = re.compile('|'.join(list_avialable_drivers)) filter(lambda x: x.endswith('_drv.so'),
display_number = re.search(r':(\d+)\..*', display) os.listdir(xorg_modules_dir)))
if display_number: else:
xorg_log_file = '/var/log/Xorg.%s.log' % \ list_avialable_drivers = []
display_number.group(1) if display and list_avialable_drivers:
if os.path.exists(xorg_log_file): reDriver = re.compile('|'.join(map(lambda x: "%s_drv.so"%x,
matchStrs = [i for i in open(xorg_log_file) list_avialable_drivers)))
if "drv" in i and reDriver.search(i)] display_number = re.search(r':(\d+)\..*', display)
if matchStrs: if display_number:
resDriver = re.search(r'([^/]+)_drv.so', xorg_log_file = '/var/log/Xorg.%s.log' % \
matchStrs[-1]) display_number.group(1)
if resDriver: if os.path.exists(xorg_log_file):
return resDriver.group(1) matchStrs = [i for i in open(xorg_log_file)
if "drv" in i and reDriver.search(i)]
if matchStrs:
resDriver = re.search(r'([^/]+)_drv.so',
matchStrs[-1])
if resDriver:
return resDriver.group(1)
# analize /etc/X11/xorg.conf # analize /etc/X11/xorg.conf
if os.path.exists(xorg_conf): if os.path.exists(xorg_conf):
@ -777,7 +726,129 @@ class fillVars(glob_attr):
matchSect.group(0),re.S) matchSect.group(0),re.S)
if resDriver: if resDriver:
return resDriver.group(1) return resDriver.group(1)
return "vesa" 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): def get_hr_video(self):
"""Производитель видеокарты""" """Производитель видеокарты"""

@ -68,7 +68,7 @@ class lang:
#self.nameDomain = '' #self.nameDomain = ''
""" Название файла перевода (Домен) если используется 1 файл перевода """ Название файла перевода (Домен) если используется 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 в котором файл перевода) ru_RU/LC_MESSAGES в котором файл перевода)
""" """

@ -217,10 +217,9 @@ class opt(optparse.OptionParser):
'action':'append', 'action':'append',
'help':_("set value for variable (comma - delimeter)") 'help':_("set value for variable (comma - delimeter)")
}, },
{'longOption':"vars", {'shortOption':"v",
'optVal':"TYPE_VAR", 'longOption':"vars",
'help':_("print variables") + " (TYPE_VAR - all: " + \ 'help':_("print variables")
_("full variables list") +")"
}] }]
color_control = \ color_control = \
@ -292,7 +291,9 @@ class opt(optparse.OptionParser):
should either exit or raise an exception. should either exit or raise an exception.
""" """
self.print_usage(sys.stderr) 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): def checkVarSyntax(self,values):
"""Check value of parameter set, was used for change vars""" """Check value of parameter set, was used for change vars"""

@ -317,7 +317,7 @@ class tableReport:
strList.append(self.columnsWidth[i]) strList.append(self.columnsWidth[i])
return strList return strList
def printReport(self): def printReport(self,printRows=True):
"""Напечатать данные в табличном виде""" """Напечатать данные в табличном виде"""
cl_overriding.printSUCCESS(self.title) cl_overriding.printSUCCESS(self.title)
listStrSep = [] listStrSep = []
@ -342,7 +342,8 @@ class tableReport:
char ="-+-" char ="-+-"
convLines.append(self._insertStrChar(lines[i], lenCols, char)) convLines.append(self._insertStrChar(lines[i], lenCols, char))
cl_overriding.printSUCCESS("\n".join(convLines)) cl_overriding.printSUCCESS("\n".join(convLines))
cl_overriding.printSUCCESS("(%s %s)"%(len(self.dataList), _("rows"))) if printRows:
cl_overriding.printSUCCESS("(%s %s)"%(len(self.dataList), _("rows")))
def _insertStrChar(self, line, lenCols, char): def _insertStrChar(self, line, lenCols, char):
"""Вставляет несколько символов char в указанные позиции """Вставляет несколько символов char в указанные позиции
@ -361,4 +362,4 @@ class tableReport:
insertChar = char insertChar = char
convLine += lineUnicode[prevPos:pos] + insertChar convLine += lineUnicode[prevPos:pos] + insertChar
prevPos = pos + 1 prevPos = pos + 1
return convLine.encode("UTF-8") return convLine.encode("UTF-8")

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

@ -27,6 +27,7 @@ import cl_overriding
import re import re
import sys import sys
import getpass import getpass
from types import StringType
import cl_lang import cl_lang
tr = cl_lang.lang() tr = cl_lang.lang()
@ -446,4 +447,31 @@ incorrect option 'flag=%s'")%flag)
_("password incorrect")+ ": " + _("try again")) _("password incorrect")+ ": " + _("try again"))
return False return False
userPwd = pwdA userPwd = pwdA
return userPwd 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 # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
#Допустимые ключи значений #Allowed keys
# mode - режим переменной r-не переназначается из командной строки, # mode - variable mode: 'w' - you can change value from command line,
# w-переназначается из командной строки # 'r' you cann't change value from command line
# type - тип переменной состоит из двух элементов(что это и для чего # type - depricated
# это) # value - value
# value - значение переменной # official - show or not variable for display values
# official - флаг того, что данная переменная служебная и не отображается
# при печати списка значений переменных
class Data: class Data:
# computer hostname
# имя компьютера
os_net_hostname = {'mode':"w"} os_net_hostname = {'mode':"w"}
# разрешенные сети
# allowed networks
os_net_allow ={} os_net_allow ={}
# ip на всех интерфейсах
# ip for all network interfaces (comma delimeter)
os_net_ip ={} os_net_ip ={}
# Существующие сетевые интерфейсы # network interfaces
os_net_interfaces={'official':True} os_net_interfaces={'official':True}
#короткое название системы (CLD) # computer domain
os_linux_shortname={}
#домен
os_net_domain = {'mode':"w"} os_net_domain = {'mode':"w"}
# Алиасы и пути к ini файлам # short system name (CLD)
os_linux_shortname={}
# aliases and path to ini files
cl_env_data = {'official':True, cl_env_data = {'official':True,
'value':[('default', '/etc/calculate/calculate2.env'), 'value':[('default', '/etc/calculate/calculate2.env'),
('local', '/var/calculate/calculate2.env'), ('local', '/var/calculate/calculate2.env'),
('remote', '/var/calculate/remote/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} cl_env_location = {'official':True}
# Пути к ini файлам (из cl_env_data) # path to ini files (from cl_env_data)
cl_env_path = {} cl_env_path = {}
# Путь к информационному файлу сервера # path to information file on server
cl_env_server_path = {'official':True, cl_env_server_path = {'official':True,
'value':'/var/calculate/remote/server.env'} 'value':'/var/calculate/remote/server.env'}
# Пути к файлам шаблонов # paths to template files
cl_template_path = {'value':["/usr/share/calculate-2.2/templates", cl_template_path = {'value':["/usr/share/calculate/templates",
"/var/calculate/templates", "/var/calculate/templates",
"/var/calculate/remote/templates"]} "/var/calculate/remote/templates"]}
# Пути к файлам шаблонов clt # paths to clt-template files
cl_template_clt_path = {'value':""} cl_template_clt_path = {}
# локаль (прим: ru_RU.UTF-8) # locale (at example: ru_RU.UTF-8)
os_locale_locale = {} os_locale_locale = {}
# язык (прим: ru_RU) # full language (at example: ru_RU)
os_locale_lang = {} os_locale_lang = {}
# язык (прим: ru) # short language (at example ru)
os_locale_language = {} os_locale_language = {}
# раскладка клавиатуры для X # keyboard layout for X server
os_locale_xkb = {} os_locale_xkb = {}
# названия используемых раскладок клавиатуры для X # keyboard layout name for X server
os_locale_xkbname = {} os_locale_xkbname = {}
# keymap of locale (used for /etc/conf.d/keymaps) # computer architecture (i686,x86_64)
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)
os_arch_machine = {} os_arch_machine = {}
#проход при наложении профилей 1,2,3,4,5 и.т д # pass for templates join 1,2,3,4,5 and etc
cl_pass_step = {} cl_pass_step = {}
# обрабатываемый файл профиля # template file performed at now
cl_pass_file = {'mode':"w"} cl_pass_file = {'mode':"w"}
# корневой раздел файловой системы # root partition of filesystem
os_root_dev = {} os_root_dev = {}
# тип носителя (ram, hdd, usb-hdd, livecd) # root type (ram, hdd, usb-hdd, livecd)
os_root_type = {} os_root_type = {}
# полное название системы # full system name
os_linux_name = {} os_linux_name = {}
# постфикс к названию системы # postfix to system name (KDE GNOME and etc)
os_linux_subname = {} os_linux_subname = {}
# system (desktop or server) # system (desktop or server)
@ -121,60 +108,74 @@ class Data:
# processors count # processors count
hr_cpu_num = {} hr_cpu_num = {}
# название виртуальной машины (virtualbox, vmware, qemu) # virtual machine name (virtualbox, vmware, qemu)
hr_virtual = {} hr_virtual = {}
# версия системы # system version
os_linux_ver = {} os_linux_ver = {}
# Логин пользователя # user login
ur_login = {} ur_login = {}
# Название группы пользователя # user group name
ur_group = {'official':True} ur_group = {'official':True}
#Полное имя пользователя # user fullname
ur_fullname = {'official':True} ur_fullname = {'official':True}
# Домашняя директория пользователя # user home directory
ur_home_path = {'official':True} ur_home_path = {'official':True}
# Путь к директории относительно которой происходит наложение профилей на # path to directory relative which perform joining templates to system files
#файлы системы (песочница) # (sandbox)
cl_root_path = {'mode':"w", 'value':"/"} cl_root_path = {'mode':"w", 'value':"/"}
# Путь к директории другой системы # path to directory which contain other system
cl_chroot_path = {'mode':"w", 'value':"/"} cl_chroot_path = {'mode':"r", 'value':"/"}
# Действие программы # program action
# user - генерация профиля пользователя # user - user profile generation
# install / uninstall - установка и удаление программы # install / uninstall - install or uninstall program
cl_pass_action = {} cl_pass_action = {}
# Состояние программы # program state
# Указываем дополнительно к cl_pass_action в случае необходимости # specifies addition to cl_pass_action for needing
cl_pass_state = {} cl_pass_state = {}
# Jabber ID пользователя # User Jabber ID
ur_jid = {'official':True} ur_jid = {'official':True}
# Почтовый адрес пользователя # user email
ur_mail = {'official':True} ur_mail = {'official':True}
# Переменные пакета calculate-client для calculate-desktop # variable for calculate-client and calculate-desktop packages
# ip или имя домена (под управлением calculate-server) # ip or domain name of CDS
cl_remote_host = {'mode':'r', 'official':True} cl_remote_host = {'mode':'r', 'official':True}
# Переменная работающая совместно с функцией шаблонов belong(имя_пакета) # this variable work with template function belong(package_name)
# Если переменная будет определена то будут использованы шаблоны # if the variable is defined then will use only template, which
# у которых параметр имя пакета функции шаблонов belong(имя_пакета) # has package_name in belong equal value of this variable or
# совпадает с значением этой переменной # hasn't belong function
# (имя_пакета == значение 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
hr_video = {'official':True} 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 # 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\(\)") patternBelongDir = re.compile("belong\(\)")
patternBelongName = re.compile("belong\(([^\(\)]+)\)") patternBelongName = re.compile("belong\(([^\(\)]+)\)")
patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*") patternSect = re.compile("^\s*\[([^\[\]]+)\]\s*")
templatePaths = ['/usr/share/calculate-2.2/templates', templatePaths = ['/usr/share/calculate/templates',
'/var/calculate/templates', '/var/calculate/templates',
'/var/calculate/remote/templates'] '/var/calculate/remote/templates']
firstEnvFile = "/etc/calculate/calculate2.env" firstEnvFile = "/etc/calculate/calculate2.env"
reCleanVer = re.compile("\d+\.?\d*\.?\d*")
def _isApplyTemplateDir(self, scanDir, nameProgram, flagSkipDesktop=True, def _isApplyTemplateDir(self, scanDir, nameProgram, flagSkipDesktop=True,
flagDir=False): flagDir=False):
@ -192,6 +193,9 @@ class updateUserConfigs(shareUpdateConfigs):
def updateConfig(self, nameProgram, category, version, xUsers): 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(_("Package %s") %nameProgram)
self.logger.info(_("Update desktop configuration files")) self.logger.info(_("Update desktop configuration files"))
if not os.path.exists(self.firstEnvFile): if not os.path.exists(self.firstEnvFile):
@ -280,6 +284,9 @@ class updateSystemConfigs(shareUpdateConfigs):
def updateConfig(self, nameProgram, category, version, configPath): 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(_("Package %s") %nameProgram)
self.logger.info(_("Update system cofiguration files")) self.logger.info(_("Update system cofiguration files"))
if not os.path.exists(configPath): if not os.path.exists(configPath):

@ -69,7 +69,7 @@ setup(
'calculate-lib.pym.server', 'calculate-lib.pym.server',
'calculate-lib.pym.client', 'calculate-lib.pym.client',
'calculate-lib.pym.update_config'], '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",[])], ("/var/calculate/remote",[])],
scripts=["./scripts/cl-update-config"], scripts=["./scripts/cl-update-config"],
cmdclass={'build_scripts':cl_build_scripts, cmdclass={'build_scripts':cl_build_scripts,

Loading…
Cancel
Save