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.

source_file.py 2.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. """Source file module."""
  16. import os
  17. import shutil
  18. import stat
  19. from pathlib import Path
  20. from mindinsight.wizard.common.exceptions import OSPermissionError, TemplateFileError
  21. class SourceFile:
  22. """Network code generator."""
  23. file_relative_path = ''
  24. template_file_path = ''
  25. content = ''
  26. @staticmethod
  27. def _make_dir(directory):
  28. permissions = os.R_OK | os.W_OK | os.X_OK
  29. mode = permissions << 6
  30. os.makedirs(directory, mode=mode, exist_ok=True)
  31. return directory
  32. def write(self, project_directory):
  33. """Generate the network files."""
  34. template_file_path = Path(self.template_file_path)
  35. if not template_file_path.is_file():
  36. raise TemplateFileError("Template file %s is not exist." % self.template_file_path)
  37. new_file_path = os.path.join(project_directory, self.file_relative_path)
  38. self._make_dir(os.path.dirname(new_file_path))
  39. with open(new_file_path, 'w', encoding='utf-8') as fp:
  40. fp.write(self.content)
  41. try:
  42. shutil.copymode(self.template_file_path, new_file_path)
  43. self.set_writeable(new_file_path)
  44. if new_file_path.endswith('.sh'):
  45. self.set_executable(new_file_path)
  46. except OSError:
  47. raise OSPermissionError("Notice: Set permission bits failed on %s." % new_file_path)
  48. @staticmethod
  49. def set_writeable(file_name):
  50. """Add write permission."""
  51. if not os.access(file_name, os.W_OK):
  52. file_stat = os.stat(file_name)
  53. permissions = stat.S_IMODE(file_stat.st_mode) | stat.S_IWUSR
  54. os.chmod(file_name, permissions)
  55. @staticmethod
  56. def set_executable(file_name):
  57. """Add executable permission."""
  58. if not os.access(file_name, os.X_OK):
  59. file_stat = os.stat(file_name)
  60. permissions = stat.S_IMODE(file_stat.st_mode) | stat.S_IXUSR
  61. os.chmod(file_name, permissions)