Reorganization

develop
Самоукин Алексей 14 years ago
parent 810e1b3f27
commit f2a972c5b0

@ -31,7 +31,7 @@ from cl_ldap import ldapFun
# Переопределение exit # Переопределение exit
import cl_overriding import cl_overriding
from cl_utils import _error, _toUNICODE, getModeFile, removeDir from cl_utils import _error, _toUNICODE, getModeFile, removeDir, typeFile
import cl_lang import cl_lang
tr = cl_lang.lang() tr = cl_lang.lang()
@ -115,7 +115,7 @@ class _terms(_error):
break break
if not flagLog: if not flagLog:
self.setError("'%s'"%term + " " + _("incorrect")) self.setError("'%s'"%term + " " + _("incorrect"))
self.setError (textError) self.setError(textError)
return False return False
else: else:
# если and # если and
@ -164,17 +164,17 @@ class _terms(_error):
self.setError("'%s'"%term + " " + _("incorrect")) self.setError("'%s'"%term + " " + _("incorrect"))
self.setError(textError) self.setError(textError)
return False return False
if "load" == searchFunct.group(1): if "load" == searchFunct.group(1) and\
if re.search("\(\s*num\s*,",vals[0]): re.search("\(\s*num\s*,",vals[0]):
if valVars: if valVars:
try: try:
valVars = int(valVars) valVars = int(valVars)
except: except:
self.setError("'%s'"%term + " " + \ self.setError("'%s'"%term + " " + \
_("incorrect")) _("incorrect"))
self.setError (textError) self.setError(textError)
return False return False
flagIntTypeVar = True flagIntTypeVar = True
else: else:
flagIntTypeVar = False flagIntTypeVar = False
else: else:
@ -218,12 +218,12 @@ class _terms(_error):
# Проверка значения на версию # Проверка значения на версию
if self._re_not_Version.search(vals[1]): if self._re_not_Version.search(vals[1]):
self.setError("'%s'"%term + " " + _("incorrect")) self.setError("'%s'"%term + " " + _("incorrect"))
self.setError (_("Value is not version")) self.setError(_("Value is not version"))
return False return False
# Проверка значения функции на версию # Проверка значения функции на версию
if self._re_not_Version.search(valVars): if self._re_not_Version.search(valVars):
self.setError("'%s'"%term + " " + _("incorrect")) self.setError("'%s'"%term + " " + _("incorrect"))
self.setError (_("Value function is not version")) self.setError(_("Value function is not version"))
return False return False
verFile, verVar = self._convertVers(vals[1],valVars) verFile, verVar = self._convertVers(vals[1],valVars)
exec("res=("+"'"+verVar+"'"+sepF+"'"+verFile+"'"+")") exec("res=("+"'"+verVar+"'"+sepF+"'"+verFile+"'"+")")
@ -233,7 +233,7 @@ class _terms(_error):
listEqual.append(False) listEqual.append(False)
flagNotIniFunct = False flagNotIniFunct = False
else: else:
if flagIntTypeVar == None: if flagIntTypeVar is None:
flagIntTypeVar = True flagIntTypeVar = True
try: try:
valVars = int(valVars) valVars = int(valVars)
@ -246,7 +246,7 @@ class _terms(_error):
valFile = int(vals[1]) valFile = int(vals[1])
except: except:
self.setError("'%s'"%term +" " +_("incorrect")) self.setError("'%s'"%term +" " +_("incorrect"))
self.setError (textError) self.setError(textError)
return False return False
valVar = valVars valVar = valVars
exec("res=(%d%s%d)"%(valVar,sepF,valFile)) exec("res=(%d%s%d)"%(valVar,sepF,valFile))
@ -273,7 +273,7 @@ class _terms(_error):
else: else:
self.setError("'%s'"%term + " "\ self.setError("'%s'"%term + " "\
+ _("incorrect")) + _("incorrect"))
self.setError (textError) self.setError(textError)
return False return False
if listEqual == [] or False in listEqual: if listEqual == [] or False in listEqual:
return False return False
@ -1896,44 +1896,6 @@ class _file(_error):
# Дескриптор файла конфигурационного файла # Дескриптор файла конфигурационного файла
self.F_CONF = False self.F_CONF = False
def getFileType(self):
"""выдать тип шаблона (text, bin)
"""
nameFile = self.nameFileTemplate
if not nameFile:
print _("ERROR:")
print _("The name of template is not specified, \
it is impossible to execute the command") + " 'file name_of_template'"
cl_overriding.exit(1)
execStr = "file '%s'"%nameFile
sp = subprocess.Popen(execStr, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
close_fds=True, shell=True)
fout, fin, ferr = (sp.stdout, sp.stdin, sp.stderr)
fin.close()
textLine = fout.readline()
fout.readlines()
fout.close()
retText = ""
# Ошибка
if "`" in textLine:
print _("Can not execute:") + ": %s"%execStr
print textLine
cl_overriding.exit(1)
if textLine:
listTextLine = textLine.split(":")
if len(listTextLine) == 2:
textFormats = ["text", "XML"]
retText = "bin"
fileTypeString = listTextLine[1]
for textFormat in textFormats:
if textFormat in fileTypeString:
retText = "text"
break
ferr.close()
return retText
def saveConfFile(self): def saveConfFile(self):
"""Записать конфигурацию""" """Записать конфигурацию"""
if self.F_CONF: if self.F_CONF:
@ -1944,7 +1906,7 @@ it is impossible to execute the command") + " 'file name_of_template'"
try: try:
self.F_CONF.write(self.textConfig) self.F_CONF.write(self.textConfig)
except: except:
self.setError (_("not open file:" ) + self.nameFileConfig) self.setError(_("not open file:" ) + self.nameFileConfig)
return False return False
self.F_CONF.flush() self.F_CONF.flush()
return True return True
@ -1955,7 +1917,7 @@ it is impossible to execute the command") + " 'file name_of_template'"
try: try:
F_TEMPL = open(nameFileTemplate, "r") F_TEMPL = open(nameFileTemplate, "r")
except: except:
self.setError (_("not open file:" ) + nameFileTemplate) self.setError(_("not open file:" ) + nameFileTemplate)
return False return False
return F_TEMPL return F_TEMPL
@ -1983,7 +1945,7 @@ it is impossible to execute the command") + " 'file name_of_template'"
os.close(fd) os.close(fd)
F_CONF = open(nameFileConfig, "r+") F_CONF = open(nameFileConfig, "r+")
except: except:
self.setError (_("not open file:" ) + nameFileConfig) self.setError(_("not open file:" ) + nameFileConfig)
return False return False
return F_CONF return F_CONF
@ -2751,9 +2713,6 @@ class templateFunction(_error, _shareTemplate):
Используеться совместно c funcIni Используеться совместно c funcIni
""" """
localVarsIni = {} localVarsIni = {}
# Выходим если есть предыдущие ошибки
if self.getError():
return False
# получить объект ini файла # получить объект ini файла
config = iniParser(iniFileName) config = iniParser(iniFileName)
# получаем все секции из конфигурационного файла # получаем все секции из конфигурационного файла
@ -2992,6 +2951,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
self.functObj = templateFunction(self.objVar) self.functObj = templateFunction(self.objVar)
# Метод применения функций к шаблонам # Метод применения функций к шаблонам
self.applyFuncTemplate = self.functObj.applyFuncTemplate self.applyFuncTemplate = self.functObj.applyFuncTemplate
# Объект для определения типа файла шаблона
self.typeFileObj = typeFile()
# Преобразование восьмеричного в целое (ввод строка, вывод число) # Преобразование восьмеричного в целое (ввод строка, вывод число)
@ -3000,14 +2961,26 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
try: try:
exec("res =" + "0" + strOct) exec("res =" + "0" + strOct)
except: except:
self.setError (_("Not valid oct value: ") + str(strOct)) self.setError(_("Not valid oct value: ") + str(strOct))
return False return False
return res return res
else: else:
self.setError (_("Empty oct value")) self.setError(_("Empty oct value"))
return False return False
def getTemplateType(self):
"""выдать тип шаблона (text, bin)"""
isBin = self.typeFileObj.isBinary(self.nameFileTemplate)
typeTemplate = "bin"
if isBin is True:
typeTemplate = "bin"
elif isBin is False:
typeTemplate = "text"
else:
self.setError(_("ERROR") + ": getTemplateType()")
self.setError(isBin)
return False
return typeTemplate
def createDir(self, dirName, mode=False, uid=False, gid=False): def createDir(self, dirName, mode=False, uid=False, gid=False):
"""Создает директорию""" """Создает директорию"""
@ -3023,7 +2996,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
try: try:
tmpMode,dUid,dGid = getModeFile(prevDir) tmpMode,dUid,dGid = getModeFile(prevDir)
except OSError: except OSError:
self.setError (_("Not access dir: " ) + prevDir) self.setError(_("Not access dir: " ) + prevDir)
return False return False
if not mode is False: if not mode is False:
dMode = mode dMode = mode
@ -3040,7 +3013,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
os.mkdir(nameDir) os.mkdir(nameDir)
os.chown(nameDir, dUid, dGid) os.chown(nameDir, dUid, dGid)
except: except:
self.setError (_("Can not create dir: " ) + nameDir) self.setError(_("Can not create dir: " ) + nameDir)
return False return False
try: try:
if dMode: if dMode:
@ -3050,7 +3023,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
os.chown(dirName, dUid, dGid) os.chown(dirName, dUid, dGid)
createDirs.append(dirName) createDirs.append(dirName)
except: except:
self.setError (_("Can not create dir: " ) + dirName) self.setError(_("Can not create dir: " ) + dirName)
return False return False
return createDirs return createDirs
@ -3132,7 +3105,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
else: else:
return True return True
else: else:
self.setError (_("name template not valid: ")+ str(fileTemplate)) self.setError(_("name template not valid: ")+ str(fileTemplate))
return False return False
def getTitle(self, comment, commentList): def getTitle(self, comment, commentList):
@ -3211,7 +3184,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
return dictTemplates return dictTemplates
if not self.objVar.defined("cl_template_path"): if not self.objVar.defined("cl_template_path"):
self.setError (_("not defined Var: ") + "cl_template_path") self.setError(_("not defined Var: ") + "cl_template_path")
return False return False
dirsTemplates = self.objVar.Get("cl_template_path") dirsTemplates = self.objVar.Get("cl_template_path")
dirsTemplates.sort() dirsTemplates.sort()
@ -3321,29 +3294,31 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
# Пропуск шаблонов директорий # Пропуск шаблонов директорий
if self.templDirNameFile == os.path.split(path)[1]: if self.templDirNameFile == os.path.split(path)[1]:
return True return True
if self.getNeedTemplate(path): # Проверка на переменные в названии файла
if self.getError(): if not self.getNeedTemplate(path):
return False
oldFile = path.partition(prefix)[2]
# файл в системе без условий
oldFile = "/".join(map(lambda x:x.split("?")[0],\
oldFile.split("/")))
listTemplTitle = prefix.split("/")[-2:]
templTitle = '"' + "/".join(listTemplTitle) + '"'
# Записываем в переменную обрабатываемый файл
self.objVar.Set("cl_pass_file",oldFile)
# Пишем время модификации *.env файлов
if oldFile.endswith(".env"):
self.timeConfigsIni[oldFile] = float(time.time())
filesApl = self.join(path, oldFile,(self.programVersion,templTitle),
optFile)
if filesApl:
self.filesApply += filesApl
else:
if self.getError(): if self.getError():
#print self.getError()
return False return False
pathTemplate, nameTemplate = os.path.split(oldFile) return True
if self.getError():
return False
nameFileConfig = path.partition(prefix)[2]
# файл в системе без условий
nameFileConfig = "/".join(map(lambda x:x.split("?")[0],\
nameFileConfig.split("/")))
listTemplTitle = prefix.split("/")[-2:]
templTitle = '"' + "/".join(listTemplTitle) + '"'
# Записываем в переменную обрабатываемый файл
self.objVar.Set("cl_pass_file",nameFileConfig)
# Пишем время модификации *.env файлов
if nameFileConfig.endswith(".env"):
self.timeConfigsIni[nameFileConfig] = float(time.time())
filesApl = self.join(path, nameFileConfig,(self.programVersion,
templTitle), optFile)
if self.getError():
return False
if filesApl:
self.filesApply += filesApl
pathTemplate, nameTemplate = os.path.split(nameFileConfig)
return {"path":pathTemplate, "name":nameTemplate} return {"path":pathTemplate, "name":nameTemplate}
def processingDirectory(self, path, prefix, opt): def processingDirectory(self, path, prefix, opt):
@ -3355,25 +3330,12 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
# Применяем шаблон # Применяем шаблон
pathDir, objHeadDir = self.__getApplyHeadDir(newDir, dirInfoFile, opt) pathDir, objHeadDir = self.__getApplyHeadDir(newDir, dirInfoFile, opt)
if objHeadDir: if objHeadDir:
if isinstance(objHeadDir, dirHeader):
if not objHeadDir.headerCorrect:
self.setError(_("Incorrect template: " ) +\
dirInfoFile)
self.setError(objHeadDir.errorMessage)
return False
if not objHeadDir.headerTerm:
if objHeadDir.getError():
self.setError(_("Incorrect template: " ) +\
dirInfoFile)
return False
crDirs = self.createDir(pathDir) crDirs = self.createDir(pathDir)
if crDirs is False: if crDirs is False:
return False return False
self.createdDirs += crDirs self.createdDirs += crDirs
else: else:
if self.getError(): if self.getError():
self.setError(_("Incorrect template: " ) +\
dirInfoFile)
return False return False
# Добавление количества файлов в пропущенной директории # Добавление количества файлов в пропущенной директории
if path in self.dictTemplates.keys(): if path in self.dictTemplates.keys():
@ -3420,11 +3382,12 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
templateDirFile) templateDirFile)
self.setError(objHead.errorMessage) self.setError(objHead.errorMessage)
return (applyDir, False) return (applyDir, False)
# Директория с профилями не будет применена
if not objHead.headerTerm: if not objHead.headerTerm:
if objHead.getError(): if objHead.getError():
self.setError(_("Incorrect template: " ) +\ self.setError(_("Incorrect template: " ) +\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
flagNoSkipDir = True flagNoSkipDir = True
if objHead.typeAppend == "skip": if objHead.typeAppend == "skip":
@ -3434,7 +3397,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if "path" in objHead.params: if "path" in objHead.params:
path = objHead.params['path'] path = objHead.params['path']
if not path or path and path[0] != "/": if not path or path and path[0] != "/":
self.setError (_("False value 'path' in template: " ) +\ self.setError(_("False value 'path' in template: " ) +\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
path = os.path.join(self._baseDir, path[1:]) path = os.path.join(self._baseDir, path[1:])
@ -3443,7 +3406,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if "name" in objHead.params: if "name" in objHead.params:
nameDir = objHead.params['name'] nameDir = objHead.params['name']
if "/" in nameDir or nameDir == ".." or nameDir == ".": if "/" in nameDir or nameDir == ".." or nameDir == ".":
self.setError (_("False value 'name' in template: " ) +\ self.setError(_("False value 'name' in template: " ) +\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
# Новый путь к директории # Новый путь к директории
@ -3477,7 +3440,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
else: else:
os.chmod(applyDir, mode) os.chmod(applyDir, mode)
else: else:
self.setError (_("False value 'chmod' in template: " ) +\ self.setError(_("False value 'chmod' in template: " ) +\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
@ -3491,16 +3454,16 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
try: try:
uid = pwd.getpwnam(strUid)[2] uid = pwd.getpwnam(strUid)[2]
except: except:
self.setError (_("Not user in this system: ") + strUid) self.setError(_("Not user in this system: ") + strUid)
self.setError (_("False value 'chown' in template: " )+\ self.setError(_("False value 'chown' in template: " )+\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
try: try:
import grp import grp
gid = grp.getgrnam(strGid)[2] gid = grp.getgrnam(strGid)[2]
except: except:
self.setError (_("Not group in this system: ")+strGid) self.setError(_("Not group in this system: ")+strGid)
self.setError (_("False value 'chown' in template: " )+\ self.setError(_("False value 'chown' in template: " )+\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
@ -3510,43 +3473,46 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
else: else:
os.chown(applyDir, uid, gid) os.chown(applyDir, uid, gid)
else: else:
self.setError (_("False value 'chown' in template: " ) +\ self.setError(_("False value 'chown' in template: " ) +\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
else: else:
self.setError (_("False value 'chown' in template: " ) +\ self.setError(_("False value 'chown' in template: " ) +\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
return (applyDir, objHead) return (applyDir, objHead)
def __getApplyHeadTemplate(self, newFile, oldFile, copyFile, optFile): def __getApplyHeadTemplate(self, nameFileTemplate, nameFileConfig,
templateFileType, optFile):
"""Применяет заголовок к шаблону (права, владелец, и.т. д)""" """Применяет заголовок к шаблону (права, владелец, и.т. д)"""
def function(text): def function(text):
"""Функция обработки функций в заголовке""" """Функция обработки функций в заголовке"""
return self.applyFuncTemplate(text, newFile, oldFile) return self.applyFuncTemplate(text,nameFileTemplate,nameFileConfig)
self.closeFiles() self.closeFiles()
# Файлы в системе к которым были применены шаблоны # Файлы в системе к которым были применены шаблоны
applyFiles = [oldFile] applyFiles = [nameFileConfig]
if copyFile: # В случае бинарного типа файла читаем шаблон
self.nameFileTemplate = os.path.abspath(newFile) if templateFileType == "bin":
self.nameFileTemplate = os.path.abspath(nameFileTemplate)
self.F_TEMPL = self.openTemplFile(self.nameFileTemplate) self.F_TEMPL = self.openTemplFile(self.nameFileTemplate)
self.textTemplate = self.F_TEMPL.read() self.textTemplate = self.F_TEMPL.read()
self.closeTemplFile() self.closeTemplFile()
objHeadNew = fileHeader(self.textTemplate, False, objHeadNew = fileHeader(self.textTemplate, False,
self.getFileType(),objVar=self.objVar, templateFileType ,objVar=self.objVar,
function=function) function=function)
if not objHeadNew.headerCorrect: if not objHeadNew.headerCorrect:
self.setError(_("Incorrect template: " ) +\ self.setError(_("Incorrect template: " ) +\
newFile) nameFileTemplate)
self.setError(objHeadNew.errorMessage) self.setError(objHeadNew.errorMessage)
return (applyFiles, False) return (applyFiles, False)
# файл шаблона не будет применен
if not objHeadNew.headerTerm: if not objHeadNew.headerTerm:
if objHeadNew.getError(): if objHeadNew.getError():
self.setError(_("Incorrect template: " ) +\ self.setError(_("Incorrect template: " ) +\
newFile) nameFileTemplate)
return (applyFiles, False) return (applyFiles, False)
pathProg = "" pathProg = ""
# Родительская директория # Родительская директория
@ -3556,7 +3522,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if "path" in objHeadNew.params: if "path" in objHeadNew.params:
path = objHeadNew.params['path'] path = objHeadNew.params['path']
if not path or path and path[0] != "/": if not path or path and path[0] != "/":
self.setError (_("False value 'path' in template: " ) +\ self.setError(_("False value 'path' in template: " ) +\
templateDirFile) templateDirFile)
return (applyDir, False) return (applyDir, False)
path = os.path.join(self._baseDir, path[1:]) path = os.path.join(self._baseDir, path[1:])
@ -3566,12 +3532,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if objHeadNew.params.has_key("name"): if objHeadNew.params.has_key("name"):
nameFile = objHeadNew.params['name'] nameFile = objHeadNew.params['name']
if "/" in nameFile or nameFile == ".." or nameFile == ".": if "/" in nameFile or nameFile == ".." or nameFile == ".":
self.setError (_("False value 'name' in template: " ) + newFile) self.setError(_("False value 'name' in template: " ) +\
nameFileTemplate)
return (applyFiles, False) return (applyFiles, False)
# Новый путь к оригинальному файлу # Новый путь к оригинальному файлу
pathOldFile = os.path.join(path,nameFile) pathOldFile = os.path.join(path,nameFile)
else: else:
pathOldFile = os.path.join(path,os.path.split(oldFile)[1]) pathOldFile = os.path.join(path,os.path.split(nameFileConfig)[1])
applyFiles = [pathOldFile] applyFiles = [pathOldFile]
# Фильтрация шаблонов по названию файла # Фильтрация шаблонов по названию файла
@ -3650,11 +3617,16 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if foundTemplateFile: if foundTemplateFile:
fd = os.open(pathOldFile, os.O_CREAT) fd = os.open(pathOldFile, os.O_CREAT)
os.close(fd) os.close(fd)
os.chmod(pathOldFile, fMode) oMode, oUid, oGid = getModeFile(pathOldFile)
os.chown(pathOldFile, fUid, fGid) # Если права не совпадают, меняем права
F_CONFN = open(pathOldFile, "r+") if fMode != oMode:
F_CONFN.write(buff) os.chmod(pathOldFile, fMode)
F_CONFN.close() # Если владелец не совпадает, меняем владельца
if (fUid, fGid) != (oUid, oGid):
os.chown(pathOldFile, fUid, fGid)
FD = open(pathOldFile, "r+")
FD.write(buff)
FD.close()
# Если символическая ссылка # Если символическая ссылка
if objHeadNew.params.has_key("symbolic"): if objHeadNew.params.has_key("symbolic"):
@ -3675,8 +3647,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
os.close(fd) os.close(fd)
os.chmod(pathOldFile, mode) os.chmod(pathOldFile, mode)
else: else:
self.setError (_("False value 'chmod' in template: " ) +\ self.setError(_("False value 'chmod' in template: " ) +\
newFile) nameFileTemplate)
return (applyFiles, False) return (applyFiles, False)
# chown - изменяем владельца и группу # chown - изменяем владельца и группу
if objHeadNew.params.has_key("chown"): if objHeadNew.params.has_key("chown"):
@ -3688,17 +3660,17 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
try: try:
uid = pwd.getpwnam(strUid)[2] uid = pwd.getpwnam(strUid)[2]
except: except:
self.setError (_("Not user in this system: ") + strUid) self.setError(_("Not user in this system: ") + strUid)
self.setError (_("False value 'chown' in template: " )+\ self.setError(_("False value 'chown' in template: " )+\
newFile) nameFileTemplate)
return (applyFiles, False) return (applyFiles, False)
try: try:
import grp import grp
gid = grp.getgrnam(strGid)[2] gid = grp.getgrnam(strGid)[2]
except: except:
self.setError (_("Not group in this system: ")+strGid) self.setError(_("Not group in this system: ")+strGid)
self.setError (_("False value 'chown' in template: " )+\ self.setError(_("False value 'chown' in template: " )+\
newFile) nameFileTemplate)
return (applyFiles, False) return (applyFiles, False)
if not os.path.exists(pathOldFile): if not os.path.exists(pathOldFile):
@ -3706,15 +3678,14 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
os.close(fd) os.close(fd)
os.chown(pathOldFile, uid, gid) os.chown(pathOldFile, uid, gid)
else: else:
self.setError (_("False value 'chown' in template: " ) +\ self.setError(_("False value 'chown' in template: " ) +\
newFile) nameFileTemplate)
return (applyFiles, False) return (applyFiles, False)
else: else:
self.setError (_("False value 'chown' in template: " ) +\ self.setError(_("False value 'chown' in template: " ) +\
newFile) nameFileTemplate)
return (applyFiles, False) return (applyFiles, False)
self.openFiles(nameFileTemplate, pathOldFile)
self.openFiles(newFile, pathOldFile)
if flagSymlink: if flagSymlink:
if os.path.exists(prevOldFile) or os.path.islink(prevOldFile): if os.path.exists(prevOldFile) or os.path.islink(prevOldFile):
if os.path.islink(prevOldFile): if os.path.islink(prevOldFile):
@ -3778,34 +3749,41 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
return False return False
return True return True
def join(self, newFile, oldFile, ListOptTitle, optFile): def join(self, nameFileTemplate, nameFileConfig, ListOptTitle, optFile):
"""Объединения шаблона и конф. файла """Объединения шаблона и конф. файла
join(newFile, oldFile, ListOptTitle) join(nameFileTemplate, nameFileConfig, ListOptTitle)
Объединение шаблона newFile и конф. файла oldFile, Объединение шаблона nameFileTemplate и конф. файла nameFileConfig,
ListOptTitle - список строк которые добавятся в заголовок ListOptTitle - список строк которые добавятся в заголовок
optFile = опции для шаблона optFile = опции для шаблона
""" """
# Выполняем условия для блока текста а так-же заменяем переменные # Выполняем условия для блока текста а так-же заменяем переменные
self.nameFileTemplate = os.path.abspath(newFile) self.nameFileTemplate = os.path.abspath(nameFileTemplate)
self.F_TEMPL = self.openTemplFile(self.nameFileTemplate) self.F_TEMPL = self.openTemplFile(self.nameFileTemplate)
self.textTemplate = self.F_TEMPL.read() self.textTemplate = self.F_TEMPL.read()
self.closeTemplFile() self.closeTemplFile()
copyFile = True # Флаг копирования шаблона в конфигурационный файл
if self.getFileType() != "bin": flagCopyTemplate = True
# Тип шаблона бинарный или текстовый
templateFileType = self.getTemplateType()
if templateFileType != "bin":
# Вычисляем условные блоки # Вычисляем условные блоки
self.textTemplate = self.applyTermsTemplate(self.textTemplate, self.textTemplate = self.applyTermsTemplate(self.textTemplate,
newFile, oldFile) nameFileTemplate,
nameFileConfig)
#print "|%s|" %(self.textTemplate) #print "|%s|" %(self.textTemplate)
# Заменяем переменные на их значения # Заменяем переменные на их значения
self.textTemplate = self.applyVarsTemplate(self.textTemplate, self.textTemplate = self.applyVarsTemplate(self.textTemplate,
newFile) nameFileTemplate)
# Вычисляем функции # Вычисляем функции
self.textTemplate = self.applyFuncTemplate(self.textTemplate, self.textTemplate = self.applyFuncTemplate(self.textTemplate,
newFile, oldFile) nameFileTemplate,
copyFile = False nameFileConfig)
filesApply, objHeadNew = self.__getApplyHeadTemplate(newFile, oldFile, flagCopyTemplate = False
copyFile, optFile) filesApply, objHeadNew = self.__getApplyHeadTemplate(nameFileTemplate,
nameFileConfig,
templateFileType,
optFile)
if not objHeadNew: if not objHeadNew:
return filesApply return filesApply
# Флаг - кодировка с бинарными примесями у файла шаблона включаем при # Флаг - кодировка с бинарными примесями у файла шаблона включаем при
@ -3813,19 +3791,19 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
flagNotUtf8New = False flagNotUtf8New = False
# Флаг - кодировка с бинарными примесями у оригинального файла # Флаг - кодировка с бинарными примесями у оригинального файла
flagNotUtf8Old = False flagNotUtf8Old = False
if not copyFile: if not flagCopyTemplate:
# проверяем кодировку шаблона # проверяем кодировку шаблона
if not self.fileIsUtf(newFile): if not self.fileIsUtf(nameFileTemplate):
flagNotUtf8New = True flagNotUtf8New = True
if not (objHeadNew.params.has_key("link") and\ if not (objHeadNew.params.has_key("link") and\
objHeadNew.params.has_key("symbolic")): objHeadNew.params.has_key("symbolic")):
# проверяем кодировку оригинального файла # проверяем кодировку оригинального файла
if not self.fileIsUtf(oldFile): if not self.fileIsUtf(nameFileConfig):
flagNotUtf8Old = True flagNotUtf8Old = True
self.textTemplate = objHeadNew.body self.textTemplate = objHeadNew.body
#if objHeadNew.fileType != "bin": #if objHeadNew.fileType != "bin":
#self.textTemplate = self.applyTermsTemplate(self.textTemplate, #self.textTemplate = self.applyTermsTemplate(self.textTemplate,
#newFile) #nameFileTemplate)
#self.textTemplate = self.applyVarsTemplate(self.textTemplate) #self.textTemplate = self.applyVarsTemplate(self.textTemplate)
# Титл конфигурационного файла # Титл конфигурационного файла
@ -3856,15 +3834,15 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
objTemplNew = self.getFormatObj(objHeadNew.fileType, objTemplNew = self.getFormatObj(objHeadNew.fileType,
self.textTemplate) self.textTemplate)
if not objTemplNew: if not objTemplNew:
self.setError (\ self.setError(\
_("Incorrect header parmeter format=%s in template")\ _("Incorrect header parmeter format=%s in template")\
%formatTemplate + " " + newFile) %formatTemplate + " " + nameFileTemplate)
return False return False
if "xml_" in objHeadNew.fileType: if "xml_" in objHeadNew.fileType:
if objTemplNew.getError(): if objTemplNew.getError():
self.setError (_("False template: " ) + newFile) self.setError(_("False template: " ) + nameFileTemplate)
return False return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0] nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0]
objTemplNew.setNameBodyNode(nameRootNode) objTemplNew.setNameBodyNode(nameRootNode)
# Объект Документ # Объект Документ
docObj = objTemplNew.docObj docObj = objTemplNew.docObj
@ -3904,8 +3882,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
# Впереди # Впереди
elif objHeadNew.typeAppend == "before": elif objHeadNew.typeAppend == "before":
if "xml_" in objHeadNew.fileType: if "xml_" in objHeadNew.fileType:
self.setError (\ self.setError(\
_("False option append=before in template %s") %newFile) _("False option append=before in template %s")\
%nameFileTemplate)
return False return False
if objHeadOld and objHeadOld.body: if objHeadOld and objHeadOld.body:
self.textConfig = objHeadOld.body self.textConfig = objHeadOld.body
@ -3926,8 +3905,9 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
# Cзади # Cзади
elif objHeadNew.typeAppend == "after": elif objHeadNew.typeAppend == "after":
if "xml_" in objHeadNew.fileType: if "xml_" in objHeadNew.fileType:
self.setError (\ self.setError(\
_("False option append=after in template %s") %newFile) _("False option append=after in template %s")\
%nameFileTemplate)
return False return False
if objHeadOld and objHeadOld.body: if objHeadOld and objHeadOld.body:
self.textConfig = objHeadOld.body self.textConfig = objHeadOld.body
@ -3952,15 +3932,15 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
objTemplNew = self.getFormatObj(objHeadNew.fileType, objTemplNew = self.getFormatObj(objHeadNew.fileType,
self.textTemplate) self.textTemplate)
if not objTemplNew: if not objTemplNew:
self.setError (\ self.setError(\
_("Incorrect header parmeter format=%s in template")\ _("Incorrect header parmeter format=%s in template")\
%formatTemplate + " " + newFile) %formatTemplate + " " + nameFileTemplate)
return False return False
if "xml_" in objHeadNew.fileType: if "xml_" in objHeadNew.fileType:
if objTemplNew.getError(): if objTemplNew.getError():
self.setError (_("False template: " ) + newFile) self.setError(_("False template: " ) + nameFileTemplate)
return False return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0] nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0]
objTemplNew.setNameBodyNode(nameRootNode) objTemplNew.setNameBodyNode(nameRootNode)
# Титл для объединения # Титл для объединения
if ListOptTitle: if ListOptTitle:
@ -3994,13 +3974,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
objTemplOld = self.getFormatObj(objHeadNew.fileType, objTemplOld = self.getFormatObj(objHeadNew.fileType,
self.textConfig) self.textConfig)
if not objTemplOld: if not objTemplOld:
self.setError (_("Error in template %s") %oldFile) self.setError(_("Error in template %s") %nameFileConfig)
return False return False
if "xml_" in objHeadNew.fileType: if "xml_" in objHeadNew.fileType:
if objTemplOld.getError(): if objTemplOld.getError():
self.setError (_("False template: " ) + oldFile) self.setError(_("False template: " ) + nameFileConfig)
return False return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0] nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0]
objTemplOld.setNameBodyNode(nameRootNode) objTemplOld.setNameBodyNode(nameRootNode)
#print "#%s#" %(objTemplOld.docObj.body.toprettyxml()) #print "#%s#" %(objTemplOld.docObj.body.toprettyxml())
@ -4010,7 +3990,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
#print objTemplNew.doc.toprettyxml() #print objTemplNew.doc.toprettyxml()
if "xml_" in objHeadNew.fileType: if "xml_" in objHeadNew.fileType:
if objTemplOld.getError(): if objTemplOld.getError():
self.setError (_("False template: " ) + newFile) self.setError(_("False template: " ) + nameFileTemplate)
return False return False
data = \ data = \
objTemplOld.getConfig().encode("UTF-8").split("\n") objTemplOld.getConfig().encode("UTF-8").split("\n")
@ -4033,11 +4013,11 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
self.saveConfFile() self.saveConfFile()
return filesApply return filesApply
else: else:
self.setError (_("False (type append) template: " ) +\ self.setError(_("False (type append) template: " ) +\
objHeadNew.typeAppend) objHeadNew.typeAppend)
return False return False
else: else:
self.setError (_("Type template not found: ") + newFile) self.setError(_("Type template not found: ") + nameFileTemplate)
return False return False
return filesApply return filesApply
@ -4126,7 +4106,7 @@ class iniParser(_error, templateFormat):
def checkIniFile(self, textIni): def checkIniFile(self, textIni):
"""Проверка на правильность формата файла""" """Проверка на правильность формата файла"""
if self.checkIni == None: if self.checkIni is None:
# Ошибка # Ошибка
if textIni == False: if textIni == False:
self.checkIni = False self.checkIni = False

@ -22,6 +22,7 @@ import types
import subprocess import subprocess
import stat import stat
from shutil import copytree, rmtree from shutil import copytree, rmtree
import ctypes
class _error: class _error:
# Здесь ошибки, если они есть # Здесь ошибки, если они есть
@ -40,6 +41,46 @@ class _error:
self.error.append(error) self.error.append(error)
return True return True
class typeFile:
"""Получение типа файла"""
__mgc = None
__cookie = None
def __init__(self):
# Загружаем libmagic.so
self.__mgc = ctypes.cdll.LoadLibrary("libmagic.so")
# Создаем новый cookie (требуется для
# работы с magic-последовательностями)
# 0x10 | 0x400 = MAGIC_MIME (константа
# декларируется в magic.h)
self.__cookie = self.__mgc.magic_open(0x10 | 0x400)
# Загружаем в __cookie
# /etc/file/magic.mime (т.к. указано None)
self.__mgc.magic_load(self.__cookie, None)
def __del__(self):
"""Закрываем __cookie"""
self.__mgc.magic_close(self.__cookie)
def getMType(self,filename):
"""информация о типе файла"""
result = self.__mgc.magic_file(self.__cookie,filename)
# magic_file возвращает указатель const char*,
# mimetype.value - это строка по указателю
mimetype = ctypes.c_char_p(result)
rez = mimetype.value
return rez
def isBinary(self,filename):
"""является ли файл бинарным"""
mime = self.getMType(filename)
if mime.count("`"):
return mime
elif mime.count("binary"):
return True
return False
def runOsCommand(cmd, inStr=None, ret_first=None, env_dict=None): def runOsCommand(cmd, inStr=None, ret_first=None, env_dict=None):
"""Выполняет внешнюю программу """Выполняет внешнюю программу

@ -16,6 +16,7 @@
import sys import sys
import time import time
import re
from xml import xpath from xml import xpath
import xml.dom.minidom import xml.dom.minidom
from format.xml_xfce import xml_xfce from format.xml_xfce import xml_xfce

Loading…
Cancel
Save