Remove needless modules

master3.3
Mike Hiretsky 12 years ago
parent 4bf3be335f
commit ccc222ccc5

@ -1,218 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys, os, re
import cl_install
import traceback
from cl_install import InstallError
__version__ = cl_install.__version__
__app__ = cl_install.__app__
from calculate.lib.datavars import DataVars
from calculate.lib.cl_template import template, templateClt
from calculate.lib.cl_print import color_print
from calculate.lib import cl_overriding
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
cl_overriding.exit = cl_install.defaultExit
cl_overriding.printERROR = cl_install.defaultPrintERROR
class DataVarsObject(DataVars):
"""Share class for variables"""
def __init__(self, section):
DataVars.__init__(self)
self.section=section
def importDataObject(self, **args):
"""Filling variables for section"""
self.importData(self.section,
('calculate.{package}.cl_vars_{package}'.format(
package=self.section),
'calculate.{package}.cl_fill_{package}'.format(
package=self.section)))
self.flIniFile()
class updateConfFiles(color_print):
"""Для обновления конфигурационных файлов"""
def __init__(self):
clVars = DataVarsObject("install")
clVars.importDataObject()
self.clVars = clVars
self.installProgs = self.clVars.GetList("cl_merges")
def applyCltTemplate(self, cltTemplatePath):
"""Применяем clt шаблон"""
realPath = "/usr/lib/calculate-2.2/calculate-install"
pymPath = os.path.join(realPath,"pym")
if not "calculate-install" in self.installProgs:
self.printERROR(_("Failed to install %s")
%"calculate-install")
self.printWARNING(\
_("To install the program, run 'cl-install --install'"))
return False
dirsTemplates = self.clVars.Get("cl_template_clt_path")
flagFoundPath = False
for dirTemplates in dirsTemplates:
if cltTemplatePath.startswith(dirTemplates):
flagFoundPath = True
if not flagFoundPath:
self.printERROR(_("Incorrect path %s")%cltTemplatePath)
self.printWARNING(_("Use the following directories: %s and their "
"subdirectories")%', '.join(dirsTemplates))
return False
if not os.path.exists(cltTemplatePath):
self.printERROR(_("File '%s' does not exist")%cltTemplatePath)
return False
if not os.access(cltTemplatePath, os.R_OK):
self.printERROR(_("Permission denied: '%s'")%cltTemplatePath)
return False
if not os.path.isfile(cltTemplatePath):
self.printERROR(_("'%s' is not a file")%cltTemplatePath)
return False
clTempl = templateClt(self.clVars)
if not cltTemplatePath.endswith(clTempl.extFileTemplate):
self.printERROR(_("the extension of file '%s' is not 'clt'")
%cltTemplatePath)
return False
calcPkg = self.clVars.Get("cl_name")+"-" + self.clVars.Get("cl_ver")
# merge
self.clVars.Set("cl_action", "merge", True)
nameFile = clTempl.applyTemplate(cltTemplatePath)
if nameFile is False:
self.printERROR(_("Template error in package %s")\
%calcPkg)
for errMess in clTempl.getError().splitlines():
self.printERROR(errMess)
return False
if nameFile is True:
if clTempl.executedFiles:
self.printWARNING(_("Template %s was applied")
%cltTemplatePath)
else:
self.printWARNING(_("Template %s not applied")
%cltTemplatePath)
else:
self.printWARNING(_("Package %s has changed files")%calcPkg+":")
self.printWARNING(" "*5 + nameFile)
return True
def printVars(self, opts=["all"]):
"""Печать существующих переменных"""
if opts == ["all"]:
self.clVars.printVars()
else:
self.clVars.printVars()
def applyAllTemplates(self, location="all", package=None):
"""Обновление конфигурационных файлов"""
if not "calculate-install" in self.installProgs:
self.printERROR(_("Failed to install %s")
%"calculate-install")
self.printWARNING(\
_("To install the program, run 'cl-install --install'"))
return False
if package and "/" in package:
package = package.partition('/')[2]
sectionsWork = map(lambda x: x.rpartition("-")[2], self.installProgs)
dictPakkages = {}
oldPymPath = ""
listIndex = []
clTempl = False
for sectName in sectionsWork:
realPath = "/usr/lib/calculate-2.2/calculate-%s"%sectName
pymPath = os.path.join(realPath,"pym")
if not os.path.isdir(pymPath):
continue
if len(filter(lambda x:x.startswith("cl_vars_") and\
x.endswith(".py") or x.startswith("cl_fill_") and\
x.endswith(".py"), os.listdir(pymPath)))==2:
if oldPymPath:
sys.path = filter(lambda x: x!=oldPymPath, sys.path)
sys.path.insert(0, os.path.abspath(pymPath))
oldPymPath = os.path.abspath(pymPath)
clVars = DataVarsObject(sectName)
clVars.importDataObject()
if location in ("local", "remote"):
listTemplatePaths = clVars.Get("cl_template_path")
if len(listTemplatePaths) != 3:
self.printERROR(\
_("Error in template variable 'cl_template_path=%s'")\
%str(listTemplatePaths))
return False
elif location == "local":
clVars.Set("cl_template_path", [listTemplatePaths[1]],
True)
elif location == "remote":
clVars.Set("cl_template_path", [listTemplatePaths[2]],
True)
# merge
clVars.Set("cl_action", "merge" ,True)
# будут применены все шаблоны .clt (cltFilter=False)
# и обычные шаблоны
clTempl = template(clVars, cltFilter=False,
printWarning=False)
error = None
if(package):
clVars.Set("cl_belong_pkg",package,True)
try:
if location=="clt":
# apply clt templates
dirsFiles = clTempl.cltObj.applyTemplates()
else:
# apply all templates
dirsFiles = clTempl.applyTemplates()
except InstallError,e:
error = e
except (Exception),e:
error = ""
for i in apply(traceback.format_exception, sys.exc_info()):
error += i
finally:
if error:
for line in filter(lambda x: x,str(error).split('\n')):
self.printERROR(line)
return False
nameAndVerPkg = clVars.Get("cl_name")+"-"+\
clVars.Get("cl_ver")
if dirsFiles is False:
self.printERROR(_("Template error in package %s")\
%nameAndVerPkg)
for errMess in clTempl.getError().splitlines():
self.printERROR(errMess)
return False
if dirsFiles and dirsFiles[1]:
if not nameAndVerPkg in listIndex:
listIndex.append(nameAndVerPkg)
dictPakkages[nameAndVerPkg] =\
sorted(list(set(dirsFiles[1])))
if dictPakkages:
for calcPkg in listIndex:
self.printWARNING(_("Package %s has changed files")%calcPkg+":")
for nameF in dictPakkages[calcPkg]:
nameFile = nameF
if nameFile[:1] != "/":
nameFile = "/" + nameFile
self.printWARNING(" "*5 + nameFile)
if clTempl and clTempl.getWarning():
cl_overriding.printSUCCESS("")
for warn in clTempl.getWarning().split("\n"):
self.printWARNING(warn)
return True

