Added grub() template function

Added pathJoin() method
develop
Самоукин Алексей 14 years ago
parent 9c360da02b
commit d16ad4b008

@ -20,6 +20,7 @@ import types
import filecmp
import pwd, grp
import cl_overriding
from cl_ldap import ldapUser
from cl_datavars import glob_attr

@ -27,12 +27,11 @@ import string
import time
from cl_ldap import ldapFun
# Переопределение exit
import cl_overriding
from cl_utils import _error, _toUNICODE, getModeFile, removeDir, typeFile,\
scanDirectory, convertStrListDict
scanDirectory, convertStrListDict, pathJoin
import cl_lang
tr = cl_lang.lang()
@ -2268,10 +2267,9 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
self._chrootDir = self.objVar.Get("cl_chroot_path")
if self._chrootDir != '/':
# Изменение директории к базе пакетов
self.basePkgDir = os.path.join(self._chrootDir, self.basePkgDir[1:])
self.basePkgDir = pathJoin(self._chrootDir, self.basePkgDir)
# Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д
self._baseDir = os.path.join(self._chrootDir,
self.objVar.Get("cl_root_path")[1:])
self._baseDir=pathJoin(self._chrootDir,self.objVar.Get("cl_root_path"))
self._reFunc = re.compile(("%s%s%s")\
%(self.varStart,self._reFunctionText,self.varEnd),re.M)
# Аттрибуты для функции шаблона ini()
@ -2284,7 +2282,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
self.uid, self.gid, self.homeDir, self.groups =\
self.getDataUser(groupsInfo=True)
# Домашняя директория, плюс базовая директория
self.homeDir = os.path.join(self._baseDir, self.homeDir[1:])
self.homeDir = pathJoin(self._baseDir, self.homeDir)
# Путь к конфигурационному файлу для ini()
self.pathConfigIni = os.path.join(self.homeDir, ".calculate")
self.fileConfigIni = os.path.join(self.pathConfigIni,"ini.env")
@ -2414,7 +2412,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
cl_overriding.printERROR(_("wrong path '%s'")%fileName)
cl_overriding.exit(1)
else:
fileName = os.path.join(self._baseDir,fileName[1:])
fileName = pathJoin(self._baseDir, fileName)
replace = ""
if os.path.exists(fileName):
replace = "1"
@ -2452,7 +2450,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
cl_overriding.printERROR(_("wrong path '%s'")%fileName)
cl_overriding.exit(1)
else:
fileName = os.path.join(self._baseDir,fileName[1:])
fileName = pathJoin(self._baseDir, fileName)
else:
fileName = terms[1].strip()
# Если домашняя директория
@ -2465,7 +2463,7 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
cl_overriding.printERROR(_("wrong path '%s'")%fileName)
cl_overriding.exit(1)
else:
fileName = os.path.join(self._baseDir,fileName[1:])
fileName = pathJoin(self._baseDir,fileName)
replace = ""
if os.path.exists(fileName):
FD = open(fileName)
@ -2943,7 +2941,7 @@ or 'lower' or 'capitalize'"))
return textTemplateTmp
def funcBelong(self, funArgv, resS, localVars, textTemplateTmp):
"""Функция шаблона belongs().
"""Функция шаблона belong().
В случае установки переменной os_belongs_pkg=имя пакета, и совпадения
имени пакета в переменной и имени пакета в функции выдает "1" иначе ""
Если переменная os_belongs_pkg пуста выдает "1"
@ -3100,6 +3098,40 @@ os_disk_install not found mount point '\' and '\%s'")%mountPoint)
textTemplateTmp[resS.end():]
return textTemplateTmp
def funcGrub(self, funArgv, resS, localVars, textTemplateTmp):
"""Функция шаблона grub().
Выдает незакоментированные разделы установки из файла /boot/grub.conf
Удаляет из выдачи строки относящиеся к разделу в который устанавливается
система
Используется при генерации файла grub.conf в новой системе
"""
terms = funArgv.replace(" ","").split(",")
if len(terms) != 1:
self.printErrTemplate()
cl_overriding.exit(1)
funcPkg = terms[0]
if funcPkg:
cl_overriding.printERROR(_("incorrect template path"))
self.printErrTemplate()
cl_overriding.exit(1)
pathGrubConf = "/boot/grub/grub.conf"
replace = ""
if access(pathGrubConf,R_OK):
reRemoveComments = re.compile("(^|\n)\s*#[^\n]*?(?=\n|$)", re.S)
reGrubEntry = re.compile("title.*?(?=title|$)", re.S | re.I )
grubconf = reRemoveComments.sub("",open(pathGrubConf,'r').read())
roothd = filter(lambda x: x[1] == '/',
zip(self.Get('os_disk_grub'),
self.Get('os_install_disk_mount')))
if roothd:
roothd = "root (hd%s)" % roothd[0][0]
replace = ("".join(filter(lambda x: not roothd in x,
reGrubEntry.findall(grubconf)))).strip()
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
textTemplateTmp[resS.end():]
return textTemplateTmp
def printErrTemplate(self):
"""Печать ошибки при обработке функций шаблона"""
cl_overriding.printERROR(_("error in template %s")%self.nameTemplate)
@ -3224,8 +3256,8 @@ re.M|re.S)
# Объект с переменными
self.objVar = objVar
# Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д
self._baseDir = os.path.join(self.objVar.Get("cl_chroot_path"),
self.objVar.Get("cl_root_path")[1:])
self._baseDir = pathJoin(self.objVar.Get("cl_chroot_path"),
self.objVar.Get("cl_root_path"))
# Последняя часть директории шаблона (имя сервиса: samba, mail)
self._servDir = servDir
if self._servDir:
@ -3258,7 +3290,7 @@ re.M|re.S)
self.typeFileObj = typeFile()
self.uid, self.gid, self.homeDir = self.getDataUser()
# Домашняя директория, плюс базовая директория
self.homeDir = os.path.join(self._baseDir, self.homeDir[1:])
self.homeDir = pathJoin(self._baseDir, self.homeDir)
# Глобальный словарь обработанных шаблонов файлов
# {путь к конф. файлу:[имена шаблонов] ...}
self.dictProcessedTemplates = {}
@ -3542,7 +3574,7 @@ re.M|re.S)
"""Сканирование и обработка шаблонов в директории scanDir"""
ret = True
if not prefix:
prefix = os.path.join(scanDir,"")[:-1]
prefix = os.path.realpath(scanDir)
if not flagDir:
# проверка корневой директории
retDir = self.processingDirectory(scanDir, scanDir, optDir)
@ -3623,7 +3655,7 @@ re.M|re.S)
"""Обработка в случае директории если возвращаем None то пропуск дир."""
# Файл шаблона директории
dirInfoFile = os.path.join(path, self.templDirNameFile)
newDir = os.path.join(self._baseDir, path.partition(prefix)[2][1:])
newDir = pathJoin(self._baseDir, path.partition(prefix)[2])
newDir = "/".join(map(lambda x:x.split("?")[0], newDir.split("/")))
# Применяем шаблон
pathDir, objHeadDir, createdDirs =\
@ -3675,7 +3707,7 @@ re.M|re.S)
path = optDir["path"]
else:
path = os.path.split(applyDir)[1]
path = os.path.join(self._baseDir, path[1:])
path = pathJoin(self._baseDir, path)
if not os.path.exists(templateDirFile):
applyDir = os.path.join(path, os.path.split(applyDir)[1])
# Фильтрация шаблонов по названию директории
@ -3730,7 +3762,7 @@ re.M|re.S)
templateDirFile)
return ("", False, [])
else:
path = os.path.join(self._baseDir, path[1:])
path = pathJoin(self._baseDir, path)
# Изменяем название директории
if "name" in objHead.params:
@ -3930,7 +3962,7 @@ re.M|re.S)
nameFileTemplate)
return ([], False)
else:
path = os.path.join(self._baseDir, path[1:])
path = pathJoin(self._baseDir, path)
# Путь к оригинальному файлу - pathOldFile
# Изменяем путь к оригинальному файлу
@ -4011,6 +4043,7 @@ re.M|re.S)
if objHeadNew.params.has_key("mirror"):
if objHeadNew.params.has_key("link"):
templateFile = objHeadNew.params['link']
templateFile = pathJoin(self._baseDir, templateFile)
if not os.path.exists(templateFile):
if os.path.exists(pathOldFile):
try:
@ -4027,6 +4060,7 @@ re.M|re.S)
if objHeadNew.params.has_key("link") and\
not objHeadNew.params.has_key("symbolic"):
templateFile = objHeadNew.params['link']
templateFile = pathJoin(self._baseDir, templateFile)
foundTemplateFile = os.path.exists(templateFile)
if foundTemplateFile:
try:

@ -403,3 +403,13 @@ def isMount(path):
reduce(lambda x,y: y, filter(lambda x: absPath in x,
map(lambda x: [x[0], x[1]], map(lambda x: x.split(" "),
open("/etc/mtab")))),[""]))[0]
def pathJoin(*paths):
"""Складывает пути, в отличии от os.path.join, складывает абсолютные пути"""
if len(paths)==1:
return paths[0]
return os.path.join(paths[0],
reduce(os.path.join,
map(lambda x: x.startswith("/") and x[1:] or x,
paths[1:]),''))

Loading…
Cancel
Save