in junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/extension/TempDirectory.java [186:252]
private SortedMap<Path, IOException> deleteAllFilesAndDirectories() throws IOException {
if (Files.notExists(dir)) {
return Collections.emptySortedMap();
}
SortedMap<Path, IOException> failures = new TreeMap<>();
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
return deleteAndContinue(file);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return deleteAndContinue(dir);
}
private FileVisitResult deleteAndContinue(Path path) {
try {
Files.delete(path);
}
catch (NoSuchFileException ignore) {
// ignore
}
catch (DirectoryNotEmptyException exception) {
failures.put(path, exception);
}
catch (IOException exception) {
makeWritableAndTryToDeleteAgain(path, exception);
}
return CONTINUE;
}
private void makeWritableAndTryToDeleteAgain(Path path, IOException exception) {
try {
tryToMakeParentDirsWritable(path);
makeWritable(path);
Files.delete(path);
}
catch (Exception suppressed) {
exception.addSuppressed(suppressed);
failures.put(path, exception);
}
}
private void tryToMakeParentDirsWritable(Path path) {
Path relativePath = dir.relativize(path);
Path parent = dir;
for (int i = 0; i < relativePath.getNameCount(); i++) {
boolean writable = parent.toFile().setWritable(true);
if (!writable) {
break;
}
parent = parent.resolve(relativePath.getName(i));
}
}
private void makeWritable(Path path) {
boolean writable = path.toFile().setWritable(true);
if (!writable) {
throw new UndeletableFileException("Attempt to make file '" + path + "' writable failed");
}
}
});
return failures;
}