@ -1,140 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os, sys, re
from os import path
from cl_apply_template import updateConfFiles, __app__, __version__
from calculate.lib.cl_opt import opt
from calculate.install.cl_share_cmd import share_cmd
from calculate.lib.utils.files import listDirectory,pathJoin
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
USAGE = _("%prog [options] path_to_the_clt_file")
COMMENT_EXAMPLES = _("Apply all templates to all packages")
EXAMPLES = _("%prog --locate all")
DESCRIPTION = _("Calculate Linux Templates Utility")
CMD_OPTIONS = [{'shortOption':"l",
'longOption':"locate",
'optVal':"LOCATE",
'type':'choice',
'choices':['all','clt','local','remote'],
'help':_("select location for \
'all','clt','local','remote' templates")},
{'longOption':'merge',
'optVal':"PACKAGE",
'help':_("apply templates to the specified package only")
},
{'longOption':"clt",
'optVal':"CLT_TEMPLATE",
'help':_("process the clt template (by default)")
}]
class apply_template_cmd(share_cmd):
def __init__(self):
# Объект опций командной строки
self.optobj = opt(\
package=__app__,
version=__version__,
usage=USAGE,
examples=EXAMPLES,
comment_examples=COMMENT_EXAMPLES,
description=DESCRIPTION,
option_list=CMD_OPTIONS + opt.color_control + opt.variable_control,
check_values=self.checkOpts)
# Создаем объект логики
self.logicObj = updateConfFiles()
reVerSplit = re.compile(r"^(.*?)-(([^-]+?)(?:-(r\d+))?)(?:.(tbz2))?$",re.S)
def checkAtom(self,atom):
"""Chech if atom is installed"""
dbPkg = '/var/db/pkg'
if "/" in atom:
category,slash,package = atom.partition("/")
categoryPath = pathJoin(dbPkg,category)
return \
map(lambda x:"%s/%s"%(category,x.groups()[0]),
filter(lambda x:x and x.groups()[0] == package,
map(self.reVerSplit.search,
filter(lambda x:x.startswith(package),
listDirectory(categoryPath)))))
else:
return reduce(lambda x,y:x+self.checkAtom("%s/%s"%(y,atom)),
listDirectory(dbPkg),[])
def checkOpts(self, optObj, args):
"""Проверка опций командной строки"""
if optObj.merge:
if not self.checkAtom(optObj.merge):
errMsg = _("incorrect option")+":"+\
" --%s" %"merge" + \
": "+_("wrong package") + ": " +\
str(optObj.merge)
self.optobj.error(errMsg)
return False
if len(args) == 0:
if not optObj.clt and not optObj.l:
errMsg = _("required option")+": --clt "+_("or")+" --locate"
self.optobj.error(errMsg)
return False
elif len(args) == 1:
if optObj.clt:
errMsg = _("incorrect option")+":"+" --%s" %"clt" + " " + \
str(optObj.clt)
self.optobj.error(errMsg)
return False
if optObj.l:
errMsg = _("incorrect option")+":"+" --%s" %"locate" + " " + \
str(optObj.l)
self.optobj.error(errMsg)
return False
else:
errMsg = _("incorrect argument") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
self.optobj.checkVarSyntax(optObj)
return optObj, args
def applyCltTemplate(self, cltTemplate):
"""Применяем clt шаблон"""
if cltTemplate[0] != "/":
currentPath = os.getcwd()
cltTemplate = os.path.join(currentPath, cltTemplate)
return self.logicObj.applyCltTemplate(cltTemplate)
def applyAllTemplates(self,pkg):
"""Применяем все шаблоны"""
return self.logicObj.applyAllTemplates(package=pkg)
def applyLocalTemplates(self,pkg):
"""We use local templates"""
return self.logicObj.applyAllTemplates(location="local",package=pkg)
def applyRemoteTemplates(self,pkg):
"""We use remote templates"""
return self.logicObj.applyAllTemplates(location="remote",package=pkg)
def applyCltTemplates(self):
"""We use all clt templates"""
return self.logicObj.applyAllTemplates(location="clt")

