Created a common interface for creating and executing executable templates. fixed #7

master
Иванов Денис 4 years ago
parent 5d0862de1a
commit a60cc5dcb1

@ -1,11 +1,10 @@
# vim: fileencoding=utf-8 # vim: fileencoding=utf-8
# #
import os import os
from .base_format import Format from .base_format import Format, FormatError
from pyparsing import Literal, Regex, SkipTo, LineEnd, lineno, LineStart from pyparsing import Literal, Regex, SkipTo, LineEnd, lineno, LineStart
from calculate.utils.package import PackageAtomParser, Package, PackageNotFound from calculate.utils.package import PackageAtomParser, Package, PackageNotFound
from calculate.utils.files import join_paths from calculate.utils.files import join_paths
from pprint import pprint
from glob import iglob from glob import iglob
from fnmatch import fnmatch from fnmatch import fnmatch
@ -24,15 +23,18 @@ class ContentsFormat(Format):
cls._initialize_parser() cls._initialize_parser()
return super().__new__(cls) return super().__new__(cls)
def __init__(self, document_text: str, def __init__(self, template_text: str,
template_path, template_path: str,
ignore_comments=False): ignore_comments=None):
self._command_methods = {ADD: self._add_command, self._command_methods = {ADD: self._add_command,
REMOVE: self._remove_command, REMOVE: self._remove_command,
MOVE: self._move_command} MOVE: self._move_command}
self._errors = [] self._parse_errors = []
self._commands = self._parse_template(document_text) self._commands = self._parse_template(template_text)
if self._parse_errors:
raise FormatError('errors while parsing template:\n{}'.
format('\n'.join(self._parse_errors)))
self._template_path = template_path self._template_path = template_path
self._packages = dict() self._packages = dict()
self._atom_parser = None self._atom_parser = None
@ -54,8 +56,7 @@ class ContentsFormat(Format):
command['path'], command['path'],
command['lineno'], command['lineno'],
source=source_package) source=source_package)
pprint(target_package.contents_dictionary) return self._save_changes()
self._save_changes()
def _add_command(self, target, glob_path, lineno, source=None): def _add_command(self, target, glob_path, lineno, source=None):
# Если файл уже есть в пакете -- ничего не делаем. # Если файл уже есть в пакете -- ничего не делаем.
@ -67,10 +68,8 @@ class ContentsFormat(Format):
# Проверяем существование файла. # Проверяем существование файла.
if not os.path.exists(file_path): if not os.path.exists(file_path):
error = (f"Format processing error:{lineno}: file " raise FormatError(f"Format processing error:{lineno}: file "
f"'{file_path}' does not exist.") f"'{file_path}' does not exist.")
self._errors.append(error)
continue
# Проверяем, не принадлежит ли файл какому-нибудь другому пакету. # Проверяем, не принадлежит ли файл какому-нибудь другому пакету.
try: try:
@ -78,11 +77,10 @@ class ContentsFormat(Format):
except PackageNotFound: except PackageNotFound:
file_package = None file_package = None
if file_package is not None: if file_package is not None:
error = (f"Format processing error:{lineno}: can not add file" raise FormatError(f"Format processing error:{lineno}: can not"
f" '{file_path}' belonging to the package" f" add file '{file_path}' belonging to the"
f" {file_package} into the package '{target}'.") f" package {file_package} into the package"
self._errors.append(error) f" '{target}'.")
continue
target.add_file(file_path) target.add_file(file_path)
@ -128,12 +126,12 @@ class ContentsFormat(Format):
target.sort_contents_dictionary() target.sort_contents_dictionary()
def _save_changes(self): def _save_changes(self):
changed_files = []
for atom_name, package in self._packages.items(): for atom_name, package in self._packages.items():
print(f"SAVING CHANGES FOR PACKAGE: {package}")
print('CONTENTS TEXT:')
print(package.render_contents_file())
package.write_contents_file() package.write_contents_file()
changed_files.append(package.contents_file_path)
self._packages = {} self._packages = {}
return changed_files
def _get_package(self, atom_name: str, chroot_path: str) -> Package: def _get_package(self, atom_name: str, chroot_path: str) -> Package:
atom = self._atom_parser.parse_package_parameter(atom_name) atom = self._atom_parser.parse_package_parameter(atom_name)
@ -154,7 +152,7 @@ class ContentsFormat(Format):
elif 'error' in parse_result: elif 'error' in parse_result:
error = (f'Parse Error:{parse_result["lineno"]}:' error = (f'Parse Error:{parse_result["lineno"]}:'
f' {parse_result["error"]}') f' {parse_result["error"]}')
self._errors.append(error) self._parse_errors.append(error)
continue continue
yield parse_result yield parse_result

