from calculate.templates.template_engine import TemplateEngine, Variables,\ FILE, DIR, LINK,\ ParametersProcessor from calculate.templates.template_processor import TemplateAction import shutil import os template_text = '''{% calculate append = 'join' -%} {% calculate package = 'dev-lang/python', format = 'samba' -%} [section one] parameter_1 = {{ vars_1.value_1 }} !parameter_2 ''' backup_template_text = '''{% calculate append = 'join' -%} [section one] parameter_1 = value parameter_2 = value_2 ''' APPENDS_SET = TemplateAction().available_appends vars_1 = Variables({'value_1': 'value_1'}) DATAVARS_MODULE = Variables({'vars_1': vars_1}) CHROOT_PATH = os.path.join(os.getcwd(), 'tests/templates/testfiles/test_root') template_engine = TemplateEngine(datavars_module=DATAVARS_MODULE, appends_set=APPENDS_SET, chroot_path=CHROOT_PATH) target_path = os.path.join(CHROOT_PATH, 'etc/dir/file.conf') class TemplateActionError(Exception): pass class TargetFile: type_checks = {DIR: os.path.isdir, FILE: os.path.isfile, LINK: os.path.islink} def __init__(self, target_file_path, template_type, package=None): self._file_path = target_file_path self._package = package if not os.path.exists(target_file_path): pass def check_conflicts(self, parameters): pass class TemplateActionDraft: def __init__(self, datavars_module=Variables(), chroot_path='/'): self.datavars_module = datavars_module self.chroot_path = chroot_path self.directory_default_parameters =\ ParametersProcessor.directory_default_parameters self.file_default_parameters =\ ParametersProcessor.file_default_parameters self.directory_appends = {'join': self._append_join_directory, 'remove': self._append_remove_directory, 'clear': self._append_clear_directory} self.file_appends = {'join': self._append_join_file} self.formats_classes = ParametersProcessor.available_formats def use_directory_template(self, target_path, parameters): print('Template parameters:') parameters.print_parameters_for_debug() self.template_parameters = parameters self.directory_appends[self.template_parameters.append](target_path) def use_file_template(self, target_path, parameters, template_text=''): print('Template parameters:') parameters.print_parameters_for_debug() self.template_parameters = parameters self.template_text = template_text self.file_appends[self.template_parameters.append](target_path) def _append_join_directory(self, target_path): print("append = 'join'") if os.access(target_path, os.F_OK): if self.template_parameters.chmod: self.chmod_directory(target_path) if self.template_parameters.chown: self.chown_directory(target_path) return directories_to_create = [target_path] directory_path = os.path.dirname(target_path) while not os.access(directory_path, os.F_OK) and directory_path: directories_to_create.append(directory_path) directory_path = os.path.dirname(directory_path) try: current_mod, current_uid, current_gid = self.get_file_info( directory_path, 'all') current_owner = {'uid': current_uid, 'gid': current_gid} except OSError: raise TemplateActionError('No access to the directory: {}'.format( directory_path)) directories_to_create.reverse() for create_path in directories_to_create: try: os.mkdir(create_path) if (self.template_parameters.chmod and self.template_parameters.chmod != current_mod): self.chmod_directory(create_path) elif 'chmod' in self.directory_default_parameters: self.chmod_directory( create_path, chmod_value=self.directory_default_parameters['chown']) if (self.template_parameters.chown and self.template_parameters.chown != current_owner): self.chown_directory elif 'chown' in self.directory_default_parameters: self.chown_directory( create_path, chown_value=self.directory_default_parameters['chmod']) except OSError as error: raise TemplateActionError( 'Failed to create directory: {}, reason: {}'. format(create_path, str(error))) def _append_remove_directory(self, target_path): print("append = 'remove'") if os.path.isdir(target_path) or os.path.exists(target_path): try: if os.path.islink(target_path): os.unlink(target_path) else: shutil.rmtree(target_path) return True except Exception as error: self.output.set_error("Failed to delete the directory: {}". format(target_path)) self.output.set_error("Reason: {}". format(str(error))) return False else: self.output.set_error("Failed to delete the directory: {}". format(target_path)) self.output.set_error( "Target file is not directory or not exists.". format(target_path)) return False def _append_clear_directory(self, target_path): print("append = 'clear'") if os.path.isdir(target_path): if os.path.exists(target_path): try: if os.path.islink(target_path): os.unlink(target_path) else: shutil.rmtree(target_path) return except Exception as error: raise TemplateActionError( ("Failed to delete the directory: {}," "reason: {}").format(target_path, str(error))) else: error_message = "target directory does not exist" else: error_message = "target file is not directory" raise TemplateActionError( "Failed to delete the directory: {}, reason: {}.". format(target_path, error_message)) def _append_skip_directory(self, target_path): print("append = 'skip'") return def _append_join_file(self, target_path): print("append = 'join'") if not self.template_parameters.format: print('Format not defined.') return format_class = self.formats_classes[self.template_parameters.format] if os.path.exists(target_path): with open(target_path, 'r') as original_file: original_file_text = original_file.read() print('ORIGINAL:') print(original_file_text) else: open(target_path, 'w').close() original_file_text = '' original_object = format_class(original_file_text) template_object = format_class(self.template_text) print('TEMPLATE:') print(self.template_text) original_object.join_template(template_object) print('RESULT:') print(original_object.document_text) def _append_clear_file(self, target_path): print("append = 'clear'") try: with open(target_path, 'w') as file: file.truncate(0) except IOError: raise TemplateActionError("Failed to clear the file: {}". format(target_path)) return False template_engine.process_template_from_string(template_text, FILE) template_parameters = template_engine.parameters template_text = template_engine.template_text template_action_obj = TemplateActionDraft(datavars_module=DATAVARS_MODULE, chroot_path=CHROOT_PATH) result = template_action_obj.use_file_template(target_path, template_parameters, template_text=template_text)