_abstract_cli.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import sys
  12. from abc import abstractmethod
  13. from difflib import SequenceMatcher
  14. from typing import List, Optional
  15. from taipy.common.logger._taipy_logger import _TaipyLogger
  16. from ._taipy_parser import _TaipyParser
  17. class _AbstractCLI:
  18. _logger = _TaipyLogger._get_logger()
  19. _COMMAND_NAME: Optional[str] = None
  20. _ARGUMENTS: List[str] = []
  21. SIMILARITY_THRESHOLD = 0.8
  22. @classmethod
  23. @abstractmethod
  24. def create_parser(cls):
  25. raise NotImplementedError
  26. @classmethod
  27. @abstractmethod
  28. def handle_command(cls):
  29. raise NotImplementedError
  30. @classmethod
  31. def _parse_arguments(cls):
  32. args, unknown_args = _TaipyParser._parser.parse_known_args()
  33. if getattr(args, "which", None) != cls._COMMAND_NAME:
  34. return
  35. if unknown_args:
  36. _TaipyParser._sub_taipyparsers.get(cls._COMMAND_NAME).print_help()
  37. for unknown_arg in unknown_args:
  38. if not unknown_arg.startswith("-"):
  39. continue
  40. error_message = f"Unknown arguments: {unknown_arg}."
  41. similar_args = [
  42. arg
  43. for arg in cls._ARGUMENTS
  44. if SequenceMatcher(None, unknown_arg, arg).ratio() > cls.SIMILARITY_THRESHOLD
  45. ]
  46. if similar_args:
  47. error_message += f" Did you mean: {' or '.join(similar_args)}?"
  48. cls._logger.error(error_message)
  49. cls._logger.error("Please refer to the help message above for more information.")
  50. sys.exit(1)
  51. return args