filesystem.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import fnmatch
  2. import os
  3. import os.path
  4. import random
  5. import sys
  6. from contextlib import contextmanager
  7. from tempfile import NamedTemporaryFile
  8. from typing import Any, BinaryIO, Generator, List, Union, cast
  9. from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed
  10. from pip._internal.utils.compat import get_path_uid
  11. from pip._internal.utils.misc import format_size
  12. def check_path_owner(path: str) -> bool:
  13. # If we don't have a way to check the effective uid of this process, then
  14. # we'll just assume that we own the directory.
  15. if sys.platform == "win32" or not hasattr(os, "geteuid"):
  16. return True
  17. assert os.path.isabs(path)
  18. previous = None
  19. while path != previous:
  20. if os.path.lexists(path):
  21. # Check if path is writable by current user.
  22. if os.geteuid() == 0:
  23. # Special handling for root user in order to handle properly
  24. # cases where users use sudo without -H flag.
  25. try:
  26. path_uid = get_path_uid(path)
  27. except OSError:
  28. return False
  29. return path_uid == 0
  30. else:
  31. return os.access(path, os.W_OK)
  32. else:
  33. previous, path = path, os.path.dirname(path)
  34. return False # assume we don't own the path
  35. @contextmanager
  36. def adjacent_tmp_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:
  37. """Return a file-like object pointing to a tmp file next to path.
  38. The file is created securely and is ensured to be written to disk
  39. after the context reaches its end.
  40. kwargs will be passed to tempfile.NamedTemporaryFile to control
  41. the way the temporary file will be opened.
  42. """
  43. with NamedTemporaryFile(
  44. delete=False,
  45. dir=os.path.dirname(path),
  46. prefix=os.path.basename(path),
  47. suffix=".tmp",
  48. **kwargs,
  49. ) as f:
  50. result = cast(BinaryIO, f)
  51. try:
  52. yield result
  53. finally:
  54. result.flush()
  55. os.fsync(result.fileno())
  56. # Tenacity raises RetryError by default, explicitly raise the original exception
  57. _replace_retry = retry(reraise=True, stop=stop_after_delay(1), wait=wait_fixed(0.25))
  58. replace = _replace_retry(os.replace)
  59. # test_writable_dir and _test_writable_dir_win are copied from Flit,
  60. # with the author's agreement to also place them under pip's license.
  61. def test_writable_dir(path: str) -> bool:
  62. """Check if a directory is writable.
  63. Uses os.access() on POSIX, tries creating files on Windows.
  64. """
  65. # If the directory doesn't exist, find the closest parent that does.
  66. while not os.path.isdir(path):
  67. parent = os.path.dirname(path)
  68. if parent == path:
  69. break # Should never get here, but infinite loops are bad
  70. path = parent
  71. if os.name == "posix":
  72. return os.access(path, os.W_OK)
  73. return _test_writable_dir_win(path)
  74. def _test_writable_dir_win(path: str) -> bool:
  75. # os.access doesn't work on Windows: http://bugs.python.org/issue2528
  76. # and we can't use tempfile: http://bugs.python.org/issue22107
  77. basename = "accesstest_deleteme_fishfingers_custard_"
  78. alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
  79. for _ in range(10):
  80. name = basename + "".join(random.choice(alphabet) for _ in range(6))
  81. file = os.path.join(path, name)
  82. try:
  83. fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL)
  84. except FileExistsError:
  85. pass
  86. except PermissionError:
  87. # This could be because there's a directory with the same name.
  88. # But it's highly unlikely there's a directory called that,
  89. # so we'll assume it's because the parent dir is not writable.
  90. # This could as well be because the parent dir is not readable,
  91. # due to non-privileged user access.
  92. return False
  93. else:
  94. os.close(fd)
  95. os.unlink(file)
  96. return True
  97. # This should never be reached
  98. raise OSError("Unexpected condition testing for writable directory")
  99. def find_files(path: str, pattern: str) -> List[str]:
  100. """Returns a list of absolute paths of files beneath path, recursively,
  101. with filenames which match the UNIX-style shell glob pattern."""
  102. result: List[str] = []
  103. for root, _, files in os.walk(path):
  104. matches = fnmatch.filter(files, pattern)
  105. result.extend(os.path.join(root, f) for f in matches)
  106. return result
  107. def file_size(path: str) -> Union[int, float]:
  108. # If it's a symlink, return 0.
  109. if os.path.islink(path):
  110. return 0
  111. return os.path.getsize(path)
  112. def format_file_size(path: str) -> str:
  113. return format_size(file_size(path))
  114. def directory_size(path: str) -> Union[int, float]:
  115. size = 0.0
  116. for root, _dirs, files in os.walk(path):
  117. for filename in files:
  118. file_path = os.path.join(root, filename)
  119. size += file_size(file_path)
  120. return size
  121. def format_directory_size(path: str) -> str:
  122. return format_size(directory_size(path))