aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/de/hysky/skyblocker/utils/FileUtils.java
blob: 59b706c4a3651aea13b4a5069eee2401cad0042b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package de.hysky.skyblocker.utils;

import com.mojang.logging.LogUtils;
import org.slf4j.Logger;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

public class FileUtils {
	private static final Logger LOGGER = LogUtils.getLogger();

	public static void recursiveDelete(Path dir) throws IOException {
		if (!Files.exists(dir)) {
			return;
		}

		if (Files.isDirectory(dir) && !Files.isSymbolicLink(dir)) {
			try (Stream<Path> stream = Files.list(dir)) {
				stream.forEach(child -> {
					try {
						recursiveDelete(child);
					} catch (Exception e) {
						LOGGER.error("[Skyblocker] Encountered an exception while deleting a file. Path: {}", child.toAbsolutePath(), e);
					}
				});
			}
		}

		if (!Files.isWritable(dir) && !dir.toFile().setWritable(true)) {
			LOGGER.error("[Skyblocker] Failed to make file writable. Path: {}", dir.toAbsolutePath());
		}

		Files.delete(dir);
	}

	/**
	 * Replaces any characters that do not match the regex: [^a-z0-9_.-]
	 *
	 * @implNote Designed to convert a file path to an {@link net.minecraft.util.Identifier}
	 */
	public static String normalizePath(Path path) {
		return path.toString().toLowerCase().replaceAll("[^a-z0-9_.-]", "");
	}
}