Added options --install and --uninstall for cl-desktop

master
Самоукин Алексей 14 years ago
parent f4679693ce
commit cb4d13327a

@ -104,9 +104,12 @@ class share(color_print):
else:
self.clVars.printVars(opts)
class install(share):
"""Методы для наложения шаблонов на систему при инсталяции программы"""
class desktop(share):
"""Методы работы с профилем пользователя"""
# Имя пользователя
userName = ""
# Объект для поиска пользовательских данных в LDAP
ldapUserObj = ldapUser()
def installProg(self):
"""Наложение шаблонов на систему при инсталяции"""
@ -126,9 +129,6 @@ class install(share):
self.printOK(_("Apply install templates"))
return True
class uninstall(share):
"""Методы для наложения шаблонов на систему при деинсталяции программы"""
def uninstallProg(self):
"""Наложение шаблонов на систему при деинсталяции"""
# Проверяем на root
@ -147,13 +147,6 @@ class uninstall(share):
self.printOK(_("Apply uninstall templates"))
return True
class desktop(share):
"""Методы работы с профилем пользователя"""
# Имя пользователя
userName = ""
# Объект для поиска пользовательских данных в LDAP
ldapUserObj = ldapUser()
def existsUser(self, userName):
"""Существует ли пользователь"""
try:

@ -36,7 +36,11 @@ DESCRIPTION = _("Create home directory for the new user account")
# Опции командной строки
CMD_OPTIONS = [{'longOption':"progress",
'help':_("show progress bar for xdm startup")}]
'help':_("show progress bar for xdm startup")},
{'longOption':"install",
'help':_("configure the system to install this package")},
{'longOption':"uninstall",
'help':_("configure the system to uninstall this package")}]
class desktop_cmd(share_cmd):
def __init__(self):
@ -54,25 +58,73 @@ class desktop_cmd(share_cmd):
self.logicObj = desktop()
# Создаем переменные
self.logicObj.createClVars()
# Названия несовместимых опций
self.optionsNamesIncompatible = ["install", "uninstall"]
def getIncompatibleOptions(self, optObj):
"""Получаем несовместимые опции"""
retList = []
for nameOpt in self.optionsNamesIncompatible:
retList.append(getattr(optObj, nameOpt))
return retList
def _getNamesAllSetOptions(self):
"""Выдает словарь измененных опций"""
setOptDict = self.optobj.values.__dict__.items()
defaultOptDict = self.optobj.get_default_values().__dict__.items()
return dict(set(setOptDict) - set(defaultOptDict)).keys()
def getStringIncompatibleOptions(self):
"""Форматированная строка несовместимых опций разделенных ','"""
listOpt = list(set(self.optionsNamesIncompatible) &\
set(self._getNamesAllSetOptions()))
return ", ".join(map(lambda x: len(x) == 1 and "'-%s'"%x or "'--%s'"%x,\
listOpt))
def checkOpts(self, optObj, args):
"""Проверка опций командной строки"""
if not args:
errMsg = _("no such argument") + ":" + " %s" %USAGE.split(" ")[-1]
self.optobj.error(errMsg)
return False
if len(args)>1:
errMsg = _("incorrect argument") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
userName = args[0]
if userName == "root":
errMsg = _("invalid username") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
# Проверка на существование пользователя
if not self.logicObj.existsUser(userName):
return False
# Несовместимые опции
if len(filter(lambda x: x, self.getIncompatibleOptions(optObj)))>1:
errMsg = _("incompatible options")+":"+" %s"\
%self.getStringIncompatibleOptions()
self.optobj.error(errMsg)
return False
if optObj.v:
if args:
if len(args)>1:
errMsg = _("incorrect argument")+":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
userName = args[0]
if userName == "root":
errMsg = _("invalid username") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
# Проверка на существование пользователя
if not self.logicObj.existsUser(userName):
return False
elif optObj.install or optObj.uninstall:
if args:
errMsg = _("invalid argument") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
else:
if not args:
errMsg = _("no such argument")+":"+" %s" %USAGE.split(" ")[-1]
self.optobj.error(errMsg)
return False
if len(args)>1:
errMsg = _("incorrect argument") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
userName = args[0]
if userName == "root":
errMsg = _("invalid username") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
# Проверка на существование пользователя
if not self.logicObj.existsUser(userName):
return False
return optObj, args
def setUserName(self, userName):
@ -81,4 +133,12 @@ class desktop_cmd(share_cmd):
def createHome(self, optObj):
"""Создание домашней директории"""
return self.logicObj.createHome(optObj.progress)
return self.logicObj.createHome(optObj.progress)
def install(self):
"""Инсталяция программы"""
return self.logicObj.installProg()
def uninstall(self):
"""Удаление программы"""
return self.logicObj.uninstallProg()

