1
0

filesystem.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.filesystem
  4. ~~~~~~~~~~~~~~~~~~~
  5. Various utilities for the local filesystem.
  6. :copyright: 2007 Pallets
  7. :license: BSD-3-Clause
  8. """
  9. import codecs
  10. import sys
  11. import warnings
  12. # We do not trust traditional unixes.
  13. has_likely_buggy_unicode_filesystem = (
  14. sys.platform.startswith("linux") or "bsd" in sys.platform
  15. )
  16. def _is_ascii_encoding(encoding):
  17. """Given an encoding this figures out if the encoding is actually ASCII (which
  18. is something we don't actually want in most cases). This is necessary
  19. because ASCII comes under many names such as ANSI_X3.4-1968.
  20. """
  21. if encoding is None:
  22. return False
  23. try:
  24. return codecs.lookup(encoding).name == "ascii"
  25. except LookupError:
  26. return False
  27. class BrokenFilesystemWarning(RuntimeWarning, UnicodeWarning):
  28. """The warning used by Werkzeug to signal a broken filesystem. Will only be
  29. used once per runtime."""
  30. _warned_about_filesystem_encoding = False
  31. def get_filesystem_encoding():
  32. """Returns the filesystem encoding that should be used. Note that this is
  33. different from the Python understanding of the filesystem encoding which
  34. might be deeply flawed. Do not use this value against Python's unicode APIs
  35. because it might be different. See :ref:`filesystem-encoding` for the exact
  36. behavior.
  37. The concept of a filesystem encoding in generally is not something you
  38. should rely on. As such if you ever need to use this function except for
  39. writing wrapper code reconsider.
  40. """
  41. global _warned_about_filesystem_encoding
  42. rv = sys.getfilesystemencoding()
  43. if has_likely_buggy_unicode_filesystem and not rv or _is_ascii_encoding(rv):
  44. if not _warned_about_filesystem_encoding:
  45. warnings.warn(
  46. "Detected a misconfigured UNIX filesystem: Will use"
  47. " UTF-8 as filesystem encoding instead of {0!r}".format(rv),
  48. BrokenFilesystemWarning,
  49. )
  50. _warned_about_filesystem_encoding = True
  51. return "utf-8"
  52. return rv