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.

command.py 4.3 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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 stat
  19. import argparse
  20. from importlib import import_module
  21. import mindinsight
  22. from mindinsight.utils.log import setup_logger
  23. from mindinsight.utils.exceptions import MindInsightException
  24. class BaseCommand:
  25. """Base command class."""
  26. name = ''
  27. description = ''
  28. # logger for console output instead of built-in print
  29. console = None
  30. # logger for log file recording in case audit is required
  31. logfile = None
  32. def add_arguments(self, parser):
  33. """
  34. Add arguments to parser.
  35. Args:
  36. parser (ArgumentParser): specify parser to which arguments are added.
  37. """
  38. def update_settings(self, args):
  39. """
  40. Update settings.
  41. Args:
  42. args (Namespace): parsed arguments to hold customized parameters.
  43. """
  44. def run(self, args):
  45. """
  46. Implementation of command logic.
  47. Args:
  48. args (Namespace): parsed arguments to hold customized parameters.
  49. """
  50. raise NotImplementedError('subclasses of BaseCommand must provide a run() method')
  51. def invoke(self, args):
  52. """
  53. Invocation of command.
  54. Args:
  55. args (Namespace): parsed arguments to hold customized parameters.
  56. """
  57. error = None
  58. try:
  59. self.update_settings(args)
  60. except MindInsightException as e:
  61. error = e
  62. self.console = setup_logger('mindinsight', 'console', console=True, logfile=False, formatter='%(message)s')
  63. if error is not None:
  64. self.console.error(error.message)
  65. sys.exit(1)
  66. self.logfile = setup_logger('scripts', self.name, console=False, logfile=True)
  67. self.run(args)
  68. def main():
  69. """Entry point for mindinsight CLI."""
  70. console = setup_logger('mindinsight', 'console', console=True, logfile=False, formatter='%(message)s')
  71. if (sys.version_info.major, sys.version_info.minor) < (3, 7):
  72. console.error('Python version should be at least 3.7')
  73. sys.exit(1)
  74. # set umask to 0o077
  75. os.umask(stat.S_IRWXG | stat.S_IRWXO)
  76. parser = argparse.ArgumentParser(
  77. prog='mindinsight',
  78. description='MindInsight CLI entry point (version: {})'.format(mindinsight.__version__),
  79. allow_abbrev=False)
  80. parser.add_argument(
  81. '--version',
  82. action='version',
  83. version='%(prog)s ({})'.format(mindinsight.__version__))
  84. subparsers = parser.add_subparsers(
  85. dest='cli',
  86. title='subcommands',
  87. description='the following subcommands are supported',
  88. )
  89. commands = {}
  90. scripts_path = os.path.realpath(os.path.join(__file__, os.pardir, os.pardir, 'scripts'))
  91. files = os.listdir(scripts_path)
  92. files.sort()
  93. for file in files:
  94. if file.startswith('_') or not file.endswith('.py'):
  95. continue
  96. module = import_module('mindinsight.scripts.{}'.format(file[:-len('.py')]))
  97. command_cls = getattr(module, 'Command', None)
  98. if command_cls is None or not issubclass(command_cls, BaseCommand):
  99. continue
  100. command = command_cls()
  101. command_parser = subparsers.add_parser(command.name, help=command.description, allow_abbrev=False)
  102. command.add_arguments(command_parser)
  103. commands[command.name] = command
  104. argv = sys.argv[1:]
  105. if not argv or argv[0] == 'help':
  106. argv = ['-h']
  107. args = parser.parse_args(argv)
  108. cli = args.__dict__.pop('cli')
  109. command = commands[cli]
  110. command.invoke(args)