CopyOnWriteFileSystem .java

net.minecraft.util.filefix.virtualfilesystem.CopyOnWriteFileSystem (class): members: resetFileTreeToBaseFolderContent, collectMoveOperations, skippedPaths.

net.minecraft.util.filefix.virtualfilesystemclass297 linescommonextends FileSystem9.3 KB

API Surface (28)

CopyOnWriteFileSystem create(final String name, final Path baseDirectory, final Path tmpDirectory, final PathMatcher skippedPaths)
FileVisitResult visitFile(final Path realPath, final BasicFileAttributes attrs)
FileVisitResult preVisitDirectory(final Path realPath, final BasicFileAttributes attrs)
void resetFileTreeToBaseFolderContent()
CopyOnWriteFSProvider provider()
void close()
boolean isOpen()
boolean isReadOnly()
String getSeparator()
Iterable<Path> getRootDirectories()
Iterable<FileStore> getFileStores()
Set<String> supportedFileAttributeViews()
CopyOnWriteFSPath getPath(final String first, final String... more)
PathMatcher getPathMatcher(final String syntaxAndPattern)
UserPrincipalLookupService getUserPrincipalLookupService()
WatchService newWatchService()
CopyOnWriteFileStore store()
CopyOnWriteFSPath rootPath()
Path baseDirectory()
Path tmpDirectory()
FileSystem backingFileSystem()
CopyOnWriteFileSystem.Moves collectMoveOperations(final Path outPath)
void createDirectories(final List<Path> directories)
void hardLinkFiles(final List<FileMove> moves)
void moveFiles(final List<FileMove> moves)
void moveFilesWithRetry(final List<FileMove> moves, final CopyOption... options)
List<FileMove> tryRevertMoves(final List<FileMove> moves, final CopyOption... options)
record Moves(List<Path> directories, List<FileMove> copiedFiles, List<FileMove> preexistingFiles)

Fields & Constants (10)

FILE_ATTRIBUTE_VIEWS
LOGGER
store
provider
baseDirectory
skippedPaths
tmpDirectory
rootPath
tmpFileIndex
fileTree

String literals (5)

"basic"
"Temporary directory already exists: "
"tmp_"
"Not a regular file: "
"Completed reverting with errors"

Full Source

