| 1 | package net.minecraft.util.filefix;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import java.io.IOException;
|
| 5 | import java.nio.file.FileAlreadyExistsException;
|
| 6 | import java.nio.file.Files;
|
| 7 | import java.nio.file.Path;
|
| 8 | import java.nio.file.StandardCopyOption;
|
| 9 | import java.util.List;
|
| 10 | import java.util.Locale;
|
| 11 | import java.util.stream.Stream;
|
| 12 | import net.minecraft.util.FileUtil;
|
| 13 | import org.slf4j.Logger;
|
| 14 |
|
| 15 | public class FileFixUtil {
|
| 16 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 17 | public static final String NAMESPACE_PATTERN = "([a-z0-9_.-]+)";
|
| 18 |
|
| 19 | public static void moveFile(final Path baseDirectory, final String from, final String to) throws IOException {
|
| 20 | Path fromAbsolute = baseDirectory.resolve(from);
|
| 21 | if (Files.exists(fromAbsolute)) {
|
| 22 | Path toAbsolute = baseDirectory.resolve(to);
|
| 23 | if (Files.exists(toAbsolute)) {
|
| 24 | throw new FileAlreadyExistsException(String.format(Locale.ROOT, "Cannot move file from %s to %s: Target already exists", from, to));
|
| 25 | }
|
| 26 |
|
| 27 | FileUtil.createDirectoriesSafe(toAbsolute.getParent());
|
| 28 | Files.move(fromAbsolute, toAbsolute, StandardCopyOption.COPY_ATTRIBUTES);
|
| 29 | }
|
| 30 | }
|
| 31 |
|
| 32 | public static void deleteFileOrEmptyDirectory(final Path baseDirectory, final String file) throws IOException {
|
| 33 | Path toDelete = baseDirectory.resolve(file);
|
| 34 | if (Files.exists(toDelete)) {
|
| 35 | if (Files.isDirectory(toDelete)) {
|
| 36 | try {
|
| 37 | try (Stream<Path> paths = Files.list(toDelete)) {
|
| 38 | List<Path> files = paths.toList();
|
| 39 | if (files.size() == 1 && files.getFirst().getFileName().toString().equals(".DS_Store")) {
|
| 40 | LOGGER.debug("Attempting to delete DS_Store at '{}'", toDelete);
|
| 41 | if (!Files.deleteIfExists(files.getFirst())) {
|
| 42 | LOGGER.warn("Failed to delete file '{}' at '{}'", files.getFirst(), toDelete);
|
| 43 | }
|
| 44 | }
|
| 45 | }
|
| 46 |
|
| 47 | List var12;
|
| 48 | try (Stream<Path> paths = Files.list(toDelete)) {
|
| 49 | var12 = paths.toList();
|
| 50 | }
|
| 51 |
|
| 52 | if (!var12.isEmpty()) {
|
| 53 | LOGGER.warn("Failed to delete directory '{}', as it's not empty. Content: {}", toDelete, var12);
|
| 54 | return;
|
| 55 | }
|
| 56 | } catch (IOException e) {
|
| 57 | LOGGER.warn("Failed to delete directory '{}' because {}", toDelete, e.toString());
|
| 58 | return;
|
| 59 | }
|
| 60 | }
|
| 61 |
|
| 62 | Files.deleteIfExists(toDelete);
|
| 63 | }
|
| 64 | }
|
| 65 | }
|
| 66 |
|