You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

templates.py 3.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """BaseNetwork module."""
  16. import os
  17. from jinja2 import Template
  18. from mindinsight.wizard.base.source_file import SourceFile
  19. def render_template(template_file_path, context):
  20. with open(template_file_path, encoding='utf-8') as fp:
  21. content = fp.read()
  22. template = Template(content, trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True)
  23. return template.render(context)
  24. class TemplateManager:
  25. """BaseNetwork code generator."""
  26. replace_template_suffixes = [('.py-tpl', '.py')]
  27. def __init__(self, template_base_dir, exclude_dirs=None, exclude_files=None):
  28. self.template_base_dir = template_base_dir
  29. self.exclude_dirs = self._get_exclude_paths(template_base_dir, exclude_dirs)
  30. self.exclude_files = self._get_exclude_paths(template_base_dir, exclude_files)
  31. @staticmethod
  32. def _get_exclude_paths(base_dir, exclude_paths):
  33. """Convert exclude path to absolute directory path."""
  34. exclude_abs_paths = []
  35. if exclude_paths is None:
  36. return exclude_abs_paths
  37. for exclude_path in exclude_paths:
  38. if exclude_path.startswith(base_dir):
  39. exclude_abs_paths.append(exclude_path)
  40. else:
  41. exclude_abs_paths.append(os.path.join(base_dir, exclude_path))
  42. return exclude_abs_paths
  43. def get_template_files(self):
  44. """Get template files for template directory."""
  45. template_files = []
  46. for root, sub_dirs, files in os.walk(self.template_base_dir):
  47. for sub_dir in sub_dirs[:]:
  48. if sub_dir.startswith('.') or \
  49. sub_dir == '__pycache__' or \
  50. os.path.join(root, sub_dir) in self.exclude_dirs:
  51. sub_dirs.remove(sub_dir)
  52. for filename in files:
  53. if os.path.join(root, filename) not in self.exclude_files:
  54. template_file_path = os.path.join(root, filename)
  55. template_files.append(template_file_path)
  56. return template_files
  57. def render(self, **options):
  58. """Generate the network files."""
  59. source_files = []
  60. template_files = self.get_template_files()
  61. extensions = tuple(options.get('extensions', '.py'))
  62. for template_file in template_files:
  63. new_file_path = template_file
  64. template_file_path = template_file
  65. for template_suffix, new_file_suffix in self.replace_template_suffixes:
  66. if new_file_path.endswith(template_suffix):
  67. new_file_path = new_file_path[:-len(template_suffix)] + new_file_suffix
  68. break
  69. source_file = SourceFile()
  70. source_file.file_relative_path = new_file_path[len(self.template_base_dir) + 1:]
  71. source_file.template_file_path = template_file_path
  72. if new_file_path.endswith(extensions):
  73. source_file.content = render_template(template_file_path, options)
  74. else:
  75. with open(template_file_path, encoding='utf-8') as fp:
  76. source_file.content = fp.read()
  77. source_files.append(source_file)
  78. return source_files