File diff suppressed because it is too large Load Diff

@ -1,94 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from calculate.lib.cl_print import color_print
from calculate.lib.utils.common import _error
import cl_install
# Перевод сообщений для программы
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
from calculate.lib import cl_overriding
class share_cmd(color_print, _error):
"""Класс общих методов обработки опций командной строки"""
def isRoot(self, printError=True):
"""Detect root user"""
if os.getuid() == 0 and os.getgid() == 0:
return True
else:
if printError:
self.printERROR(_("The user is not root"))
return False
def printVars(self, optObj):
"""Печать переменных"""
if optObj.v:
varsFilter = None
varsNames = []
format = "default"
# Фильтрование переменных
if optObj.filter:
optCmd = optObj.filter
if ',' in optCmd:
varsNames = optCmd.split(",")
else:
varsFilter = optCmd
if optObj.xml:
format = "xml"
try:
v = int(optObj.v)
except:
v = 1
cl_overriding.exit = cl_install.defaultExit
cl_overriding.printERROR = cl_install.defaultPrintERROR
self.logicObj.clVars.printVars(varsFilter, varsNames,
outFormat=format,
verbose=v)
def setVars(self, optObj):
"""Установка переменных"""
if optObj.set:
for val in optObj.set:
k,o,v = val.partition('=')
if self.logicObj.clVars.exists(k):
if self.logicObj.clVars.SetWriteVar(k,v) == False:
return False
else:
self.printERROR(_('variable %s not found')%k)
return False
return True
def writeVars(self, optObj):
"""Запись переменных"""
if not self.logicObj.clVars.WriteVars(header="install"):
errMsg = self.getError()
if errMsg:
self.printERROR(errMsg.strip())
self.printERROR(_("Failed to write template variables"))
return False
return True
def setPrintNoColor(self, optObj):
"""Установка печати сообщений без цвета"""
if optObj.color and optObj.color=="never":
color_print.colorPrint = lambda *arg : sys.stdout.write(arg[-1]) or\
sys.stdout.flush()

