Using of the import_variables function in the variables files is

available now. fixed #49
master
Иванов Денис 3 years ago
parent 9140335ad5
commit dbf841c689

@ -245,7 +245,8 @@ class NamespaceIniFiller:
self.current_namespace = None
return
self.current_namespace = self.current_namespace._namespaces[section]
self.current_namespace = self.current_namespace.\
_namespaces[section]
def clear_section(self, sections: list, lineno) -> None:
'''Метод для очистки пространства имен.'''
@ -310,7 +311,8 @@ class NamespaceIniFiller:
table_name, section))
self.current_namespace = None
return
self.current_namespace = self.current_namespace._namespaces[section]
self.current_namespace = self.current_namespace.\
_namespaces[section]
if table_name not in self.current_namespace._variables:
if not self.modify_only:
@ -609,6 +611,8 @@ class VariableLoader:
file_node.path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if hasattr(module, 'import_variables'):
module.import_variables()
# Обходим остальные директории.
for directory_node in directory_nodes:
@ -752,7 +756,8 @@ class Datavars:
# ini-файлах.
try:
self.variables_to_save = {target: dict() for target in
self.main.cl.system.env_order if target in
self.main.cl.system.env_order
if target in
self.main.cl.system.env_path}
except VariableNotFoundError:
self.variables_to_save = dict()

