compat.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # -*- coding: utf-8 -*-
  2. # config.py
  3. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  4. #
  5. # This module is part of GitPython and is released under
  6. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  7. """utilities to help provide compatibility with python 3"""
  8. # flake8: noqa
  9. import locale
  10. import os
  11. import sys
  12. from gitdb.utils.encoding import (
  13. force_bytes, # @UnusedImport
  14. force_text, # @UnusedImport
  15. )
  16. # typing --------------------------------------------------------------------
  17. from typing import (
  18. Any,
  19. AnyStr,
  20. Dict,
  21. IO,
  22. Optional,
  23. Tuple,
  24. Type,
  25. Union,
  26. overload,
  27. )
  28. # ---------------------------------------------------------------------------
  29. is_win: bool = os.name == "nt"
  30. is_posix = os.name == "posix"
  31. is_darwin = os.name == "darwin"
  32. defenc = sys.getfilesystemencoding()
  33. @overload
  34. def safe_decode(s: None) -> None:
  35. ...
  36. @overload
  37. def safe_decode(s: AnyStr) -> str:
  38. ...
  39. def safe_decode(s: Union[AnyStr, None]) -> Optional[str]:
  40. """Safely decodes a binary string to unicode"""
  41. if isinstance(s, str):
  42. return s
  43. elif isinstance(s, bytes):
  44. return s.decode(defenc, "surrogateescape")
  45. elif s is None:
  46. return None
  47. else:
  48. raise TypeError("Expected bytes or text, but got %r" % (s,))
  49. @overload
  50. def safe_encode(s: None) -> None:
  51. ...
  52. @overload
  53. def safe_encode(s: AnyStr) -> bytes:
  54. ...
  55. def safe_encode(s: Optional[AnyStr]) -> Optional[bytes]:
  56. """Safely encodes a binary string to unicode"""
  57. if isinstance(s, str):
  58. return s.encode(defenc)
  59. elif isinstance(s, bytes):
  60. return s
  61. elif s is None:
  62. return None
  63. else:
  64. raise TypeError("Expected bytes or text, but got %r" % (s,))
  65. @overload
  66. def win_encode(s: None) -> None:
  67. ...
  68. @overload
  69. def win_encode(s: AnyStr) -> bytes:
  70. ...
  71. def win_encode(s: Optional[AnyStr]) -> Optional[bytes]:
  72. """Encode unicodes for process arguments on Windows."""
  73. if isinstance(s, str):
  74. return s.encode(locale.getpreferredencoding(False))
  75. elif isinstance(s, bytes):
  76. return s
  77. elif s is not None:
  78. raise TypeError("Expected bytes or text, but got %r" % (s,))
  79. return None