filesystem.py 5.8 KB

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