You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-2.1-lib/pym/cl_utils.py

180 lines
6.5 KiB

#-*- coding: utf-8 -*-
#Copyright 2008 Calculate Pack, http://www.calculate-linux.ru
#
# 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 filecmp
import string
from random import choice
from re import search
import os
def getdirlist(s_path):
#Получить список директорий по указаному пути
fdir=filecmp.dircmp(s_path, s_path)
dir_list=fdir.common_dirs
return dir_list
#вернуть случайный пароль
def genpassword():
res=''.join([choice(string.ascii_letters+string.digits)\
for i in xrange(9)])
return res
#заполнить строку указанным количеством символов
def fillstr(char, width):
return str(char) * width
#вернуть пути для запуска утилит
def getpathenv():
bindir=['/sbin','/bin','/usr/sbin','/usr/bin']
env=os.environ
if env and env.has_key('PATH'):
lpath=env['PATH'].split(":")
npath=[]
for dirname in bindir:
if os.path.exists(dirname) and dirname not in lpath:
npath.append(dirname)
lpath=npath+lpath
return "PATH="+":".join(lpath)+" && "
#класс для работы с установленными пакетами
class pakages:
#путь к директории установленнх пакетов
pkgdir="/var/db/pkg/"
#список установленных пакетов
pkglist={}
#Объект содержащий параметры пакета
class pakage(object):
#имя пакета с версией
fullname=""
#имя пакета
name=""
#версия
ver=""
#тип пакета в портижах
portdir=""
def __init__(self, **args):
for atname,atvalue in args.items():
setattr(self,atname, atvalue)
def __init__(self):
self.pkglist=self.__getpkglist()
#разбить имя пакета на тип и имя
def __getpkgver(self, fname):
res=search('^(.+)\-([0-9]+.*)$',fname)
if res:
return res.groups()
else:
return (None,None)
#собрать установленные в системе пакеты
def __getpkglist(self):
portageDirs=[]
instaledPkg={}
#проверим на существование директории с установленными пакетами
if os.path.exists(self.pkgdir):
#получим список типов пакетов
portageDirs=getdirlist(self.pkgdir)
if len(portageDirs)>0:
#обрабатываем содержимое каждого из типов
for portageDir in portageDirs:
pkgList=getdirlist(self.pkgdir+portageDir)
for pkg in pkgList:
fullname=pkg
pkgName,pkgVer= self.__getpkgver(pkg)
pobj=self.pakage(fullname=fullname,
name=pkgName, \
ver=pkgVer,\
portdir=portageDir)
fpkg=portageDir+"/"+pkgName
if instaledPkg.has_key(fpkg):
instaledPkg[fpkg].append(pobj)
else:
instaledPkg[fpkg]=[pobj]
return instaledPkg
#разбить pkgname на составляющие имени пакета
def __partname(self, pkgname):
if not pkgname.strip():
return False
res=search('^(.+\/)?(.+)',pkgname)
tname=None
if res.group(1):
tname=res.group(1)
if res.group(2):
res2=search('^(.+)(\-[0-9]+.+$)',res.group(2))
if res2:
name=res2.group(1)
ver=res2.group(2)
else:
name=res.group(2)
ver=None
if res:
if name and name[-1:]=='-':
name=name[:-1]
if tname and tname[-1:]=='/':
tname=tname[:-1]
if ver and ver[0]=='-':
ver=ver[1:]
return [tname, name, ver]
#проверить установленн ли пакет
#isinstalled('dev-db/postgresql')
def isinstalled(self, pkgname):
res=self.getinstpkg(pkgname)
if len(res)>0:
return True
else:
return False
#вернуть список объектов pakage() соответствующих pkgname
#getinstpkg('dev-db/postgresql')
#в случае отсутствия пакетов возвращает пустой список
def getinstpkg(self, pkgname):
pinfo=self.__partname(pkgname)
if pinfo:
ret=[]
if pinfo[0] and pinfo[1] and pinfo[2]:
if not self.pkglist.has_key(pinfo[0]+'/'+pinfo[1]):
return []
fpkg=self.pkglist[pinfo[0]+'/'+pinfo[1]]
ret=[]
for i in fpkg:
if i.ver==pinfo[2]:
ret.append(i)
return ret
elif pinfo[0] and pinfo[1]:
if not self.pkglist.has_key(pinfo[0]+'/'+pinfo[1]):
return []
return self.pkglist[pinfo[0]+'/'+pinfo[1]]
elif pinfo[1] and pinfo[2]:
for i in self.pkglist.keys():
if search('^.+\/%s$'%(pinfo[1]),i):
for el in self.pkglist[i]:
if el.ver==pinfo[2]:
ret.append(el)
return ret
elif pinfo[1]:
for i in self.pkglist.keys():
if search('^.+\/%s$'%(pinfo[1]),i):
ret+=self.pkglist[i]
return ret
return []
def getListPkg(self):
return self.pkglist