FileUtils.java 7.57 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.utils;

KingRainbow44's avatar
KingRainbow44 committed
3
4
import emu.grasscutter.Grasscutter;

Melledy's avatar
Melledy committed
5
6
import java.io.File;
import java.io.IOException;
7
8
9
10
11
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
12
import java.util.Map;
13
import java.util.stream.Collectors;
14
import java.util.stream.Stream;
Melledy's avatar
Melledy committed
15

KingRainbow44's avatar
KingRainbow44 committed
16
public final class FileUtils {
17
18
19
20
21
22
23
24
    private static final Path DATA_DEFAULT_PATH;
    private static final Path DATA_USER_PATH = Path.of(Grasscutter.config.folderStructure.data);
    private static final Path PACKETS_PATH = Path.of(Grasscutter.config.folderStructure.packets);
    private static final Path PLUGINS_PATH = Path.of(Grasscutter.config.folderStructure.plugins);
    private static final Path RESOURCES_PATH;
    private static final Path SCRIPTS_PATH;
    static {
        FileSystem fs = null;
25
26
        Path path = null;
        // Setup access to jar resources
27
        try {
28
29
30
31
32
33
34
35
36
37
38
39
40
            var uri = Grasscutter.class.getResource("/defaults/data").toURI();
            switch (uri.getScheme()) {
                case "jar":  // When running normally, as a jar
                case "zip":  // Honestly I have no idea what setup would result in this, but this should work regardless
                    fs = FileSystems.newFileSystem(uri, Map.of());  // Have to mount zip filesystem. This leaks, but we want to keep it forever anyway.
                    // Fall-through
                case "file":  // When running in an IDE
                    path = Path.of(uri);  // Can access directly
                    break;
                default:
                Grasscutter.getLogger().error("Invalid URI scheme for class resources: "+uri.getScheme());
                    break;
            }
41
42
        } catch (URISyntaxException | IOException e) {
            // Failed to load this jar. How?
43
            Grasscutter.getLogger().error("Failed to load jar?!");
44
45
        } finally {
            DATA_DEFAULT_PATH = path;
46
            Grasscutter.getLogger().debug("Setting path for default data: "+path.toAbsolutePath());
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        }

        // Setup Resources path
        final String resources = Grasscutter.config.folderStructure.resources;
        fs = null;
        path = Path.of(resources);
        if (resources.endsWith(".zip")) {  // Would be nice to support .tar.gz too at some point, but it doesn't come for free in Java
            try {
                fs = FileSystems.newFileSystem(path);
            } catch (IOException e) {
                Grasscutter.getLogger().error("Failed to load resources zip \"" + resources + "\"");
            }
        }

        if (fs != null) {
            var root = fs.getPath("");
            try (Stream<Path> pathStream = Files.find(root, 3, (p, a) -> {
                        var filename = p.getFileName();
                        if (filename == null) return false;
                        return filename.toString().equals("ExcelBinOutput");
            })) {
                var excelBinOutput = pathStream.findFirst();
                if (excelBinOutput.isPresent()) {
                    path = excelBinOutput.get().getParent();
                    if (path == null)
                        path = root;
                    Grasscutter.getLogger().debug("Resources will be loaded from \"" + resources + "/" + path.toString() + "\"");
                } else {
                    Grasscutter.getLogger().error("Failed to find ExcelBinOutput in resources zip \"" + resources + "\"");
                }
            } catch (IOException e) {
                Grasscutter.getLogger().error("Failed to scan resources zip \"" + resources + "\"");
            }
        }
        RESOURCES_PATH = path;

        // Setup Scripts path
        final String scripts = Grasscutter.config.folderStructure.scripts;
        SCRIPTS_PATH = (scripts.startsWith("resources:"))
            ? RESOURCES_PATH.resolve(scripts.substring("resources:".length()))
            : Path.of(scripts);
    };

    public static Path getDataPath(String path) {
        Path userPath = DATA_USER_PATH.resolve(path);
        if (Files.exists(userPath)) return userPath;
        Path defaultPath = DATA_DEFAULT_PATH.resolve(path);
        if (Files.exists(defaultPath)) return defaultPath;
        return userPath;  // Maybe they want to write to a new file
    }

    public static Path getDataUserPath(String path) {
        return DATA_USER_PATH.resolve(path);
    }

    public static Path getPacketPath(String path) {
        return PACKETS_PATH.resolve(path);
    }

    public static Path getPluginPath(String path) {
        return PLUGINS_PATH.resolve(path);
    }

    public static Path getResourcePath(String path) {
        return RESOURCES_PATH.resolve(path);
    }

    public static Path getScriptPath(String path) {
        return SCRIPTS_PATH.resolve(path);
    }

github-actions's avatar
github-actions committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    public static void write(String dest, byte[] bytes) {
        Path path = Path.of(dest);

        try {
            Files.write(path, bytes);
        } catch (IOException e) {
            Grasscutter.getLogger().warn("Failed to write file: " + dest);
        }
    }

    public static byte[] read(String dest) {
        return read(Path.of(dest));
    }

    public static byte[] read(Path path) {
        try {
            return Files.readAllBytes(path);
        } catch (IOException e) {
            Grasscutter.getLogger().warn("Failed to read file: " + path);
        }

        return new byte[0];
    }

    public static InputStream readResourceAsStream(String resourcePath) {
        return Grasscutter.class.getResourceAsStream(resourcePath);
    }

    public static byte[] readResource(String resourcePath) {
        try (InputStream is = Grasscutter.class.getResourceAsStream(resourcePath)) {
            return is.readAllBytes();
        } catch (Exception exception) {
            Grasscutter.getLogger().warn("Failed to read resource: " + resourcePath);
            exception.printStackTrace();
        }

        return new byte[0];
    }

    public static byte[] read(File file) {
        return read(file.getPath());
    }

    public static void copyResource(String resourcePath, String destination) {
        try {
            byte[] resource = FileUtils.readResource(resourcePath);
            FileUtils.write(destination, resource);
        } catch (Exception exception) {
            Grasscutter.getLogger().warn("Failed to copy resource: " + resourcePath + "\n" + exception);
        }
    }

170
    @Deprecated  // No current uses of this anyway
github-actions's avatar
github-actions committed
171
    public static String getFilenameWithoutPath(String fileName) {
172
173
174
        int i = fileName.lastIndexOf(".");
        if (i > 0) {
           return fileName.substring(0, i);
github-actions's avatar
github-actions committed
175
176
177
178
179
180
181
182
        } else {
           return fileName;
        }
    }

    public static List<Path> getPathsFromResource(String folder) throws URISyntaxException {
        try {
            // file walks JAR
183
            return Files.walk(Path.of(Grasscutter.class.getResource(folder).toURI()))
github-actions's avatar
github-actions committed
184
185
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
186
        } catch (IOException e) {
github-actions's avatar
github-actions committed
187
            // Eclipse puts resources in its bin folder
188
189
190
191
192
            try {
                return Files.walk(Path.of(System.getProperty("user.dir"), folder))
                        .filter(Files::isRegularFile)
                        .collect(Collectors.toList());
            } catch (IOException ignored) {
github-actions's avatar
github-actions committed
193
194
195
196
197
198
199
200
201
202
203
                return null;
            }
        }
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static String readToString(InputStream file) throws IOException {
        byte[] content = file.readAllBytes();

        return new String(content, StandardCharsets.UTF_8);
    }
Melledy's avatar
Melledy committed
204
}