Passed
Push — main ( 38f95c...d9c512 )
by Andreas
01:16
created

builder.BuildConfig.__init__()   A

Complexity

Conditions 3

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 24
rs 9.45
c 0
b 0
f 0
cc 3
nop 2
1
import zipfile
2
from yaml import full_load as loadyaml
3
from os import system as runCommand
4
from os import path
5
from sys import argv
6
from datetime import datetime
7
# from functions.man import manpage as man
8
9
class BuildConfig:
10
    """Класс динамической конфигурации
11
    """
12
    def __init__(self, build_config: str = 'configs/config.yaml') -> None:
13
        config_file = f'./configs/{build_config}.yaml'
14
        try:
15
            with open(config_file, 'r') as build_config:
16
                self.config_file = loadyaml(build_config)
17
        except FileNotFoundError:
18
            exit(f'[Err.:6] Файл не найден или не указан: {config_file}')
19
        # Cекция source конфига
20
        self.mainfile, self.outfile, self.workdir = [
21
            self.config_file['source']['mainfile'],
22
            self.config_file['source']['output'],
23
            self.config_file['source']['workdir']
24
        ]
25
        # Секция main конфига
26
        self.version, self.author, self.authorlink = [
27
            self.config_file['main']['version'],
28
            self.config_file['main']['author'],
29
            self.config_file['main']['authorlink']
30
            ]
31
        # Прочие детали конфига
32
        self.plugins = self.config_file['plugins']
33
        self.params: list = self.config_file['params']
34
        self.addition_files = self.config_file['files']
35
        self.product_name: str = self.config_file['main']['product_name']
36
    # Вывод параметров конфига, в случае необходимости
37
    def outprint(self) -> None:
38
        """Вывод параметров конфига
39
        """
40
        today = datetime.today().strftime('%d-%m-%Y  %H:%M:%S')
41
        print('-' * 10, f'\n{today}\n', '-' * 10)
42
        print('Config directives\n'
43
              # Секция предварительных настроек
44
              f'WorkDir: {self.workdir}\n'
45
              f'Main File: {self.mainfile}\n'
46
              f'Output File: {self.outfile}\n'
47
              # Секция продукта / сборки
48
              '\nProdut info\n'
49
              f'Version: {self.version}\n'
50
              f'Author: {self.author}\n'
51
              f'Authorlink: {self.authorlink}\n'
52
              f'Product Name: {self.product_name}\n'
53
              # Секция плагинов
54
              '\nBuild Plugins\n'
55
              f'Plugins: {self.plugins}'
56
              # Секция параметров
57
              '\nBuild parameters\n'
58
              f'Parameters: {self.params}\n'
59
              )
60
        print('-' * 10)
61
    # Упаковка сборки в архив
62
    def zip_output(self) -> None:
63
        """Упаковывает собранные файлы в архив
64
        """
65
        with zipfile.ZipFile(f'{self.product_name}.zip',
66
                             'w',
67
                             compression=zipfile.ZIP_DEFLATED,
68
                             compresslevel=9) as zipArch:
69
            zipArch.write(self.outfile)
70
            if len(self.addition_files) > 0: # Протестировать бы, но потом...
71
                for f in self.addition_files:
72
                    secondpth = f'{path.basename(path.dirname(path.abspath(f)))}/{path.basename(f)}'
73
                    zipArch.write(path.abspath(f), secondpth)
74
        zipArch.close() # Но это не точно...
75
# Получение основного конфига (не тестировалось)
76
def get_core_config() -> dict:
77
    """Читает конфиг сборщка
78
79
    Returns:
80
        dict: Словарь с параметрами конфигурации сборщика
81
    """
82
    try:
83
        with open('configs/core.yaml', 'r') as core_c:
84
            core_config = loadyaml(core_c)
85
    except FileNotFoundError:
86
        print('File not found')
87
        exit(6)
88
    return core_config
0 ignored issues
show
introduced by
The variable core_config does not seem to be defined for all execution paths.
Loading history...
89
# Получение конфига сборки (не тестировалось)
90
def get_build_config(conf_path: str) -> dict:
91
    """Читает конфиг сборки
92
93
    Args:
94
        conf_path (str): Путь до персонализированного конфига сборки
95
96
    Returns:
97
        dict: Словарь с параметрами конфигурации определенной сборки
98
    """
99
    if conf_path == '':
100
        print(
101
            'Не указан файл конфигурации сборки.\n'
102
            f'Необходимо запускать "{argv[0]} <путь до конфига>"')
103
    else:
104
        with open(conf_path, 'r') as build_conf_yaml:
105
            build_config = loadyaml(build_conf_yaml)
106
            return build_config
107
# Запуск алгоритма сборки
108
def build_start(config_input: str) -> None:
109
    """Запуск алгоритма сборки
110
111
    Args:
112
        config_input (str): Путь к файлу конфига сборки
113
    """
114
    config = BuildConfig(config_input)
115
    config.outprint()
116
# Запуск скрипта
117
if __name__ == '__main__':
118
    """Запуск скрипта
119
    """
120
    # man()
121
    config_input = input('Укажите файл сборки конфига:')
122
    if config_input is None or config_input == '':
123
        print('Конфиг сборки не указан')
124
    else:
125
        build_start(config_input)
126
127
### Старые наработки, они будут понемногу переноситься в основной код,
128
### Но в нормальном виде. После переноса и тестирования они должны быть удалены.
129
130
# def getconfig() -> dict:
131
#     """Загружает данные из конфига сборки.
132
133
#     Returns:
134
#         dict: Список переменных конфига
135
#     """
136
#     try:
137
#         with open('./config.yaml', 'r') as confFile:
138
#             conf: dict = loadyaml(confFile)
139
#     except FileNotFoundError:
140
#         print('File not found')
141
#     return conf
142
143
# def zipOutput():
144
#     """Упаковывает готовый файл в архив.
145
#     """
146
#     with zipfile.ZipFile('SimpleTester.zip', 'w',
147
#                          compression=zipfile.ZIP_DEFLATED,
148
#                          compresslevel=9) as zipArch:
149
#         zipArch.write('SimpleTester.exe')
150
151
# def makeParamStr(getconfig) -> str:
152
#     """Создает строку параметров сборки из данных конфига.
153
154
#     Args:
155
#         getconfig (function): Принимает на вход функцию парсинга конфига
156
157
#     Returns:
158
#         str: Строка с набором параметров сборки
159
#     """
160
#     paramList = []
161
#     for param in getconfig['params']:
162
#         if param == 'windows-product-version':
163
#             param = '{}="{}"'.format(param, getconfig['main']['version'])
164
#         paramList.append(param)
165
#     paramStr = '--' + ' --'.join(paramList)
166
#     return paramStr    
167
168
# if __name__ == '__main__':
169
#     """Запуск сборки бинарного файла и его упаковка в архив.
170
#     """
171
#     paramsStr = makeParamStr(getconfig())
172
#     plugins = getconfig()['plugins']
173
#     icon = getconfig()['main']['icon']
174
#     runCommand(f'nuitka {paramsStr} --plugin-enable={plugins} --windows-icon-from-ico={icon} --include-data-files=../ui/imgs/*.png=imgs/ ../SimpleTester.py')
175
#     zipOutput()