@ -1,57 +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.
from cl_desktop import install, __app__, __version__
from cl_opt import opt
import sys
from cl_share_cmd import share_cmd
# Перевод сообщений для программы
from cl_lang import lang
lang().setLanguage(sys.modules[__name__])
# Использование программы
USAGE = _("%prog [options]")
# Описание программы (что делает программа)
DESCRIPTION = _("Configure the system to calculate-desktop package")
class install_cmd(share_cmd):
def __init__(self):
# Объект опций командной строки
self.optobj = opt(\
package=__app__,
version=__version__,
usage=USAGE,
description=DESCRIPTION,
option_list=opt.variable_control+opt.color_control,
check_values=self.checkOpts)
# Создаем объект логики
self.logicObj = install()
# Создаем переменные
self.logicObj.createClVars()
def checkOpts(self, optObj, args):
"""Проверка опций командной строки"""
if args:
errMsg = _("invalid argument") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
return optObj, args
def installProg(self):
"""Наложение шаблонов на систему при инсталяции"""
return self.logicObj.installProg()

@ -1,57 +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.
from cl_desktop import uninstall, __app__, __version__
from cl_opt import opt
import sys
from cl_share_cmd import share_cmd
# Перевод сообщений для программы
from cl_lang import lang
lang().setLanguage(sys.modules[__name__])
# Использование программы
USAGE = _("%prog [options]")
# Описание программы (что делает программа)
DESCRIPTION = _("Configure the system to calculate-desktop package")
class uninstall_cmd(share_cmd):
def __init__(self):
# Объект опций командной строки
self.optobj = opt(\
package=__app__,
version=__version__,
usage=USAGE,
description=DESCRIPTION,
option_list=opt.variable_control+opt.color_control,
check_values=self.checkOpts)
# Создаем объект логики
self.logicObj = uninstall()
# Создаем переменные
self.logicObj.createClVars()
def checkOpts(self, optObj, args):
"""Проверка опций командной строки"""
if args:
errMsg = _("invalid argument") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
return optObj, args
def uninstallProg(self):
"""Наложение шаблонов на систему при деинсталяции"""
return self.logicObj.uninstallProg()

@ -34,11 +34,16 @@ if __name__ == "__main__":
if ret is False:
sys.exit(1)
opts, args = ret
userName = args[0]
if len(args) > 0:
userName = args[0]
else:
userName = ""
# Установка цвета при печати сообщений
obj.setPrintNoColor(opts)
# Установка имени пользователя
obj.setUserName(userName)
if userName:
# Установка имени пользователя
obj.setUserName(userName)
# Установка переменных
if not obj.setVars(opts):
sys.exit(1)
@ -46,9 +51,18 @@ if __name__ == "__main__":
obj.printVars(opts)
# Если нет печати переменных выполняем логику программы
if not opts.v:
# Создаем домашнюю директорию, и применяем шаблоны
if not obj.createHome(opts):
sys.exit(1)
if opts.install:
# Наложение шаблонов на систему при инсталяции
if not obj.install():
sys.exit(1)
elif opts.uninstall:
# Наложение шаблонов на систему при деинсталяции
if not obj.uninstall():
sys.exit(1)
elif userName:
# Создаем домашнюю директорию, и применяем шаблоны
if not obj.createHome(opts):
sys.exit(1)
# Запись переменных
if not obj.writeVars(opts):
sys.exit(1)

@ -1,52 +0,0 @@
#!/usr/bin/python
#-*- 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-desktop/pym'))
from cl_install_cmd import install_cmd
from cl_lang import lang
tr = lang()
tr.setGlobalDomain('cl_desktop')
tr.setLanguage(sys.modules[__name__])
if __name__ == "__main__":
obj = install_cmd()
ret = obj.optobj.parse_args()
if ret is False:
sys.exit(1)
opts, args = ret
# Установка цвета при печати сообщений
obj.setPrintNoColor(opts)
# Установка переменных
if not obj.setVars(opts):
sys.exit(1)
# Печать переменных
obj.printVars(opts)
# Если нет печати переменных выполняем логику программы
if not opts.v:
# Наложение шаблонов на систему при инсталяции
if not obj.installProg():
sys.exit(1)
# Запись переменных
if not obj.writeVars(opts):
sys.exit(1)
sys.exit(0)

