From 194d70be6f3735066edf8da27ad85797091dd673 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Tue, 20 Jul 2010 14:10:59 +0400 Subject: [PATCH 01/23] Modify table display --- pym/cl_string.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pym/cl_string.py b/pym/cl_string.py index 80fbb1a..7d9ab26 100644 --- a/pym/cl_string.py +++ b/pym/cl_string.py @@ -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,7 +342,8 @@ class tableReport: char ="-+-" convLines.append(self._insertStrChar(lines[i], lenCols, char)) 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): """Вставляет несколько символов char в указанные позиции @@ -361,4 +362,4 @@ class tableReport: insertChar = char convLine += lineUnicode[prevPos:pos] + insertChar prevPos = pos + 1 - return convLine.encode("UTF-8") \ No newline at end of file + return convLine.encode("UTF-8") From 837bc752e0ef2f32cf0450bfa64b6301d1fe4f97 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Tue, 20 Jul 2010 15:50:37 +0400 Subject: [PATCH 02/23] Fix error message for opt object --- pym/cl_opt.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pym/cl_opt.py b/pym/cl_opt.py index 6b37229..bba24e3 100644 --- a/pym/cl_opt.py +++ b/pym/cl_opt.py @@ -292,7 +292,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" % (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""" From 498034b68a78e615103065fb3754cdc65fe7371d Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Tue, 20 Jul 2010 16:05:34 +0400 Subject: [PATCH 03/23] Bugfix --- pym/cl_opt.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pym/cl_opt.py b/pym/cl_opt.py index bba24e3..e5924a9 100644 --- a/pym/cl_opt.py +++ b/pym/cl_opt.py @@ -292,9 +292,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())) + ("%s --help"%self.get_prog_name()))) def checkVarSyntax(self,values): """Check value of parameter set, was used for change vars""" From eb4406704d2ad1c71935ea4b71ec90e3bdcd0d66 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 21 Jul 2010 09:46:06 +0400 Subject: [PATCH 04/23] Add bulgarian language. Add variable os_locale_consolefont for keeping name of terminus-font. --- pym/cl_fill.py | 14 ++++++++++++++ pym/cl_vars.py | 17 ++++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/pym/cl_fill.py b/pym/cl_fill.py index f983512..3e0ffe0 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -35,6 +35,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', @@ -588,6 +597,11 @@ class fillVars(glob_attr): locale = clLocale() return locale.getFieldByLang("language",self.Get('os_locale_lang')) + def get_os_locale_consolefont(self): + """consolefont""" + locale = clLocale() + return locale.getFieldByLang("consolefont",self.Get('os_locale_lang')) + def get_os_locale_xkb(self): """xkb layouts (example: en,ru)""" locale = clLocale() diff --git a/pym/cl_vars.py b/pym/cl_vars.py index e2da81e..ec74359 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -57,23 +57,23 @@ class Data: cl_env_server_path = {'official':True, 'value':'/var/calculate/remote/server.env'} - # Пути к файлам шаблонов + # paths to template files cl_template_path = {'value':["/usr/share/calculate-2.2/templates", "/var/calculate/templates", "/var/calculate/remote/templates"]} - # Пути к файлам шаблонов clt + # paths to clt-template files cl_template_clt_path = {'value':""} - # локаль (прим: ru_RU.UTF-8) + # 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) @@ -82,6 +82,9 @@ class Data: # dumpkeys_charset for keymap os_locale_dumpkeys = {} + # consolefont + os_locale_consolefont = {} + # timezone for clock os_clock_timezone = {} From 2881a51155925b4cbac37cb23a5136ba3edbaf76 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 21 Jul 2010 10:37:48 +0400 Subject: [PATCH 05/23] Change fill method of video driver --- pym/cl_fill.py | 53 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/pym/cl_fill.py b/pym/cl_fill.py index 3e0ffe0..95e7a81 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -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 = { @@ -765,22 +766,28 @@ class fillVars(glob_attr): 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)) - display_number = re.search(r':(\d+)\..*', display) - if display_number: - xorg_log_file = '/var/log/Xorg.%s.log' % \ - display_number.group(1) - if os.path.exists(xorg_log_file): - 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) + 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' % \ + display_number.group(1) + if os.path.exists(xorg_log_file): + 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 if os.path.exists(xorg_conf): @@ -791,7 +798,19 @@ class fillVars(glob_attr): matchSect.group(0),re.S) if resDriver: 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 get_hr_video(self): """Производитель видеокарты""" From 5050c488596f2eb90a606a0d23cb044948108329 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 21 Jul 2010 13:57:26 +0400 Subject: [PATCH 06/23] Move to lib some variables from calculate-desktop --- pym/cl_fill.py | 142 +++++++++++++++++++++++++++++++++++++++++++++++++ pym/cl_vars.py | 22 +++++++- 2 files changed, 162 insertions(+), 2 deletions(-) diff --git a/pym/cl_fill.py b/pym/cl_fill.py index 95e7a81..d2a2eb8 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -812,6 +812,148 @@ class fillVars(glob_attr): 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_hr_x11_height(self): + """Получить высоту экрана в пикселах""" + resolution = self.getX11Resolution() + if resolution: + self.Set('hr_x11_width',resolution[0]) + return resolution[1] + return "768" + + def get_hr_x11_width(self): + """Получить ширину экрана в пикселах""" + resolution = self.getX11Resolution() + if resolution: + self.Set('hr_x11_height',resolution[1]) + return resolution[0] + return "1024" + + def get_hr_x11_standart(self): + """Получить ближайший стандартный размер изображения к текущему разрешению""" + #Стандартные разрешения + widthVal = self.Get('hr_x11_width') + heightVal = self.Get('hr_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_hr_x11_composite(self): + """Включен ли композитный режим видеокарты on/off""" + defaultCompositeOn = ["nvidia","intel"] + if self.Get('hr_x11_video_drv') in defaultCompositeOn: + defaultComposite = "on" + else: + defaultComposite = "off" + xorgConfig = "/etc/X11/xorg.conf" + try: + confLines = open(xorgConfig,"r").readlines() + except: + return defaultComposite + + 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 defaultComposite + + 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") diff --git a/pym/cl_vars.py b/pym/cl_vars.py index ec74359..f420679 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -175,9 +175,27 @@ class Data: # (имя_пакета == значение cl_belong_pkg) cl_belong_pkg = {'mode':'r', 'official':True} + # Video driver used by xorg + hr_x11_video_drv = {'official':True} + + #Разрешение X по вертикали + hr_x11_height = {'mode':"w"} + + #Разрешение X по горизонтали + hr_x11_width = {'mode':"w"} + + # ближайший стандартный размер изображения к текущему разрешению + hr_x11_standart = {} + + # Если компьютер ноутбук, то его производитель + hr_laptop = {} + # Название производителя видеокарты - hr_video = {'official':True} + hr_video = {} # Video driver used by xorg - hr_x11_video_drv = {'official':True} + hr_x11_video_drv = {} + + # Включен ли композитный режим видеокарты on/off + hr_x11_composite = {} From 041a5064ba794dc7637b74f901b0268e7e1baafc Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 21 Jul 2010 14:05:33 +0400 Subject: [PATCH 07/23] Fix duplicate variables --- pym/cl_vars.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/pym/cl_vars.py b/pym/cl_vars.py index f420679..a4f7143 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -175,9 +175,6 @@ class Data: # (имя_пакета == значение cl_belong_pkg) cl_belong_pkg = {'mode':'r', 'official':True} - # Video driver used by xorg - hr_x11_video_drv = {'official':True} - #Разрешение X по вертикали hr_x11_height = {'mode':"w"} From ffe261cb25d6a80a584fdf133acc13b1bacd976c Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 21 Jul 2010 14:52:24 +0400 Subject: [PATCH 08/23] Change print vars method --- pym/cl_opt.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pym/cl_opt.py b/pym/cl_opt.py index e5924a9..74d0020 100644 --- a/pym/cl_opt.py +++ b/pym/cl_opt.py @@ -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 = \ From 1606d39240844fe4d9f4c6c9f0d91aa6b79c43b8 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 21 Jul 2010 16:52:06 +0400 Subject: [PATCH 09/23] Rename variables: hr_x11_composite -> os_x11_composite hr_x11_height -> os_x11_height hr_x11_width -> os_x11_width hr_x11_standart -> os_x11_standart hr_x11_video_drv -> os_x11_video_drv --- pym/cl_fill.py | 20 ++++++++++---------- pym/cl_vars.py | 10 +++++----- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/pym/cl_fill.py b/pym/cl_fill.py index d2a2eb8..e1a9721 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -760,7 +760,7 @@ 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' @@ -828,27 +828,27 @@ class fillVars(glob_attr): else: return "" - def get_hr_x11_height(self): + def get_os_x11_height(self): """Получить высоту экрана в пикселах""" resolution = self.getX11Resolution() if resolution: - self.Set('hr_x11_width',resolution[0]) + self.Set('os_x11_width',resolution[0]) return resolution[1] return "768" - def get_hr_x11_width(self): + def get_os_x11_width(self): """Получить ширину экрана в пикселах""" resolution = self.getX11Resolution() if resolution: - self.Set('hr_x11_height',resolution[1]) + self.Set('os_x11_height',resolution[1]) return resolution[0] return "1024" - def get_hr_x11_standart(self): + def get_os_x11_standart(self): """Получить ближайший стандартный размер изображения к текущему разрешению""" #Стандартные разрешения - widthVal = self.Get('hr_x11_width') - heightVal = self.Get('hr_x11_height') + widthVal = self.Get('os_x11_width') + heightVal = self.Get('os_x11_height') if not widthVal or not heightVal: return "" width = int(widthVal) @@ -900,10 +900,10 @@ class fillVars(glob_attr): else: return "%sx%s"%(stWidth,stHeight) - def get_hr_x11_composite(self): + def get_os_x11_composite(self): """Включен ли композитный режим видеокарты on/off""" defaultCompositeOn = ["nvidia","intel"] - if self.Get('hr_x11_video_drv') in defaultCompositeOn: + if self.Get('os_x11_video_drv') in defaultCompositeOn: defaultComposite = "on" else: defaultComposite = "off" diff --git a/pym/cl_vars.py b/pym/cl_vars.py index a4f7143..0b526bd 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -176,13 +176,13 @@ class Data: cl_belong_pkg = {'mode':'r', 'official':True} #Разрешение X по вертикали - hr_x11_height = {'mode':"w"} + os_x11_height = {'mode':"w"} #Разрешение X по горизонтали - hr_x11_width = {'mode':"w"} + os_x11_width = {'mode':"w"} # ближайший стандартный размер изображения к текущему разрешению - hr_x11_standart = {} + os_x11_standart = {} # Если компьютер ноутбук, то его производитель hr_laptop = {} @@ -191,8 +191,8 @@ class Data: hr_video = {} # Video driver used by xorg - hr_x11_video_drv = {} + os_x11_video_drv = {} # Включен ли композитный режим видеокарты on/off - hr_x11_composite = {} + os_x11_composite = {} From 237c427745feff4c17abb20b1ce3fc98ccd373e6 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 21 Jul 2010 17:57:44 +0400 Subject: [PATCH 10/23] Change place of detect composite --- pym/cl_datavars.py | 33 +++++++++++++++++++++++++++++++++ pym/cl_fill.py | 37 ++----------------------------------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/pym/cl_datavars.py b/pym/cl_datavars.py index 12169f3..f72764d 100644 --- a/pym/cl_datavars.py +++ b/pym/cl_datavars.py @@ -646,3 +646,36 @@ 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 diff --git a/pym/cl_fill.py b/pym/cl_fill.py index e1a9721..2ea9ddd 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -902,41 +902,8 @@ class fillVars(glob_attr): def get_os_x11_composite(self): """Включен ли композитный режим видеокарты on/off""" - defaultCompositeOn = ["nvidia","intel"] - if self.Get('os_x11_video_drv') in defaultCompositeOn: - defaultComposite = "on" - else: - defaultComposite = "off" - xorgConfig = "/etc/X11/xorg.conf" - try: - confLines = open(xorgConfig,"r").readlines() - except: - return defaultComposite - - 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 defaultComposite + state = self.get_composite_from_xorgconf() + return state or "off" def get_hr_laptop(self): """Если компьютер ноутбук, то его производитель""" From ab4f58351e191b7030a058434bdf14ecbbc13915 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Thu, 22 Jul 2010 09:00:33 +0400 Subject: [PATCH 11/23] Move os_clock_timezone and os_clock_type variables to calculate-install. --- pym/cl_datavars.py | 21 +++++++++++++++++++++ pym/cl_fill.py | 46 ---------------------------------------------- pym/cl_vars.py | 6 ------ 3 files changed, 21 insertions(+), 52 deletions(-) diff --git a/pym/cl_datavars.py b/pym/cl_datavars.py index f72764d..fe80bad 100644 --- a/pym/cl_datavars.py +++ b/pym/cl_datavars.py @@ -679,3 +679,24 @@ class glob_attr: 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 "" + diff --git a/pym/cl_fill.py b/pym/cl_fill.py index 2ea9ddd..c809628 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -531,26 +531,6 @@ class fillVars(glob_attr): 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" @@ -640,32 +620,6 @@ class fillVars(glob_attr): 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): """Имя пользователя""" uid = os.getuid() diff --git a/pym/cl_vars.py b/pym/cl_vars.py index 0b526bd..e50b6cf 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -85,12 +85,6 @@ class Data: # consolefont os_locale_consolefont = {} - # timezone for clock - os_clock_timezone = {} - - # type of clock (UTC or local) - os_clock_type = {} - # архитектура компьютера (i686,x86_64) os_arch_machine = {} From 36ecb9f36c10f8d7f3cc86a87e2ece28d873e0ed Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Thu, 22 Jul 2010 09:47:33 +0400 Subject: [PATCH 12/23] Move method getValueFromConfig from Fill to globattr --- pym/cl_datavars.py | 19 +++++++++++++++++++ pym/cl_fill.py | 18 ------------------ 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/pym/cl_datavars.py b/pym/cl_datavars.py index fe80bad..3960735 100644 --- a/pym/cl_datavars.py +++ b/pym/cl_datavars.py @@ -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 @@ -700,3 +701,21 @@ class glob_attr: 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 + diff --git a/pym/cl_fill.py b/pym/cl_fill.py index c809628..4c97066 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -513,24 +513,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 get_hr_board_model(self): """motherboard model""" modelFile = "/sys/class/dmi/id/board_name" From baf6c90b467a03cbe5d61f1c5786a006fb29c1e8 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Thu, 22 Jul 2010 10:19:55 +0400 Subject: [PATCH 13/23] Move varaibles to install: os_locale_consolefont os_locale_dumpkeys os_locale_keymap --- pym/cl_fill.py | 55 +++++++++----------------------------------------- pym/cl_vars.py | 9 --------- 2 files changed, 10 insertions(+), 54 deletions(-) diff --git a/pym/cl_fill.py b/pym/cl_fill.py index 4c97066..a94cfdb 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -428,13 +428,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") @@ -560,47 +553,18 @@ class fillVars(glob_attr): locale = clLocale() return locale.getFieldByLang("language",self.Get('os_locale_lang')) - def get_os_locale_consolefont(self): - """consolefont""" - locale = clLocale() - return locale.getFieldByLang("consolefont",self.Get('os_locale_lang')) - 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')) + 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_locale_xkbname(self): + """названия используемых раскладок клавиатуры для X""" + localeXkb = self.Get("os_locale_xkb") + if localeXkb: + return localeXkb.split("(")[0] + return "" def get_ur_login(self): """Имя пользователя""" @@ -781,7 +745,8 @@ class fillVars(glob_attr): 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') diff --git a/pym/cl_vars.py b/pym/cl_vars.py index e50b6cf..a501802 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -76,15 +76,6 @@ class Data: # 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 = {} - - # consolefont - os_locale_consolefont = {} - # архитектура компьютера (i686,x86_64) os_arch_machine = {} From 77d5f78dfca4bb39445cd81c2ef79357b59b7cb2 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Thu, 22 Jul 2010 11:37:51 +0400 Subject: [PATCH 14/23] Restructure cl_vars --- pym/cl_vars.py | 116 ++++++++++++++++++++++++------------------------- 1 file changed, 57 insertions(+), 59 deletions(-) diff --git a/pym/cl_vars.py b/pym/cl_vars.py index a501802..3b98d02 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -14,46 +14,45 @@ # 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'} @@ -76,25 +75,25 @@ class Data: # keyboard layout name for X server os_locale_xkbname = {} - # архитектура компьютера (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) @@ -109,75 +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} - #Разрешение X по вертикали + # vertical resolution for X server os_x11_height = {'mode':"w"} - #Разрешение X по горизонтали + # 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 os_x11_video_drv = {} - # Включен ли композитный режим видеокарты on/off + # on/off composite mode os_x11_composite = {} - From b63a9c364617da385e706036dcb7d5253dc7cfa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B8=D1=80=D0=B5=D1=86=D0=BA=D0=B8=D0=B9=20=D0=9C?= =?UTF-8?q?=D0=B8=D1=85=D0=B0=D0=B8=D0=BB?= Date: Mon, 26 Jul 2010 16:09:25 +0000 Subject: [PATCH 15/23] Fix calculate template conditions --- pym/cl_template.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pym/cl_template.py b/pym/cl_template.py index 74f4e41..1bf97dd 100644 --- a/pym/cl_template.py +++ b/pym/cl_template.py @@ -130,8 +130,9 @@ class _terms(_error, _shareTermsFunction): if k == " and ": flagOR = False if listEqual == [] or False in listEqual: - listEqual = [] - break +# listEqual = [] +# break + listEqual = [False] else: listEqual = [True] # если or @@ -144,8 +145,10 @@ class _terms(_error, _shareTermsFunction): listEqual = [True] flagOR = True else: - if flagOR: - continue + #if flagOR: + # continue + if flagOR and listEqual and all(listEqual): + break #проверка на допустимость названия переменной flagFunction = False if self._reDenyName.search(vals[0]): From 9d07f26af39e0166a0c14a7b6f0eb01c0b61ee83 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Tue, 27 Jul 2010 13:49:41 +0400 Subject: [PATCH 16/23] Fix grub() function. Similar section detect by 'root=/dev/' substring --- pym/cl_template.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pym/cl_template.py b/pym/cl_template.py index 74f4e41..e6781ee 100644 --- a/pym/cl_template.py +++ b/pym/cl_template.py @@ -3122,10 +3122,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 +\ From b5ea69731958a3ac28483e719b81a23efb217b53 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Tue, 27 Jul 2010 17:06:54 +0400 Subject: [PATCH 17/23] Clean version specified by parameter --pkg-version. (bugfix ntp version 4.2.4_p7) --- pym/update_config/cl_update_config.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pym/update_config/cl_update_config.py b/pym/update_config/cl_update_config.py index cbb1f10..507213a 100644 --- a/pym/update_config/cl_update_config.py +++ b/pym/update_config/cl_update_config.py @@ -111,6 +111,7 @@ class shareUpdateConfigs(color_print, writeLog): '/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): From d8c8c1d25b47f8cd3cd2debdfe1324dd0336351d Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 28 Jul 2010 09:20:05 +0400 Subject: [PATCH 18/23] Fix refilling empty variable. --- pym/cl_datavars.py | 9 +++++---- pym/cl_vars.py | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/pym/cl_datavars.py b/pym/cl_datavars.py index 3960735..04e0533 100644 --- a/pym/cl_datavars.py +++ b/pym/cl_datavars.py @@ -34,7 +34,7 @@ class var: #(Main, Builder, Client итд) service = None # значение переменной - value = "" + value = None # режим записи (атрибут mode) mode = "r" # переменная для внутреннего использования (official) @@ -80,9 +80,9 @@ class var: if self.dynamic: self.value = self.Fill() return self.value - if not self.value: + if self.value is None: if self.countFill>0: - return self.value + return "" self.countFill += 1 self.value = self.Fill() if self.dependValues and self.is_update(): @@ -97,9 +97,10 @@ class var: def Fill(self): """Заполнение переменной в далнейшем заменяем методом заполнения""" + if self.value is None: + self.value = "" return self.value - class DataVars(object): """Класс хранения переменных шаблонов""" diff --git a/pym/cl_vars.py b/pym/cl_vars.py index 3b98d02..dfa7eb2 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -61,7 +61,7 @@ class Data: "/var/calculate/templates", "/var/calculate/remote/templates"]} # paths to clt-template files - cl_template_clt_path = {'value':""} + cl_template_clt_path = {} # locale (at example: ru_RU.UTF-8) os_locale_locale = {} # full language (at example: ru_RU) From 2fb6992962a53eeb371466027b369f91d1fdbc6c Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 28 Jul 2010 10:23:58 +0400 Subject: [PATCH 19/23] Fix change directory, which createing relative symlink --- pym/cl_template.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pym/cl_template.py b/pym/cl_template.py index 99eeec7..4b3e752 100644 --- a/pym/cl_template.py +++ b/pym/cl_template.py @@ -4236,6 +4236,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] From 7183d1f6c705f57e182208233330ba9a58269e8b Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 28 Jul 2010 16:07:01 +0400 Subject: [PATCH 20/23] Add cl_chroot_path for getting name_calclate_ini --- pym/cl_datavars.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pym/cl_datavars.py b/pym/cl_datavars.py index 04e0533..278fc91 100644 --- a/pym/cl_datavars.py +++ b/pym/cl_datavars.py @@ -335,7 +335,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 файл переменной From 088fe60b8f066fca735fee54d6e6cc383294a1b3 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Wed, 28 Jul 2010 16:48:47 +0400 Subject: [PATCH 21/23] Modify filling os_linux_ver os_linux_shortname --- pym/cl_fill.py | 94 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 61 insertions(+), 33 deletions(-) diff --git a/pym/cl_fill.py b/pym/cl_fill.py index a94cfdb..dc08591 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -275,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) @@ -299,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: @@ -326,32 +335,51 @@ class fillVars(glob_attr): return "" def get_os_linux_ver(self): - '''Получить версию системы''' - path = '/etc/calculate/calculate.ini' - if os.path.exists(path): - FD = open(path) - data = FD.readlines() - FD.close() - shortNameList = filter(lambda y:y, - map(lambda x:\ - len(x.split("="))==2 and\ - x.split("=")[0]=="linuxver" and\ - x.split("=")[1].strip(), data)) - if shortNameList: - return shortNameList[0] - 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: + '''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) + data = FD.readlines() + FD.close() + shortNameList = filter(lambda y:y, + 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") 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''' From 9250630f886e5c516922ef3ac8f43c1708b8c162 Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Thu, 29 Jul 2010 10:33:44 +0400 Subject: [PATCH 22/23] Add version compare functions. --- pym/cl_utils.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/pym/cl_utils.py b/pym/cl_utils.py index 8f1cd1a..1ddeac0 100644 --- a/pym/cl_utils.py +++ b/pym/cl_utils.py @@ -27,6 +27,7 @@ import cl_overriding import re import sys import getpass +from types import StringType import cl_lang tr = cl_lang.lang() @@ -446,4 +447,31 @@ incorrect option 'flag=%s'")%flag) _("password incorrect")+ ": " + _("try again")) return False userPwd = pwdA - return userPwd \ No newline at end of file + 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] From bc8cc442552e2dcbe0119a8df9cab534d1a5efdd Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Tue, 3 Aug 2010 16:40:02 +0400 Subject: [PATCH 23/23] Change templates directory. --- pym/cl_lang.py | 2 +- pym/cl_vars.py | 2 +- pym/update_config/cl_update_config.py | 2 +- setup.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pym/cl_lang.py b/pym/cl_lang.py index 2fa94db..eb0cf69 100644 --- a/pym/cl_lang.py +++ b/pym/cl_lang.py @@ -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 в котором файл перевода) """ diff --git a/pym/cl_vars.py b/pym/cl_vars.py index dfa7eb2..3656c20 100644 --- a/pym/cl_vars.py +++ b/pym/cl_vars.py @@ -57,7 +57,7 @@ class Data: '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/remote/templates"]} # paths to clt-template files diff --git a/pym/update_config/cl_update_config.py b/pym/update_config/cl_update_config.py index 507213a..b584a80 100644 --- a/pym/update_config/cl_update_config.py +++ b/pym/update_config/cl_update_config.py @@ -106,7 +106,7 @@ 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" diff --git a/setup.py b/setup.py index e9cfd51..1f94646 100755 --- a/setup.py +++ b/setup.py @@ -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,