utils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import io
  19. import sys
  20. from typing import TYPE_CHECKING, Collection
  21. if TYPE_CHECKING:
  22. from io import IOBase
  23. class CliConflictError(Exception):
  24. """Error for when CLI commands are defined twice by different sources."""
  25. pass
  26. def is_stdout(fileio: IOBase) -> bool:
  27. """
  28. Check whether a file IO is stdout.
  29. The intended use case for this helper is to check whether an argument parsed
  30. with argparse.FileType points to stdout (by setting the path to ``-``). This
  31. is why there is no equivalent for stderr; argparse does not allow using it.
  32. .. warning:: *fileio* must be open for this check to be successful.
  33. """
  34. return fileio.fileno() == sys.stdout.fileno()
  35. def print_export_output(command_type: str, exported_items: Collection, file: io.TextIOWrapper):
  36. if not file.closed and is_stdout(file):
  37. print(f"\n{len(exported_items)} {command_type} successfully exported.", file=sys.stderr)
  38. else:
  39. print(f"{len(exported_items)} {command_type} successfully exported to {file.name}.")