@ -1,54 +0,0 @@
#!/usr/bin/python
#-*- 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-desktop/pym'))
from cl_uninstall_cmd import uninstall_cmd
from cl_lang import lang
tr = lang()
tr.setGlobalDomain('cl_desktop')
tr.setLanguage(sys.modules[__name__])
if __name__ == "__main__":
obj = uninstall_cmd()
ret = obj.optobj.parse_args()
if ret is False:
sys.exit(1)
opts, args = ret
# Установка цвета при печати сообщений
obj.setPrintNoColor(opts)
# Установка переменных
if not obj.setVars(opts):
sys.exit(1)
# Печать переменных
obj.printVars(opts)
# Если нет печати переменных выполняем логику программы
if not opts.v:
# Наложение шаблонов на систему при деинсталяции
if not obj.uninstallProg():
sys.exit(1)
# Запись переменных
if not obj.writeVars(opts):
sys.exit(1)
sys.exit(0)

@ -21,8 +21,6 @@ import os
import stat
from distutils.core import setup
from distutils.command.install_data import install_data
from distutils.command.build_scripts import build_scripts
from distutils.command.install_scripts import install_scripts
__app__ = "calculate-desktop"
@ -32,11 +30,9 @@ data_files = []
var_data_files = []
#data_dirs_template = ['templates']
data_dirs_share = ['i18n']
share_calculate_dir = "/usr/share/calculate"
#template_calculate_dir = os.path.join(share_calculate_dir, "templates")
#template_replace_dirname = "desktop"
def __scanDir(scanDir, prefix, replace_dirname, dirData, flagDir=False):
"""Scan directory"""
@ -70,8 +66,6 @@ def create_data_files(data_dirs, prefix="", replace_dirname=""):
return data_files
#data_files += create_data_files(data_dirs_template, template_calculate_dir,
# template_replace_dirname)
data_files += create_data_files(data_dirs_share, share_calculate_dir)
data_files += [('/usr/share/calculate/xdm', ['data/cmd_login',
'data/functions',
@ -83,7 +77,6 @@ data_files += [('/usr/share/calculate/xdm', ['data/cmd_login',
'data/login.d/99final'])] +\
[('/usr/share/calculate/xdm/logout.d',
['data/logout.d/00init'])]
# [('/var/calculate/templates', [])]
class cl_install_data(install_data):
@ -116,35 +109,6 @@ class cl_install_data(install_data):
os.chmod(path, mode)
class cl_build_scripts(build_scripts):
"""Class for build scripts"""
def run (self):
scripts = ['./scripts/install', './scripts/uninstall']
backup_build_dir = self.build_dir
backup_scripts = filter(lambda x: not x in scripts, self.scripts)
self.scripts = scripts
self.build_dir = self.build_dir + "-bin"
build_scripts.run(self)
self.scripts = backup_scripts
self.build_dir = backup_build_dir
build_scripts.run(self)
class cl_install_scripts(install_scripts):
"""Class for install scripts"""
def run (self):
backup_install_dir = self.install_dir
backup_build_dir = self.build_dir
cl_cmd_obj = self.distribution.get_command_obj("install")
self.build_dir = self.build_dir + "-bin"
self.install_dir = os.path.join(cl_cmd_obj.install_platlib, __app__,
"bin")
install_scripts.run(self)
self.build_dir = backup_build_dir
self.install_dir = backup_install_dir
install_scripts.run(self)
setup(
name = __app__,
version = __version__,
@ -156,10 +120,6 @@ setup(
package_dir = {'calculate-desktop': "."},
packages = ['calculate-desktop.pym'],
data_files = data_files,
scripts=["./scripts/cl-desktop",
"./scripts/install",
"./scripts/uninstall"],
cmdclass={'install_data': cl_install_data,
'build_scripts':cl_build_scripts,
'install_scripts':cl_install_scripts},
scripts=["./scripts/cl-desktop"],
cmdclass={'install_data': cl_install_data},
)

Loading…
Cancel
Save