1
0
mirror of https://github.com/240596448/onec_codetemplate_parser.git synced 2025-11-23 21:34:39 +02:00

навел порядок

This commit is contained in:
Vladimir Nadulich
2025-11-04 20:39:58 +03:00
parent e8cf7cb173
commit 97ff83e73c
6 changed files with 9 additions and 61 deletions

View File

@@ -8,7 +8,7 @@ class Node:
"""Базовый класс узла дерева шаблона"""
name: str
parent: Union["Group", "Root", None] = None
children: List[Union["Group", "Leaf"]] = [] # ERROR ??
children: List[Union["Group", "Leaf"]] = []
position: int = 0
def __init__(self, name: str):
@@ -140,12 +140,8 @@ class Root(Node):
return "".join(parts)
def to_src(self, path):
"""Сохраняет группу в репозиторий"""
# self.repo = GroupRepository(self)
# self.repo.save(path, self.position)
"""Сохраняет дочерние группы в репозиторий"""
for child in self.children:
# child.to_src(self.repo.path)
child.to_src(path)
@staticmethod
@@ -166,50 +162,3 @@ def src_items(path: Path|str) -> List[Union[Group, Leaf]]:
child = Leaf.from_src(item)
children.append(child)
return children
# def main():
# if len(sys.argv) < 2:
# print("Использование: python parse_skobkofile.py <путь_к_файлу>")
# sys.exit(1)
# path = sys.argv[1]
# with open(path, "r", encoding="utf-8-sig", errors="ignore") as f:
# text = f.read()
# root = parser(text)
# print("\n✅ Файл успешно прочитан\n")
# root.pretty_print()
# recompiled = root.compile()
# if recompiled == text:
# print("✅ Файл успешно скомпилирован и совпадает с исходником")
# else:
# # запись обратно в контрольный файл
# output_path = path + ".out"
# with open(output_path, "w", encoding="utf-8-sig") as f:
# f.write(recompiled)
# print("❌ Файл успешно скомпилирован, но не совпадает с исходником")
# print(f"Скомпилированный файл сохранен в {output_path}")
# source_path = 'temp/src'
# root.to_src(source_path)
# root2 = Root.from_src(source_path)
# recompiled = root2.compile()
# if recompiled == text:
# print("✅ Файл успешно скомпилирован и совпадает с исходником")
# else:
# # запись обратно в контрольный файл
# output_path = path + ".out"
# with open(output_path, "w", encoding="utf-8-sig") as f:
# f.write(recompiled)
# print("❌ Файл успешно скомпилирован, но не совпадает с исходником")
# print(f"Скомпилированный файл сохранен в {output_path}")
# if __name__ == "__main__":
# main()

View File

@@ -64,7 +64,6 @@ def parse(text: str) -> Root:
Парсит один объект — либо группу, либо лист
{ count, { "Имя", флаг1, флаг2, "Поле4", "Поле5" } }
"""
# nonlocal pos
take("{")
count = numeric_value()
take(",")

View File

@@ -94,4 +94,4 @@ def dir_items(path: Path|str) -> list[Path]:
if item.name != GroupRepository.metafile():
items.append(item)
items.sort(key=lambda p: p.name)
return items
return items

View File

@@ -3,14 +3,14 @@ from pathlib import Path
def check_files_sequential(files: list[str]):
files.sort() # Сортируем по имени
files.sort()
expected_number = 1
for name in files:
m = re.match(r"^(\d{3})\.0_.*", name)
assert m, f"Неверный формат имени папки: {name}"
number = m.group(1) # первые три цифры
number = m.group(1)
true_number = f'{expected_number:03}'
assert number == true_number, f"Пропущен номер: ожидаем {true_number}, получили {number}"

View File

@@ -1,7 +1,7 @@
from onec_codetemplate_parser import parse_to_src, render_from_src
from tests.common import folder_is_empty
class Test_API:
class TestAPI:
def test_parse(self, file_path_spec, temp_src):
"""Тест библиотеки: парсинг"""
@@ -10,7 +10,7 @@ class Test_API:
assert not folder_is_empty(temp_src), f"Папка src пустая {temp_src}"
else:
assert folder_is_empty(temp_src), f"Для пустого файла что-то распарсилось {temp_src}"
def test_render(self, file_path, temp_src, tmp_path):
"""Тест библиотеки: сборка"""
@@ -18,4 +18,4 @@ class Test_API:
temp_file = tmp_path / "output.st"
render_from_src(str(temp_src), str(temp_file))
assert temp_file.exists(), f"Файл сборки не создан {temp_file}"
assert file_path.read_text(encoding='utf-8-sig') == temp_file.read_text(encoding='utf-8-sig'), 'Собранный файл не совпадает с исходным'
assert file_path.read_text(encoding='utf-8-sig') == temp_file.read_text(encoding='utf-8-sig'), 'Собранный файл не совпадает с исходным'

View File

@@ -52,7 +52,7 @@ class TestWriteToFiles:
files = [p for p in next(temp_src.iterdir()).iterdir() if p.is_file()]
assert len(files) == 2, f"Ожидалось 2 файла в src/001(.meta и leaf), получили {len(files)}"
if file_data_spec.name == "09-brackets":
folder = "001.0_Новый1"
assert (temp_src/folder).exists(), f"Папка первого уровня {folder} не найдена в {file_data_spec.name}"