Добавлена проверка не используется ли образ, который должен быть перезаписан

Mike Khiretskiy 9 years ago
parent 025deae3b6
commit 986de7437c

@ -37,19 +37,23 @@ from calculate.lib.datavars import Variable, VariableError, ReadonlyVariable, \
TableVariable TableVariable
from functools import wraps from functools import wraps
_ = lambda x:x _ = lambda x: x
from calculate.lib.cl_lang import setLocalTranslate from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_builder3',sys.modules[__name__])
setLocalTranslate('cl_builder3', sys.modules[__name__])
def debug(func): def debug(func):
@wraps(func) @wraps(func)
def _wrapped_func(*args, **kw): def _wrapped_func(*args, **kw):
ret = func(*args, **kw) ret = func(*args, **kw)
print "MYDEBUG",ret print "MYDEBUG", ret
return ret return ret
return _wrapped_func return _wrapped_func
def is_action(*available_action, **action_kwargs): def is_action(*available_action, **action_kwargs):
def decorator(func): def decorator(func):
@wraps(func) @wraps(func)
@ -58,13 +62,17 @@ def is_action(*available_action, **action_kwargs):
return func(self, *args, **kw) return func(self, *args, **kw)
else: else:
return action_kwargs.get('default_value', '') return action_kwargs.get('default_value', '')
return _wrapped_func return _wrapped_func
return decorator return decorator
def as_list(func): def as_list(func):
@wraps(func) @wraps(func)
def _wrapped_func(self, *args, **kw): def _wrapped_func(self, *args, **kw):
return list(func(self, *args, **kw)) return list(func(self, *args, **kw))
return _wrapped_func return _wrapped_func
@ -109,16 +117,19 @@ class BaseBuildId(Variable):
self.label = _("Build ID") self.label = _("Build ID")
self.help = _("build ID") self.help = _("build ID")
class VariableClBuilderVideoDriverPath(Variable): class VariableClBuilderVideoDriverPath(Variable):
""" """
Имя файла, содержащего данные об установки драйверов во время загрузки Имя файла, содержащего данные об установки драйверов во время загрузки
""" """
def get(self): def get(self):
builder_path = self.Get('cl_builder_path') builder_path = self.Get('cl_builder_path')
return path.join( return path.join(
builder_path, builder_path,
'var/cache/calculate/video_drivers') 'var/cache/calculate/video_drivers')
class VariableClBuilderVideodrvSet(Variable): class VariableClBuilderVideodrvSet(Variable):
""" """
Нужно ли скачивать пакеты в дистрибутив для установки проприетарных Нужно ли скачивать пакеты в дистрибутив для установки проприетарных
@ -177,7 +188,7 @@ class VariableClBuilderSourceFilename(Variable):
if subname: if subname:
subname = " %s" % subname subname = " %s" % subname
if ver: if ver:
ver = " %s"%ver ver = " %s" % ver
arch = self.Get('os_builder_arch_machine') arch = self.Get('os_builder_arch_machine')
build = self.Get('os_builder_linux_build') build = self.Get('os_builder_linux_build')
@ -213,12 +224,14 @@ class VariableClBuilderSource(ReadonlyVariable):
return filename.getType() return filename.getType()
return filename return filename
class VariableClBuilderPreparePath(Variable): class VariableClBuilderPreparePath(Variable):
""" """
Путь по умолчанию для собираемой системы Путь по умолчанию для собираемой системы
""" """
value = "/var/calculate/builder" value = "/var/calculate/builder"
class VariableClBuilderDiskDev(Variable): class VariableClBuilderDiskDev(Variable):
""" """
Диск или директория, куда будет развёрнут образ Диск или директория, куда будет развёрнут образ
@ -235,8 +248,8 @@ class VariableClBuilderDiskDev(Variable):
def get_builder_image_dn(self): def get_builder_image_dn(self):
if self.Get('os_root_type') != "livecd": if self.Get('os_root_type') != "livecd":
default_path = self.Get('cl_builder_prepare_path') default_path = self.Get('cl_builder_prepare_path')
for i in range(1,9999): for i in range(1, 9999):
dn = "image%d"%i dn = "image%d" % i
full_dn = path.join(default_path, dn) full_dn = path.join(default_path, dn)
if not path.exists(full_dn) or not isMount(full_dn): if not path.exists(full_dn) or not isMount(full_dn):
return full_dn return full_dn
@ -307,6 +320,7 @@ class VariableClBuilderDiskSize(DiskFreeHelper):
""" """
""" """
def init(self): def init(self):
self.label = _("Free disk space") self.label = _("Free disk space")
@ -322,10 +336,12 @@ class VariableClBuilderDiskSize(DiskFreeHelper):
return str(self.get_free_for(device)) return str(self.get_free_for(device))
return "0" return "0"
class VariableClBuilderPrepareFreeSize(DiskFreeHelper): class VariableClBuilderPrepareFreeSize(DiskFreeHelper):
""" """
Свободное место используемое для подготовки образа Свободное место используемое для подготовки образа
""" """
def init(self): def init(self):
self.label = _("Free disk space for ISO building") self.label = _("Free disk space for ISO building")
@ -334,10 +350,12 @@ class VariableClBuilderPrepareFreeSize(DiskFreeHelper):
dn = self.Get('cl_builder_iso_base_path') dn = self.Get('cl_builder_iso_base_path')
return str(self.get_free_for(dn)) return str(self.get_free_for(dn))
class VariableClBuilderImageFreeSize(DiskFreeHelper): class VariableClBuilderImageFreeSize(DiskFreeHelper):
""" """
Свободное место на диске, где создается iso образ Свободное место на диске, где создается iso образ
""" """
def init(self): def init(self):
self.label = _("Free disk space for ISO image") self.label = _("Free disk space for ISO image")
@ -376,7 +394,7 @@ class VariableClBuilderLayeredSet(Variable):
def check_on(self): def check_on(self):
if not self.check_kernel_option(): if not self.check_kernel_option():
raise VariableError( raise VariableError(
_("You need kernel with %s for use layers")%self.kernel_opt) _("You need kernel with %s for use layers") % self.kernel_opt)
if self.Get('cl_builder_disk_dev').startswith('/dev'): if self.Get('cl_builder_disk_dev').startswith('/dev'):
raise VariableError( raise VariableError(
_("Layers are used for building in a directory only")) _("Layers are used for building in a directory only"))
@ -394,6 +412,7 @@ class VariableClBuilderPath(ReadonlyVariable):
""" """
Путь, где будет собираться дистрбутив Путь, где будет собираться дистрбутив
""" """
def get(self): def get(self):
image = self.Get('cl_builder_target') image = self.Get('cl_builder_target')
if image: if image:
@ -461,6 +480,7 @@ class VariableClBuilderClearSet(Variable):
self.label = _("Clear after unmount") self.label = _("Clear after unmount")
self.help = _("clear data after unmount") self.help = _("clear data after unmount")
class VariableClBuilderClearPkgSet(Variable): class VariableClBuilderClearPkgSet(Variable):
""" """
Удалять бинарные пакеты при отключении сборки Удалять бинарные пакеты при отключении сборки
@ -526,7 +546,7 @@ class VariableClBuilderNewId(BaseBuildId):
if value and not re.match("^[A-Za-z][A-Za-z0-9/:_+-]+$", value): if value and not re.match("^[A-Za-z][A-Za-z0-9/:_+-]+$", value):
raise VariableError(_("Wrong symbols in the build ID")) raise VariableError(_("Wrong symbols in the build ID"))
if value in self.Get('cl_builder_storage'): if value in self.Get('cl_builder_storage'):
raise VariableError(_("Build %s already exists")%value) raise VariableError(_("Build %s already exists") % value)
class VariableClBuilderPreparedId(BaseBuildId): class VariableClBuilderPreparedId(BaseBuildId):
@ -613,20 +633,24 @@ class VariableClBuilderBrokenId(BaseBuildId):
if not l: if not l:
raise VariableError(_("Build %s is not found") % value) raise VariableError(_("Build %s is not found") % value)
class VariableClBuilderIdPath(ReadonlyVariable): class VariableClBuilderIdPath(ReadonlyVariable):
""" """
Преобразование сборки id в имя походящее для путей Преобразование сборки id в имя походящее для путей
""" """
def get(self): def get(self):
build_id = self.Get('cl_builder_id') build_id = self.Get('cl_builder_id')
if build_id: if build_id:
return re.sub("[/:]", "_", self.Get('cl_builder_id')) return re.sub("[/:]", "_", self.Get('cl_builder_id'))
return "" return ""
class VariableClBuilderId(ReadonlyVariable): class VariableClBuilderId(ReadonlyVariable):
""" """
Общий id сборки Общий id сборки
""" """
def get(self): def get(self):
action = self.Get('cl_action') action = self.Get('cl_action')
if action in Actions.NewAssemble: if action in Actions.NewAssemble:
@ -642,6 +666,7 @@ class VariableOsBuilderMakeopts(Variable):
""" """
Параметры MAKEOPTS Параметры MAKEOPTS
""" """
def get(self): def get(self):
return self.Get('install.os_install_makeopts') return self.Get('install.os_install_makeopts')
@ -666,11 +691,13 @@ class VariableClBuilderParentPath(ReadonlyVariable):
""" """
Путь в ".." до родительской системы Путь в ".." до родительской системы
""" """
def get(self): def get(self):
builder_path = self.Get('cl_builder_path') builder_path = self.Get('cl_builder_path')
return ("../"*len(filter(None, return ("../" * len(filter(None,
builder_path.split('/'))))[:-1] builder_path.split('/'))))[:-1]
class VariableClBuilderStageSet(ReadonlyVariable): class VariableClBuilderStageSet(ReadonlyVariable):
""" """
Разворачиваемый образ является stage (Gentoo системой) Разворачиваемый образ является stage (Gentoo системой)
@ -682,10 +709,12 @@ class VariableClBuilderStageSet(ReadonlyVariable):
if self.Get('os_builder_linux_shortname') == "Gentoo" if self.Get('os_builder_linux_shortname') == "Gentoo"
else "off") else "off")
class VariableClBuilderPkgdir(Variable): class VariableClBuilderPkgdir(Variable):
""" """
Путь собираемых бинарных архивов Путь собираемых бинарных архивов
""" """
def fallback(self): def fallback(self):
return path.join(self.Get('cl_builder_base_path'), return path.join(self.Get('cl_builder_base_path'),
self.Get('cl_builder_id_path')) self.Get('cl_builder_id_path'))
@ -700,6 +729,7 @@ class VariableClBuilderPkgdir(Variable):
else: else:
return "" return ""
class VariableClBuilderAction(ReadonlyVariable): class VariableClBuilderAction(ReadonlyVariable):
""" """
Дополнительное действие по созданию образа: iso, squash. Дополнительное действие по созданию образа: iso, squash.
@ -724,6 +754,11 @@ class VariableClBuilderImageFilename(Variable):
def check(self, value): def check(self, value):
if not value: if not value:
raise VariableError(_("You must specify image filename")) raise VariableError(_("You must specify image filename"))
for line in process("/bin/losetup", "-j", value):
lodev, op, line = line.partition(":")
if lodev:
raise VariableError(
_("Image %s is already used") % value)
def _isoname(self, dn, rewrite=False): def _isoname(self, dn, rewrite=False):
shortname = self.Get('os_builder_linux_shortname').lower() shortname = self.Get('os_builder_linux_shortname').lower()
@ -769,6 +804,7 @@ class VariableClBuilderIsoPath(ReadonlyVariable):
""" """
Путь, где будут подготавливаться данные, которые будут запакованы в iso Путь, где будут подготавливаться данные, которые будут запакованы в iso
""" """
def get(self): def get(self):
base_dn = self.Get('cl_builder_iso_base_path') base_dn = self.Get('cl_builder_iso_base_path')
build_id = self.Get('cl_builder_id') build_id = self.Get('cl_builder_id')
@ -790,6 +826,7 @@ class VariableClBuilderSquashPath(ReadonlyVariable):
""" """
Путь от iso до содержимого squash Путь от iso до содержимого squash
""" """
@is_action(Actions.Image) @is_action(Actions.Image)
def get(self): def get(self):
return path.relpath(self.Get('cl_builder_path'), return path.relpath(self.Get('cl_builder_path'),
@ -800,6 +837,7 @@ class VariableClBuilderImage(ReadonlyVariable):
""" """
Создаваемый образ Создаваемый образ
""" """
@is_action(Actions.Image) @is_action(Actions.Image)
def get(self): def get(self):
image_name = self.Get('cl_builder_image_filename') image_name = self.Get('cl_builder_image_filename')
@ -830,6 +868,7 @@ class VariableClBuilderCdname(ReadonlyVariable):
""" """
Type of iso (CD/DVD) Type of iso (CD/DVD)
""" """
@is_action(Actions.Image) @is_action(Actions.Image)
def get(self): def get(self):
squashfile = pathJoin(self.Get('cl_builder_iso_path'), squashfile = pathJoin(self.Get('cl_builder_iso_path'),
@ -857,6 +896,7 @@ class VariableClBuilderIsoLabel(Variable):
""" """
LABEL для iso LABEL для iso
""" """
@is_action(Actions.Image) @is_action(Actions.Image)
def get(self): def get(self):
return "%s-%s" % (self.Get('os_builder_linux_shortname').upper(), return "%s-%s" % (self.Get('os_builder_linux_shortname').upper(),
@ -886,6 +926,7 @@ class VariableClBuilderKernelCmd(ReadonlyVariable):
""" """
value = "" value = ""
class KernelInfo(ReadonlyVariable): class KernelInfo(ReadonlyVariable):
def get_current_kernel_src(self, prefix): def get_current_kernel_src(self, prefix):
src_path = "usr/src" src_path = "usr/src"
@ -895,10 +936,12 @@ class KernelInfo(ReadonlyVariable):
raise ValueError("Failed to determine current kernel version") raise ValueError("Failed to determine current kernel version")
return path.join(src_path, os.readlink(symlink_kernel)) return path.join(src_path, os.readlink(symlink_kernel))
class VariableClBuilderKernelConfig(KernelInfo): class VariableClBuilderKernelConfig(KernelInfo):
""" """
Конфиг ядра Конфиг ядра
""" """
def get(self): def get(self):
prefix = self.Get('cl_builder_path') prefix = self.Get('cl_builder_path')
if prefix: if prefix:
@ -907,10 +950,12 @@ class VariableClBuilderKernelConfig(KernelInfo):
return KernelConfig(path.join(prefix, config_path)) return KernelConfig(path.join(prefix, config_path))
return "" return ""
class VariableClBuilderKernelVer(KernelInfo): class VariableClBuilderKernelVer(KernelInfo):
""" """
Текущая версия ядра Текущая версия ядра
""" """
def init(self): def init(self):
self.label = _("Kernel version") self.label = _("Kernel version")
@ -918,7 +963,7 @@ class VariableClBuilderKernelVer(KernelInfo):
prefix = self.Get('cl_builder_path') prefix = self.Get('cl_builder_path')
if prefix: if prefix:
current_src = self.get_current_kernel_src(prefix) current_src = self.get_current_kernel_src(prefix)
src = path.join(prefix,current_src) src = path.join(prefix, current_src)
return self.get_src_kernel_version(src) return self.get_src_kernel_version(src)
def get_config_version(self, configfile): def get_config_version(self, configfile):
@ -1111,6 +1156,7 @@ class VariableClBuilderBranchName(Variable):
return [branch for x in dv.Get('cl_update_rep_name')] return [branch for x in dv.Get('cl_update_rep_name')]
return [] return []
class VariableClBuilderCompress(Variable): class VariableClBuilderCompress(Variable):
""" """
Тип сжатия образа squash Тип сжатия образа squash
@ -1141,7 +1187,7 @@ class VariableClBuilderCompress(Variable):
else: else:
yield compress yield compress
weight = {'xz':2, 'gzip':1} weight = {'xz': 2, 'gzip': 1}
return list(sorted(generator(), return list(sorted(generator(),
key=lambda x: (-weight.get(x, 0), x))) key=lambda x: (-weight.get(x, 0), x)))
@ -1152,6 +1198,7 @@ class VariableClBuilderCompress(Variable):
return values[0] return values[0]
return "" return ""
class VariableClBuilderIsohybridSet(Variable): class VariableClBuilderIsohybridSet(Variable):
""" """
Преобразовать полученный iso образ в гибридный Преобразовать полученный iso образ в гибридный
@ -1164,6 +1211,7 @@ class VariableClBuilderIsohybridSet(Variable):
self.help = _("create the ISO image with isohybrid") self.help = _("create the ISO image with isohybrid")
self.label = _("ISO hybrid feature") self.label = _("ISO hybrid feature")
class VariableClBuilderKeepTreeSet(Variable): class VariableClBuilderKeepTreeSet(Variable):
""" """
Не удалять ебилды из портежей о оверлеев Не удалять ебилды из портежей о оверлеев
@ -1176,6 +1224,7 @@ class VariableClBuilderKeepTreeSet(Variable):
self.help = _("keep portage tree in image") self.help = _("keep portage tree in image")
self.label = _("Keep portage tree") self.label = _("Keep portage tree")
class VariableClBuilderSquashExclude(ReadonlyVariable): class VariableClBuilderSquashExclude(ReadonlyVariable):
""" """
Список файлов, которые не будут запакованы в livecd.squashfs Список файлов, которые не будут запакованы в livecd.squashfs
@ -1206,6 +1255,7 @@ class VariableClBuilderSquashExclude(ReadonlyVariable):
return list(generator()) return list(generator())
return [] return []
class VariableClBuilderPrelinkSet(Variable): class VariableClBuilderPrelinkSet(Variable):
""" """
Выполнять ли prelink Выполнять ли prelink
@ -1220,6 +1270,7 @@ class VariableClBuilderPrelinkSet(Variable):
def get(self): def get(self):
return "on" if self.GetBool('cl_builder_binary_set') else "off" return "on" if self.GetBool('cl_builder_binary_set') else "off"
class VariableClBuilderRebuildChangedSet(Variable): class VariableClBuilderRebuildChangedSet(Variable):
""" """
Выполнять ли prelink Выполнять ли prelink
@ -1232,6 +1283,7 @@ class VariableClBuilderRebuildChangedSet(Variable):
self.help = _("rebuild changed packages") self.help = _("rebuild changed packages")
self.label = _("Rebuild changed packages") self.label = _("Rebuild changed packages")
class VariableClBuilderRescratchSet(ReadonlyVariable): class VariableClBuilderRescratchSet(ReadonlyVariable):
""" """
Сборка iso образа на самой флешке Сборка iso образа на самой флешке
@ -1247,6 +1299,7 @@ class VariableClBuilderRescratchSet(ReadonlyVariable):
return "on" return "on"
return "off" return "off"
class VariableClBuilderFlashRepository(ReadonlyVariable): class VariableClBuilderFlashRepository(ReadonlyVariable):
""" """
Хранилище по умолчанию для iso образов на flash Хранилище по умолчанию для iso образов на flash
@ -1256,6 +1309,7 @@ class VariableClBuilderFlashRepository(ReadonlyVariable):
def get(self): def get(self):
return path.join(self.Get('cl_builder_flash_path'), "iso") return path.join(self.Get('cl_builder_flash_path'), "iso")
class VariableClBuilderFlashDevPath(Variable): class VariableClBuilderFlashDevPath(Variable):
""" """
Путь до устройства flash Путь до устройства flash
@ -1287,14 +1341,14 @@ class VariableClBuilderFlashDevPath(Variable):
else: else:
choices = [] choices = []
return choices + \ return choices + \
[(x,x) for x in self.select('install.os_disk_dev', [(x, x) for x in self.select('install.os_disk_dev',
install_os_disk_format="vfat")] install_os_disk_format="vfat")]
def check(self, value): def check(self, value):
if not value: if not value:
raise VariableError(_("Please specify Flash drive")) raise VariableError(_("Please specify Flash drive"))
if not path.exists(value): if not path.exists(value):
raise VariableError(_("Flash drive %s not found")%value) raise VariableError(_("Flash drive %s not found") % value)
try: try:
image = IsoDistributive(value) image = IsoDistributive(value)
image.getIsoContentDirectory() image.getIsoContentDirectory()
@ -1302,6 +1356,7 @@ class VariableClBuilderFlashDevPath(Variable):
except DistributiveError as e: except DistributiveError as e:
raise VariableError(str(e).strip()) raise VariableError(str(e).strip())
class VariableClBuilderFlashDev(ReadonlyVariable): class VariableClBuilderFlashDev(ReadonlyVariable):
""" """
Устройство flash Устройство flash
@ -1317,10 +1372,12 @@ class VariableClBuilderFlashDev(ReadonlyVariable):
return "" return ""
return "" return ""
class VariableClBuilderFlashPath(ReadonlyVariable): class VariableClBuilderFlashPath(ReadonlyVariable):
""" """
Путь, куда подключена flash (загрузка либо с флешки, либо с iso) Путь, куда подключена flash (загрузка либо с флешки, либо с iso)
""" """
def get(self): def get(self):
try: try:
iso = self.Get('cl_builder_flash_dev') iso = self.Get('cl_builder_flash_dev')
@ -1330,10 +1387,12 @@ class VariableClBuilderFlashPath(ReadonlyVariable):
return "" return ""
return "" return ""
class VariableClBuilderFlashUuid(ReadonlyVariable): class VariableClBuilderFlashUuid(ReadonlyVariable):
""" """
UUID flash, используется для перестроения меню UUID flash, используется для перестроения меню
""" """
def get(self): def get(self):
flash_path = self.Get('cl_builder_flash_path') flash_path = self.Get('cl_builder_flash_path')
dev = isMount(flash_path) dev = isMount(flash_path)

Loading…
Cancel
Save