CopyOnWriteFileSystem.java297 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.util.filefix.virtualfilesystem;
2
3
import com.google.common.annotations.VisibleForTesting;
4
import com.mojang.logging.LogUtils;
5
import java.io.IOException;
6
import java.nio.file.CopyOption;
7
import java.nio.file.FileStore;
8
import java.nio.file.FileSystem;
9
import java.nio.file.FileVisitResult;
10
import java.nio.file.Files;
11
import java.nio.file.Path;
12
import java.nio.file.PathMatcher;
13
import java.nio.file.SimpleFileVisitor;
14
import java.nio.file.WatchService;
15
import java.nio.file.attribute.BasicFileAttributes;
16
import java.nio.file.attribute.UserPrincipalLookupService;
17
import java.util.ArrayList;
18
import java.util.List;
19
import java.util.Objects;
20
import java.util.Set;
21
import java.util.concurrent.atomic.AtomicInteger;
22
import net.minecraft.util.Util;
23
import net.minecraft.util.filefix.virtualfilesystem.exception.CowFSCreationException;
24
import net.minecraft.util.filefix.virtualfilesystem.exception.CowFSSymlinkException;
25
import org.apache.commons.io.file.PathUtils;
26
import org.slf4j.Logger;
27
28
public class CopyOnWriteFileSystem extends FileSystem {
29
	private static final Set<String> FILE_ATTRIBUTE_VIEWS = Set.of("basic");
30
	private static final Logger LOGGER = LogUtils.getLogger();
31
	private final CopyOnWriteFileStore store;
32
	private final CopyOnWriteFSProvider provider;
33
	private final Path baseDirectory;
34
	private final PathMatcher skippedPaths;
35
	private final Path tmpDirectory;
36
	private final CopyOnWriteFSPath rootPath;
37
	private final AtomicInteger tmpFileIndex = new AtomicInteger();
38
	private DirectoryNode fileTree;
39
40
	private CopyOnWriteFileSystem(final String name, final Path baseDirectory, final Path tmpDirectory, final PathMatcher skippedPaths) throws IOException {
41
		this.baseDirectory = baseDirectory;
42
		this.tmpDirectory = tmpDirectory;
43
		this.skippedPaths = skippedPaths;
44
		this.provider = new CopyOnWriteFSProvider(this);
45
		this.store = new CopyOnWriteFileStore(name, this);
46
		this.rootPath = this.getPath("/");
47
		this.fileTree = this.buildFileTreeFrom(baseDirectory);
48
	}
49
50
	public static CopyOnWriteFileSystem create(final String name, final Path baseDirectory, final Path tmpDirectory, final PathMatcher skippedPaths) throws IOException {
51
		if (Files.exists(tmpDirectory)) {
52
			throw new CowFSCreationException("Temporary directory already exists: " + tmpDirectory);
53
		}
54
55
		CopyOnWriteFileSystem fileSystem = new CopyOnWriteFileSystem(name, baseDirectory, tmpDirectory, skippedPaths);
56
		Files.createDirectory(tmpDirectory);
57
		return fileSystem;
58
	}
59
60
	private DirectoryNode buildFileTreeFrom(final Path baseDirectory) throws IOException {
61
		final DirectoryNode fileTree = new DirectoryNode(this.rootPath);
62
		Files.walkFileTree(baseDirectory, new SimpleFileVisitor<Path>() {
63
			public FileVisitResult visitFile(final Path realPath, final BasicFileAttributes attrs) throws IOException {
64
				checkAttributes(realPath, attrs);
65
				if (CopyOnWriteFileSystem.this.skippedPaths.matches(realPath)) {
66
					return FileVisitResult.CONTINUE;
67
				}
68
69
				CopyOnWriteFSPath cowPath = this.toCowPath(realPath);
70
				DirectoryNode parentNode = fileTree.directoryByPath(Objects.requireNonNull(cowPath.getParent()));
71
				parentNode.addChild(new FileNode(cowPath, realPath, false));
72
				return FileVisitResult.CONTINUE;
73
			}
74
75
			public FileVisitResult preVisitDirectory(final Path realPath, final BasicFileAttributes attrs) throws IOException {
76
				checkAttributes(realPath, attrs);
77
				if (CopyOnWriteFileSystem.this.skippedPaths.matches(realPath)) {
78
					return FileVisitResult.SKIP_SUBTREE;
79
				}
80
81
				if (realPath.equals(baseDirectory)) {
82
					return FileVisitResult.CONTINUE;
83
				}
84
85
				CopyOnWriteFSPath cowPath = this.toCowPath(realPath);
86
				DirectoryNode parentNode = fileTree.directoryByPath(Objects.requireNonNull(cowPath.getParent()));
87
				parentNode.addChild(new DirectoryNode(cowPath));
88
				return FileVisitResult.CONTINUE;
89
			}
90
91
			private static void checkAttributes(final Path realPath, final BasicFileAttributes attrs) throws CowFSCreationException {
92
				if (!attrs.isRegularFile() && !attrs.isDirectory()) {
93
					throw new CowFSSymlinkException("Cannot build copy-on-write file system when symlink is present: " + realPath);
94
				}
95
96
				if (!Files.isWritable(realPath)) {
97
					throw new CowFSCreationException("Cannot build copy-on-write file system, missing write access for file: " + realPath);
98
				}
99
			}
100
101
			private CopyOnWriteFSPath toCowPath(final Path realPath) {
102
				return fileTree.path().resolve(baseDirectory.relativize(realPath).toString());
103
			}
104
		});
105
		return fileTree;
106
	}
107
108
	@VisibleForTesting
109
	protected void resetFileTreeToBaseFolderContent() throws IOException {
110
		this.fileTree = this.buildFileTreeFrom(this.baseDirectory);
111
	}
112
113
	public CopyOnWriteFSProvider provider() {
114
		return this.provider;
115
	}
116
117
	@Override
118
	public void close() throws IOException {
119
		if (Files.exists(this.tmpDirectory)) {
120
			PathUtils.deleteDirectory(this.tmpDirectory);
121
		}
122
	}
123
124
	@Override
125
	public boolean isOpen() {
126
		return true;
127
	}
128
129
	@Override
130
	public boolean isReadOnly() {
131
		return false;
132
	}
133
134
	@Override
135
	public String getSeparator() {
136
		return this.backingFileSystem().getSeparator();
137
	}
138
139
	@Override
140
	public Iterable<Path> getRootDirectories() {
141
		return List.of(this.rootPath());
142
	}
143
144
	@Override
145
	public Iterable<FileStore> getFileStores() {
146
		return List.of(this.store);
147
	}
148
149
	@Override
150
	public Set<String> supportedFileAttributeViews() {
151
		return FILE_ATTRIBUTE_VIEWS;
152
	}
153
154
	public CopyOnWriteFSPath getPath(final String first, final String... more) {
155
		return CopyOnWriteFSPath.of(this, first, more);
156
	}
157
158
	@Override
159
	public PathMatcher getPathMatcher(final String syntaxAndPattern) {
160
		throw new UnsupportedOperationException();
161
	}
162
163
	@Override
164
	public UserPrincipalLookupService getUserPrincipalLookupService() {
165
		throw new UnsupportedOperationException();
166
	}
167
168
	@Override
169
	public WatchService newWatchService() {
170
		throw new UnsupportedOperationException();
171
	}
172
173
	public CopyOnWriteFileStore store() {
174
		return this.store;
175
	}
176
177
	public CopyOnWriteFSPath rootPath() {
178
		return this.rootPath;
179
	}
180
181
	DirectoryNode fileTree() {
182
		return this.fileTree;
183
	}
184
185
	public Path baseDirectory() {
186
		return this.baseDirectory;
187
	}
188
189
	public Path tmpDirectory() {
190
		return this.tmpDirectory;
191
	}
192
193
	Path createTemporaryFilePath() {
194
		return this.tmpDirectory.resolve("tmp_" + this.tmpFileIndex.incrementAndGet());
195
	}
196
197
	public FileSystem backingFileSystem() {
198
		return this.tmpDirectory.getFileSystem();
199
	}
200
201
	public CopyOnWriteFileSystem.Moves collectMoveOperations(final Path outPath) {
202
		CopyOnWriteFileSystem.Moves result = new CopyOnWriteFileSystem.Moves(new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
203
		this.collectMoveOperations(outPath, this.fileTree, result);
204
		return result;
205
	}
206
207
	private void collectMoveOperations(final Path outPath, final DirectoryNode folder, final CopyOnWriteFileSystem.Moves result) {
208
		for (Node childNode : folder.children()) {
209
			Path target = outPath.resolve(Objects.requireNonNull(childNode.name()));
210
			switch (childNode) {
211
				case FileNode fileNode:
212
					FileMove move = new FileMove(fileNode.storagePath(), target);
213
					if (fileNode.isCopy) {
214
						result.copiedFiles.add(move);
215
					} else {
216
						result.preexistingFiles.add(move);
217
					}
218
					break;
219
				case DirectoryNode directoryNode:
220
					result.directories.add(target);
221
					this.collectMoveOperations(target, directoryNode, result);
222
					break;
223
				default:
224
					throw new MatchException(null, null);
225
			}
226
		}
227
	}
228
229
	public static void createDirectories(final List<Path> directories) throws IOException {
230
		for (Path directory : directories) {
231
			Files.createDirectory(directory);
232
		}
233
	}
234
235
	public static void hardLinkFiles(final List<FileMove> moves) throws IOException {
236
		for (FileMove move : moves) {
237
			if (!Files.exists(move.to())) {
238
				if (!Files.isRegularFile(move.from())) {
239
					throw new IllegalStateException("Not a regular file: " + move.from());
240
				}
241
242
				Files.createLink(move.to(), move.from());
243
			}
244
		}
245
	}
246
247
	public static void moveFiles(final List<FileMove> moves) throws IOException {
248
		for (FileMove move : moves) {
249
			Files.move(move.from(), move.to());
250
		}
251
	}
252
253
	public static void moveFilesWithRetry(final List<FileMove> moves, final CopyOption... options) throws IOException {
254
		for (FileMove move : moves) {
255
			if (Files.exists(move.from()) || !Files.exists(move.to())) {
256
				if (!Files.isRegularFile(move.from())) {
257
					throw new IOException("Not a regular file: " + move.from());
258
				}
259
260
				Files.move(move.from(), move.to(), options);
261
			}
262
		}
263
	}
264
265
	public static List<FileMove> tryRevertMoves(final List<FileMove> moves, final CopyOption... options) {
266
		List<FileMove> failedMoves = new ArrayList<>();
267
268
		for (FileMove move : moves) {
269
			if (Files.exists(move.to()) || !Files.exists(move.from())) {
270
				if (Files.isRegularFile(move.to())) {
271
					boolean success = Util.safeMoveFile(move.to(), move.from(), options);
272
					if (success) {
273
						LOGGER.info("Reverted move from {} to {}", move.from(), move.to());
274
					} else {
275
						LOGGER.error("Failed to revert move from {} to {}", move.from(), move.to());
276
						failedMoves.add(move);
277
					}
278
				} else {
279
					LOGGER.error("Skipping reverting move from {} to {} as it's not a file", move.from(), move.to());
280
					failedMoves.add(move);
281
				}
282
			}
283
		}
284
285
		if (failedMoves.isEmpty()) {
286
			LOGGER.info("Successfully reverted back to previous world state");
287
		} else {
288
			LOGGER.error("Completed reverting with errors");
289
		}
290
291
		return failedMoves;
292
	}
293
294
	public record Moves(List<Path> directories, List<FileMove> copiedFiles, List<FileMove> preexistingFiles) {
295
	}
296
}
297

Decompiled Minecraft 26.3 source of CopyOnWriteFileSystem (net/minecraft/util/filefix/virtualfilesystem/CopyOnWriteFileSystem.java) with Mojang official mappings, stored verbatim on the site.