Reorganization

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

@ -31,7 +31,7 @@ from cl_ldap import ldapFun
# Переопределение exit
import cl_overriding
from cl_utils import _error, _toUNICODE, getModeFile, removeDir
from cl_utils import _error, _toUNICODE, getModeFile, removeDir, typeFile
import cl_lang
tr = cl_lang.lang()
@ -164,8 +164,8 @@ class _terms(_error):
self.setError("'%s'"%term + " " + _("incorrect"))
self.setError(textError)
return False
if "load" == searchFunct.group(1):
if re.search("\(\s*num\s*,",vals[0]):
if "load" == searchFunct.group(1) and\
re.search("\(\s*num\s*,",vals[0]):
if valVars:
try:
valVars = int(valVars)
@ -233,7 +233,7 @@ class _terms(_error):
listEqual.append(False)
flagNotIniFunct = False
else:
if flagIntTypeVar == None:
if flagIntTypeVar is None:
flagIntTypeVar = True
try:
valVars = int(valVars)
@ -1896,44 +1896,6 @@ class _file(_error):
# Дескриптор файла конфигурационного файла
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):
"""Записать конфигурацию"""
if self.F_CONF:
@ -2751,9 +2713,6 @@ class templateFunction(_error, _shareTemplate):
Используеться совместно c funcIni
"""
localVarsIni = {}
# Выходим если есть предыдущие ошибки
if self.getError():
return False
# получить объект ini файла
config = iniParser(iniFileName)
# получаем все секции из конфигурационного файла
@ -2992,6 +2951,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
self.functObj = templateFunction(self.objVar)
# Метод применения функций к шаблонам
self.applyFuncTemplate = self.functObj.applyFuncTemplate
# Объект для определения типа файла шаблона
self.typeFileObj = typeFile()
# Преобразование восьмеричного в целое (ввод строка, вывод число)
@ -3007,7 +2968,19 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
self.setError(_("Empty oct value"))
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):
"""Создает директорию"""
@ -3321,29 +3294,31 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
# Пропуск шаблонов директорий
if self.templDirNameFile == os.path.split(path)[1]:
return True
if self.getNeedTemplate(path):
# Проверка на переменные в названии файла
if not self.getNeedTemplate(path):
if self.getError():
return False
return True
if self.getError():
return False
oldFile = path.partition(prefix)[2]
nameFileConfig = path.partition(prefix)[2]
# файл в системе без условий
oldFile = "/".join(map(lambda x:x.split("?")[0],\
oldFile.split("/")))
nameFileConfig = "/".join(map(lambda x:x.split("?")[0],\
nameFileConfig.split("/")))
listTemplTitle = prefix.split("/")[-2:]
templTitle = '"' + "/".join(listTemplTitle) + '"'
# Записываем в переменную обрабатываемый файл
self.objVar.Set("cl_pass_file",oldFile)
self.objVar.Set("cl_pass_file",nameFileConfig)
# Пишем время модификации *.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 nameFileConfig.endswith(".env"):
self.timeConfigsIni[nameFileConfig] = float(time.time())
filesApl = self.join(path, nameFileConfig,(self.programVersion,
templTitle), optFile)
if self.getError():
#print self.getError()
return False
pathTemplate, nameTemplate = os.path.split(oldFile)
if filesApl:
self.filesApply += filesApl
pathTemplate, nameTemplate = os.path.split(nameFileConfig)
return {"path":pathTemplate, "name":nameTemplate}
def processingDirectory(self, path, prefix, opt):
@ -3355,25 +3330,12 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
# Применяем шаблон
pathDir, objHeadDir = self.__getApplyHeadDir(newDir, dirInfoFile, opt)
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)
if crDirs is False:
return False
self.createdDirs += crDirs
else:
if self.getError():
self.setError(_("Incorrect template: " ) +\
dirInfoFile)
return False
# Добавление количества файлов в пропущенной директории
if path in self.dictTemplates.keys():
@ -3420,6 +3382,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
templateDirFile)
self.setError(objHead.errorMessage)
return (applyDir, False)
# Директория с профилями не будет применена
if not objHead.headerTerm:
if objHead.getError():
self.setError(_("Incorrect template: " ) +\
@ -3519,33 +3482,36 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
return (applyDir, False)
return (applyDir, objHead)
def __getApplyHeadTemplate(self, newFile, oldFile, copyFile, optFile):
def __getApplyHeadTemplate(self, nameFileTemplate, nameFileConfig,
templateFileType, optFile):
"""Применяет заголовок к шаблону (права, владелец, и.т. д)"""
def function(text):
"""Функция обработки функций в заголовке"""
return self.applyFuncTemplate(text, newFile, oldFile)
return self.applyFuncTemplate(text,nameFileTemplate,nameFileConfig)
self.closeFiles()
# Файлы в системе к которым были применены шаблоны
applyFiles = [oldFile]
if copyFile:
self.nameFileTemplate = os.path.abspath(newFile)
applyFiles = [nameFileConfig]
# В случае бинарного типа файла читаем шаблон
if templateFileType == "bin":
self.nameFileTemplate = os.path.abspath(nameFileTemplate)
self.F_TEMPL = self.openTemplFile(self.nameFileTemplate)
self.textTemplate = self.F_TEMPL.read()
self.closeTemplFile()
objHeadNew = fileHeader(self.textTemplate, False,
self.getFileType(),objVar=self.objVar,
templateFileType ,objVar=self.objVar,
function=function)
if not objHeadNew.headerCorrect:
self.setError(_("Incorrect template: " ) +\
newFile)
nameFileTemplate)
self.setError(objHeadNew.errorMessage)
return (applyFiles, False)
# файл шаблона не будет применен
if not objHeadNew.headerTerm:
if objHeadNew.getError():
self.setError(_("Incorrect template: " ) +\
newFile)
nameFileTemplate)
return (applyFiles, False)
pathProg = ""
@ -3566,12 +3532,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if objHeadNew.params.has_key("name"):
nameFile = objHeadNew.params['name']
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)
# Новый путь к оригинальному файлу
pathOldFile = os.path.join(path,nameFile)
else:
pathOldFile = os.path.join(path,os.path.split(oldFile)[1])
pathOldFile = os.path.join(path,os.path.split(nameFileConfig)[1])
applyFiles = [pathOldFile]
# Фильтрация шаблонов по названию файла
@ -3650,11 +3617,16 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if foundTemplateFile:
fd = os.open(pathOldFile, os.O_CREAT)
os.close(fd)
oMode, oUid, oGid = getModeFile(pathOldFile)
# Если права не совпадают, меняем права
if fMode != oMode:
os.chmod(pathOldFile, fMode)
# Если владелец не совпадает, меняем владельца
if (fUid, fGid) != (oUid, oGid):
os.chown(pathOldFile, fUid, fGid)
F_CONFN = open(pathOldFile, "r+")
F_CONFN.write(buff)
F_CONFN.close()
FD = open(pathOldFile, "r+")
FD.write(buff)
FD.close()
# Если символическая ссылка
if objHeadNew.params.has_key("symbolic"):
@ -3676,7 +3648,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
os.chmod(pathOldFile, mode)
else:
self.setError(_("False value 'chmod' in template: " ) +\
newFile)
nameFileTemplate)
return (applyFiles, False)
# chown - изменяем владельца и группу
if objHeadNew.params.has_key("chown"):
@ -3690,7 +3662,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
except:
self.setError(_("Not user in this system: ") + strUid)
self.setError(_("False value 'chown' in template: " )+\
newFile)
nameFileTemplate)
return (applyFiles, False)
try:
import grp
@ -3698,7 +3670,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
except:
self.setError(_("Not group in this system: ")+strGid)
self.setError(_("False value 'chown' in template: " )+\
newFile)
nameFileTemplate)
return (applyFiles, False)
if not os.path.exists(pathOldFile):
@ -3707,14 +3679,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
os.chown(pathOldFile, uid, gid)
else:
self.setError(_("False value 'chown' in template: " ) +\
newFile)
nameFileTemplate)
return (applyFiles, False)
else:
self.setError(_("False value 'chown' in template: " ) +\
newFile)
nameFileTemplate)
return (applyFiles, False)
self.openFiles(newFile, pathOldFile)
self.openFiles(nameFileTemplate, pathOldFile)
if flagSymlink:
if os.path.exists(prevOldFile) or os.path.islink(prevOldFile):
if os.path.islink(prevOldFile):
@ -3778,34 +3749,41 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
return False
return True
def join(self, newFile, oldFile, ListOptTitle, optFile):
def join(self, nameFileTemplate, nameFileConfig, ListOptTitle, optFile):
"""Объединения шаблона и конф. файла
join(newFile, oldFile, ListOptTitle)
Объединение шаблона newFile и конф. файла oldFile,
join(nameFileTemplate, nameFileConfig, ListOptTitle)
Объединение шаблона nameFileTemplate и конф. файла nameFileConfig,
ListOptTitle - список строк которые добавятся в заголовок
optFile = опции для шаблона
"""
# Выполняем условия для блока текста а так-же заменяем переменные
self.nameFileTemplate = os.path.abspath(newFile)
self.nameFileTemplate = os.path.abspath(nameFileTemplate)
self.F_TEMPL = self.openTemplFile(self.nameFileTemplate)
self.textTemplate = self.F_TEMPL.read()
self.closeTemplFile()
copyFile = True
if self.getFileType() != "bin":
# Флаг копирования шаблона в конфигурационный файл
flagCopyTemplate = True
# Тип шаблона бинарный или текстовый
templateFileType = self.getTemplateType()
if templateFileType != "bin":
# Вычисляем условные блоки
self.textTemplate = self.applyTermsTemplate(self.textTemplate,
newFile, oldFile)
nameFileTemplate,
nameFileConfig)
#print "|%s|" %(self.textTemplate)
# Заменяем переменные на их значения
self.textTemplate = self.applyVarsTemplate(self.textTemplate,
newFile)
nameFileTemplate)
# Вычисляем функции
self.textTemplate = self.applyFuncTemplate(self.textTemplate,
newFile, oldFile)
copyFile = False
filesApply, objHeadNew = self.__getApplyHeadTemplate(newFile, oldFile,
copyFile, optFile)
nameFileTemplate,
nameFileConfig)
flagCopyTemplate = False
filesApply, objHeadNew = self.__getApplyHeadTemplate(nameFileTemplate,
nameFileConfig,
templateFileType,
optFile)
if not objHeadNew:
return filesApply
# Флаг - кодировка с бинарными примесями у файла шаблона включаем при
@ -3813,19 +3791,19 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
flagNotUtf8New = False
# Флаг - кодировка с бинарными примесями у оригинального файла
flagNotUtf8Old = False
if not copyFile:
if not flagCopyTemplate:
# проверяем кодировку шаблона
if not self.fileIsUtf(newFile):
if not self.fileIsUtf(nameFileTemplate):
flagNotUtf8New = True
if not (objHeadNew.params.has_key("link") and\
objHeadNew.params.has_key("symbolic")):
# проверяем кодировку оригинального файла
if not self.fileIsUtf(oldFile):
if not self.fileIsUtf(nameFileConfig):
flagNotUtf8Old = True
self.textTemplate = objHeadNew.body
#if objHeadNew.fileType != "bin":
#self.textTemplate = self.applyTermsTemplate(self.textTemplate,
#newFile)
#nameFileTemplate)
#self.textTemplate = self.applyVarsTemplate(self.textTemplate)
# Титл конфигурационного файла
@ -3858,13 +3836,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if not objTemplNew:
self.setError(\
_("Incorrect header parmeter format=%s in template")\
%formatTemplate + " " + newFile)
%formatTemplate + " " + nameFileTemplate)
return False
if "xml_" in objHeadNew.fileType:
if objTemplNew.getError():
self.setError (_("False template: " ) + newFile)
self.setError(_("False template: " ) + nameFileTemplate)
return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0]
nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0]
objTemplNew.setNameBodyNode(nameRootNode)
# Объект Документ
docObj = objTemplNew.docObj
@ -3905,7 +3883,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
elif objHeadNew.typeAppend == "before":
if "xml_" in objHeadNew.fileType:
self.setError(\
_("False option append=before in template %s") %newFile)
_("False option append=before in template %s")\
%nameFileTemplate)
return False
if objHeadOld and objHeadOld.body:
self.textConfig = objHeadOld.body
@ -3927,7 +3906,8 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
elif objHeadNew.typeAppend == "after":
if "xml_" in objHeadNew.fileType:
self.setError(\
_("False option append=after in template %s") %newFile)
_("False option append=after in template %s")\
%nameFileTemplate)
return False
if objHeadOld and objHeadOld.body:
self.textConfig = objHeadOld.body
@ -3954,13 +3934,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
if not objTemplNew:
self.setError(\
_("Incorrect header parmeter format=%s in template")\
%formatTemplate + " " + newFile)
%formatTemplate + " " + nameFileTemplate)
return False
if "xml_" in objHeadNew.fileType:
if objTemplNew.getError():
self.setError (_("False template: " ) + newFile)
self.setError(_("False template: " ) + nameFileTemplate)
return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0]
nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0]
objTemplNew.setNameBodyNode(nameRootNode)
# Титл для объединения
if ListOptTitle:
@ -3994,13 +3974,13 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
objTemplOld = self.getFormatObj(objHeadNew.fileType,
self.textConfig)
if not objTemplOld:
self.setError (_("Error in template %s") %oldFile)
self.setError(_("Error in template %s") %nameFileConfig)
return False
if "xml_" in objHeadNew.fileType:
if objTemplOld.getError():
self.setError (_("False template: " ) + oldFile)
self.setError(_("False template: " ) + nameFileConfig)
return False
nameRootNode = oldFile.rpartition("/")[2].split(".")[0]
nameRootNode=nameFileConfig.rpartition("/")[2].split(".")[0]
objTemplOld.setNameBodyNode(nameRootNode)
#print "#%s#" %(objTemplOld.docObj.body.toprettyxml())
@ -4010,7 +3990,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
#print objTemplNew.doc.toprettyxml()
if "xml_" in objHeadNew.fileType:
if objTemplOld.getError():
self.setError (_("False template: " ) + newFile)
self.setError(_("False template: " ) + nameFileTemplate)
return False
data = \
objTemplOld.getConfig().encode("UTF-8").split("\n")
@ -4037,7 +4017,7 @@ class template(_file, _terms, xmlShare, templateFormat, _shareTemplate):
objHeadNew.typeAppend)
return False
else:
self.setError (_("Type template not found: ") + newFile)
self.setError(_("Type template not found: ") + nameFileTemplate)
return False
return filesApply
@ -4126,7 +4106,7 @@ class iniParser(_error, templateFormat):
def checkIniFile(self, textIni):
"""Проверка на правильность формата файла"""
if self.checkIni == None:
if self.checkIni is None:
# Ошибка
if textIni == False:
self.checkIni = False

@ -22,6 +22,7 @@ import types
import subprocess
import stat
from shutil import copytree, rmtree
import ctypes
class _error:
# Здесь ошибки, если они есть
@ -40,6 +41,46 @@ class _error:
self.error.append(error)
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):
"""Выполняет внешнюю программу

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

Loading…
Cancel
Save