@ -1,7 +1,6 @@
# vim: fileencoding=utf-8 # vim: fileencoding=utf-8
# #
from .base_format import Format from .base_format import Format
from ..template_engine import ParametersContainer
from calculate.utils.files import Process from calculate.utils.files import Process
from calculate.templates.format.base_format import FormatError from calculate.templates.format.base_format import FormatError
from os import path from os import path
@ -13,8 +12,7 @@ class PatchFormat(Format):
def __init__(self, patch_text: str, def __init__(self, patch_text: str,
template_path: str, template_path: str,
ignore_comments=None, ignore_comments=None):
parameters=ParametersContainer()):
self._patch_text = patch_text self._patch_text = patch_text
self._cwd_path = '/' self._cwd_path = '/'
self._last_level = 0 self._last_level = 0
@ -22,7 +20,7 @@ class PatchFormat(Format):
# Измененные файлы. # Измененные файлы.
self.changed_files = dict() self.changed_files = dict()
def execute_format(self, target_path): def execute_format(self, target_path, chroot_path='/'):
'''Метод для запуска работы формата.''' '''Метод для запуска работы формата.'''
self._cwd_path = target_path self._cwd_path = target_path
if not path.isdir(self._cwd_path): if not path.isdir(self._cwd_path):
@ -59,7 +57,6 @@ class PatchFormat(Format):
if patch_dry_run.success(): if patch_dry_run.success():
return '' return ''
else: else:
print('Exception')
raise FormatError('correction failed') raise FormatError('correction failed')
self._last_level = level self._last_level = level
@ -68,7 +65,6 @@ class PatchFormat(Format):
patch_run.write(self._patch_text) patch_run.write(self._patch_text)
if patch_run.success(): if patch_run.success():
print('SUCCESS')
for line in patch_run.read_lines(): for line in patch_run.read_lines():
if line.startswith('patching file'): if line.startswith('patching file'):
changed_file_path = path.join(self._cwd_path, changed_file_path = path.join(self._cwd_path,

@ -913,6 +913,7 @@ class TemplateExecutor:
input_text = input_file.read() input_text = input_file.read()
else: else:
# В противном случае используем пустой файл. (!) # В противном случае используем пустой файл. (!)
# TODO КАВО ЧЕГО
input_text = '' input_text = ''
else: else:
input_text = '' input_text = ''
@ -981,7 +982,8 @@ class TemplateExecutor:
# изменения CONTENTS и при этом задан пакет -- обновляем # изменения CONTENTS и при этом задан пакет -- обновляем
# CONTENTS. # CONTENTS.
if (self.dbpkg and changed_files and if (self.dbpkg and changed_files and
template_object.target_package): template_object.target_package and
template_object.format_class.FORMAT != 'contents'):
template_object.update_contents_from_list(changed_files) template_object.update_contents_from_list(changed_files)
else: else:
if template_object.target_type is not None and not replace: if template_object.target_type is not None and not replace:

@ -477,7 +477,6 @@ class PackageAtomParser:
'''Метод для разбора значения package, после разбора инициирует '''Метод для разбора значения package, после разбора инициирует
проверку полученных значений. Возвращает объект PackageAtomName.''' проверку полученных значений. Возвращает объект PackageAtomName.'''
self.package_atom = package_atom self.package_atom = package_atom
# self._atom_dictionary = {}
if isinstance(package_atom, str): if isinstance(package_atom, str):
self._atom_dictionary = self.parse_atom_name(package_atom) self._atom_dictionary = self.parse_atom_name(package_atom)
elif isinstance(package_atom, dict): elif isinstance(package_atom, dict):

@ -60,11 +60,6 @@ sym /etc/dir_3/link_0 -> ../dir_1/file_0 {2}
test_package = Package(test_package_name, test_package = Package(test_package_name,
chroot_path=chroot_path) chroot_path=chroot_path)
if contents_format._errors:
for error in contents_format._errors:
print(error)
assert False
assert '/etc/dir_0/file_0' in test_package assert '/etc/dir_0/file_0' in test_package
assert '/etc/dir_0/file_1' in test_package assert '/etc/dir_0/file_1' in test_package
@ -112,11 +107,6 @@ dir /etc/dir_3
test_package = Package(test_package_name, test_package = Package(test_package_name,
chroot_path=chroot_path) chroot_path=chroot_path)
if contents_format._errors:
for error in contents_format._errors:
print(error)
assert False
assert '/etc/dir_0/file_0' in test_package assert '/etc/dir_0/file_0' in test_package
assert '/etc/dir_0/file_1' not in test_package assert '/etc/dir_0/file_1' not in test_package

Loading…
Cancel
Save