unicode_paths.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (c) 2013 Will Bond <will@wbond.net>
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. import sys
  24. from watchdog.utils import platform
  25. try:
  26. # Python 2
  27. str_cls = unicode
  28. bytes_cls = str
  29. except NameError:
  30. # Python 3
  31. str_cls = str
  32. bytes_cls = bytes
  33. # This is used by Linux when the locale seems to be improperly set. UTF-8 tends
  34. # to be the encoding used by all distros, so this is a good fallback.
  35. fs_fallback_encoding = 'utf-8'
  36. fs_encoding = sys.getfilesystemencoding() or fs_fallback_encoding
  37. def encode(path):
  38. if isinstance(path, str_cls):
  39. try:
  40. path = path.encode(fs_encoding, 'strict')
  41. except UnicodeEncodeError:
  42. if not platform.is_linux():
  43. raise
  44. path = path.encode(fs_fallback_encoding, 'strict')
  45. return path
  46. def decode(path):
  47. if isinstance(path, bytes_cls):
  48. try:
  49. path = path.decode(fs_encoding, 'strict')
  50. except UnicodeDecodeError:
  51. if not platform.is_linux():
  52. raise
  53. path = path.decode(fs_fallback_encoding, 'strict')
  54. return path