filesystem.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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._internal.utils.compat import get_path_uid
  10. from pip._internal.utils.misc import format_size
  11. from pip._internal.utils.retry import retry
  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. replace = retry(stop_after_delay=1, wait=0.25)(os.replace)
  57. # test_writable_dir and _test_writable_dir_win are copied from Flit,
  58. # with the author's agreement to also place them under pip's license.
  59. def test_writable_dir(path: str) -> bool:
  60. """Check if a directory is writable.
  61. Uses os.access() on POSIX, tries creating files on Windows.
  62. """
  63. # If the directory doesn't exist, find the closest parent that does.
  64. while not os.path.isdir(path):
  65. parent = os.path.dirname(path)
  66. if parent == path:
  67. break # Should never get here, but infinite loops are bad
  68. path = parent
  69. if os.name == "posix":
  70. return os.access(path, os.W_OK)
  71. return _test_writable_dir_win(path)
  72. def _test_writable_dir_win(path: str) -> bool:
  73. # os.access doesn't work on Windows: http://bugs.python.org/issue2528
  74. # and we can't use tempfile: http://bugs.python.org/issue22107
  75. basename = "accesstest_deleteme_fishfingers_custard_"
  76. alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
  77. for _ in range(10):
  78. name = basename + "".join(random.choice(alphabet) for _ in range(6))
  79. file = os.path.join(path, name)
  80. try:
  81. fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL)
  82. except FileExistsError:
  83. pass
  84. except PermissionError:
  85. # This could be because there's a directory with the same name.
  86. # But it's highly unlikely there's a directory called that,
  87. # so we'll assume it's because the parent dir is not writable.
  88. # This could as well be because the parent dir is not readable,
  89. # due to non-privileged user access.
  90. return False
  91. else:
  92. os.close(fd)
  93. os.unlink(file)
  94. return True
  95. # This should never be reached
  96. raise OSError("Unexpected condition testing for writable directory")
  97. def find_files(path: str, pattern: str) -> List[str]:
  98. """Returns a list of absolute paths of files beneath path, recursively,
  99. with filenames which match the UNIX-style shell glob pattern."""
  100. result: List[str] = []
  101. for root, _, files in os.walk(path):
  102. matches = fnmatch.filter(files, pattern)
  103. result.extend(os.path.join(root, f) for f in matches)
  104. return result
  105. def file_size(path: str) -> Union[int, float]:
  106. # If it's a symlink, return 0.
  107. if os.path.islink(path):
  108. return 0
  109. return os.path.getsize(path)
  110. def format_file_size(path: str) -> str:
  111. return format_size(file_size(path))
  112. def directory_size(path: str) -> Union[int, float]:
  113. size = 0.0
  114. for root, _dirs, files in os.walk(path):
  115. for filename in files:
  116. file_path = os.path.join(root, filename)
  117. size += file_size(file_path)
  118. return size
  119. def format_directory_size(path: str) -> str:
  120. return format_size(directory_size(path))