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.

cli.py 7.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. """Command module."""
  16. import os
  17. import sys
  18. import argparse
  19. import mindinsight
  20. from mindinsight.mindconverter.converter import main
  21. class FileDirAction(argparse.Action):
  22. """File directory action class definition."""
  23. @staticmethod
  24. def check_path(parser, values, option_string=None):
  25. """
  26. Check argument for file path.
  27. Args:
  28. parser (ArgumentParser): Passed-in argument parser.
  29. values (object): Argument values with type depending on argument definition.
  30. option_string (str): Optional string for specific argument name. Default: None.
  31. """
  32. outfile = values
  33. if outfile.startswith('~'):
  34. outfile = os.path.realpath(os.path.expanduser(outfile))
  35. if not outfile.startswith('/'):
  36. outfile = os.path.realpath(os.path.join(os.getcwd(), outfile))
  37. if os.path.exists(outfile) and not os.access(outfile, os.R_OK):
  38. parser.error(f'{option_string} {outfile} not accessible')
  39. return outfile
  40. def __call__(self, parser, namespace, values, option_string=None):
  41. """
  42. Inherited __call__ method from argparse.Action.
  43. Args:
  44. parser (ArgumentParser): Passed-in argument parser.
  45. namespace (Namespace): Namespace object to hold arguments.
  46. values (object): Argument values with type depending on argument definition.
  47. option_string (str): Optional string for specific argument name. Default: None.
  48. """
  49. outfile_dir = self.check_path(parser, values, option_string)
  50. if os.path.isfile(outfile_dir):
  51. parser.error(f'{option_string} {outfile_dir} is a file')
  52. setattr(namespace, self.dest, outfile_dir)
  53. class OutputDirAction(argparse.Action):
  54. """File directory action class definition."""
  55. def __call__(self, parser, namespace, values, option_string=None):
  56. """
  57. Inherited __call__ method from argparse.Action.
  58. Args:
  59. parser (ArgumentParser): Passed-in argument parser.
  60. namespace (Namespace): Namespace object to hold arguments.
  61. values (object): Argument values with type depending on argument definition.
  62. option_string (str): Optional string for specific argument name. Default: None.
  63. """
  64. output = values
  65. if output.startswith('~'):
  66. output = os.path.realpath(os.path.expanduser(output))
  67. if not output.startswith('/'):
  68. output = os.path.realpath(os.path.join(os.getcwd(), output))
  69. if os.path.exists(output):
  70. if not os.access(output, os.R_OK):
  71. parser.error(f'{option_string} {output} not accessible')
  72. if os.path.isfile(output):
  73. parser.error(f'{option_string} {output} is a file')
  74. setattr(namespace, self.dest, output)
  75. class InFileAction(argparse.Action):
  76. """Input File action class definition."""
  77. def __call__(self, parser, namespace, values, option_string=None):
  78. """
  79. Inherited __call__ method from argparse.Action.
  80. Args:
  81. parser (ArgumentParser): Passed-in argument parser.
  82. namespace (Namespace): Namespace object to hold arguments.
  83. values (object): Argument values with type depending on argument definition.
  84. option_string (str): Optional string for specific argument name. Default: None.
  85. """
  86. outfile_dir = FileDirAction.check_path(parser, values, option_string)
  87. if not os.path.exists(outfile_dir):
  88. parser.error(f'{option_string} {outfile_dir} not exists')
  89. if not os.path.isfile(outfile_dir):
  90. parser.error(f'{option_string} {outfile_dir} is not a file')
  91. setattr(namespace, self.dest, outfile_dir)
  92. class LogFileAction(argparse.Action):
  93. """Log file action class definition."""
  94. def __call__(self, parser, namespace, values, option_string=None):
  95. """
  96. Inherited __call__ method from FileDirAction.
  97. Args:
  98. parser (ArgumentParser): Passed-in argument parser.
  99. namespace (Namespace): Namespace object to hold arguments.
  100. values (object): Argument values with type depending on argument definition.
  101. option_string (str): Optional string for specific argument name. Default: None.
  102. """
  103. outfile_dir = FileDirAction.check_path(parser, values, option_string)
  104. if os.path.exists(outfile_dir) and not os.path.isdir(outfile_dir):
  105. parser.error(f'{option_string} {outfile_dir} is not a directory')
  106. setattr(namespace, self.dest, outfile_dir)
  107. def cli_entry():
  108. """Entry point for mindconverter CLI."""
  109. permissions = os.R_OK | os.W_OK | os.X_OK
  110. os.umask(permissions << 3 | permissions)
  111. parser = argparse.ArgumentParser(
  112. prog='mindconverter',
  113. description='MindConverter CLI entry point (version: {})'.format(mindinsight.__version__))
  114. parser.add_argument(
  115. '--version',
  116. action='version',
  117. version='%(prog)s ({})'.format(mindinsight.__version__))
  118. parser.add_argument(
  119. '--in_file',
  120. type=str,
  121. action=InFileAction,
  122. required=True,
  123. help="""
  124. Specify path for script file.
  125. """)
  126. parser.add_argument(
  127. '--output',
  128. type=str,
  129. action=OutputDirAction,
  130. default=os.path.join(os.getcwd(), 'output'),
  131. help="""
  132. Specify path for converted script file directory.
  133. Default is output directory in the current working directory.
  134. """)
  135. parser.add_argument(
  136. '--report',
  137. type=str,
  138. action=LogFileAction,
  139. default=os.getcwd(),
  140. help="""
  141. Specify report directory. Default is the current working directory.
  142. """)
  143. argv = sys.argv[1:]
  144. if not argv:
  145. argv = ['-h']
  146. args = parser.parse_args(argv)
  147. else:
  148. args = parser.parse_args()
  149. mode = permissions << 6
  150. os.makedirs(args.output, mode=mode, exist_ok=True)
  151. os.makedirs(args.report, mode=mode, exist_ok=True)
  152. _run(args.in_file, args.output, '', args.report)
  153. def _run(in_files, out_dir, in_module, report):
  154. """
  155. Run converter command.
  156. Args:
  157. in_files (str): The file path or directory to convert.
  158. out_dir (str): The output directory to save converted file.
  159. in_module (str): The module name to convert.
  160. report (str): The report file path.
  161. """
  162. files_config = {
  163. 'root_path': in_files if in_files else '',
  164. 'in_files': [],
  165. 'outfile_dir': out_dir,
  166. 'report_dir': report,
  167. 'in_module': in_module
  168. }
  169. if os.path.isfile(in_files):
  170. files_config['root_path'] = os.path.dirname(in_files)
  171. files_config['in_files'] = [in_files]
  172. else:
  173. for root_dir, _, files in os.walk(in_files):
  174. for file in files:
  175. files_config['in_files'].append(os.path.join(root_dir, file))
  176. main(files_config)