@ -1,39 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2010-2012 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0 #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# mode - read only or writeable variable
# value - default variable value
# select - list of posible values for variable
# hide - flag, if it is True, then the variable is not printable
# printval - print value of variable
from cl_install import __version__, __app__
from calculate.lib.cl_vars import Data as LibData
from calculate.lib.datavars import Variables
from calculate.lib.variables import System, Net, Env, X11
from calculate.install.variables import (InstallAction, InstallLocale,
Distro,InstallKernel,InstallX11,InstallNet,
InstallSystem,InstallLinux,InstallDisk)
class Data(InstallAction,InstallLocale,Distro,InstallKernel,
InstallX11,InstallNet,InstallSystem,InstallLinux,
InstallDisk,LibData):
section = "install"
vars = ["cl_name","cl_ver"]
# program name
cl_name = {'value':__app__}
# program version
cl_ver = {'value':__version__}

@ -1,76 +0,0 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
sys.path.insert(0,os.path.abspath('/usr/lib/calculate-2.2/calculate-lib/pym'))
sys.path.insert(0,
os.path.abspath('/usr/lib/calculate-2.2/calculate-install/pym'))
from cl_lang import lang
tr = lang()
tr.setGlobalDomain('cl_install')
tr.setLanguage(sys.modules[__name__])
from cl_apply_template_cmd import apply_template_cmd
if __name__ == "__main__":
obj = apply_template_cmd()
ret = obj.optobj.parse_args()
if ret is False:
sys.exit(1)
options, args = ret
# set color/nocolor for display messages
obj.setPrintNoColor(options)
# set values to variables
if not obj.setVars(options):
sys.exit(1)
# Печать переменных
if options.v:
obj.printVars(options)
sys.exit(0)
# check root
if not obj.isRoot():
sys.exit(1)
listLocate = options.l
if listLocate:
if 'all' in listLocate:
# apply all templates
if not obj.applyAllTemplates(options.merge):
sys.exit(1)
elif 'local' in listLocate:
# apply local templates
if not obj.applyLocalTemplates(options.merge):
sys.exit(1)
elif 'remote' in listLocate:
# apply remote templates
if not obj.applyRemoteTemplates(options.merge):
sys.exit(1)
elif 'clt' in listLocate:
# apply clt templates
if not obj.applyCltTemplates():
sys.exit(1)
elif options.clt:
cltPath = options.clt
# apply one clt template
if not obj.applyCltTemplate(cltPath):
sys.exit(1)
elif args:
cltPath = args[0]
# apply one clt template
if not obj.applyCltTemplate(cltPath):
sys.exit(1)
sys.exit(0)
Loading…
Cancel
Save