Handle known read-only errors during rmtree. The returned value is used only by our own tests.
(func, path: str, exc, *, start_path: Path)
| 64 | |
| 65 | |
| 66 | def on_rm_rf_error(func, path: str, exc, *, start_path: Path) -> bool: |
| 67 | """Handle known read-only errors during rmtree. |
| 68 | |
| 69 | The returned value is used only by our own tests. |
| 70 | """ |
| 71 | exctype, excvalue = exc[:2] |
| 72 | |
| 73 | # Another process removed the file in the middle of the "rm_rf" (xdist for example). |
| 74 | # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018 |
| 75 | if isinstance(excvalue, FileNotFoundError): |
| 76 | return False |
| 77 | |
| 78 | if not isinstance(excvalue, PermissionError): |
| 79 | warnings.warn( |
| 80 | PytestWarning(f"(rm_rf) error removing {path}\n{exctype}: {excvalue}") |
| 81 | ) |
| 82 | return False |
| 83 | |
| 84 | if func not in (os.rmdir, os.remove, os.unlink): |
| 85 | if func not in (os.open,): |
| 86 | warnings.warn( |
| 87 | PytestWarning( |
| 88 | "(rm_rf) unknown function {} when removing {}:\n{}: {}".format( |
| 89 | func, path, exctype, excvalue |
| 90 | ) |
| 91 | ) |
| 92 | ) |
| 93 | return False |
| 94 | |
| 95 | # Chmod + retry. |
| 96 | import stat |
| 97 | |
| 98 | def chmod_rw(p: str) -> None: |
| 99 | mode = os.stat(p).st_mode |
| 100 | os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR) |
| 101 | |
| 102 | # For files, we need to recursively go upwards in the directories to |
| 103 | # ensure they all are also writable. |
| 104 | p = Path(path) |
| 105 | if p.is_file(): |
| 106 | for parent in p.parents: |
| 107 | chmod_rw(str(parent)) |
| 108 | # Stop when we reach the original path passed to rm_rf. |
| 109 | if parent == start_path: |
| 110 | break |
| 111 | chmod_rw(str(path)) |
| 112 | |
| 113 | func(path) |
| 114 | return True |
| 115 | |
| 116 | |
| 117 | def ensure_extended_length_path(path: Path) -> Path: |