@ -1,11 +1,19 @@
import os
from calculate.utils.fs import readFile
from calculate.variables.datavars import Variable, Namespace, Dependence, \
StringType, BooleanType, HashType, Calculate
from calculate.variables.datavars import (
Variable,
Namespace,
StringType,
BooleanType,
HashType,
Calculate
)
def get_ebuild_phase():
return os.environ.get("EBUILD_PHASE", "")
def get_chroot_status():
"""Detect chroot mode by different mountinfo"""
pid = os.getpid()
@ -19,25 +27,16 @@ def get_chroot_status():
except Exception:
return False
def is_system_boot():
if os.readlink('/proc/self/fd/0') == '/dev/console':
return True
else:
return False
Variable("ebuild_phase", type=StringType,
source=Calculate(get_ebuild_phase))
Variable("chroot_status", type=BooleanType,
source=Calculate(get_chroot_status))
Variable("system_boot_set", type=BooleanType,
source=Calculate(is_system_boot))
# Переменная, в которую будут помещаться пути к текущим шаблонам.
Variable("current_template", type=StringType, source="")
class CmdlineParams(object):
"""
Параметры опции загрузки ядра calculate=
"""Параметры опции загрузки ядра calculate=
"""
# названия параметров
Calculate = "calculate"
@ -56,6 +55,7 @@ class CmdlineParams(object):
Audio = "audio"
Clock = "clock"
def get_cmdline_parameter(paramname):
cmdLine = "/proc/cmdline"
for param in readFile(cmdLine).split(" "):
@ -64,6 +64,7 @@ def get_cmdline_parameter(paramname):
return value
return None
def get_calculate_cmdline():
names = (
CmdlineParams.Locale,
@ -89,27 +90,45 @@ def get_calculate_cmdline():
pass
return params
def get_isoscan_filename():
value = get_cmdline_parameter(CmdlineParams.IsoscanFile)
if value is not None:
return value
return ""
def get_isoscan_fullpath(base_path, filename):
if filename:
return os.path.join(base_path.value, filename.value.lstrip("/"))
return ""
def import_variables():
Variable("ebuild_phase", type=StringType,
source=Calculate(get_ebuild_phase))
Variable("chroot_status", type=BooleanType,
source=Calculate(get_chroot_status))
Variable("system_boot_set", type=BooleanType,
source=Calculate(is_system_boot))
# Переменная, в которую будут помещаться пути к текущим шаблонам.
Variable("current_template", type=StringType, source="")
with Namespace('cmdline'):
Variable("calculate", type=HashType.fixed,
source=Calculate(get_calculate_cmdline))
Variable("isoscan_filename", type=StringType,
source=Calculate(get_isoscan_filename))
with Namespace('isoscan'):
Variable("base_path", type=StringType,
source="/run/initramfs/isoscan")
Variable("full_path", type=StringType,
source=Calculate(get_isoscan_fullpath,
'.base_path', 'main.cl.cmdline.isoscan_filename'
))
'.base_path',
'main.cl.cmdline.isoscan_filename'))

@ -3,6 +3,9 @@ from calculate.utils.files import stderr_devnull
from calculate.utils.files import read_link, FilesError
from calculate.variables.datavars import Variable, Namespace, Dependence,\
StringType, TableType
def import_variables():
'''
gentoo:
make_profile -> string
@ -14,7 +17,8 @@ gentoo:
'''
# Путь до файла, указывающего на активный профиль
Variable('make_profile', type=StringType, source='/etc/portage/make.profile')
Variable('make_profile', type=StringType,
source='/etc/portage/make.profile')
# Параметры текущего профиля.
with Namespace('profile'):
@ -26,8 +30,8 @@ with Namespace('profile'):
return ""
if profile_link:
profile_link = os.path.normpath(
os.path.join(make_profile_dir, profile_link))
profile_link = os.path.normpath(os.path.join(make_profile_dir,
profile_link))
return profile_link
else:
return ""
@ -54,12 +58,11 @@ with Namespace('profile'):
source=Dependence('.path', '..repositories',
depend=get_profile_name))
def get_repository_table(config):
return [{'name': name,
'path': path}
for path, name in config.value.repositories.location_map.items()]
for path, name
in config.value.repositories.location_map.items()]
# Информация о репозиториях
# name: имя репозитория
@ -67,14 +70,12 @@ def get_repository_table(config):
Variable('repositories', type=TableType,
source=Dependence('.config', depend=get_repository_table))
def get_config_object(chroot_path):
from portage.package.ebuild.config import config
if chroot_path.value == '/':
with stderr_devnull():
return config()
# Объект текущей конфигурации Portage
Variable('config', source=Dependence('main.cl_chroot_path',
depend=get_config_object))

@ -1,7 +1,14 @@
from calculate.variables.datavars import Namespace, Variable, Dependence,\
StringType, HashType, TableType,\
ListType, FloatType
def import_variables():
from calculate.variables.datavars import (
Namespace,
Variable,
Dependence,
StringType,
HashType,
TableType,
ListType,
FloatType
)
Variable('simple', type=StringType, source='simple value')
@ -36,7 +43,6 @@ Variable('shortname_test', type=StringType,
Variable('device_list', type=ListType,
source=["/dev/sda", "/dev/sdb"])
def get_device_table(device_list):
map_data = {'/dev/sda': ["hdd", "Samsung SSD"],
'/dev/sdb': ["flash", "Transcend 64GB"],
@ -48,8 +54,8 @@ def get_device_table(device_list):
"name": map_data.get(device, default_value)[1]}
for device in device_list.value]
Variable('device', type=TableType, source=Dependence('.device_list',
Variable('device', type=TableType, source=Dependence(
'.device_list',
depend=get_device_table))
Variable('device_child', type=StringType,

@ -1,6 +1,6 @@
def import_variables():
from calculate.variables.datavars import Variable, StringType, Calculate
Variable('vargetter', type=StringType,
source=Calculate(lambda chroot: '{} test'.format(chroot.value),
'main.chroot'))

@ -1,4 +1,4 @@
def import_variables():
from calculate.variables.datavars import Variable, StringType
Variable('chroot', type=StringType.readonly, source='/')

@ -1,15 +1,13 @@
import os
from calculate.variables.datavars import Variable, ListType, HashType
def import_variables():
'''
system:
env_order -> list
env_path -> hash
'''
import os
from calculate.variables.datavars import Variable, ListType, HashType
TESTFILES_PATH = os.path.join(os.getcwd(), 'tests/variables/testfiles')
# Список мест, где есть calculate.ini файлы.
Variable('env_order', type=ListType, source=['system', 'local'])

@ -1,6 +1,14 @@
from calculate.variables.datavars import Namespace, Variable, Dependence,\
StringType, HashType, TableType,\
ListType, IntegerType, FloatType
def import_variables():
from calculate.variables.datavars import (
Namespace,
Variable,
Dependence,
StringType,
HashType,
TableType,
IntegerType,
FloatType
)
with Namespace('linux'):
Variable('shortname', source='', type=StringType)
@ -19,7 +27,9 @@ with Namespace('linux'):
def get_title(subname, fullname, ver):
if subname.value:
return '{} {} {}'.format(fullname.value, subname.value, ver.value)
return '{} {} {}'.format(fullname.value,
subname.value,
ver.value)
else:
return '{} {}'.format(fullname.value, ver.value)
Variable('title', type=StringType,

@ -7,11 +7,14 @@ import calculate.vars.install.os.func as install_os
import mock
from itertools import chain
class Var:
def __init__(self, value):
self.value = value
@pytest.mark.parametrize('case',
@pytest.mark.parametrize(
'case',
[
{
"name": "failed xdpyinfo",
@ -35,11 +38,13 @@ class Var:
@pytest.mark.calculate_vars
def test_main_os_x11_resolution(case):
with mock.patch('calculate.vars.main.os.x11.Process.failed') as failed:
with mock.patch('calculate.vars.main.os.x11.Process.read_lines') as read_lines:
with mock.patch('calculate.vars.main.os.x11.Process.read_lines'
) as read_lines:
failed.return_value = case["failed"]
read_lines.return_value = case["data"].split("\n")
assert main_os_x11.get_resolution_by_xdpyinfo() == case["result"]
empty_calculate_cmdhash = {
CmdlineParams.Locale: "",
CmdlineParams.Keymap: "",
@ -53,10 +58,13 @@ empty_calculate_cmdhash = {
CmdlineParams.Clock: ""
}
def concat_dict(d1, **d2):
return {x: y for x, y in chain(d1.items(), d2.items())}
@pytest.mark.parametrize('case',
@pytest.mark.parametrize(
'case',
[
{
"name": "empty cmdline",
@ -97,7 +105,8 @@ def test_main_cl_cmdline(case):
assert main_cl.get_calculate_cmdline() == case["result"]
@pytest.mark.parametrize('case',
@pytest.mark.parametrize(
'case',
[
{
"source": "i686",
@ -118,7 +127,8 @@ def test_main_os_get_arch_gentoo(case):
assert main_os.get_arch_gentoo(Var(case["source"])) == case["result"]
@pytest.mark.parametrize('case',
@pytest.mark.parametrize(
'case',
[
{
"name": "pulseaudio exists",
@ -138,7 +148,9 @@ def test_install_os_get_available_audio_system(case):
exists.return_value = case["exists"]
assert install_os.get_available_audio_system() == case["result"]
@pytest.mark.parametrize('case',
@pytest.mark.parametrize(
'case',
[
{
"name": "default all available",
@ -179,7 +191,7 @@ def test_install_os_get_available_audio_system(case):
],
ids=lambda x: x["name"])
@pytest.mark.calculate_vars
def test_install_os_get_available_audio_system(case):
def test_install_os_get_available_audio_system_other(case):
assert install_os.get_audio_selected(
Var(case["available_systems"]),
Var(case["cmdline_audio"])) == case["result"]

Loading…
Cancel
Save